齐头并进

齐头并进

一张 \(n\)\(m\) 边的无向图,一个人在这张图上走最短路,另一个人在补图上走,要求二人中途不能同时在一个点(除起点、终点)。问两人最短路的较大值。

\(2\le n\le 400,0\le m\le n(n-1)/2\)

考虑到如果原图没有边 \((1,n)\),那么补图一定有;反之亦然。

所以一个人肯定是一步登天的,肯定不会和另一人有交集。

那么在原图/补图上跑最短路即可。

#include<cstdio>
using namespace std;
#define Ed for(int i=h[x];~i;i=ne[i])
#define Ls(i,l,r) for(int i=l;i<r;++i)
#define Rs(i,l,r) for(int i=l;i>r;--i)
#define Le(i,l,r) for(int i=l;i<=r;++i)
#define Re(i,l,r) for(int i=l;i>=r;--i)
#define L(i,l) for(int i=0;i<l;++i)
#define E(i,l) for(int i=1;i<=l;++i)
#define W(t) while(t--)
#define Wh while

const int N=410;
int n,m,g[N][N],q[N],st[N];
int main(){
    #ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
    #endif
    scanf("%d%d",&n,&m);
    E(i, m){
        int a,b;
        scanf("%d%d",&a,&b);
        g[b][a]=g[a][b]=1;
    }
    if(g[1][n])
        E(i, n)
            E(j, n)g[i][j]^=1;
    int hh=0,tt=0;
    q[tt++]=1;
    st[1]=1;
    Wh(hh!=tt){
        int x=q[hh++];
        if(x==n)return printf("%d",st[x]-1),0;
        E(i, n)
            if(g[x][i]&&!st[i]){
                st[i]=st[x]+1;
                q[tt++]=i;
            }
    }
    puts("-1");
    return 0;
}
posted @ 2023-08-29 17:01  wscqwq  阅读(4)  评论(0编辑  收藏  举报