确定比赛名次——拓扑排序

来源:互联网 发布:披肩品牌知乎 编辑:程序博客网 时间:2024/05/08 03:06
 确定比赛名次
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。
 

Input

输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。
 

Output

给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。

其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。
 

Sample Input

4 31 22 34 3
 

Sample Output

1 2 4 3
拓扑排序:
用一个数组记录每个点的入度,首先找到入度为零的点,将这个点从图中摘除,并将这个点所连接的所有点的入度减1。
拓扑排序可以用于:
判断一个图有无环;计算顺序。。。。。。
#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;int jl[509][509];int ru[509];int dis[509],cun[509];void tuop(int N){    int i,j,k;    int top = -1,low = 0;    for(i = 1;i <= N;i++)    {        if(ru[i] == 0)            dis[++top] = i;    }    j = 0;    while(low <= top)    {        k = dis[low++];        cun[j++] = k;        for(i = 1;i <= N;i++)        {            if(jl[k][i] != 0)            {                ru[i]--;                if(ru[i] == 0)                dis[++top] = i;            }        }        sort(dis+low,dis+top+1);//如果同级,则按照从小到大顺序,所以需要再次排序。。。。。。    }    for(i = 0;i < j;i++)    {        if(i == 0)            printf("%d",cun[i]);        else            printf(" %d",cun[i]);    }    printf("\n");}int main(){    int N,n;    int i,j,k;    int x,y;    while(scanf("%d%d",&N,&n)!=EOF)    {        memset(ru,0,sizeof(ru));        memset(jl,0,sizeof(jl));        for(i = 0;i < n;i++)        {            scanf("%d%d",&x,&y);            if(jl[x][y] == 0)                 ru[y]++;            jl[x][y] = 1;        }        tuop(N);    }    return 0;}
以下代码出自大神WJW之手,省内存又省时。
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>#include <queue>const int INF = 1e6;const int ma = 1010;#define MAX 0x3f3f3f3fusing namespace std;struct no{    int u,v,next;}g[11100];int head[1110],n,m,rudu[1100],t;void add(int a,int b){    g[t].u = a;    g[t].v = b;    g[t].next = head[a];    head[a] = t++;}int aa[1100],l;void TOP(){    l = 0;    for(int i = 1;i<=n;i++)    {        for(int j = 1;j<=n;j++)        {            if(rudu[j]==0)            {                rudu[j]--;                aa[l++] = j;                for(int pp = head[j];pp != 0;pp = g[pp].next)                {                    rudu[g[pp].v]--;                }                break;            }        }    }}int main(){    int a,b;    while(~scanf("%d%d",&n,&m))    {        memset(rudu,0,sizeof(rudu));        memset(head,0,sizeof(head));        t = 1;        for(int i = 0;i<m;i++)        {             scanf("%d%d",&a,&b);             add(a,b);        rudu[b]++;        }           TOP();           for(int i = 0;i<l-1;i++)            printf("%d ",aa[i]);            printf("%d\n",aa[l-1]);    }    return 0;}



0 0
原创粉丝点击