Park Visit HDU - 4607 树的直径 链试前向星 寒假集训

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-ans-1)*2

这道题树的直径好像不能把每个点用数组去存,会MLE,只能存个最大的直径

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdio>
#define ls (p<<1)
#define rs (p<<1|1)
//#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
bool father[maxn];
int dp[maxn],a[maxn];
struct edge{
    int ver,nex;
}e[maxn];
int head[maxn],tot,ans;
void addedge(int u,int v){
    e[++tot].ver=v;
    e[tot].nex=head[u];
    head[u]=tot;
}
void dfs(int u,int fa){
    for(int i=head[u];i;i=e[i].nex){
        int v=e[i].ver;
        if(v==fa) continue;
        dfs(v,u);
        ans=max(ans,dp[u]+dp[v]+1);
        dp[u]=max(dp[u],dp[v]+1);
    }
}
void solve(){
    int t;
    cin>>t;
    while(t--){
        memset(head,0,sizeof(head));
        memset(dp,0,sizeof(dp));
        tot=0;
        int m,n;
        cin>>m>>n;
        for(int i=1;i<m;i++){
            int a,b;
            cin>>a>>b;
            addedge(a,b);
            addedge(b,a);
        }
        ans=0;
        dfs(1,1);
        for(int i=1;i<=n;i++){
            int k; 
            cin>>k;
            if(k<=ans+1)
                cout<<k-1<<endl;
            else
                cout<<ans+(k-ans-1)*2<<endl;
        }
    }
}
int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值