hdu-4607-Park Visit

來源:互聯網
上載者:User

Park Visit

題目串連:Click here~~~~

Problem DescriptionClaire 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? 解析:類似於找一個最長的樹根,即

*__*__*__*__*__*__*__*__*__
          |         |    |    |
          *        *    *    *
          |         |
          *        * 

其次就是找最長的樹根時,要兩次遍曆:

1. 第一次遍以任意一個點A出發,找到距離最遠的那個點B。

 2. 再從B出發,找到距離B最遠的那個點C,則BC線段長度即為樹根長。

 證明:首先,B 一定是直徑的一端。

     a) 如果 A 是直徑的一端,那麼 B 顯然是直徑的另一端,結論成立。

     b) 如果 A 不是直徑的一端,那麼路徑(A->B)一定與直徑交於一點 p,且(p->B)一定是直徑的一部分,推出 B 是直徑的一端,結論成立。

      1> 為什麼一定存在交點 p?

          如果不存在交點 p ,由於樹是連通的,那麼加若干邊使得直徑經過(A->B)上的一點 p,直徑不會變得更短。

      2>為什麼(p->B)一定是直徑的一部分。

          如果不是,(A->B)就不是從 A 到 B 最長的路徑。

然後大家就明白了,設樹根長為L,假如要參觀的景點N<=L,則輸出 N-1 ,否則,輸出 L - 1 + 2 * ( N - L )。  
具體代碼如下:

#include<stdio.h>#include<string.h>#include<vector>#include<queue>using namespace std;int s[100005];int main(){    int N,m,n,a,b,i,l;    scanf("%d",&N);    while(N--)    {        scanf("%d%d",&m,&n);        vector<int> Q[100005];        queue<int> q;        memset(s,0,sizeof(s));        for(i=0;i<m-1;i++)        {            scanf("%d%d",&a,&b);            Q[a].push_back(b);            Q[b].push_back(a);        }        q.push(1);s[1]=1;        while(!q.empty())        {            a=q.front();            for(i=0;i<Q[a].size();i++)            {                if(!s[Q[a][i]])  q.push(Q[a][i]);            }            s[a]=1;q.pop();        }        q.push(a);memset(s,0,sizeof(s));s[a]=1;        while(!q.empty())        {            a=q.front();            for(i=0;i<Q[a].size();i++)            {                if(!s[Q[a][i]])  {q.push(Q[a][i]);s[Q[a][i]]=s[a]+1;}            }            q.pop();        }        l=s[a];        while(n--)        {            scanf("%d",&a);            if(a<=l) printf("%d\n",a-1);            else     printf("%d\n",l-1+2*(a-l));        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.