ACM-ICPC 2018 南京赛区网络预赛 L. Magical Girl Haze (分层图)

本文介绍了一种通过将图拓展为多层来解决特定最短路径问题的方法,适用于需要将某些边权重变为0或其他数值的情况。通过实例演示如何实现算法,并详细解释了从输入读取到输出结果的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这一类的题目,都有一个很相同特点,就是把某些边变为0,或者是变为一个其他的数,我们只要把这个图拓展成K层。原来的一条边扩展成与下一层的一条边,这样再跑最短路算法就可以了。然后遍历每层你要到的那个终点选出最小的一个就可以了。
思路简单。
对于这个题也是,不过注意总的最大边数是2*K*MAX_E,因为两层之间的边数和原来的边数是相等的,不是等于点的数目。所以注意这里。我WA了一次就是这个数量没考虑好。

代码如下:

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
const int MAX_V = 100010;
const int MAX_E = 200010;
const ll INF = 1e16+10;
class Edge{
public:
    int to,nex;
    ll cost;
    Edge();
    Edge(int _to,int _nex,ll _cost);
};
Edge edg[2*MAX_E*12];
int head[MAX_V*12],cnt;
ll dis[MAX_V*12];
void init(){
    memset(head,-1,sizeof(head));
    cnt = 0;
}
void add_Edge(int u,int v,ll w){
    edg[cnt] = Edge(v,head[u],w);
    head[u] = cnt++;
}
int N,M,K;
class Rule{
public:
    bool operator() (const int A,const int B){
        return dis[A] > dis[B];
    }
};
void Dijkstra(){
    for(int i=0;i<=(K+1)*N;++i) dis[i] = INF;
    priority_queue<int,vector<int>,Rule > que;
    dis[1] = 0;
    que.push(1);
    while(!que.empty()){
        int u = que.top();que.pop();
        for(int i=head[u];~i;i=edg[i].nex){
            Edge &e = edg[i];
            if(dis[e.to] > dis[u] + e.cost){
                dis[e.to] = dis[u] + e.cost;
                que.push(e.to);
            }
        }
    }
    //遍历每一层的终点。
    ll res = INF;
    for(int i=0;i<=K;++i){
        res = min(res,dis[N+i*N]);
    }
    printf("%lld\n",res);
}
int main(void){
    int T;
    scanf("%d",&T);
    while(T--){
        init();
        scanf("%d%d%d",&N,&M,&K);
        int u,v;
        ll w;
        for(int i=1;i<=M;++i){
            scanf("%d%d%lld",&u,&v,&w);
            for(int l=0;l<=K;++l){
                add_Edge(u+l*N,v+l*N,w);
                //建立相邻两层的边,如果是最高层就不用了。
                if(l != K){
                    add_Edge(u+l*N,v+(l+1)*N,0);
                }
            }
        }
        Dijkstra();
    }

    return 0;
}
Edge::Edge(){
    to = nex = 0;
    cost = 0;
}
Edge::Edge(int _to,int _nex,ll _cost){
    to = _to;
    nex = _nex;
    cost = _cost;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值