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).
一直在纠结cycle和loop,想了半天才看到题面有说。其实就是个二分图,问你能加多少不产生自环和多重边的边。就染个色算出来两边各多少个结点,然后把没连上的点都连上就是了。
- #include <bits/stdc++.h>
- #include <cstring>
- using namespace std;
- vector <int>edge[100005];
- int vis[100005];
- int main()
- {
- int n;
- scanf("%d",&n);
- int a,b;
- for(int i=1;i<n;i++)
- {
- scanf("%d%d",&a,&b);
- edge[a].push_back(b);
- edge[b].push_back(a);
- }
- long long num=1;
- vis[1]=1;
- queue<int> que;
- que.push(1);
- while(!que.empty())
- {
- int now=que.front();
- que.pop();
- for(int i=0;i<edge[now].size();i++)
- {
- if(vis[edge[now][i]]==0)
- {
- que.push(edge[now][i]);
- if(vis[now]==1)
- vis[edge[now][i]]=2;
- else
- {
- vis[edge[now][i]]=1;
- num++;
- }
- }
- }
- }
- //cout<<num<<endl;
- long long ans=0;
- for(int i=1;i<=n;i++)
- {
- if(vis[i]==2)
- ans+=num-edge[i].size();
- else
- ans+=n-num-edge[i].size();
- }
- cout<<ans/2<<endl;
- return 0;
- }