题目链接:http://icpc.njust.edu.cn/Problem/Hdu/1224/
无负环。
代码如下:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef unsigned int ui; 4 typedef long long ll; 5 typedef unsigned long long ull; 6 #define pf printf 7 #define mem(a,b) memset(a,b,sizeof(a)) 8 #define prime1 1e9+7 9 #define prime2 1e9+9 10 #define pi 3.14159265 11 #define lson l,mid,rt<<1 12 #define rson mid+1,r,rt<<1|1 13 #define scand(x) scanf("%llf",&x) 14 #define f(i,a,b) for(int i=a;i<=b;i++) 15 #define scan(a) scanf("%d",&a) 16 #define mp(a,b) make_pair((a),(b)) 17 #define P pair<int,int> 18 #define dbg(args) cout<<#args<<":"<<args<<endl; 19 #define inf 0x3f3f3f3f 20 const int maxn=1e4+5; 21 int n,m,t,e; 22 int c[maxn],head[maxn],nxt[maxn],pre[maxn],d[maxn],in[maxn]; 23 void init() 24 { 25 e=0; 26 mem(head,-1); 27 mem(nxt,-1); 28 mem(pre,0); 29 mem(d,-inf); 30 mem(in,0); 31 } 32 struct edge{ 33 int v,w; 34 }p[maxn]; 35 void addedge(int u,int v,int w) 36 { 37 p[e].v=v; 38 p[e].w=w; 39 nxt[e]=head[u]; 40 head[u]=e++; 41 } 42 void SPFA(int src) 43 { 44 d[src]=0; 45 queue<int>q; 46 q.push(src); 47 in[src]=1; 48 while(!q.empty()) 49 { 50 int now=q.front(); 51 q.pop(); 52 in[now]=0; 53 for(int i=head[now];~i;i=nxt[i]) 54 { 55 if(d[p[i].v]<d[now]+p[i].w) 56 { 57 pre[p[i].v]=now; 58 d[p[i].v]=d[now]+p[i].w; 59 in[p[i].v]=1; 60 q.push(p[i].v); 61 } 62 } 63 } 64 } 65 void print(int now) 66 { 67 if(pre[now]==0)return; 68 print(pre[now]); 69 pf("->%d",now); 70 } 71 int main() 72 { 73 //freopen("input.txt","r",stdin); 74 //freopen("output.txt","w",stdout); 75 std::ios::sync_with_stdio(false); 76 scan(t); 77 f(tt,1,t) 78 { 79 init(); 80 scan(n); 81 f(i,1,n)scan(c[i]); 82 scan(m); 83 int u,v; 84 f(i,1,m) 85 { 86 scanf("%d%d",&u,&v); 87 if(v==n+1)addedge(u,v,0); 88 else addedge(u,v,c[v]); 89 } 90 SPFA(1); 91 pf("CASE %d# ",tt); 92 pf("points : %d ",d[n+1]); 93 pf("circuit : 1"); 94 print(pre[n+1]); 95 pf("->1 "); 96 if(tt!=t)pf(" "); 97 } 98 }