现在的位置: 首页 > 综合 > 正文

poj1511

2013年03月12日 ⁄ 综合 ⁄ 共 1315字 ⁄ 字号 评论关闭

此题结合了最短路经典变形,即将图边反向,再用单元最短路即单目标最短路,题解就是单元最短路和单目标最短路之和。有负权不可用dijkstra,看数据量和时间bellman-ford可能超时,事实证明有可能不超,用SPFA,又加了点优化用SLF。

View Code

 1 #include <queue>
2 #include <stdio.h>
3 #include <string.h>
4 using std::deque;
5 #define MAXN 1000010
6 #define INF (1<<30)
7 deque <int> que;
8 int N,p,q;
9 struct node
10 {
11 int d;
12 int cost;
13 node* next;
14 };
15 node *head[MAXN],edge[MAXN],*p1,*head1[MAXN],edge1[MAXN],*q1;
16 int a,b,c,t;
17 __int64 sum;
18 int dist[MAXN];
19 bool v[MAXN];
20 void input()
21 {
22 scanf("%d %d %d",&a,&b,&c);
23 p1->d=b;
24 p1->cost=c;
25 p1->next=head[a];
26 head[a]=p1++;
27 q1->d=a;
28 q1->cost=c;
29 q1->next=head1[b];
30 head1[b]=q1++;
31 }
32 void SPFA(bool is)
33 {
34 memset(v,false,sizeof(v));
35 for(int i=0;i<=p;++i) dist[i]=INF;
36 dist[1]=0;
37 que.push_front(1);
38 v[1]=true;
39 while(!que.empty())
40 {
41 t=que.front();
42 que.pop_front();
43 v[t]=false;
44 for(p1=(is?head[t]:head1[t]);p1;p1=p1->next)
45 if(dist[p1->d]>dist[t]+p1->cost)
46 {
47 dist[p1->d]=dist[t]+p1->cost;
48 if(!v[p1->d])
49 {
50 if(!que.empty()&&dist[p1->d]<dist[que.front()])
51 que.push_front(p1->d);
52 else
53 que.push_back(p1->d);
54 v[p1->d]=true;
55 }
56 }
57 }
58 for(int i=1;i<=p;++i) sum+=dist[i];
59 }
60 int main()
61 {
62 scanf("%d",&N);
63 while(N--)
64 {
65 p1=edge,q1=edge1,sum=0;
66 scanf("%d %d",&p,&q);
67 for(int i=0;i<=p;++i) head[i]=head1[i]=NULL;
68 for(int i=0;i<q;++i) input();
69 SPFA(true);
70 SPFA(false);
71 printf("%I64d\n",sum);
72 }
73 return 0;
74 }

抱歉!评论已关闭.