【bzoj1579/Usaco2009 Feb】Revamping Trails 道路升级——分层图最短路

题目链接

建立0~k共k+1层图,用dis[x][d]表示x到源点(此题为1)将d条道路距离降为0的距离,dijkstra跑的话因为从堆顶取出的就是已经确定的,因此当从堆顶取出的元素是n时,就可以直接返回并输出了。

用了堆优化,注意每次从堆顶取出元素后如果p.w!=dis[p.to][p.d],说明这条路径所到达的点到源点的路径已经被其他路径所松弛,换句话说,此时1~x走的根本不是存的这条路径,所以要重新从堆顶取满足条件的元素。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<queue>
 4 #include<algorithm>
 5 #define mem1(a) memset(a,127,sizeof(a))
 6 const int N=5e4+10,inf=0x3f3f3f3f;
 7 int n,m,k,tot=0,first[N],dis[N][22];
 8 struct point{int w,to,ne;}e[N*2];
 9 struct node{
10     int to,w,d;
11     bool operator <(const node &p)const {return p.w<w;}
12 };
13 std::priority_queue<node>q;
14 int read(){
15     int ans=0,f=1;char c=getchar();
16     while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
17     while(c>='0'&&c<='9'){ans=ans*10+c-48;c=getchar();}
18     return ans*f;
19 }
20 void ins(int u,int v,int w){
21     tot++;e[tot].ne=first[u];first[u]=tot;e[tot].to=v;e[tot].w=w;
22     tot++;e[tot].ne=first[v];first[v]=tot;e[tot].to=u;e[tot].w=w;
23 }
24 int dj(){
25     q.push((node){1,0,0});
26     mem1(dis);dis[1][0]=0;
27     while(!q.empty()){
28         node p=q.top();q.pop();
29         if(p.w!=dis[p.to][p.d])continue;
30         if(p.to==n)return p.w;
31         int x=p.to;
32         for(int i=first[p.to];i;i=e[i].ne){
33             int to=e[i].to,d=p.d;
34             if(dis[to][d]>dis[x][d]+e[i].w){dis[to][d]=dis[x][d]+e[i].w;q.push((node){to,dis[to][d],d});}
35             if(d<k&&dis[to][d+1]>dis[x][d]){dis[to][d+1]=dis[x][d];q.push((node){to,dis[to][d+1],d+1});}
36         }
37     }
38     return 0;
39 }
40 int main(){
41     n=read();m=read();k=read();
42     for(int i=1,a,b,c;i<=m;i++){
43         a=read();b=read();c=read();
44         ins(a,b,c);
45     }
46     printf("%d",dj());
47     return 0;
48 }
bzoj1579

 

posted @ 2017-09-14 22:00  Child-Single  阅读(139)  评论(0编辑  收藏  举报