## E. Egor in the Republic of Dagestan(DAG最短路+dp)详解

https://codeforces.com/contest/1407/problem/E

|------(1,0)------->4

b[x]:x点为黑色,到x点的最短路。

w[x]:x点为白色时,到x点的最短路。

x--->z的时候用b[x]+1和w[x]+1更小的那个更新b[z],w[z]；

b[y]=min(b[y],dp[x]+1);

w[y]=min(w[y],dp[x]+1);

dp[y]=max(w[y],b[y]);

dp[1]最后是否为无穷来判能否到1点。如果w[x]>=b[x]--->输出1，不然就0。

``````#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e5+100;
typedef long long LL;
LL w[maxn],b[maxn],dp[maxn],n,m;
struct P{
LL to,col;
};
vector<P>g[maxn];
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
cin>>n>>m;
for(LL i=1;i<=m;i++){
LL x,y,c;cin>>x>>y>>c;
g[y].push_back({x,c});
}
memset(w,0x3f,sizeof(w));
memset(b,0x3f,sizeof(b));
memset(dp,0x3f,sizeof(dp));
w[n]=b[n]=dp[n]=0;
queue<LL>q;
q.push(n);
while(!q.empty())
{
LL t=q.front();q.pop();
for(LL i=0;i<g[t].size();i++){
LL v=g[t][i].to;
LL c=g[t][i].col;
if(c==0)
{
if(b[v]<=n) continue;
b[v]=min(b[v],dp[t]+1);
if(max(b[v],w[v])<=n){
dp[v]=max(b[v],w[v]);
q.push(v);
}
}
else{
if(w[v]<=n) continue;
w[v]=min(w[v],dp[t]+1);
if(max(b[v],w[v])<=n){
dp[v]=max(b[v],w[v]);
q.push(v);
}
}
}
}
if(dp[1]>n)
{
cout<<"-1"<<endl;
for(LL i=1;i<=n;i++){
if(w[i]>=b[i]) cout<<1;
else cout<<0;
}
}
else{
cout<<dp[1]<<endl;
for(LL i=1;i<=n;i++)
{
if(w[i]>=b[i]) cout<<1;
else cout<<0;
}
cout<<endl;
}
return 0;
}

``````