Codeforces Round #389 (Div. 2) 752F(樹的權值重心)

來源:互聯網
上載者:User

標籤:back   二分   using   empty   class   城市   ons   std   oid   

題目大意

給定2k個隊伍分別住在2k個城市裡,需要設定若干個城市,然後選取2個隊伍要在它們的最短路徑上設一個城市作為休息站

要求設立最少的休息站,然後輸出如何安排2個隊伍

 

首先若干個其實就是在坑人,實際上1個就可以了

這一個點就是樹的權值重心。

權值重心的定義:若選取權值重心為根,則它的任意子樹的權值和不會大於所有子樹權值和的二分之一

那麼接下來證明權值重心是可行的

只需要構造出來一組分組即可

我是這麼構造的

先搜每一個子樹,搜集齊k個點放到A,然後繼續搜集剩下的點放到B,如果權值重心上也有隊伍,那麼就把它加到B

然後依次輸出A[i],B[i]即可

這樣做是可行的,因為任意子樹的權值和不會大於所有子樹權值和的二分之一。(稍微想想就可以知道啦)

 

#include <iostream>#include <vector>#include <queue>using namespace std;const int maxn = 222222;vector<int> G[maxn];queue<int> Q[2];int f[maxn], v[maxn], sz[maxn], son[maxn];int n, k, x, y, X;void dfs(int x, int fa){    for(int i = 0; i < G[x].size(); i++)    {        int to = G[x][i];        if(fa == to) continue;        dfs(to, x);        sz[x] += sz[to];        son[x] = max(son[x], sz[to]);    }    son[x] = max(son[x], 2*k - sz[x]);}void dfs2(int x, int fa, int c){    if(!f[x] && Q[c-1].size() < k && v[x])    {        f[x] = c;        Q[c-1].push(x);    }    for(int i = 0; i < G[x].size(); i++)    {        int to = G[x][i];        if(fa == to) continue;        dfs2(to, x, c);    }}int main(){    cin>>n>>k;    for(int i = 1; i < n; i++)    {        cin>>x>>y;        G[x].push_back(y);        G[y].push_back(x);    }    for(int i = 1; i <= 2*k; i++) cin>>x, sz[x] = v[x] = 1;    dfs(1, 0);    for(int i = 1; i <= n; i++)        if(son[i] <= k) X = i;    cout<<1<<endl<<X<<endl;    for(int i = 0; i < G[X].size(); i++)    {        if(Q[0].size() < k)            dfs2(G[X][i], X, 1);        if(Q[0].size() == k)            dfs2(G[X][i], X, 2);    }    if(Q[1].size() == k-1) Q[1].push(X);    while(!Q[0].empty())    {        cout<<Q[0].front()<<" "<<Q[1].front()<<" "<<X<<endl;        Q[0].pop(); Q[1].pop();    }}

 

Codeforces Round #389 (Div. 2) 752F(樹的權值重心)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.