POJ 1655 Balancing Act

樹形dp,水。 平衡值是去掉當前節點後剩下的樹中節點數最大的樹的節點數,求最小平衡值。多個答案任意輸出一組。把2378的代碼稍微改改就行了。。。

ps:雙向存邊時,邊數應至少爲節點的兩倍,否則會RE.

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
typedef long long LL;
#define INF 1000000007
#define N 200005
int n;
struct Node{
    int v;
    Node *next;
}e[N], *head[N];
int mv[N], sum[N];
int ptr = 0;
void init(){
    ptr = 0;
    for(int i = 0; i <= n; i++){
        head[i] = NULL;
        mv[i] = 0;
        sum[i] = 0;
    }
}
void adde(int x, int y){
    e[ptr].v = x;
    e[ptr].next = head[y];
    head[y] = &e[ptr ++];
    e[ptr].v = y;
    e[ptr].next = head[x];
    head[x] = &e[ptr ++];
}
int tdp(int x, int par){
    Node *p = head[x];
    while(p){
        if(p -> v != par){
            int vv = tdp(p -> v, x);
            sum[x] += vv;
            if(vv > mv[x])mv[x] = vv;
        }
        p = p -> next;
    }
    return sum[x] + 1;
}
int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        int x, y;
        init();
        for(int i = 1; i < n; i++){
            scanf("%d%d", &x, &y);
            adde(x, y);
        }
        tdp(1, 0);
        int maxv = INF;
        int id = 0;
        for(int i = 1; i <= n; i++){
            int xx = max((n - sum[i] - 1), mv[i]);
            if(maxv > xx){
                maxv = xx;
                id = i;
            }
        }
        printf("%d %d\n", id, maxv);
    }


    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章