编程介的小学生 2019-12-20 21:34 采纳率: 20.5%
浏览 86

Family Fortune 用编程来实现

Problem Description
While studying the history of wealthy families, researchers want to know just how much of a fortune each family has amassed. There are various 'net worth' figures for each individual throughout history, but totaling them 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 or a descendant of anyone else 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. Also, there is exactly one person who is an ancestor of all other family members.
Given information about a family tree, what is the wealth of the family, by this measure?

Input
There will be several test cases in the input. Each test case will begin with two integers:
N K
Where N (1 ≤ N ≤ 100,000) is the total number of family members in the records, and K (1 ≤ K ≤ 1,000) is the size of the desired set of people.
Each of the next N lines will hold two integers:
P W
Where P (0 ≤ P ≤ N) indicates the parent of that family member. The family members are numbered from 1 to N, with the parent and fortune of family member i appearing on the i^th line. There will be a single root, with P=0. The tree will not have a depth greater than 1,000, and, of course, it won’t have any cycles. W (1 ≤ W ≤ 1,000) is the wealth (in millions) of that family member.
The input will end with a line with two 0s.

Output
For each test case, output a single integer on its own line, which is the maximum sum (in millions) of the fortunes of a set of K family members in the tree, where no member of the set is an ancestor or descendant of any other member of the set. If you cannot find K such nodes, then output 0. Output no extra spaces, and do not separate answers with blank lines.

Sample Input
11 5
0 1
1 1
1 1
2 1
2 1
3 1
3 1
3 1
5 1
7 1
7 1
11 5
11 3
1 1
4 1
1 2
10 2
10 2
6 2
6 1
10 2
11 3
0 4
7 3
0 18
1 20
1 15
2 12
2 6
3 8
3 8
0 0

Sample Output
5
10
36

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
    • ¥15 电力市场出清matlab yalmip kkt 双层优化问题