Problem 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 3 1 2 2 3 4 3 Sample Output 1 2 4 3 Author SmallBeer(CML) 分析: 拓撲排序、就這麼搞~
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 510
using namespace std;
int map[maxn][maxn];//路徑
int in_degree[maxn];//入度
int ans[maxn];
int n,m,x,y;
void topo()
{
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(map[i][j])
in_degree[j]++;//記錄各個入度
for(int i=1; i<=n; i++)
{
int k=1;
while(in_degree[k]!=0)
k++;
ans[i]=k;
in_degree[k]=-1;
/*更新為-1,後邊檢測時不受影響、
相當於刪除節點*/
for(int j=1; j<=n; j++)
if(map[k][j])
in_degree[j]--;//相關聯的入度減1
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(in_degree,0,sizeof(in_degree));
memset(ans,0,sizeof(ans));
memset(map,0,sizeof(map));
for(int i=0; i<m; i++)
{
scanf("%d%d",&x,&y);
map[x][y]=1;
}
topo();
for(int i=1; i<n; i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n]);
}
return 0;
}