HDU 3394 Railway(點雙連通分量的應用)

題意:給定一個無向圖,分別求出不在任何環中的邊的數量和同時在兩個或以上的環中的邊的數量。

解法:橋上的邊就是不在任何環中的。而如果一個點雙連通分量中邊的數量比點的數量要多,那麼該雙連通分量的所有邊都同時在兩個或以上的環中(這個可以想象一下,在一個簡單環中多加一條端點不同的邊,這樣簡單環就會被分割成兩個小的簡單環,任何一條在大的環中的邊都會同時處於一個其中一個小的環中)。

在tarjan算法中,當lowv>pre[u]時(u是起始點,v是邊的下一個點),邊(u,v)就是一條橋。而點雙連通分量的邊的數量可以通過棧的pop次數來統計。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<climits>
#include<queue>
#include<vector>
#include<stack>
#include<map>
#include<climits>
using namespace std;


const int maxn=10005;
struct Edge
{
	int u,v;
	Edge(int uu,int vv)
	:u(uu),v(vv){}
	Edge(){}
};
int pre[maxn],bccno[maxn],dfs_clock,bcc_cnt;
bool iscut[maxn];
std::vector<int> G[maxn],bcc[maxn];
int ans,ans1;
stack<Edge>s;

int dfs(int u,int fa)
{
	int lowu=pre[u]=++dfs_clock;
	int child=0;
	for(int i=0;i<G[u].size();i++)
	{
		int v=G[u][i];
		Edge e=Edge(u,v);
		if(!pre[v])
		{
			s.push(e);
			child++;
			int lowv=dfs(v,u);
			lowu=min(lowu,lowv);
			if(lowv>=pre[u])//條件必須是》=,如果只寫==,那麼橋的邊就不會被彈出棧,造成後面的雙連通分量的邊數計算錯誤
			{
				if(lowv>pre[u]) ans1++;//(u,v)是一條橋
				iscut[u]=true;
				bcc_cnt++;bcc[bcc_cnt].clear();
				int cnt=0;
				for(;;)
				{
					cnt++;
					Edge x=s.top();s.pop();
					if(bccno[x.u]!=bcc_cnt)
					{
						bcc[bcc_cnt].push_back(x.u);
						bccno[x.u]=bcc_cnt;
					}
					if(bccno[x.v]!=bcc_cnt)
					{
						bcc[bcc_cnt].push_back(x.v);
						bccno[x.v]=bcc_cnt;
					}
					if(x.u==u&&x.v==v) break;
				}
				if(cnt>bcc[bcc_cnt].size()) ans+=cnt;//當點雙連通分量中邊的數量大於點的數量
			}
		}
		else if(pre[v]<pre[u]&&v!=fa)
		{
			s.push(e);
			lowu=min(lowu,pre[v]);
		}
	}
	if(fa<0&&child==1) iscut[u]=false;
	return lowu;
}

void find_bcc(int n)
{
	memset(pre,0,sizeof(pre));
	memset(bccno,0,sizeof(bccno));
	memset(iscut,0,sizeof(iscut));
	dfs_clock=bcc_cnt=0;
	for(int i=0;i<n;i++)
	{
		if(!pre[i]) dfs(i,-1);
	}
}

int main()
{
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		if(n==0&&m==0) break;
		int a,b;
		for(int i=0;i<n;i++) G[i].clear();
		for(int i=0;i<m;i++)
		{
			scanf("%d%d",&a,&b);
			G[a].push_back(b);
			G[b].push_back(a);
		}
		ans=0,ans1=0;
		find_bcc(n);
		printf("%d %d\n",ans1,ans);
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章