POJ 1947 -- Rebuilding Roads


1947 -- Rebuilding Roads
The cows have reconstructed Farmer John's farm, with its N barns (1 <= N <= 150, number 1..N) after the terrible earthquake last May. The cows didn't have time to rebuild any extra roads, so now there is exactly one way to get from any given barn to any other barn. Thus, the farm transportation system can be represented as a tree.

Farmer John wants to know how much damage another earthquake could do. He wants to know the minimum number of roads whose destruction would isolate a subtree of exactly P (1 <= P <= N) barns from the rest of the barns.
Input
* Line 1: Two integers, N and P

* Lines 2..N: N-1 lines, each with two integers I and J. Node I is node J's parent in the tree of roads.
Output
A single line containing the integer that is the minimum number of roads that need to be destroyed for a subtree of P nodes to be isolated.
Sample Input
11 6
1 2
1 3
1 4
1 5
2 6
2 7
2 8
4 9
4 10
4 11
Sample Output
2
Hint
[A subtree with nodes (1, 2, 3, 6, 7, 8) will become isolated if roads 1-4 and 1-5 are destroyed.]
http://www.gonglin91.com/poj-1947-rebuilding-roads/
由于我们不知道最后得到的是哪个子树,所有可以全部求出来,最后枚举每个点,以该点作为根的子树下有p个节点的切割次数是多少
定义:dp[u][m]:表示以u为根的子树下有m个节点的最小切割次数,注意这里,u和它的父亲fa的连边是没有切断的,但是我们并不考虑它的fa分支,只看u这个子树,所以最后要使的u这个子树完全独立出来,还要切割多一次,切断u和fa的连线
最终的答案是
ans = dp[1][p];以1为根的子树下有p个节点的最少切割次数,由于1没有fa,所以不用加1
ans = min{ dp[u][p] } + 1 ; 以其他点为根的子树下有p个节点的最少切割次数,但是其他节点u都有fa,所以还要切掉u和fa的边
dp的转移:我们先来考虑这个问题。u为根的子树有m个节点,u有儿子v1,v2,v3,…….假设v1子树有k1个节点,v2子树有k2的节点,v3子树有k3个节点………….这其实就是一个组合起来的结果
dp[u][m] = dp[v1][k1] + dp[v2][k2] + dp[v3][k3] + dp[v4][k4]………………….
但每个子树下面保留多少个节点,是不确定的,可以1个,0个,多个。这其实就转化为了背包
总容量为m,每个子树下应该选进去多少个点ki,使得不超过容量m,价值最小
转移方程为
dp[u][j] = min(dp[u][j],dp[u][j-k] + dp[v][k] – 1);
有时候写dp[u][j]会不好理解,实际上是dp[u][c][j]的,只不过和背包一样,进行了空间的优化,降维
dp[u][c][j]表示以u为根的子树,在考虑第前c个儿子子树后,包含了j个节点的最少切割次数,这和dp[u][j]是一样的
dp[u][1] = son; 以u为根的子树只保留一个节点u,那么说明其儿子都切断了,有多少个儿子子树只需要切多少刀,因而切son次
关于转移方程 dp[u][j] = min(dp[u][j],dp[u][j-k] + dp[v][k] – 1);
dp[u][j-k] + dp[v][k] – 1 , dp[u][j-k]表示前c个儿子一共贡献了j-k个节点给u这个子树,dp[v][k]表示第c+1个儿子贡献了k个节点给u,为何要减1,因为对于u而言,相当于v子树拼接到u上次,要抵消掉之前切去的那条u—v的边.
int dp[N][N];
 
void dfs(int u,int fa){
 int son = 0;
 for(int i = 0; i < e[u].size(); i++){
  int v = e[u][i];
  if(v == fa) continue;
  dfs(v,u);
  son++;
 }
 dp[u][1] = son;
 for(int i = 0; i < e[u].size(); i++){
  int v = e[u][i];
  if(v == fa) continue;
  for(int j = p; j >= 2; j--)
   for(int k = 1; k < j; k++)
    if(dp[u][j-k] != INF && dp[v][k] != INF){
     dp[u][j] = min(dp[u][j],dp[u][j-k] + dp[v][k] - 1);
    }
 }
}
 
