Tree-shaped DP: Water
------------------------------------------------------------------------
#include <cstdio>#include <algorithm>#include <cstring>#include <iostream>#define REP (i, n) for (int i = 0; i < n; i++)#define CLR (x, C) memset (x, C, sizeof (x))#define REP (x) for (edge* E = head[x]; e; e = e = next)using namespace std;const int MAXN = 50000 + 5;struct Edge {int to;edge* Next;}; edge* pt, edge[MAXN << 1];edge* head[MAXN];void Edge_init () {pt = EDGE;CLR (head, 0);}void Add (int u, int v) {pt-to = V;pt-Next = head[u];head[U] = pt++;}#define Add_edge (U, v) Add (U, v), add (V, u)int d[MAXN [2];int DP (int x, int k, int fa) {int &ans = d[x [k];if (ans! =-1)return ans;ans = 0;if (k) {REP (x) if (e-to! = FA)ans + = DP (e-To, 0, X);ans++;} else {REP (x) if (e-to! = FA)ans + = max (DP (e-To, 1, x), DP (e-To, 0, X));}return ans;} int main () {freopen ("test.in", "R", stdin);int n;cin >> N;edge_init ();Rep (i, n-1) {int u, v;scanf ("%d%d", &u, &v);u--, v--;Add_edge (U, v); }CLR (d,-1);cout << Max (DP (0, 0,-1), DP (0, 1,-1)) << "\ n";return 0;}
------------------------------------------------------------------------
2060: [Usaco2010 nov]visiting cows visit cow time limit: 3 Sec Memory Limit: MB
Submit: 267 Solved: 198
[Submit] [Status] [Discuss] Description After weeks of hard work, Bessie finally ushered in a holiday. As the most sociable cow in the herd, she wants to visit N (1<=n<=50000) friends. These friends are labeled as 1. N. These cows have an unusual transport system with N-1 roads, each connecting a pair of cows numbered C1 and C2 (1 <= C1 <= N; 1 <= C2 <= N; C1<>C2). In this way, there is a unique pathway between each pair of cows. FJ hoped that Bessie would return to the farm as soon as possible. So he instructed Bessie to visit only one of the two cows that were directly connected to a road. Of course, Bessie wanted her vacation to be as long as possible, so she wanted to know the maximum number of cows she could visit. Input line 1th: A single integer n 2nd. N rows: Two integers per line representing a single integer of C1 and C2.output of a road, representing the maximum number of cows that Bessie can visit. Sample Input7
6 2
3 4
2 3
1 2
7 6
5 6
INPUT DETAILS:
Bessie knows 7 cows. Cows 6 and 2 is directly connected by a road,
As is cows 3 and 4, cows 2 and 3, etc. The illustration below depicts the
Roads that connect the cows:
1--2--3--4
|
5--6--7
Sample Output4
OUTPUT DETAILS:
Bessie can visit four cows. The best combinations include the cows
On the top row and both on the bottom. She can ' t visit Cow 6 since
That would preclude visiting cows 5 and 7; Thus she visits 5 and
7. She can also visit the cows on the top row: {1,3}, {1,4}, or
{2,4}.
HINT
Source
Gold
Bzoj 2060: [Usaco2010 nov]visiting cows visit Cow (DP)