题解:AT_abc375_g [ABC375G] Road Blocked 2

· · 题解

English version is at the end of the text.

先 Dijkstra 跑出 1 到点 i 的最短路 dis_i 和 n 到点 i 的距离 dis'_i。

考虑一条边 (u,v,w) 在 1\rightarrow n 的最短路上当且仅当 dis_u+dis'_v+w=dis_n 或 dis_v+dis'_u+w=dis_n。将满足条件的边加入新图。原题就是求每条边是否是新图上的割边,跑 Tarjan 即可。

#include<iostream>
#include<algorithm>
#include<queue>
using ll=long long;
using piit=std::pair<ll,int>;
const int sz=2e5+10;
const ll inf=0x3fffffffffffffff;
struct edge{
    int nxt,to;
    ll w;
}graph[sz<<1];
int head[sz],hpp;
void addEdge(int from,int to,int w){
    graph[++hpp]=edge{head[from],to,w};
    head[from]=hpp;
}
ll dis[2][sz],n,m;
int u[sz],v[sz],w[sz];
bool vis[sz];
std::priority_queue<piit,std::vector<piit>,std::greater<piit>>pq;
void dijkstra(int s,ll *dis){
    std::fill(dis+1,dis+n+1,inf);
    std::fill(vis+1,vis+n+1,0);
    dis[s]=0,pq.push(std::make_pair(dis[s],s));
    while(!pq.empty()){
        int u=pq.top().second;
        pq.pop();
        if(vis[u])continue;
        vis[u]=true;
        for(int p=head[u];p;p=graph[p].nxt){
            int v=graph[p].to;
            if(dis[v]>dis[u]+graph[p].w){
                dis[v]=dis[u]+graph[p].w;
                pq.push(std::make_pair(dis[v],v));
            }
        }
    }
}
int dfn[sz],low[sz],dpp,id[sz];
bool bridge[sz<<1];
void tarjan(int u,int pid){
    dfn[u]=low[u]=++dpp;
    for(int p=head[u];p;p=graph[p].nxt){
        int v=graph[p].to;
        if(dfn[v]==0){
            tarjan(v,p),low[u]=std::min(low[u],low[v]);
            if(low[v]>dfn[u])bridge[p]=bridge[p^1]=true;
        }else if(p!=(pid^1))low[u]=std::min(low[u],dfn[v]);
    }
}
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cin>>n>>m;
    for(int i=1;i<=m;i++)
        std::cin>>u[i]>>v[i]>>w[i],addEdge(u[i],v[i],w[i]),addEdge(v[i],u[i],w[i]);
    dijkstra(1,dis[0]),dijkstra(n,dis[1]);
    std::fill(head+1,head+n+1,0),hpp=1;
    for(int i=1;i<=m;i++){
        if(dis[0][u[i]]+dis[1][v[i]]+w[i]!=dis[0][n]&&dis[0][v[i]]+dis[1][u[i]]+w[i]!=dis[0][n])continue;
        vis[i]=true,addEdge(u[i],v[i],w[i]),addEdge(v[i],u[i],w[i]),id[i]=hpp;
    }
    for(int i=1;i<=n;i++)
        if(dfn[i]==0)dpp=0,tarjan(i,0);
    for(int i=1;i<=m;i++){
        if(id[i]==0)std::cout<<"No\n";
        else std::cout<<(bridge[id[i]]?"Yes\n":"No\n");
    }
    return 0;
}

First of all, we use Dijkstra algorithm to find the shortest path from vertex 1 to vertex i, which is called dis_i, and the shortest path from vertex n to vertex i, which is called dis'_i.

Consider if an edge (u,v,w) is on the shortest path from 1 to n, there must exist dis_u+dis'_v+w=dis_n or dis_v+dis'_u+w=dis_n. We add all the edges satisfy this into a new graph. You need to find whether an edge is a bridge in the new graph. That will be easy by using Tarjan algorithm.