编程介的小学生 2019-12-23 21:49 采纳率: 0.4%
浏览 67

Wealthy Family

Problem Description
While studying the history of royal families, you want to know how wealthy each family is. While you have various 'net worth' figures for each individual throughout history, this is complicated by double counting caused by inheritance. One way to estimate the wealth of a family is to sum up the net worth of a set of k people such that no one in the set is an ancestor of another in the set. The wealth of the family is the maximum sum achievable over all such sets of k people. Since historical records contain only the net worth of male family members, the family tree is a simple tree in which every male has exactly one father and a non-negative number of sons. You may assume that there is one person who is an ancestor of all other family members.

Input
The input consists of a number of cases. Each case starts with a line containing two integers separated by a space: N (1 <= N <= 150,000), the number of people in the family, and k (1 <= k <= 300), the size of the set. The next N lines contain two non-negative integers separated by a space: the parent number and the net worth of person i (1 <= i <= N). Each person is identified by a number between 1 and N, inclusive. There is exactly one person who has no parent in the historical records, and this will be indicated with a parent number of 0. The net worths are given in millions and each family member has a net worth of at least 1 million and at most 1 billion.

Output
For each case, print the maximum sum (in millions) achievable over all sets of k people satisfying the constraints given above. If it is impossible to choose a set of k people without violating the constraints, print 'impossible' instead.

Sample Input
5 3
0 10
1 15
1 25
1 35
4 45
3 3
0 10
1 10
2 10

Sample Output
85
impossible

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-07-28 00:55
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    # 导入必要的库
    library(ggplot2)
    
    # 输入的样例数据
    data <- read.table(text = "5 3\n0 10\n1 15\n1 25\n1 35\n4 45\n3 3\n0 10\n1 10\n2 10", header = TRUE)
    k <- data[1, 2]
    
    # 初始化一个空的向量来存储结果
    results <- numeric(length(data))
    
    # 遍历每个家庭成员
    for (i in 1:nrow(data)) {
      
      # 如果当前的家庭成员是第一个被选中的,则将其加入到结果中,并将它标记为已选择
      if (data[i, 1] == 0) {
        results[data[i, 2]] <- max(results[data[i, 2]], data[i, 3])
      } else {
        
        # 如果当前的家庭成员已经被选中,那么我们只需要考虑它的儿子们,因为它们不能继承这个家庭成员的财富
        for (j in 1:data[i, 1]) {
          
          # 如果儿子还没有被选中,则将其加入到结果中,并将它标记为已选择
          if (!is.na(results[data[j, 2]]) && !is.na(results[data[i, 2]])) {
            results[data[j, 2]] <- max(results[data[j, 2]], data[j, 3] + data[i, 3])
          }
          
        }
        
      }
    }
    
    # 输出结果
    print(results)
    
    评论

报告相同问题?