一年后再写其实写拓扑序并没有什么问题,但是这题目竟然有重边。。。然后又wa到死了。。。
代码如下:
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<utility>
#include<stack>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<map>
using namespace std;
const int maxn = 505;
int in[maxn];
int G[maxn][maxn];
int n, m;
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
while(scanf("%d%d", &n, &m) != EOF) {
memset(in, 0, sizeof(in));
memset(G, 0, sizeof(G));
while(m--) {
int u, v;
scanf("%d%d", &u, &v);
if(G[u][v] != 1) {
G[u][v] = 1;
in[v]++;
}
}
for(int k = 0; k < n; k++) {
if(k)
printf(" ");
for(int i = 1; i <= n; i++) {
if(in[i] == 0) {
in[i]--;
printf("%d", i);
for(int j = 1; j <= n; j++) {
if(G[i][j] == 1) {
G[i][j] = 0;
in[j]--;
}
}
break;
}
}
}
printf("\n");
}
return 0;
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
这是我写的第一道拓扑排序的题目,但是很神奇的发现,这道题目用dfs那种拓扑很难写出来,我想了很久也没想法,最后只能求助于题解,然后发现真的没有人用dfs来写。。。我也是醉了。后来看别人题解发现了一种很巧妙的方法,大牛果然多,像我这种弱鸡只能默默地看题解。
08:比赛排名--拓扑排序
-
总时间限制:
- 2000ms 单个测试点时间限制:
- 1000ms 内存限制:
- 65535kB
-
描述
-
有N个比赛队(1<=n<=500),编号依次为1,2,3,......,n进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即p1赢p2,用p1,p2表示,排名时p1在p2之前。现在请你编程序确定排名。
输入
- 输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。 输出
-
给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。
其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。
样例输入
-
4 3 1 2 2 3 4 3
样例输出
-
1 2 4 3
代码如下:
#include<cstdio>
using namespace std;
const int MAXN = 505;
int insert[MAXN],G[MAXN][MAXN],level[MAXN];
int n,m;
void toposort()
{
int k=0,pos,i,j;
for(i=1;i<=n;i++)
{
pos=-1;
for(j=1;j<=n;j++)
{
if(insert[j]==0)
{
level[k++]=j;
insert[j]--;
pos=j;
break;
}
}
for(j=1;j<=n;j++)
{
if(G[pos][j])
{
insert[j]--;
G[pos][j]=0;
}
}
}
}
int main()
{
int i,j,a,b;
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
if(G[a][b]!=1)
{
G[a][b]=1;
insert[b]++;
}
}
toposort();
for(i=0;i<n-1;i++)
printf("%d ",level[i]);
printf("%d\n",level[n-1]);
return 0;
}