首页 > 其他 > 详细

BZOJ2763 [JLOI2011]飞行路线 - SPFA&分层图

时间:2018-04-21 16:47:45      阅读:213      评论:0      收藏:0      [点我收藏+]

思路:将每个点拆成k个点,形成一个分层图。

最短路为dis[i][j],分别代表“到点i为止免费飞行的次数为j时的最短路是多少”。

其中不免费飞行的转移为dis[v][cnt]=dis[u][cnt]+e[i].w,免费飞行的转移为dis[v][cnt+1]=dis[u][cnt]。

最后比较一下免费飞行0~k次的最短路,得到答案。

AC Code:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int read()
{
    char ch= ;int w=1,a=0;
    while(ch<0||ch>9)
    {
        if(ch==-) w=-1;
        ch=getchar();
    }
    while(ch>=0&&ch<=9) a=a*10+ch-0,ch=getchar();
    return w*a;
}
const int N=10000+100,M=50000+100;
struct node{
    int to,nxt,w;
}e[M<<1];
int head[N],tot;
void add(int u,int v,int w)
{
    e[++tot].to=v,e[tot].nxt=head[u],e[tot].w=w;
    head[u]=tot;
}
int n,m,k,s,t;
struct poi{
    int pos,cnt;
};
queue<poi>q;
bool vis[N][15];//vis[][] 
int dis[N][15];
void SPFA()
{
    memset(dis,0x3f,sizeof(dis));
    q.push((poi){s,0}),dis[s][0]=0,vis[s][0]=1;
    while(q.size())
    {
        poi a=q.front();q.pop();
        int u=a.pos,tmp=a.cnt;
        vis[u][tmp]=0;
        for(int i=head[u];i;i=e[i].nxt)
        {
            int v=e[i].to;
            if(dis[v][tmp]>dis[u][tmp]+e[i].w)
            {
                dis[v][tmp]=dis[u][tmp]+e[i].w;
                if(!vis[v][tmp])
                {
                    q.push((poi){v,tmp});vis[v][tmp]=1;
                }
            }
            if(dis[v][tmp+1]>dis[u][tmp]&&tmp<k)
            {
                dis[v][tmp+1]=dis[u][tmp];
                if(!vis[v][tmp+1])
                {
                    q.push((poi){v,tmp+1});vis[v][tmp+1]=1;
                }
            }
        }
    }
}
int main()
{
    n=read();m=read();k=read();
    s=read();t=read();
    for(int i=1;i<=m;i++)
    {
        int u,v,w;
        u=read(),v=read(),w=read();
        add(u,v,w);add(v,u,w);
    }
    SPFA();
    int ans=(1<<30);
    for(int i=0;i<=k;i++)
    {
        ans=min(ans,dis[t][i]);
    }
    printf("%d",ans);
    return 0;
}
/*
5 6 1
0 4
0 1 5
1 2 5
2 3 5
3 4 5
2 3 3
0 2 100
*/

 

BZOJ2763 [JLOI2011]飞行路线 - SPFA&分层图

原文:https://www.cnblogs.com/Loi-Brilliant/p/8901860.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!