Light oj 1074 spfa

https://vjudge.net/problem/LightOJ-1074

首先吐槽一个单词,directional是有方向的,undirectional是无向的,这个unidirectional是tm单向的。。。。好吧我又学会一个单词。

由于有负边权,用spfa好啦,判断负环时不要遇见就return,还有其他的节点要更新呢,直接continue掉就好,这样只跑一次spfa根据记录的d直接输出答案。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define inf 0x3f3f3f3f
 4 struct Edge
 5 {
 6     int to,w,next;
 7 }e[10005];
 8 int cnt,first[205],c[205];
 9 void add(int u,int v,int w)
10 {
11     e[cnt].to=v;
12     e[cnt].w=w;
13     e[cnt].next=first[u];
14     first[u]=cnt++;
15 }
16 int d[205];
17 bool spfa(int N)
18 {
19     int inq[205];
20     bool vis[205];
21     queue<int>Q;
22     memset(vis,0,sizeof(vis));
23     memset(inq,0,sizeof(inq));
24     memset(d,inf,sizeof(d));
25     Q.push(1);
26     vis[1]=inq[1]=1;
27     d[1]=0;
28     while(!Q.empty()){
29         int u=Q.front(); Q.pop();
30         vis[u]=0;
31         for(int i=first[u];i+1;i=e[i].next){
32             Edge x=e[i];
33             if(inq[x.to]>N) continue;
34             if(d[x.to]>d[u]+x.w){
35                 d[x.to]=d[u]+x.w;
36                 if(!vis[x.to]){
37                     Q.push(x.to);
38                     inq[x.to]++;
39                 }
40             }
41         }
42     }
43     return 1;
44 }
45 int main()
46 {
47     int T,N,M,Q,i,j,k=0;
48     int u,v,w;
49     cin>>T;
50     while(T--){cnt=0;
51         memset(first,-1,sizeof(first));
52         cin>>N;
53         for(i=1;i<=N;++i) cin>>c[i];
54         cin>>M;
55         while(M--){
56             cin>>u>>v;
57             add(u,v,(c[v]-c[u])*(c[v]-c[u])*(c[v]-c[u]));
58         }
59         cin>>Q;
60         printf("Case %d:\n",++k);
61         bool ok=spfa(N);
62         while(Q--){
63             cin>>u;
64             if(d[u]<3||d[u]==inf) puts("?");
65             else cout<<d[u]<<endl;
66         }
67     }
68     return 0;
69 }

 

posted @ 2017-08-14 18:37  *zzq  阅读(180)  评论(0编辑  收藏  举报