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
3
1 2
1 3
output
0
input
5
1 2
2 3
3 4
4 5
output
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).
问一颗树在确保是可以构成二分图的前提下,最多还可以连几条线,仍然是二分图。
先将二分图染色,分为两个集合,求出集合大小分别是s1,s2。最多连线个数为s1*s2,去掉已经连接的,
所以答案为s1*s2-n+1。s1,s2第一次用了int,wa了一次。
#include
#include
#include
#include
#define LL long long
using namespace std;
const int maxn=100005;
vector<int> graph[maxn];
int vis[maxn];
LL s1,s2;
void dfs(int u,int c)
{
vis[u]=1;
if(c==1)s1++;//将颜色置为1或-1
if(c==-1)s2++;
for(int i=0;iif(vis[graph[u][i]]==0)
{
vis[graph[u][i]]=1;
dfs(graph[u][i],-c);//因为给的是一个树,所以直接搜索相邻的点就可以遍历所有点了
}
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
memset(vis,0,sizeof(vis));
int u,v;
for(int i=0;i1;i++)
{
scanf("%d%d",&u,&v);
graph[u].push_back(v);
graph[v].push_back(u);
}
s1=0,s2=0;
dfs(1,1);
printf("%lld\n",s1*s2-n+1);
}
return 0;
}