Codeforces 346D :Robot Control

传送门

题解:
这道题好神啊。

首先如果原图是DAG,那么DP显然:

f i = min { min { f v + 1 } , max { f v } }

这是一个0/1最短路, 从小到大DP,维护队列0/1即可。

不过这道题是有环的,这样DP会出问题。
不过我们发现,成为min的是第一次更新一个点的时候,max是最后一次更新一个点的时候。我们在这两次都加入队列,最后取较小的那次就好了。 同样这样可以保证DP出来的方案合法。 具体细节可以看代码。

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

const int RLEN=1<<18|1;
inline char nc() {
    static char ibuf[RLEN],*ib,*ob;
    (ib==ob) && (ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
    return (ib==ob) ? -1 : *ib++;
}
inline int rd() {
    char ch=nc(); int i=0,f=1;
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=nc();}
    while(isdigit(ch)) {i=(i<<1)+(i<<3)+ch-'0'; ch=nc();}
    return i*f;
}

const int N=1e6+50;
int n,m,f[N],deg[N],vis[N];
deque <int> q;
vector <int> edge[N];
int main() {
    n=rd(), m=rd();
    for(int i=1;i<=m;i++) {
        int x=rd(), y=rd();
        edge[y].push_back(x);
        ++deg[x];
    }
    memset(f,-1,sizeof(f));
    int st=rd(), ed=rd();
    f[ed]=0; q.push_back(ed);
    while(!q.empty()) {
        int u=q.front(); q.pop_front();
        if(vis[u]) continue; vis[u]=1;
        if(u==st) break;
        for(auto v:edge[u]) {
            if(!--deg[v]) {
                if(f[u]<f[v] || f[v]==-1) {
                    f[v]=f[u]; q.push_front(v);
                }
            } else if(f[v]==-1) {
                f[v]=f[u]+1; q.push_back(v);
            }
        } 
    } cout<<f[st];
}

猜你喜欢

转载自blog.csdn.net/qq_35649707/article/details/80977814