BZOJ2662 [BeiJing wc2012]冻结 最短路

这道题有两种做法。

第一种做法:

对于每个节点,记录经过它时已经使用x次魔法卡片时的最短时间,然后使用最短路算法更新这个值。注意,如果使用的是SPFA算法,不论是使用几次的最短时间被更新了,都要将其重新入队。

第二种做法:

我们把图复制K次,在两个相邻的图之间,如果原图中存在一条边<vi,vj>,其权值为w,那么在新图的第p层和第p+1层中,连接一条边<vi(p),vj(p+1)>,其权值为w/2,这样就保证了只有K条边经过时使用了魔法卡片。

下面的代码对应上面的第一种做法。

//BZOJ2662
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<vector>
#include<queue>
#include<utility>
using namespace std;
const int INF=1e9;
int n,m,k,in1,in2,in3,f[110][110],ans=INF;
bool used[110];
vector<pair<int,int> > graph[110];
queue<int> q;
void SPFA(int s)
{
    for(int i=1;i<=n;i++)
        for(int j=0;j<=k;j++)
            f[i][j]=INF;
    f[s][0]=0;
    used[s]=true;
    q.push(s);
    while(!q.empty())
    {
        int x=q.front(),len=graph[x].size();
        q.pop();
        used[x]=false;
        for(int i=0;i<len;i++)
        {
            bool relaxed=false;
            int t=graph[x][i].first,w=graph[x][i].second;
            for(int j=0;j<=k;j++)
            {
                if(f[t][j]>f[x][j]+w) f[t][j]=f[x][j]+w,relaxed=true;
                if(j&&f[t][j]>f[x][j-1]+(w>>1)) f[t][j]=f[x][j-1]+(w>>1),relaxed=true;
            }
            if(relaxed&&!used[t])
            {
                used[t]=true;
                q.push(t);
            }
        }
    }
}
int main()
{
    scanf("%d%d%d",&n,&m,&k);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&in1,&in2,&in3);
        graph[in1].push_back(make_pair(in2,in3));
        graph[in2].push_back(make_pair(in1,in3));
    }
    SPFA(1);
    for(int i=0;i<=k;i++)
        ans=min(ans,f[n][i]);
    printf("%d\n",ans);
    return 0;
}


你可能感兴趣的:(BZOJ2662 [BeiJing wc2012]冻结 最短路)