[CSP-S Simulation Test]: beauty (search)

Title Description

From the United States.
$ $ N-tree comprising a number of points, there are 2K $ $ different critical points, we now need to match the two points, as for a form:
$$ (U_1, V_1), (U_2, V_2) , ..., (u_k, v_k) $$
pairing scheme, which we define beauty value:
$$ beauty = \ SUM \ limits_ {I}. 1 ^ K dist = (u_i, V_I) $$
(where $ dist (u, v) $ $ U $ point represents the number of edges to a simple path of $ $ V).
Now, you find out the value of the maximum beautiful beautiful value pairing scheme.


Input Format

The first line contains three integers $ n, k, a $ where $ A $ 1 to $ $ expressed special properties, $ a $ $ $ 0 means no special properties.
The second line contains $ $ 2K different integers $ u_1, u_2, ..., u_ {2k} $, showing key.
Next $ -1 $ lines contains two integers $ u, v $, it represents an edge.


Output Format

An output line, comprising a maximum integer value of $ $ Beauty.


Sample

Sample input:

7 2 0
1 5 6 2
1 3
3 2
4 5
3 7
4 3
4 6

Sample output:

6


Data range and tips

Sample explained:

Sample Explanation: $ (1,6), (2,5) $ pairing scheme beautiful this maximum value, is $ 6 (dist (1,6) + dist (2,5) = 3 + 3 = 6) $.

data range:

Special properties: degree of each point is less than $ 2 $ equal
for all data: $ 1 \ leqslant u_i, v_i \ leqslant n $ and $ 1 \ leqslant u, v \ leqslant n $.


answer

We use $ dp [u] $ $ u $ express went to the edge of this node at most how many, it went from $ u $ father's side is $ min (dp [u], 2k-size [u]) $ , where $ size [u] $ $ U $ denotes the number of keypoints subtree tree, in front of a $ $ min is the number of up to $ $ U provided, is behind a number of the received up to the outside both the smaller value is the $ to the number of their father the most from $ u, we need only look at the last count after several pieces of each side and can be.
Time complexity: $ \ Theta (n) $ .

Expectations score: $ 100 $ points.

Actual score: $ 100 $ points.


Code time

#include<bits/stdc++.h>
using namespace std;
struct rec{int nxt,to;}e[200000];
int head[100001],cnt;
int n,k,a;
int size[100001];
bool u[100001],vis[100001];
long long ans;
void add(int x,int y)
{
	e[++cnt].nxt=head[x];
	e[cnt].to=y;
	head[x]=cnt;
}
void dfs(int x)
{
	if(u[x])size[x]=1;
	vis[x]=1;
	for(int i=head[x];i;i=e[i].nxt)
		if(!vis[e[i].to])
		{
			dfs(e[i].to);
			size[x]+=size[e[i].to];
		}
	ans+=min(size[x],(k<<1)-size[x]);
}
int main()
{
	scanf("%d%d%d",&n,&k,&a);
	for(int i=1;i<=(k<<1);i++){int x;scanf("%d",&x);u[x]=1;}
	for(int i=1;i<n;i++){int x,y;scanf("%d%d",&x,&y);add(x,y);add(y,x);}
	dfs(1);printf("%d",ans);
	return 0;
}

rp++

Guess you like

Origin www.cnblogs.com/wzc521/p/11566658.html