最短路
每次写最短路都被鄙视- -!
都说题很滥很滥(泛滥)。
单源最短:dijkstra ,bellman-ford
hdu 3790 很直白。(优先队列优化的时候注意<号重载,堆的形态)
1 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 #include <cstring> 5 6 using namespace std; 7 const int INF=100000000; 8 9 struct node{ 10 int d; 11 int w; 12 node(){} 13 node(int d,int w):d(d),w(w){} 14 node friend operator+(const node & a,const node &b){ 15 node c; 16 c.d=b.d+a.d; 17 c.w=b.w+a.w; 18 return c; 19 } 20 bool operator<(const node & a)const{ 21 if(d<a.d||d==a.d&&w<a.w)return 1; 22 return 0; 23 } 24 void inf(){d=w=INF;} 25 void zero(){d=w=0;} 26 }d[1005]; 27 struct M{ 28 int x; 29 node no; 30 M(){} 31 M(int xx,node nno){x=xx;no=nno;} 32 bool operator<(const M &a)const{ 33 if(no.d>a.no.d||no.d==a.no.d&& 34 no.w>a.no.w)return 1; 35 return 0; 36 } 37 }; 38 bool done[1005]; 39 int n,m; 40 struct edge{ 41 int to; 42 int next; 43 node no; 44 }e[2100000]; 45 int head[1005],num; 46 void _add(int u,int v,int d,int w){ 47 e[num].to=v; 48 e[num].no=node(d,w); 49 e[num].next=head[u]; 50 head[u]=num++; 51 } 52 void add(int u,int v,int d,int w){ 53 _add(u,v,d,w); 54 _add(v,u,d,w); 55 } 56 void Dij(int S,int T){ 57 for(int i=0;i<=n;i++)d[i].inf(); 58 d[S].zero(); 59 priority_queue<M>q; 60 while(!q.empty())q.pop(); 61 q.push(M(S,d[S])); 62 memset(done,0,sizeof(done)); 63 while(!q.empty()){ 64 M x=q.top();q.pop(); 65 if(done[x.x])continue; 66 done[x.x]=1; 67 for(int i=head[x.x];i!=-1;i=e[i].next)if((d[x.x]+e[i].no)<d[e[i].to]){ 68 d[e[i].to]=e[i].no+d[x.x]; 69 q.push(M(e[i].to,d[e[i].to])); 70 } 71 } 72 printf("%d %d\n",d[T].d,d[T].w); 73 } 74 75 int main() 76 { 77 int u,v,d,w; 78 while(scanf("%d%d",&n,&m),n||m){ 79 memset(head,-1,sizeof(head)); 80 num=0; 81 for(int i=1;i<=m;i++){ 82 scanf("%d%d%d%d",&u,&v,&d,&w); 83 add(u,v,d,w); 84 } 85 scanf("%d%d",&u,&v); 86 Dij(u,v); 87 } 88 89 return 0; 90 }

浙公网安备 33010602011771号