Codeforces 715B

Codeforces 715B


学号:16340050
数据科学与计算机学院(http://sdcs.sysu.edu.cn/)


目录


原题链接

Codeforces
http://codeforces.com/problemset/problem/715/B

题目大意

ZS画了一幅有n条边m个点的带权无向图,但是有一些边的权值被擦去了,ZS想知道,是否存在一种方案,将所有被擦去的边的权值重新赋值一个正整数,使得从u到v的最短路恰好为L。如果有,则输出Yes和修改方案。如果无,则输出No

思路分析

我们不妨先将无权值的边视为断边,求出u到能到达的点i的最短路1dis(u,i)。然后求v到j的最短路dis(v,j),其中,当遇到无权值的边时令权值

cost[i,j]=max(1,Ldis[u,i]dis[v,j])

如果存在合法的方案,那么这种赋值方式保证我们可以得到其中一种合法的修改方案。如果不存在合法的方案,那么这种赋值方法则保证我们将所有的可修改边都赋值成了1
最后判断一下dis(u,v)是否等于L即可得出答案

Codeforces

实现代码

C++
#include<cstdio>
#include<queue>
#include<utility>
#include<cstring>
#include<algorithm>
#define MAXM 50100
#define MAXN 1100

using namespace std;

int n,m,L,s,t,num,tot;
int g[MAXN],next[MAXM],cost[MAXM],y[MAXM];
int dis[MAXN],f[MAXN];
bool vis[MAXN];

struct rec{
    int u,v,z;
}edge[MAXM];

void Insert(int u,int v,int z){
    y[++tot]=v;
    next[tot]=g[u];
    g[u]=tot;
    cost[tot]=z;
}

int Scan(){
    int u,v,z;
    scanf("%d%d%d%d%d",&n,&m,&L,&s,&t);
    tot=1;
    for (int i=1;i<=m;i++){
        scanf("%d%d%d",&u,&v,&z);
        edge[++num].u=u;edge[num].v=v;edge[num].z=z;
        Insert(u,v,z); Insert(v,u,z);
    }
}

struct cmp{
    bool operator ()(pair<int,int> a,pair<int,int> b){
        return a.second>b.second;
    }
};

void Dijkstra(int st,int*d,int*anti,bool flag){
    priority_queue<pair<int,int>,vector<pair<int,int> >,cmp> q;
    memset(vis,0,sizeof(vis));
    d[st]=0;
    q.push(make_pair<int,int>(st,d[st]));
    while (!q.empty()){
        pair<int,int>sa=q.top(); q.pop();
        int now=sa.first;
        int used=sa.second;
        if (vis[now]) continue;
        vis[now]=true;
        for (int e=g[now];e!=0;e=next[e]){
            int son=y[e];
            if (cost[e]==0&&flag==0) continue;
            if (cost[e]==0&&flag==1) {
                cost[e]=cost[e^1]=max(1,L-used-anti[son]);
                edge[e/2].z=edge[(e^1)/2].z=cost[e];
            }
            if (d[son]>used+cost[e]) {
                d[son]=used+cost[e];
                q.push(make_pair<int,int>(son,d[son]));
            }
        }
    }
}

void Work(){
    memset(dis,60,sizeof(dis));
    memset(f,60,sizeof(f));
    Dijkstra(t,f,dis,false);
    Dijkstra(s,dis,f,true);
}

void Print(){
    if (dis[t]==L){
        printf("YES\n");
        for (int i=1;i<=m;i++) printf("%d %d %d\n",edge[i].u,edge[i].v,max(1,edge[i].z));
    } else printf("NO\n");
}

int main(){
    Scan();
    Work();
    Print();
}

  1. 在本文代码中,求最短路径使用优先队列优化Dijkstra https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值