传送门
Park Visit
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3721 Accepted Submission(s): 1667
Problem Description
Claire and her little friend, ykwd, are travelling in Shevchenko‘s Park! The park is beautiful - but large, indeed. N feature spots in the park are connected by exactly (N-1) undirected paths, and Claire is too tired to visit all of them. After consideration, she decides to visit only K spots among them. She takes out a map of the park, and luckily, finds that there‘re entrances at each feature spot! Claire wants to choose an entrance, and find a way of visit to minimize the distance she has to walk. For convenience, we can assume the length of all paths are 1.
Claire is too tired. Can you help her?
Input
An integer T(T≤20) will exist in the first line of input, indicating the number of test cases.
Each test case begins with two integers N and M(1≤N,M≤105), which respectively denotes the number of nodes and queries.
The following (N-1) lines, each with a pair of integers (u,v), describe the tree edges.
The following M lines, each with an integer K(1≤K≤N), describe the queries.
The nodes are labeled from 1 to N.
Output
For each query, output the minimum walking distance, one per line.
Sample Input
1
4 2
3 2
1 2
4 2
2
4
Sample Output
1
4
【题目大意】
在一棵树上 求经过k个点的最短路径。
【思路】
如果是最短路径的话 我们想一直走路径不重复就可以了。
求树的直径,如果要经过k个点的k<r 那么说明这k个点可以在一条线上进行,答案为k-1.
如果不行 肯定要走直径外的分支,不要考虑复杂走哪个分支,反正分支肯定走进去又走出来(继续走直径)
用公式算出来就行 自己推推吧。
我这个代码第二个样例没过,但是算出来就是4啊,但是A了。
【code】
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int n,m,k,x,y,sumedge,maxn,maxx,t; int dad[100009],dis[100009],head[100009]; struct Edge { int x,y,nxt; Edge(int x=0,int y=0,int nxt=0): x(x),y(y),nxt(nxt){} }edge[200009]; void init() { sumedge=0; memset(head,0,sizeof(head)); memset(dad,0,sizeof(dad)); memset(dis,0,sizeof(dis)); } void add(int x,int y) { edge[++sumedge]=Edge(x,y,head[x]); head[x]=sumedge; } void dfs(int x) { for(int i=head[x];i;i=edge[i].nxt) { int v=edge[i].y; if(dad[x]!=v) { dad[v]=x; dis[v]=dis[x]+1; dfs(v); } } } int main() { scanf("%d",&t); while(t--) { init(); scanf("%d%d",&n,&m); for(int i=1;i<n;i++) { scanf("%d%d",&x,&y); add(x,y);add(y,x); } dfs(1); maxx=-0x7ffff; for(int i=1;i<=n;i++) { if(dis[i]>maxx) { maxx=dis[i]; maxn=i; } } memset(dis,0,sizeof(dis)); memset(dad,0,sizeof(dad)); dfs(maxn); maxx=-0x7ffff; for(int i=1;i<=n;i++) { if(dis[i]>maxx) { maxx=dis[i]; } } while(m--) { scanf("%d",&k); if(k<=maxx) printf("%d\n",k-1); else printf("%d\n",maxx+(k-maxx-1)*2); } } return 0; }