Problem - E - CodeforcesCodeforces. Programming competitions and contests, programming communityhttps://codeforces.com/contest/1407/problem/E一道很有趣的最短路题,题意说明我们需要求没有最短路或如果必须有则求最长最短路。
我们先考虑正向建边,如果求最短路的话我们需要有两种可能以0去求和以1去求,到最后我们无法确定该城市用的是白天还是黑夜,所以我们需要反向建边,这样我们就能知道某一点最短路其点为0还是1。
所以我们设w[i]为该点为白天时的最短路,b[i]为i为黑夜时的最短路。
我们又可以思考到,只有点能被0和1都更新时才能保证连通,因为如果有一点不能被1更新说明他选择黑夜时这个点就废掉了。
然后又回到了求最长最短路的问题,所以在更新点的值的时候,需要考虑到用上一个点最大的最短路来更新该点最短路。
所以我们有递推公式为
w[v]=dp[t]+1;
b[v]=dp[t]+1;
dp[v]=max(w[v],b[v]);
然后就可以愉快的解决问题啦~
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
#include <bitset>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1e6 + 10;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
//using P = pair<int, int>;
int head[MAXN];
int nxt[MAXN];
int cnt;
int cost[MAXN];
int ver[MAXN];
void add(int x, int y, int c) {
ver[++cnt] = y;
cost[cnt] = c;
nxt[cnt] = head[x];
head[x] = cnt;
}
int b[MAXN];
int w[MAXN];
int dp[MAXN];
int main() {
int n, m;
scanf("%d %d", &n, &m);
int x, y, c;
for (int i = 1; i <= m; i++) {
scanf("%d %d %d", &x, &y, &c);
add(y, x, c);
}
memset(dp, 0x3f, sizeof(dp));
memset(b, 0x3f, sizeof(b));
memset(w, 0x3f, sizeof(w));
dp[n] = w[n] = b[n] = 0;
queue<int> que;
que.push(n);
while (!que.empty()) {
int t = que.front();
que.pop();
for (int i = head[t]; i; i = nxt[i]) {
int v = ver[i];
c = cost[i];
if (c == 0) {
if (b[v] <= n)
continue;
b[v] = dp[t] + 1;
if (max(w[v], b[v]) <= n) {
dp[v] = max(w[v], b[v]);
que.push(v);
}
} else {
if (w[v] <= n)
continue;
w[v] = dp[t] + 1;
if (max(w[v], b[v]) <= n) {
dp[v] = max(w[v], b[v]);
que.push(v);
}
}
}
}
if (dp[1] > n)
printf("-1\n");
else
printf("%d\n", dp[1]);
for (int i = 1; i <= n; i++) {
if (b[i] > w[i])
printf("0");
else
printf("1");
}
// putchar()'';
return 0;
}