BZOJ2763 [JLOI2011]飞行路线(洛谷P4568)

版权声明:蒟蒻Blog随意转载 https://blog.csdn.net/a1799342217/article/details/81877487

分层图最短路

BZOJ题目传送门
洛谷题目传送门

妙蛙

把原图分成k+1层,每一层向下一层连距离为0的边,然后跑一遍最短路就好了。

代码:

#include<queue>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 110005
#define F inline
using namespace std;
struct edge{ int nxt,to,d; }ed[N*20];
struct P{ int x,d; };
int n,m,k,p,s,t,ans=1e9,h[N],d[N];
priority_queue <P> q;
F char readc(){
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    return l==r?EOF:*l++;
}
F int _read(){
    int x=0; char ch=readc();
    while (!isdigit(ch)) ch=readc();
    while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x;
}
#define add(x,y,z) ed[++k]=(edge){h[x],y,z},h[x]=k
F bool operator < (P a,P b){ return a.d>b.d; }
F int Dij(){
    for (int i=1;i<=n*(p+1);i++) d[i]=1e9;
    for (q.push((P){s,d[s]=0});!q.empty();q.pop()){
        if (q.top().d>d[q.top().x]) continue;
        int x=q.top().x;
        for (int i=h[x],v;i;i=ed[i].nxt)
            if (d[x]+ed[i].d<d[v=ed[i].to])
                d[v]=d[x]+ed[i].d,q.push((P){v,d[v]});
    }
    for (int i=0;i<=p;i++) ans=min(ans,d[t+n*i]);
    return ans;
}
int main(){
    n=_read(),m=_read(),p=_read(),s=_read()+1,t=_read()+1;
    for (int i=1,x,y,z;i<=m;i++){
        x=_read()+1,y=_read()+1,z=_read(),add(x,y,z),add(y,x,z);
        for (int j=0,u=0,v=n;j<p;j++,u+=n,v+=n){
            add(x+u,y+v,0),add(y+u,x+v,0);
            add(x+v,y+v,z),add(y+v,x+v,z);
        }
    }
    return printf("%d\n",Dij()),0;
}

猜你喜欢

转载自blog.csdn.net/a1799342217/article/details/81877487
今日推荐