本文主要是介绍【ATC】Blocked Roads 删边最短路,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
传送⻔
题意
给出点数为 n n n,边数为 m m m的有向图,问每次删去一条边时, 1 − n 1 - n 1−n的最短路,每次询问相互独立。 n < = 400 n < = 400 n<=400
分析
分情况讨论,我们先求出这个图内的最短路,并且路径还原就可以知道哪些边在最短路中,这些边在图中最多不超过 n − 1 n - 1 n−1条
如果当前枚举的边不是最短路中的边,那么直接输出答案,如果是,那么考虑把这条边删去然后跑最短路
时间复杂度为 O ( n ∗ ( n + m ) ) O(n * (n + m)) O(n∗(n+m))
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 500,M = N * N;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int h[N],e[M],ne[M],idx;
PII edge[M];
bool st[N];
bool is[M];
int d[N];
int per[M];
int n,m;void add(int x,int y){ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}void bfs(){queue<int> q;memset(d,0x3f,sizeof d);d[1] = 0;q.push(1);while(q.size()){int t = q.front();q.pop();if(t == n) return;for(int i = h[t];~i;i = ne[i]){int j = e[i];if(d[j] > d[t] + 1){d[j] = d[t] + 1;per[j] = i;q.push(j);}}}
}void bfs(int x){queue<int> q;memset(d,0x3f,sizeof d);d[1] = 0;q.push(1);while(q.size()){int t = q.front();q.pop();for(int i = h[t];~i;i = ne[i]){int j = e[i];if(t == edge[x].fi && j == edge[x].se) continue;if(d[j] > d[t] + 1){d[j] = d[t] + 1;q.push(j);}}}
}int main() { read(n),read(m);memset(h,-1,sizeof h);for(int i = 1;i <= m;i++){int x,y;read(x),read(y);add(x,y);edge[i] = {x,y};} bfs();if(d[n] == INF){for(int i = 1;i <= m;i++) di(-1);return 0;}int s = n;int ans = d[n];while(s != 1){is[per[s]] = 1;s = edge[per[s]].fi;}for(int i = 1;i <= m;i++){if(is[i]){bfs(i);if(d[n] == INF) d[n] = -1;di(d[n]);}else {di(ans);}}return 0;
}
这篇关于【ATC】Blocked Roads 删边最短路的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!