HDU - 4607 Park Visit 求一个图中的最长链

本文介绍了一种用于解决旅行者如何在多个景点中选择特定数量的景点并从任一入口开始旅行以最小化总行走距离的问题。通过两次深度优先搜索找到最长路径,进而计算出最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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≤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.
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

思路:

求所给图中的最长连,思路就是以任意的点为起点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; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值