Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6012 | Accepted: 2163 |
Description
Farmer John has decided to give each of his cows a cell phone in hopes to encourage their social interaction. This, however, requires him to set up cell phone towers on his N (1 ≤ N ≤ 10,000) pastures (conveniently numbered 1..N) so they can all communicate.
Exactly N-1 pairs of pastures are adjacent, and for any two pastures A and B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B) there is a sequence of adjacent pastures such that A is the first pasture in the sequence and B is the last. Farmer John can only place cell phone towers in the pastures, and each tower has enough range to provide service to the pasture it is on and all pastures adjacent to the pasture with the cell tower.
Help him determine the minimum number of towers he must install to provide cell phone service to each pasture.
Input
* Line 1: A single integer: N
* Lines 2..N: Each line specifies a pair of adjacent pastures with two space-separated integers: A and B
Output
* Line 1: A single integer indicating the minimum number of towers to install
Sample Input
5 1 3 5 2 4 3 3 5
Sample Output
2
Source
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAXN = 10005; struct Edge { int from, to, next; Edge() { } Edge(int u, int v) : from(u), to(v) { } }edges[MAXN << 1]; int first[MAXN], tots; int f[MAXN][3], n; void add(int a, int b) { edges[tots] = Edge(a, b); edges[tots].next = first[a]; first[a] = tots++; } void dfs(int x) { memset(f[x], 0, sizeof(f[x])); bool flag = true; int mint = 0x7fffffff; for (int i = first[x]; i != -1; i = edges[i].next) { Edge &e = edges[i]; if (f[e.to][0] == -1) { dfs(e.to); f[x][0] += min(f[e.to][0], min(f[e.to][1], f[e.to][2])); f[x][2] += min(f[e.to][0], f[e.to][1]); if (f[e.to][0] <= f[e.to][1]) { flag = false; f[x][1] += f[e.to][0]; } else { mint = min(mint, f[e.to][0] - f[e.to][1]); f[x][1] += f[e.to][1]; } } } if (flag) f[x][1] += mint; f[x][0]++; } int main() { scanf("%d", &n); tots = 0; memset(first, -1, sizeof(first)); for (int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } memset(f, -1, sizeof(f)); dfs(1); printf("%d\n", min(f[1][0], f[1][1])); return 0; }