Original title: https://www.facebook.com/hackercup/problems.php?pid=759650454070547&round=344496159068801
Test instructions: Given a root tree, the nodes in the lower layer of the tree to give the upper node gifts, the root node of the gift to the charity, but the gift of a condition is that you can not send your parent node has been sent gifts. Ask for the minimum cost of meeting the requirements.
Solution: This problem card for a period of time, similar to the problem of dyeing, can be solved with tree-shaped dynamic programming. Because the number of known nodes is N, the maximum cost of our individual nodes will not exceed log2 (n) = 18.
1. Set DP[I][J] is the total cost required for the I node to be the subtree of the root node when I spend J.
2. Then dp[i][j] = sum{min{dp[son][k],1 <= k <= 18 and K! = J},son for each child node of i};
At the start of the game, DFS was used, and it was not noticed that the node size would cause a stack of mobs when the tree was chained. But time is too late, unfortunately did not enter the Round 2.
The code is as follows:
#include <cstdio>#include <cstring>#include <algorithm>#include <vector>#include <queue>using namespace STD;#define MAXN 200005#define MAXM vector<vector<int> >SonsintNintMINCOST[MAXN][MAXM];structnode{intID;intDepthfriend BOOL operator< (node X,node y) {returnX.depth > y.depth; }}EMPLOYEE[MAXN];intBFS () { for(inti =1; I <= n;i++) {employee[i].id = i; } employee[1].depth =0;intNow,next;intSonsize; Queue<int>Q Q.push (1); while(!q.empty ()) {now = Q.front (); Q.pop (); Sonsize = Sons[now].size (); for(inti =0; i < sonsize;i++) {next = Sons[now][i]; Q.push (next); Employee[next].depth = employee[now].depth+1; } }}intDP () {intFa,son,sonsize;intI,j,k,m;intTmpmincost; BFS (); Sort (employee+1, employee+n+1); for(i =1; I <= n;i++) {fa = employee[i].id; Sonsize = Sons[fa].size (); for(j =1; J <= maxm;j++) {mincost[fa][j] = j; for(k =0K < sonsize;k++) {son = Sons[fa][k]; Tmpmincost = Int_max; for(intm =1; M <= maxm;m++) {if(m = = j)Continue; tmpmincost = min (tmpmincost,mincost[son][m]); } Mincost[fa][j] + = Tmpmincost; } } }intans = int_max; for(i =1; I <= maxm;i++) {ans = min (ans,mincost[1][i]); }returnAns;}intMain () {Freopen ("Corporate_gifting.txt","R", stdin); Freopen ("OUT.txt","W", stdout);intTintFascanf("%d", &t); for(inti =1; I <= t;i++) {scanf("%d", &n); vector<vector<int> >(). Swap (sons); Sons.resize (n+1); for(intj =1; J <= n;j++) {scanf("%d", &FA); Sons[fa].push_back (j); }printf("Case #%d;%d\n", I,DP ()); }return 0;}
Facebook Hacker Cup Round 1--corporate gifting (tree-shaped dynamic planning)