洛谷 1339 [USACO09OCT]热浪Heat Wave

【题解】  

  最短路。那么直接写dijkstra就好了。

 

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #define LL long long
 5 #define rg register
 6 #define N 200010
 7 using namespace std;
 8 int n,m,s,t,tot,last[N],dis[N],pos[N];
 9 struct edge{
10     int to,pre,dis;
11 }e[N<<1];
12 struct heap{
13     int poi,dis;
14 }h[N<<1];
15 inline int read(){
16     int k=0,f=1; char c=getchar();
17     while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
18     while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar();
19     return k*f;
20 }
21 inline void up(int x){
22     int fa;
23     while((fa=(x>>1))&&h[fa].dis>h[x].dis){
24         swap(h[fa],h[x]); swap(pos[h[fa].poi],pos[h[x].poi]);
25         x=fa;
26     }
27 }
28 inline void down(int x){
29     int son;
30     while((son=x<<1)<=tot){
31         if(son<tot&&h[son].dis>h[son+1].dis) son++;
32         if(h[son].dis<h[x].dis){
33             swap(h[son],h[x]); swap(pos[h[son].poi],pos[h[x].poi]);
34             x=son;
35         }
36         else return;
37     }
38 }
39 inline void dijkstra(int x){
40     for(rg int i=1;i<=n;i++) dis[i]=2e9;
41     h[tot=pos[x]=1]=(heap){x,dis[x]=0};
42     while(tot){
43         int now=h[1].poi; h[1]=h[tot--]; if(tot) down(1);
44         for(rg int i=last[now],to;i;i=e[i].pre)
45         if(dis[to=e[i].to]>dis[now]+e[i].dis){
46             dis[to]=dis[now]+e[i].dis;
47             if(!pos[to]) h[pos[to]=++tot]=(heap){to,dis[to]};
48             else h[pos[to]].dis=dis[to];
49             up(pos[to]);
50         }
51         pos[now]=0;
52     }
53 }
54 int main(){
55     n=read(); m=read(); s=read(); t=read();
56     for(rg int i=1;i<=m;i++){
57         int u=read(),v=read(),d=read();
58         e[++tot]=(edge){v,last[u],d}; last[u]=tot;
59         e[++tot]=(edge){u,last[v],d}; last[v]=tot;
60     }
61     dijkstra(s);
62     printf("%d\n",dis[t]);
63     return 0;
64 }
View Code

猜你喜欢

转载自www.cnblogs.com/DriverLao/p/9397619.html