cf #311 D. Vitaly and Cycle (二分圖染色)

題目:http://codeforces.com/contest/557/problem/D

題意:給定沒有自環,沒有重邊的無向圖。問最少添加幾條邊使得存在有奇數個節點的環。並且求出可行的方案數。

分析:

分情況討論:

①圖裏面沒有邊,都是點,那麼最少要加3條邊。然後然選3個點作爲環的頂點。

②圖中最長的鏈的長度爲1,那麼最少要加2條邊。以已知邊最爲環的一條邊,再在剩餘的頂點內選一個頂點。

③圖中存在鏈長大於1的鏈,且不存在奇數個節點的環,那麼最少添加1條邊。將每個連通分量進行染色,對於每一個連通分量,假設黑色頂點x個,白色頂點y個,那麼方案數就是C(x,2)+C(y,2)。

④圖中存在奇數個節點的環,那麼最少添加0條邊,有1種方案。

代碼:

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
const LL INF = 1E9+9;
const int maxn = 1e6+7;
int n,m;

struct node
{
	int v,next;
}List[maxn];
int head[maxn],cnt;
bool visit[maxn];
void add(int u,int v)
{
	List[cnt].v=v;
	List[cnt].next=head[u];
	head[u]=cnt++;
}
int cs[maxn];
bool hasOddCycle;

void dfs(int cur,int pre,int len)
{
	if(hasOddCycle)
		return ;
	visit[cur]=true;
	for(int i=head[cur];~i;i=List[i].next)
	{
		int to=List[i].v;
		if(to==pre)
			continue ;
		if(visit[to])
		{
			int num=cs[to]+1+len;
		//	cout<<"num:"<<num<<endl;
			if(num&1)
			{
				hasOddCycle=true;
				return ;
			}
			continue ;
		}
		cs[to]=len+1;
		dfs(to,cur,len+1);
	}
}

int c1,c0;
void color(int cur,int cur_color)
{
//	printf("cur: %d\n",cur);
	cur_color?c1++:c0++;
	visit[cur]=true;
	for(int i=head[cur];~i;i=List[i].next)
	{
		int to=List[i].v;
		if(!visit[to])
			color(to,!cur_color);
	}
} 

int d[maxn];
int main()
{
	int i,j,u,v;
	bool Chain=0;
	scanf("%d%d",&n,&m);
	cnt=0;
	memset(head,-1,sizeof(head));
	for(i=1;i<=m;i++)
	{
		scanf("%d%d",&u,&v);
		add(u,v);
		add(v,u);
		d[u]++;
		d[v]++;
		if(d[u]>1 || d[v]>1)
			Chain=true;
	}
	if(m==0)
	{
		printf("3 %lld\n",n*(n-1ll)*(n-2ll)/6ll);
		return 0;
	}
	if(!Chain)
	{
		printf("2 %lld\n",m*(n-2ll));
		return 0;
	}
	for(i=1;i<=n;i++) if(!visit[i])
		dfs(i,-1,0);
	if(hasOddCycle)
	{
		printf("0 1\n");
		return 0;
	}
	LL ans=0;
	memset(visit,0,sizeof(visit));
	for(int i=1;i<=n;i++) if(!visit[i]) 
	{
		c1=c0=0;
		color(i,1);
	//	printf("c1: %d  c0: %d\n",c1,c0);
		ans+=c1*(c1-1ll)/2ll+c0*(c0-1ll)/2ll;
	}
	printf("1 %lld\n",ans);
	return 0;
}


發佈了203 篇原創文章 · 獲贊 10 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章