1Y
比较遗憾的是,我的耗时比较多,用了64MS。
本题要判断有向图的环,我用了Bellman Ford。这里的Bellman 用于求最远距离。当一个图的最远距离是N-1时(N是点数),则有解。
如果即没有环也没有解,则输出无解
有拓扑排序的算法,过一阵我去学习一下
#include <iostream> #include <cstring> #include <algorithm> #define F(i,a,b) for (int i=a;i<=b;i++) using namespace std; int N, NE, ne, ind[1002], f[30], d[30]; class edge { public: int s, t; edge() {} edge(int a, int b) { s=a, t=b; } }E[1002]; char res[30]; bool relax(int x) { int s=E[x].s, t=E[x].t; if (d[t]<d[s]+1) { d[t]=d[s]+1; f[t]=s; return true; } return false; } bool bellman(int s) { fill(d, d+N+1, 0); fill(f, f+N+1, 0); bool refresh=true; for (int i=1;i<=N-1 && refresh;i++) { refresh=false; F(j,1,ne) refresh=relax(j)||refresh; } F(i,1,ne) if ( relax(i) ) return true; return false; } void getPath(int x) { int now=0; while (x!=0) { res[now]=x+64; x=f[x]; now++; } reverse(&res[0], &res[now]); } int main() { bool cycle, done; int max_, pos, a ,b, s; string str; //freopen ("in.txt", "r", stdin); while (cin >> N >> NE && N!=0 && NE!=0) { memset( ind, 0,sizeof(ind) ); cycle=false; done=false; F(i,1,NE) { cin >> str; a=str[0]-64; b=str[2]-64; ind[b]++; E[i]=edge(a,b); //outd[a] if ( !done && !cycle ) { ne=i; F(j,1,N) cycle=bellman(j)||cycle; if (!cycle) { max_=0,pos=0; F(j,1,N) if (d[j]>max_) { max_=d[j]; pos=j; } if (max_==N-1) { cout << "Sorted sequence determined after " << i <<" relations: "; getPath(pos); F(i,0,N-1) cout << res[i]; cout << "./n"; done=true; } } else cout << "Inconsistency found after "<<i<<" relations./n"; } } if (!done && !cycle) cout << "Sorted sequence cannot be determined./n"; } return 0; }