所谓关键路径就是DAG的最长路径,用dfs找
#include<bitset> #include<iostream> #include<set> #include<algorithm> using namespace std; const int N=103,INF=1<<30,src=0,dst=N-1; int n,m,pre[N],dis[N][N],nth[N][N],maxlen,nocycle=true; struct road{ int src,dst,nth; road(int a,int b,int c):src(a),dst(b),nth(c){} bool operator<(const road&x)const{ return src!=x.src?src<x.src:nth>x.nth;} }; set<road>path; void storepath(int k){ if(pre[k]!=src)storepath(pre[k]); if(pre[k]!=src&&k!=dst) path.insert(road(pre[k],k,nth[pre[k]][k])); } void dfs(int k,int len){ static bitset<N>used; used.set(k); if(k==dst){ if(maxlen<len){ maxlen=len; path.clear(); storepath(k); }else if(maxlen==len) storepath(k); }else{ for(int i=0;i<N;++i) if(dis[k][i]!=INF){ if(used[i]) nocycle=false; pre[i]=k; dfs(i,len+dis[k][i]);} } used.reset(k); } void initial(){ fill_n(*dis,N*N,INF); fill_n(pre,N,-1); vector<bool>nopre(N,true),nonext(N,true); cin>>n>>m; for(int i=1;i<=m;++i){ int a,b,c;cin>>a>>b>>c; dis[a][b]=c; nth[a][b]=i; nopre[b]=false,nonext[a]=false; } for(int i=1;i<=n;++i){ if(nopre[i])dis[src][i]=0; if(nonext[i])dis[i][dst]=0; } } int main(){ initial(); dfs(src,0); if(nocycle){ cout<<maxlen<<endl; for(auto it=path.begin();it!=path.end();++it) cout<<it->src<<"->"<<it->dst<<endl; }else cout<<0; return 0; }