//UVA10305OrderingTasks
#include<cstdio>
#include<cstdlib>
#include<cstring>
//#define LOCAL
const int MAXN = 100 + 10;
char pre[MAXN][MAXN];
char topo_series[MAXN];
int m ,n;
int tag[MAXN];//标记访问状态
int now = 0;
void read() {
int x, y;
for(int i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
pre[y][x] = 1;
}
}
bool DFS(int node) {
tag[node] = -1;//开始调用函数的标志
for(int i = 1; i <= n; i++) {
if(pre[node][i]) {//有比node优先级低的
if(tag[i] < 0) {printf("node = %d, i = %d", node, i); return false;}//有环存在
if(!tag[i] && !DFS(i)) {printf("node = %d, i = %d", node, i); return false;}//若未被访问,则进行访问,若出现错误,则返回false
}
}
//printf("now = %d, node = %d\n", now, node);
topo_series[now++] = node;//优先级最后的存在最后
tag[node] = 1;//函数调用结束的标志
return true;
}
bool topo() {
for(int i = 1; i <= n; i++) {
if(!tag[i]) //未被访问过
if(!DFS(i)) return false;
}
return true;
}
int main() {
#ifdef LOCAL
freopen("UVA10305in.txt", "r", stdin);
freopen("UVA10305out.txt", "w", stdout);
#endif
while((scanf("%d%d", &n, &m)) == 2 && n) {
memset(topo_series, 0, sizeof(topo_series));
memset(tag, 0, sizeof(tag));
memset(pre, 0, sizeof(pre));
read();
now = 1;//now标记当前存储位置的指向
if(!topo()) printf("ERROR\n");
for(int i = 1; i <= n; i++) {
if(i - 1) printf(" ");
printf("%d", topo_series[i]);
}
printf("\n");
}
return 0;
}
/*
5 4
1 2
2 3
1 3
1 5
2 1
1 2
2 1
2 1
0 0
0 0
*/
UVA10305OrderingTasks
最新推荐文章于 2020-04-05 10:08:40 发布
