HDU 4607 Park Visit

http://acm.hdu.edu.cn/showproblem.php?pid=4607

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define ll long long
#include<vector>
#include<algorithm>
#define N 100033
#define prt(k) cout<<#k"="<<k<<endl;
vector<int> g[N];
int n;
//int dist[N];
vector<int> dist;
int pre[N];
int vis[N];
int res[N];
void dfs(int p,int u,int d)
{
    dist[u]=d; pre[u]=p;
    for(int i=0;i<g[u].size();i++)
    {
        int v=g[u][i];
        if(v!=p)
            dfs(u,v,d+1);
    }
}
int root, r2;
vector<int> dd;
#include<queue>
bool inq[N];
void spfa(int src)
{
    queue<int> q;
    memset(inq,0,sizeof inq );
    inq[src]=1;
    for(int i=0;i<n;i++) dist[i]=1e9;
    dist[src]=0;
    q.push(src);
    while(!q.empty())
    {
        int u=q.front();  q.pop();
        for(int i=0;i<g[u].size();i++)
        {
            int v=g[u][i];
            if(dist[v]>dist[u]+1)
            {
                dist[v]=dist[u]+1;
                if(!inq[v])
                {
                    inq[v]=1;
                    q.push(v);
                }
            }
        }
        inq[u]=0;
    }
}
int getd()
{
    dist.resize(n+2);
    //dfs(-1,0,0);
    spfa(0);
    int u=max_element(dist.begin(),dist.end())-dist.begin();
    memset(pre,0,sizeof pre);
   // for(int i=0;i<n;i++)prt(dist[i])
    //dfs(-1,u,0);
    spfa(u);
    root=u;
    r2=max_element(dist.begin(),dist.end())-dist.begin();
    dd.clear();
    return *max_element(dist.begin(),dist.end());
}
int main()
{
    int m; int re; cin>>re;
    while(re--)
    {
        cin>>n>>m;
        for(int i=0;i<n;i++)g[i].clear();
        for(int i=1;i<n;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);    u--,v--;
            g[u].push_back(v);
            g[v].push_back(u);
        }
        int d=getd();
        res[0]=0;
        //for(int i=1;i<=d+1;i++) res[i]=i-1;
        while(m--)
        {
            int q; scanf("%d",&q);
            if(q-1<=d)
            {
                printf("%d\n",q-1);     //cout<<q-1<<endl;
                continue;
            }
            else {
                int ans=d+(q-d-1)*2;    ///每多去一个未去的点多走2步
                printf("%d\n",ans);
            }
        }
    }
}


你可能感兴趣的:(HDU 4607 Park Visit)