Codeforces Round #435 (Div. 2), problem: (B) Mahmoud and Ehab and the bipartiteness
题意:给你一个树形的二分图,问最多可以添加多少条边让其始终为二分图。
题解:利用二分图的染色判断出两个集合中各有多少个数,总的边数应该为两个集合顶点数乘积,所以输出乘积减n-1就可以了。
PS:注意要用long long,因为这个比赛的时候WA了无数发。。。
代码:
# include<iostream>
# include<vector>
#include<cstdio>
using namespace std;
const int MAX_V = 110000;
long long V,tot=0,cnt=0;
vector<int> G[MAX_V];//新建了一个图,G数组中的每一个元素都是一个顶点,对应着一个vector,其中包含了它指向的顶点。
int color[MAX_V],flag[MAX_V];//记录顶点的颜色(只有两种,1或-1)
void dfs(int v,int c)
{
color[v] = c;
flag[v]=1;//将顶点v染成颜色c
for (int i = 0; i < G[v].size(); i++)
{
if (color[G[v][i]] == 0&&flag[G[v][i]]==0 )
dfs(G[v][i], -c);
}
return;
}
int main()
{
scanf("%lld",&V);
for (int i = 0; i < V-1; i++)
{
int s, t;
scanf("%d%d",&s,&t);
G[s].push_back(t);//从s向t连边
G[t].push_back(s);//因为是无向图反过来再连接一次
}
dfs(1,1);
for(int i=1;i<=V;i++){
if(color[i]==1) tot++;
else cnt++;
}
long long ans;
ans=tot*cnt-V+1;
printf("%lld\n",ans);
return 0;
}

浙公网安备 33010602011771号