题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6867
Problem Description
You are given a tree consisting of n vertices numbered 1 to n rooted at node 1. The parent of the i-th vertices is pi. You can move from a vertex to any of its children. What’s more, you can add one directed edge between any two different vertices, and you can move through this edge too. You need to maximize the number of pairs (x,y) such that x can move to y through the edges after adding the edge. Note that x can also move to x.
Input
The first line contains one integer T (1≤T≤100000) — the number of test cases.
The first line of each test case contains only one integer n(1≤n≤5×10^5) — the number of vertices in the tree.
The second line of each test case contains n−1 integers p2,p3,…,pn(1≤pi
The sum of n over all test cases does not exceed 106.
Output
Print T integers — for each test case output the maximum number of pairs (x,y) that vertices x can move to y after adding one edge.
Sample Input
2
5
1 1 2 2
6
1 2 3 1 3
Sample Output
17
26
翻译:
一个树有n个结点,编号从1到n。第一行输入一个n
p i p_i pi为第i个结点的父亲结点,接下来n-1个数: p 2 , p 3 , … , p n p2,p3,…,pn p2,p3,…,pn
一个结点能任意移动到它的孩子结点。
(x,y)表示从x能移动到y,在任意两个不同的结点之间添加一条边,使(x,y)二元组的数目最多,输出最大数量。(x,x)也是一个。
样例:
从叶子结点向根节点加一条边后:
分析:
从一个点出发可以到达他的所有子节点和他自己,添加一条边使得(x,y)(从x到y)最多,添加的这条边的终点最好的情况就是连一个子节点最多的点,也就是直接连到根节点。
对于同一条链上的点,将叶子结点连到根节点,比链上其他点连到根节点更优。
求出所有的叶子结点。然后依次连边,并选择最优情况
for(int i=1; i<n; i++)
{
int x;
scanf("%d",&x);
tree[x].push_back(i+1);///结点i+1的父亲为x
}
LL dfs(int root)
{
LL sum=1;//加上本身
for(int i=0; i<tree[root].size(); i++)
sum+=dfs(tree[root][i]);
son[root]=sum;
init_edge+=sum;//init_edge记录未加边之前有多少对二元组
return sum;
}
dfs(1);
void traverse(int step,int root)///step记录从某个结点到叶子结点的链上有几个结点
{
res+=son[root];
if(!tree[root].size())//遍历到叶子结点
{
LL k=(LL)n*step+init_edge-res;//这链上的step个结点都能到达所有的结点,init_edge-res为剩余的结点能到达的点的二元组
sum_edge=max(sum_edge,k);
res-=1;//减去叶子结点本身
return;
}
for(int i=0; i<tree[root].size(); i++)
traverse(step+1,tree[root][i]);
res-=son[root];
return;
}
traverse(1,1);
完整代码:
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
const int N=5*1e5+10;
LL son[N];
vector<int>tree[N];
LL sum_edge,init_edge;
LL res;
int n;
LL dfs(int root)
{
LL sum=1;
for(int i=0; i<tree[root].size(); i++)
sum+=dfs(tree[root][i]);
son[root]=sum;
init_edge+=sum;
return sum;
}
void traverse(int step,int root)
{
res+=son[root];
if(!tree[root].size())//遍历到叶子结点
{
LL k=(LL)n*step+init_edge-res;
sum_edge=max(sum_edge,k);
res-=1;
return;
}
for(int i=0; i<tree[root].size(); i++)
traverse(step+1,tree[root][i]);
res-=son[root];
return;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0; i<=n; i++)
{
tree[i].clear();
son[i]=0;
}
init_edge=0;
res=0;
for(int i=1; i<n; i++)
{
int x;
scanf("%d",&x);
tree[x].push_back(i+1);///结点i+1的父亲为x
}
dfs(1);
sum_edge=init_edge;
traverse(1,1);
printf("%lld\n",sum_edge);
}
return 0;
}