知识兔

小w的铁路图「多校联考 2019」

29

题意

给定一张有向图,对于每一条边,求删去该边后两端点最短路长度。


思路

数据过水,直接bfs就过了。

代码

#include <bits/stdc++.h>

using namespace std;

namespace StandardIO {

    template<typename T>inline void read (T &x) {
        x=0;T f=1;char c=getchar();
        for (; c<'0'||c>'9'; c=getchar()) if (c=='-') f=-1;
        for (; c>='0'&&c<='9'; c=getchar()) x=x*10+c-'0';
        x*=f;
    }

    template<typename T>inline void write (T x) {
        if (x<0) putchar('-'),x*=-1;
        if (x>=10) write(x/10);
        putchar(x%10+'0');
    }

}

using namespace StandardIO;

namespace Project {
    
    const int N=1001;

    int n,m;
    int cnt;
    int head[N];
    struct node {
        int to,next;
    } edge[100001];
    int a[100001],b[100001];
    int vis[N],dis[N];
    queue<int> q;
    
    inline void add (int a,int b) {
        edge[++cnt].to=b,edge[cnt].next=head[a],head[a]=cnt;
    } 
    inline int bfs (int s,int t) {
        memset(vis,0,sizeof(vis));
        while (q.size()) q.pop();
        q.push(s),dis[s]=0,vis[s]=1;
        for (register int i=head[s]; i; i=edge[i].next) {
            int to=edge[i].to;
            if (to==t) continue;
            q.push(to),dis[to]=1,vis[to]=1;
        }
        q.pop();
        while (q.size()) {
            int now=q.front();q.pop();
            for (register int i=head[now]; i; i=edge[i].next) {
                int to=edge[i].to;
                if (vis[to]) continue;
                if (to==t) return dis[now]+1;
                dis[to]=dis[now]+1,vis[to]=1,q.push(to);
            }
        }
        return -1;
    }

    inline void MAIN () {
        read(n),read(m);
        for (register int i=1; i<=m; ++i) {
            read(a[i]),read(b[i]);
            add(a[i],b[i]);
        }
        for (register int i=1; i<=m; ++i) {
            write(bfs(a[i],b[i])),putchar(' ');
        }
    }
    
}

int main () {
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    Project::MAIN();
}
知识兔
计算机