Claire is too tired. Can you help her?
Each test case begins with two integers N and M(1≤N,M≤10 5), 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.
1 4 2 3 2 1 2 4 2 2 4
14
思路:
求所给图中的最长连,思路就是以任意的点为起点dfs找到离他最远的点,再以这个最短的点为起点找到的离他最远的点就是要找的点,在找的过程记录查找路径就可以了
如果所给的景点数小于最长路径,直接输出所给景点-1,否则输出最长路径-1+(所给景点-最长路径)*2
ac代码:
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <queue> const int maxn=1e5+5; using namespace std; vector<int> mp[maxn]; bool vis[maxn]; int phi[maxn]; int dfs(int t) { memset(vis,0,sizeof(vis)); memset(phi,0,sizeof(phi)); vis[t]=true; queue<int> p; int q; p.push(t); phi[t]=1; while(!p.empty()) { q=p.front(); p.pop(); for(int i=0;i<mp[q].size();i++) { if(!vis[mp[q][i]]) { p.push(mp[q][i]); vis[mp[q][i]]=true; phi[mp[q][i]]=phi[q]+1; } } } return q; } int main() { int n,a,b,x,y,z; cin>>n; while(n--) { memset(mp,0,sizeof(mp)); scanf("%d%d",&a,&b); for(int i=1;i<a;i++) { scanf("%d%d",&x,&y); mp[x].push_back(y); mp[y].push_back(x); } int g=dfs(1); int h=dfs(g); int s=phi[h]; for(int i=0;i<b;i++) { scanf("%d",&z); if(z<=s) printf("%d\n",z-1); else printf("%d\n",s-1+(z-s)*2); } } return 0; }