B. Mahmoud and Ehab and the bipartiteness
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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 .
Input
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
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
input
Copy
3 1 2 1 3
output
Copy
0
input
Copy
5 1 2 2 3 3 4 4 5
output
Copy
2
Note
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).
明确题意,一定不会有成环或者多条边的情况存在。求二项图中,除了已知边外,还可以有多少条边。
将所有的边压入vector v中,通过dfs去搜索边,并在搜索时,分辨二项图中两个分布的点。
可以用step,来表示搜索了多少边,将step %2 是否 == 0,来判断两个阵营中的点各有多少个。
void dfs (int x,int step){
for(int i=0;i<v[x].size();i++){
if(!vis[v[x][i]]){
if(step % 2 == 1)
num0++;
else
num1++;
vis[v[x][i]] = 1;
dfs(v[x][i],step+1);
}
}
}
最后将两个阵营个数相乘减去已给的边个数,即为最终答案。
总代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
vector<int> v[100005];
int vis[100005];
ll num0 ,num1;
void dfs (int x,int step){
for(int i=0;i<v[x].size();i++){
if(!vis[v[x][i]]){
if(step % 2 == 1)
num0++;
else
num1++;
vis[v[x][i]] = 1;
dfs(v[x][i],step+1);
}
}
}
int main(){
int n,u;
cin >> n;
for(int i=0;i<n-1;i++){
int a,b;
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
// for(int i=0;i<v[1].size();i++)
// cout << v[1][i] << endl;
num0 = 1,num1=0;
int step = 1;
vis[1] =1;
dfs(1,0);
// cout <<num0 << " " <<num1<<endl;
cout << num0 * num1 - n + 1<<endl;
}