int main(){
 while(scanf("%d%d",&n,&p)!=EOF){
  for(int i = 1; i <= n; i++)
   e[i].clear();
  for(int i = 1; i < n; i++){
   int u,v;
   scanf("%d%d",&u,&v);
   e[u].pb(v); e[v].pb(u);
  }
  cl(dp,0x3f);
  dfs(1,-1);
  int ans = INF;
  for(int i = 1; i <= n; i++){
   if(i == 1) ans = min(ans,dp[i][p]);
   else ans = min(ans,dp[i][p]+1);
  }
  printf("%d\n",ans);
 }
 return 0;
}
一颗含有n个结点的树,求减去最少的边使得该树只含有p个结点
题目分析:典型的树形dp,在树上进行动态规划,设dp[s][i]表示以s为根的子树含有i个结点需要删去的边数,则得到转移方程:
对于i的子树k:
1.不加子树k,dp[s][i] = dp[s][i] + 1 (不加子树k,相当于删去一条边)
2.加子树k,dp[s][i] = min(dp[s][j] + dp[k][i - j])  (1<= j <= i)   (以s为根的树的结点数加上其子树的结点数等于i)
最后答案就是在dp[i][m]中取小,要注意的一点是,如果i不是根,值还需要+1,因为要脱离原来的根,还要去掉一条边
这里需要注意,dp过程是自下而上的,也就是从叶子到根,而不是从根到叶子
  1. struct Edge  
  2. {  
  3.     int to, next;  
  4. }e[MAX * MAX / 2];  
  5.   
  6. int n, m;  
  7. int head[MAX], cnt, root;  
  8. int fa[MAX], dp[MAX][MAX];  
  9.   
  10. void Add(int x, int y)  //加边  
  11. {  
  12.     e[cnt].to = y;  
  13.     e[cnt].next = head[x];  
  14.     head[x] = cnt++;  
  15. }  
  16.   
  17. void DFS(int u)  
  18. {  
  19.     for(int i = 0; i <= m; i++) //初始化为无穷大  
  20.         dp[u][i] = INF;                 
  21.     dp[u][1] = 0;               //根结点本就一个点,不需要减边  
  22.     for(int i = head[u]; i != -1; i = e[i].next)  //同层  
  23.     {  
  24.         int v = e[i].to;    //u的子树  
  25.         DFS(v);  
  26.         for(int j = m; j >= 1; j--)   
  27.         {  
  28.             for(int k = 0; k < j; k++)  
  29.             {  
  30.                 if(k)   //不加子树k  
  31.                     dp[u][j] = min(dp[u][j], dp[u][j - k] + dp[v][k]);  
  32.                 else    //加上子树k  
  33.                     dp[u][j] = dp[u][j] + 1;  
  34.             }  
  35.         }  
  36.     }  
  37. }  
  38.   
  39. int main()  
  40. {  
  41.     scanf("%d %d", &n, &m);  
  42.     cnt = 0;  
  43.     memset(fa, -1, sizeof(fa));  
  44.     memset(head, -1, sizeof(head));  
  45.     for(int i = 1; i < n; i++)  
  46.     {  
  47.         int x, y;  
  48.         scanf("%d %d", &x, &y);  
  49.         Add(x, y);  
  50.         fa[y] = x;  
  51.     }  
  52.     for(root = 1; fa[root] != -1; root = fa[root]);  
  53.     DFS(root);  
  54.     int ans = dp[root][m];  
  55.     for(int i = 1; i <= n; i++)     //除了根节点,其他节点要想成为独立的根,必先与父节点断绝关系,所以要先加1  
  56.         ans = min(ans, dp[i][m] + 1);  
  57.     printf("%d\n",ans);      
  58. }  
http://blog.csdn.net/sdjzping/article/details/18563289
这是一道树形DP,对于第k条边来说要么删除要么不删除
dp[i][j]表示以i为根的树有j个结点的最小代价(最少删除的边数),
dp[u][j]=max(dp[u][j]+1,dp[u][j-k]+dp[v][k])
要是删除第k条边那么dp[u][j]=dp[u][j]+1,不删除第K条边就等于dp[u][j-k]+dp[v][k]
http://blog.csdn.net/wujysh/article/details/38356847
树形DP,dp[i][j]表示以i节点为根,恰有j个节点时,需要去除几条边。
dp[father][i+j] = min(dp[father][i+j],  dp[father][i] + dp[child[father][k]][j] - 2);
dp[father][1] = child[father].size() + 1;
dp[root][1] = child[root].size();
  1. void dfs(int x) {  
  2.     for (int i = 0; i < child[x].size(); i++) {  
  3.         dfs(child[x][i]);  
  4.     }  
  5.   
  6.     for (int s = 0; s < child[x].size(); s++) {  
  7.         for (int i = p; i >= 1; i--) {  
  8.             for (int j = 1; j <= i; j++) {  
  9.                 dp[x][i] = min(dp[x][i-j] + dp[child[x][s]][j] - 2, dp[x][i]);  
  10.             }  
  11.         }  
  12.     }  
  13. }  
  14.   
  15. void work() {  
  16.     for (int i = 0; i <= n; i++) {  
  17.         dp[i][1] = child[i].size() + 1;  
  18.     }  
  19.     dp[root][1] = child[root].size();  
  20.   
  21.     dfs(root);  
  22.   
  23.     for (int i = 1; i <= n; i++) {  
  24.         ans = min(ans, dp[i][p]);  
  25.     }  
  26. }  
http://www.cnblogs.com/CKboss/p/3350821.html
int dp[200][200],sum[200],N,P;
vector<int> g[200];
bool vis[200];

void Tree_DP(int s)
{
    if(vis[s]) return;
    int tot = 0;
    vis[s]=true;sum[s]=1;
    for(int i=0;i<g[s].size();i++)
    {
        int v=g[s];
        if(vis[v]) continue;
        Tree_DP(v);
        sum[s]+=sum[v];
        tot++;
    }
    dp[s][1]=tot;
    for(int i=0;i<g[s].size();i++)
    {
        int v=g[s];
        for(int j=sum[s];j>=2;j--)
        {
            for(int k=1;k<j;k++)
            {
                if(dp[s][k]!=INF&&dp[v][j-k]!=INF)
                {
                    dp[s][j]=min(dp[s][j],dp[s][k]+dp[v][j-k]-1);
                }
            }
        }
    }
}

int main()
{
    while(scanf("%d%d",&N,&P)!=EOF)
    {
        for(int i=0;i<N+10;i++)
            g.clear();
        for(int i=0;i<N-1;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            g[a].push_back(b);
            g.push_back(a);
        }
        memset(dp,63,sizeof(dp));
        memset(vis,false,sizeof(vis));
        memset(sum,0,sizeof(sum));
        Tree_DP(1);
        int ans=INF;
        for(int i=1;i<=N;i++)
        {
            if(i==1)
                ans=min(ans,dp[P]);
            else ans=min(dp[P]+1,ans);
        }
        printf("%d\n",ans);
    }
    return 0;
}

http://www.java3z.com/cwbwebhome/article/article17/acm894.html
Read full article from 1947 -- Rebuilding Roads

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts