hdu1535 spfa反向表示多到一

 1 #include<stdio.h>
 2 #include<math.h>
 3 #include<string.h>
 4 #include<queue>
 5 using namespace std;
 6 struct Edge
 7 {
 8     int to;  //边终点
 9     int w;   //边值
10     int next;//结构体模拟链表
11 }edge[1000005];
12 int m,n,target,outqueue[1000005],used[1000005],head[1000005],dis[1000005],f1[1000005],f2[1000005],f3[1000005];
13 void spfa(int sta)
14 {
15     int temp,i;
16     queue<int>q;
17     while (!q.empty()) q.pop();
18     used[sta]=1; dis[sta]=0; q.push(sta);
19     while (!q.empty())
20     {
21         temp=q.front(); q.pop();
22         outqueue[temp]++; used[temp]=0;
23         if (outqueue[temp]>n) return;
24         for (i=head[temp];i!=-1;i=edge[i].next)
25         if (dis[edge[i].to]>dis[temp]+edge[i].w)
26         {
27             dis[edge[i].to]=dis[temp]+edge[i].w;
28             if (used[edge[i].to]==0)
29             {
30                 used[edge[i].to]=1;
31                 q.push(edge[i].to);
32             }
33         }
34     }
35     return;
36 }
37 int main()
38 {
39     int i,k,a,b,w,t,sum;
40     while (~scanf("%d",&t))
41     while (t--)
42     {
43         scanf("%d%d",&n,&k);
44         memset(outqueue,0,sizeof(outqueue));//出队次数判断负权回路
45         memset(used,0,sizeof(used));//用不用加入队列
46         memset(head,-1,sizeof(head));//数组模拟链表
47         for (i=1;i<=n;i++) dis[i]=0x3f3f3f3f;
48         for (i=1;i<=k;i++) scanf("%d%d%d",&f1[i],&f2[i],&f3[i]);
49         for (i=1;i<=k;i++)
50         {
51             a=f1[i]; b=f2[i]; w=f3[i];
52             edge[i].to=b;
53             edge[i].w=w;
54             edge[i].next=head[a];
55             head[a]=i;
56         }
57         sum=0; spfa(1);
58         for (i=2;i<=n;i++) sum+=dis[i];
59         memset(outqueue,0,sizeof(outqueue));//出队次数判断负权回路
60         memset(used,0,sizeof(used));//用不用加入队列
61         memset(head,-1,sizeof(head));//数组模拟链表
62         for (i=1;i<=n;i++) dis[i]=0x3f3f3f3f;
63         for (i=1;i<=k;i++)
64         {
65             a=f2[i]; b=f1[i]; w=f3[i];
66             edge[i].to=b;
67             edge[i].w=w;
68             edge[i].next=head[a];
69             head[a]=i;
70         } spfa(1);
71         for (i=2;i<=n;i++) sum+=dis[i];
72         printf("%d\n",sum);
73     }
74 }

http://acm.hdu.edu.cn/showproblem.php?pid=1535

posted on 2014-07-17 17:24  xiao_xin  阅读(127)  评论(0编辑  收藏  举报

导航