首页 > 代码库 > POJ 2378 Tree Cutting (DFS)

POJ 2378 Tree Cutting (DFS)

题目链接:http://poj.org/problem?id=2378

一棵树,去掉一个点剩下的每棵子树节点数不超过n/2。问有哪些这样的点,并按照顺序输出。

dfs回溯即可。

 1 //#pragma comment(linker, "/STACK:102400000, 102400000") 2 #include <algorithm> 3 #include <iostream> 4 #include <cstdlib> 5 #include <cstring> 6 #include <cstdio> 7 #include <vector> 8 #include <cmath> 9 #include <ctime>10 #include <list>11 #include <set>12 #include <map>13 using namespace std;14 typedef long long LL;15 typedef pair <int, int> P;16 const int N = 1e4 + 5;17 vector <int> ans;18 struct Edge {19     int next, to;20 }edge[N << 1];21 int d[N], head[N], cnt, n;22 23 inline void add(int u, int v) {24     edge[cnt].next = head[u];25     edge[cnt].to = v;26     head[u] = cnt++;27 }28 29 void dfs(int u, int p) {30     bool ok = true;31     d[u] = 1;32     for(int i = head[u]; ~i; i = edge[i].next) {33         int v = edge[i].to;34         if(v == p)35             continue;36         dfs(v, u);37         if(d[v] * 2 > n)38             ok = false;39         d[u] += d[v];40     }41     if((n - d[u]) * 2 > n)42         ok = false;43     if(ok)44         ans.push_back(u);45 }46 47 int main()48 {49     while(~scanf("%d", &n)) {50         int u, v;51         memset(head, -1, sizeof(head));52         cnt = 0;53         ans.clear();54         for(int i = 1; i < n; ++i) {55             scanf("%d %d", &u, &v);56             add(u, v);57             add(v, u);58         }59         dfs(1, -1);60         sort(ans.begin(), ans.end());61         for(int i = 0; i < ans.size(); ++i) {62             printf("%d\n", ans[i]);63         }64     }65     return 0;66 }

 

POJ 2378 Tree Cutting (DFS)