1. 程式人生 > >POJ 1511 Invitation Cards

POJ 1511 Invitation Cards

mes dijkstra return poj inf stl ted operator printf

題意

  ? 給出一個有向圖,n的點,m條邊,問從1節點出發到2,3,...n 這些節點路程和從從這些節點回來到節點1的路程和最小值。

解題思路

?   把圖正向存一遍,跑一遍dijkstra,求出1到各個點的距離和。然後再把圖反向存一遍,跑一遍dijkstra,求出1到各個點的距離和。思路很清晰。開始的時候用的dijkstra+vector+heap,結果TLE了。然後把vector換成了鄰接表,結果過了。看來STL雖然方便,但是速度太慢。註意數據很大,long long會炸。

技術分享圖片
  1 #include<stdio.h>
  2 #include<iostream>
  3
#include<stdlib.h> 4 #include<queue> 5 using namespace std; 6 #define maxn 1000005 7 #define inf 0x3f3f3f3f 8 9 typedef struct Edgenode 10 { 11 int x,val; 12 Edgenode *next; 13 } Edgenode; 14 typedef struct Edgehead 15 { 16 int x; 17 Edgenode *firstedge; 18
} Edgehead,adjlist[maxn]; 19 typedef struct graph 20 { 21 int n,m; 22 adjlist Adjlist; 23 } graph; 24 graph g; 25 long long d[maxn]; 26 int flag; 27 struct node 28 { 29 int x,y,val; 30 } nodes[maxn]; 31 32 void init() 33 { 34 for(int i=0; i<=g.n; i++) 35 g.Adjlist[i].firstedge=NULL;
36 } 37 void build() 38 { 39 int a,b,c; 40 Edgenode *p; 41 for(int i=0; i<g.m; i++) 42 { 43 if(flag)/*正向建圖*/ 44 { 45 p=(Edgenode *)malloc(sizeof(Edgenode)); 46 p->x=nodes[i].y; 47 p->val=nodes[i].val; 48 p->next=g.Adjlist[nodes[i].x].firstedge; 49 g.Adjlist[nodes[i].x].firstedge=p; 50 } 51 else/*反向建圖*/ 52 { 53 p=(Edgenode *)malloc(sizeof(Edgenode)); 54 p->x=nodes[i].x; 55 p->val=nodes[i].val; 56 p->next=g.Adjlist[nodes[i].y].firstedge; 57 g.Adjlist[nodes[i].y].firstedge=p; 58 } 59 } 60 } 61 struct cmp 62 { 63 bool operator()(const int a,const int b) 64 { 65 return d[a]>d[b]; 66 } 67 }; 68 long long dijkstra() 69 { 70 priority_queue<int,vector<int>,cmp> q; 71 for(int i=2; i<=g.n; i++) 72 d[i]=inf; 73 d[1]=0; 74 q.push(1); 75 while(!q.empty()) 76 { 77 int now=q.top(); 78 q.pop(); 79 Edgenode *p=g.Adjlist[now].firstedge; 80 while(p) 81 { 82 if(d[p->x]>d[now]+p->val) 83 { 84 d[p->x]=d[now]+p->val; 85 q.push(p->x); 86 } 87 p=p->next; 88 } 89 } 90 long long ans=0; 91 for(int i=2; i<=g.n; i++) 92 ans+=d[i]; 93 return ans; 94 } 95 int main() 96 { 97 //freopen("in.txt","r",stdin); 98 int t; 99 cin>>t; 100 while(t--) 101 { 102 scanf("%d%d",&g.n,&g.m); 103 for(int i=0; i<g.m; i++) 104 scanf("%d%d%d",&nodes[i].x,&nodes[i].y,&nodes[i].val); 105 long long ans=0; 106 flag=1; 107 init(); 108 build(); 109 ans+=dijkstra(); 110 flag=0; 111 init(); 112 build(); 113 ans+=dijkstra(); 114 printf("%lld\n",ans); 115 } 116 return 0; 117 }
View Code

POJ 1511 Invitation Cards