确定比赛名次(拓扑排序)

213 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。​

数据:

Input

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

Output

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

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

Sample Input

4 3
1 2
2 3
4 3

题意:给n,m   n表示队伍个数,然后m行数据,每行是x,y   表示x赢了y...最后从前往后依次排名 

思路:比较裸的拓扑排序;优先队列加拓扑排序   入度为零即输出!见代码~ 

the first: 

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1E5+10;
#define mem(a,b) memset(a,b,sizeof(a))
int ans[550],ru[550];
int dp[550][550];
int n,m;
void toposort()
{
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
        {
            if(dp[i][j])
                ru[j]++;
        }
    }
    for(int i=1; i<=n; i++)
    {
        int k=1;
        while(ru[k]!=0)k++;
        ans[i]=k;
        ru[k]=-1;
        for(int j=1; j<=n; j++)
        {
            if(dp[k][j])
                ru[j]--;
        }
    }
}
int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        mem(dp,0),mem(ru,0),mem(ans,0);
        int x,y;
        for(int i=1; i<=m; i++)
        {
            scanf("%d %d",&x,&y);
            dp[x][y]=1;
        }
        toposort();
        for(int i=1; i<n; i++)
            printf("%d ",ans[i]);
        printf("%d\n",ans[n]);
    }
    return 0;
}

the second:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
const int N=550;
#define mem(a,b) memset(a,b,sizeof(a))
priority_queue<int,vector<int>,greater<int> >q;
int ru[N],dp[N][N];
int n,m;
void toposort()
{
    for(int i=1; i<=n; i++)
        if(ru[i]==0)
            q.push(i);
    int k=1;
    while(!q.empty())
    {
        int x=q.top();
        q.pop();
        if(k!=n)
        {
            printf("%d ",x);
            k++;
        }
        else printf("%d\n",x);
        for(int i=1; i<=n; i++)
        {
            if(dp[x][i]==0)continue;
            ru[i]--;
            if(ru[i]==0)
                q.push(i);
        }
    }
}
int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        mem(dp,0),mem(ru,0);
        for(int i=1; i<=m; i++)
        {
            int x,y;
            scanf("%d %d",&x,&y);
            if(dp[x][y])continue;
            dp[x][y]=1;
            ru[y]++;
        }
        toposort();
    }
    return 0;
}