AtCoder Beginner Contest 218 F - Blocked Roads (最短路径还原 思维)

该博客探讨了如何解决在有向图中每次删除一条边时,从节点1到节点n的最短路径变化的问题。通过使用BFS算法求解初始最短路径并记录路径上的边,然后判断每次删除的边是否在最短路径上,来更新最短路径。文章提供了C++代码实现,适用于边数和节点数较小的情况。
摘要由CSDN通过智能技术生成

linkk
题意:
给出点数为 n n n,边数为 m m m的有向图,问每次删去一条边时, 1 − n 1-n 1n的最短路,每次询问相互独立。 n < = 400 n<=400 n<=400

思路:

如果要删去的边不在 1 1 1 n n n的最短路上的话,那么不会对最短路造成影响。
如果在最短路上的话,就需要重新跑一遍最短路。
由于 n n n只有 400 400 400,时间复杂度为 O ( n ∗ ( n + m ) ) O(n*(n+m)) O(n(n+m))
具体操作为:

  • 求出 1 1 1 n n n的最短路 r e s res res并且记录下最短路上的边。
  • 对于 m m m条边,看是否在最短路上,如果不在的话,直接输出 r e s res res
  • 如果在的话,重新跑一遍最短路,并且不能用到第 i i i条边。在 b f s bfs bfs的时候传入参数 x x x表示不能用第 x x x条边,如果 x = = 0 x==0 x==0的话,说明全部边都可以用,在这次记录前驱。

代码:

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

typedef pair<int, int>PII;

inline ll read(){ll x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;}

inline void write(ll x){if (x < 0) x = ~x + 1, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}

#define read read()

#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)

ll ksm(ll a, ll b,ll mod){ll res = 1;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;}

const int maxn=2e5+7,inf=0x3f3f3f3f;

int n,m,pre[maxn];
vector<int>g[maxn];
PII edge[maxn];
set<PII>st;

int dis[maxn];

int bfs(int x){
    memset(dis,0x3f,sizeof dis);
    queue<int>q;
    q.push(1);dis[1]=0;
    while(!q.empty()){
        int t=q.front();q.pop();
        if(t==n) return dis[n];
        for(auto tt:g[t]){
            if(edge[x].first==t&&edge[x].second==tt) continue;
            if(dis[tt]>dis[t]+1){
                dis[tt]=dis[t]+1;
                if(x==0) pre[tt]=t;
                q.push(tt);
            }
        }
    }
    return -1;
}

int main(){
    n=read,m=read;
    rep(i,1,m){
        edge[i].first=read,edge[i].second=read;
        g[edge[i].first].push_back(edge[i].second);
    }
    int res=bfs(0);
    int now=n;
    while(now!=1){
        if(!pre[now]) break;
        PII tmp={pre[now],now};
        now=pre[now];
        st.insert(tmp);
    }
    for(int i=1;i<=m;i++)
        if(st.count(edge[i])) printf("%d\n",bfs(i));
        else cout<<res<<endl;
    return 0;
}
/*


*/





/**/
















  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆沙睡不醒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值