您的位置:首页 > 其它

UVA10305 Ordering Tasks 拓扑排序

2016-10-20 17:50 543 查看


用了dfs模版写居然wa了。。。

抓狂。。。。两道拓扑排序都和我有仇。。。

还以为自己写错了。。。。看了好几遍还是没啥问题。。。

结果居然。。。这题的m可能等于0.。。。。

我的判断是m==0的话就停止输入。。。

呵呵。。。

代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <set>
using namespace std;
const double pi = 3.14159265358979323846264338327950288419716939937511;
const double eps = 1e-8;

const int maxn = 110;
int c[maxn],n;
int topo[maxn],t;
bool G[maxn][maxn];
bool dfs(int u){
c[u]=-1;//been visited
for(int v=1;v<=n;v++){
if(G[u][v]){
if(c[v]<0){
return false;
}else if(!c[v]&&!dfs(v)){
return false;
}
}
}
c[u]=1;
topo[t--]=u;
return true;
}
bool topoSort(){
t = n;
memset(c, 0, sizeof(c));
for(int u=1;u<=n;u++){
if(!c[u]){
if(!dfs(u)){
return false;
}
}
}
return true;
}
int main(){
int m;
while(scanf("%d%d",&n,&m)&&n){
int i;
memset(G, false, sizeof(G));
for(i=1;i<=m;i++){
int a,b;
scanf("%d%d",&a,&b);
G[a][b]=true;
}
topoSort();
for(i=1;i<=n;i++){
printf("%d%c",topo[i],i==n?'\n':' ');
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: