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

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

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

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

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

缺陷:

1.当时想成把点拆开后连边跑SPFA,但是数据范围过大--->不必实际连边,只要有转移即可。

2.后来想到一个错误的贪心:将第1~k大的边的权值变为0,然后跑SPFA,结果。。。。

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
*/

 

posted @ 2018-04-21 16:11  dprswdr  阅读(226)  评论(0编辑  收藏  举报