1. 程式人生 > 其它 >#邊雙縮點,並查集#洛谷 2416 泡芙

#邊雙縮點,並查集#洛谷 2416 泡芙

邊雙縮點,並查集

題目

給出一張 \(n\) 個點,\(m\) 條邊的無向圖,邊權為0或1,
問是否存在一條每條邊最多經過一次的路徑中至少有一條邊的邊權為1,
多組資料給出起點和終點


分析

考慮在一個邊雙中只要有邊權為1的邊,那麼這個邊雙就是合法的,
那麼跑一遍Tarjan之後,給邊雙縮點,
不存在當且僅當起點和終點所在邊雙不合法且路徑上(橋)邊權全為0,
那麼將橋邊權為0的用並查集縮成連通塊,如果連通那麼邊權全為0


程式碼

#include <cstdio>
#include <cctype>
#define rr register
using namespace std;
const int N=300011; struct node{int y,w,next;}e[N<<1];
int dfn[N],low[N],f[N],bridge[N<<1],et=1,n,w[N],tot,as[N],col[N],cnt;
inline signed iut(){
	rr int ans=0; rr char c=getchar();
	while (!isdigit(c)) c=getchar();
	while (isdigit(c)) ans=(ans<<3)+(ans<<1)+(c^48),c=getchar();
	return ans;
}
inline signed min(int x,int y){return x<y?x:y;}
inline signed getf(int u){return f[u]==u?u:f[u]=getf(f[u]);}
inline void tarjan(int x,int F){
	dfn[x]=low[x]=++tot;
	for (rr int i=as[x];i;i=e[i].next)
	if (!dfn[e[i].y]){
		tarjan(e[i].y,i^1),low[x]=min(low[x],low[e[i].y]);
		if (dfn[x]<low[e[i].y]) bridge[i]=bridge[i^1]=1;
	}else if (i!=F) low[x]=min(low[x],dfn[e[i].y]);
}
inline void dfs(int x){
	col[x]=cnt;
	for (rr int i=as[x];i;i=e[i].next)
	    if (!col[e[i].y]&&!bridge[i]) dfs(e[i].y);
}
inline void Merge(int x,int y){
	rr int fa=getf(x),fb=getf(y);
	if (fa==fb) return; f[fa]=fb;
} 
signed main(){
	n=iut();
	for (rr int m=iut();m;--m){
		rr int x=iut(),y=iut(),w=iut();
		e[++et]=(node){y,w,as[x]},as[x]=et;
		e[++et]=(node){x,w,as[y]},as[y]=et;
	}
    tarjan(1,0);
    for (rr int i=1;i<=n;++i)
	    if (!col[i]) ++cnt,dfs(i);
	for (rr int i=1;i<=cnt;++i) f[i]=i;
    for (rr int i=2;i<=et;i+=2)
	if (col[e[i^1].y]==col[e[i].y]) w[col[e[i].y]]+=e[i].w;
	    else if (!e[i].w) Merge(col[e[i^1].y],col[e[i].y]);
	for (rr int Q=iut();Q;--Q){
		rr int x=col[iut()],y=col[iut()];
		if (w[x]||w[y]) puts("YES");
		else if (getf(x)==getf(y)) puts("NO");
		    else puts("YES");
	}
	return 0;
}