热爱互联网

poj 1655 Balancing Act

题目地址: http://poj.org/problem?id=1655
很水,和上一个题目一样,输出有些微区别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
const int inf=0x3fffffff,MM=20005;
int dp[MM],V[MM],cnt,min_balance,N;//dp[i]表示删除节点i的balance
bool visited[MM];
struct Edge{
       int p,next;
}adj[MM*2];
void add(int a,int b){
     adj[cnt].p=b;
     adj[cnt].next=V[a];
     V[a]=cnt++;
}
int dfs(int v){
    if(visited[v])
        return 0;
    visited[v]=true;
    int now,t=1,MAX=-inf;
    for(int i=V[v];i;i=adj[i].next){
        int w=adj[i].p;
        if(visited[w])
            continue;
        now=dfs(w);
        MAX=max(MAX,now); //求v的最大子树
        t+=now;
    }
    MAX=max(MAX,N-t);
    dp[v]=MAX;
    if(MAX<min_balance)
        min_balance=MAX;
    return t;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&N);
        cnt=1;
        min_balance=inf;
        memset(visited,false,sizeof(visited));
        memset(V,0,sizeof(V));
        int a,b;
        for(int i=1;i<n;i++){
            scanf("%d%d",&a,&b);
            add(a,b);
            add(b,a);
        }
        dfs(1);
        for(int i=1;i<=N;i++){
            if(dp[i]==min_balance){
                 printf("%d %dn",i,min_balance);
                 break;
            }
        }
   }
//system("pause");
return 0;
}

5 Comments

  • Posted 25/08/2016 at 09:33 | Permalink

    Admiring the time and effort you put into your website and in depth information you provide.
    It’s awesome to come across a blog every once in a while that isn’t
    the same old rehashed information. Great read!
    I’ve saved your site and I’m including your
    RSS feeds to my Google account.

  • Posted 17/10/2016 at 16:37 | Permalink

    Great post. I used to be checking continuously this weblog and I’m inspired!
    Extremely useful information specifically the remaining phase 🙂 I handle such information a lot.

    I was seeking this particular info for a very lengthy
    time. Thank you and good luck.

    • Posted 20/11/2016 at 10:01 | Permalink

      At last! Someone with the insight to solve the prlmeob!

    • Posted 27/04/2017 at 16:07 | Permalink

      Excellent post. Keep writing such kind of information on your
      page. Im really impressed by your site.
      Hello there, You have done a great job. I will certainly digg it and for my part recommend to my friends.
      I’m sure they will be benefited from this website.

Post a Comment

Your email is kept private. Required fields are marked *