CodeForces - 862B




http://codeforces.com/problemset/problem/862/B





题目大意:

给一棵树   问最多能添加多少条边   使其仍为二分图



分析:

最近很烦写dfs 很烦很烦      分成t1,t1两个图    最多能加的边数=t1*t2-(n-1)



AC代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int cnt;
int head[1000005];
int vis[1000005];
struct edge{
	int next;
	int to;
}edge[1000005];
void add(int u,int v){
	edge[cnt].to=v;
	edge[cnt].next=head[u];
	head[u]=cnt++;
}
void init(){
	cnt=0;
	memset(head,-1,sizeof(head));
	memset(vis,0,sizeof(vis));
}
LL t1=0,t2=0;
void dfs(int u,int step){
	if (step%2==0) t1++;
	else if (step%2) t2++;
	for (int i=head[u];i!=-1;i=edge[i].next){
		int v=edge[i].to;
		if (!vis[v]){
			vis[v]=1;
			dfs(v,step+1);	
		}
	} 
}
int main (){
	int n;
	while (scanf ("%d",&n)!=EOF){
		int u,v;
		init();
		int maxn=0;
		for (int i=0;i<n-1;i++){
			scanf ("%d%d",&u,&v);
			add(u,v);
			add(v,u);
			maxn=max(u,max(v,maxn));
		}
		t1=t2=0;
		for (int i=1;i<=maxn;i++){
			if (!vis[i]){
				vis[i]=1;
				dfs(i,0);
			}
		}
		printf ("%lld\n",t1*t2-n+1);
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值