您的位置:首页 > Web前端

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

2017-09-14 22:00 381 查看

题目链接

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

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

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define mem1(a) memset(a,127,sizeof(a))
const int N=5e4+10,inf=0x3f3f3f3f;
int n,m,k,tot=0,first
,dis
[22];
struct point{int w,to,ne;}e[N*2];
struct node{
int to,w,d;
bool operator <(const node &p)const {return p.w<w;}
};
std::priority_queue<node>q;
int read(){
int ans=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){ans=ans*10+c-48;c=getchar();}
return ans*f;
}
void ins(int u,int v,int w){
tot++;e[tot].ne=first[u];first[u]=tot;e[tot].to=v;e[tot].w=w;
tot++;e[tot].ne=first[v];first[v]=tot;e[tot].to=u;e[tot].w=w;
}
int dj(){
q.push((node){1,0,0});
mem1(dis);dis[1][0]=0;
while(!q.empty()){
node p=q.top();q.pop();
if(p.w!=dis[p.to][p.d])continue;
if(p.to==n)return p.w;
int x=p.to;
for(int i=first[p.to];i;i=e[i].ne){
int to=e[i].to,d=p.d;
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});}
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});}
}
}
return 0;
}
int main(){
n=read();m=read();k=read();
for(int i=1,a,b,c;i<=m;i++){
a=read();b=read();c=read();
ins(a,b,c);
}
printf("%d",dj());
return 0;
}
bzoj1579

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: