More than 2019 cattle off summer school camp (fourth) A meeting (dfs or dp, dp to be updated)

Example 1:

Input:

4 2
1 2
3 1
3 4
2 4

Output: 2

Description:

They can meet at place 1 or 3.

Meaning of the questions : K points from the shortest time required for a point not connected graph, the shortest time is the time required for the K individual who last arrived.

Ideas :( I think that the official copy to the very good solution to a problem of understanding came here directly)

A topic Solution: Consider two key points farthest distance, provided their distance d, that is the answer rounded d / 2.

Necessity: the two men to meet, must walk at least d / 2 steps.

Sufficiency: we take two paths and a distance of rounding a point on d / 2, so that all in this together. If there is a person in the d / 2 time or not, and then it from two paths with one of its far larger than d, and assuming the farthest contradiction.

Find such a pair of points farthest find similar diameter trees . Direct dp, can also be used twice dfs:

Start from any key point, find the furthest away from its critical point x, then x from the start dfs, find the farthest point of the new formation and x is the diameter.

Of course, the question facing surface directly dp also can be done, but more difficult to write. (Not write dp, the need to enhance the capacity).

1, dfs Code:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int inf=0x3f3f3f3f,maxn=1e5+5;
 4 vector<int>a[maxn];
 5 int top,n,k,x,y,t,summ,book[maxn];
 6 void dfs(int p,int q,int step)//p为当前节点,q记录父节点,step记录已走步数
 7 {
 8     if(book[p]&&step>summ)//当当前步数大于已标记最大步数和该点上有人时更新最大步数和标记最远端点,以便做第二次寻找最长路的起点
 9         summ=step,top=p;
10     for(int i=0; i<a[p].size(); i++)
11     {
12         if(a[p][i]!=q)
13             dfs(a[p][i],p,step+1);
14     }
15 }
16 int main()
17 {
18     scanf("%d%d",&n,&k);
19     for(int i=1; i<n; i++)
20     {
21         scanf("%d%d",&x,&y);
22         a[x].push_back(y),a[y].push_back(x);
23     }
24     for(int i=0; i<k; i++)
25     {
26         scanf("%d",&t);
27         book[t]=1;//book数组标记某个点有人
28     }
29     dfs(t,0,1);
30     dfs(top,0,1);
31     printf("%d\n",summ/2);
32     return 0;
33 }

2、dp代码(以后更新)

Guess you like

Origin www.cnblogs.com/Aamir-Dan/p/11263080.html