Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
3 1 2 1 3
0
5 1 2 2 3 3 4 4 5
2
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: https://en.wikipedia.org/wiki/Bipartite_graph
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
题意:给你一个树,让你增加n条边,使得该树仍是二分图,n尽可能大
分析:二分图又称作二部图,是图论中的一种特殊模型。 设G=(V,E)是一个无向图,如果顶点V可分割为两个互不相交的子集(A,B),并且图中的每条边(i,j)所关联的两个顶点i和j分别属于这两个不同的顶点集(i in A,j in B),则称图G为一个二分图。
容易知道一个二分图,如果顶点确定,最多的边数=两个集合元素个数之积
从 第二组案例增加2条边,(1, 4) and (2, 5).,可以看出答案等于两个集合元素个数之积减去已有的(n-1)条边
AC代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn=1e5+10;
typedef long long ll;
vector<int> v[maxn];
int a[maxn],b[maxn];
int index[maxn];
ll num1=0,num2=0;
void dfs(int cur,int step)
{
index[cur]=step;
for(int i=0;i<v[cur].size();i++)
{
if(!index[v[cur][i]])
{
index[v[cur][i]]=1;
if(step%2==1) num1++;
else num2++;
dfs(v[cur][i],step+1);
}
}
}
int main()
{
int n;
while(cin>>n)
{
num1=num2=0;
memset(v,0,sizeof(v));
memset(index,0,sizeof(index));
for(int i=0;i<n-1;i++)
{
cin>>a[i]>>b[i];
v[a[i]].push_back(b[i]);
v[b[i]].push_back(a[i]);
}
num2=1;
index[a[0]]=1;
dfs(a[0],1);
ll ans=num1*num2-(n-1);
cout<<ans<<endl;
}
return 0;
}