Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town.
In Treeland there are 2k universities which are located in different towns.
Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done!
To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible.
Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1.
The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n / 2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n.
The second line contains 2k distinct integers u1, u2, ..., u2k (1 ≤ ui ≤ n) — indices of towns in which universities are located.
The next n - 1 line contains the description of roads. Each line contains the pair of integers xj and yj (1 ≤ xj, yj ≤ n), which means that thej-th road connects towns xj and yj. All of them are two-way roads. You can move from any town to any other using only these roads.
Print the maximum possible sum of distances in the division of universities into k pairs.
7 2
1 5 6 2
1 3
3 2
4 5
3 7
4 3
4 6
6
9 3
3 2 1 6 5 9
8 9
3 2
2 7
3 4
7 6
4 5
2 1
2 8
9
The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example.
题意:
给你一棵n个节点的树,然后给你2*k的节点,现在让你使者2*k个节点两两配对,这k对节点的路径和最长
题解:
这题可以求这2*k个点的重心,然后每个点到这个重心的路径和就是答案,也可以算每条边的贡献值,每条边的贡献值为边两端配对点最小的个数
我这里用的树的重心来求

1 #include<bits/stdc++.h> 2 #define F(i,a,b) for(int i=a;i<=b;++i) 3 using namespace std; 4 typedef long long ll; 5 6 const int N=2e5+7; 7 int n,k,a[N],g[N],v[N*2],nxt[N*2],ed,x,y,son[N],zhong,zmx=1<<29; 8 ll ans=0; 9 10 inline void adg(int x,int y){v[++ed]=y,nxt[ed]=g[x],g[x]=ed;} 11 12 void dfs(int x=1,int pre=1) 13 { 14 son[x]=a[x]; 15 int mx=0; 16 for(int i=g[x];i;i=nxt[i])if(v[i]!=pre) 17 dfs(v[i],x),son[x]+=son[v[i]],mx=max(mx,son[v[i]]); 18 mx=max(mx,2*k-son[x]+1); 19 if(zmx>mx)zhong=x,zmx=mx; 20 } 21 22 void find(int x=zhong,int pre=zhong,int dis=0) 23 { 24 if(a[x])ans+=dis; 25 for(int i=g[x];i;i=nxt[i])if(v[i]!=pre)find(v[i],x,dis+1); 26 } 27 28 int main() 29 { 30 scanf("%d%d",&n,&k); 31 F(i,1,k<<1)scanf("%d",&x),a[x]=1; 32 F(i,1,n-1)scanf("%d%d",&x,&y),adg(x,y),adg(y,x); 33 dfs(),find(),printf("%I64d ",ans); 34 return 0; 35 }