1. 程式人生 > 實用技巧 >【URAL1018】Binary Apple Tree

【URAL1018】Binary Apple Tree

題目連結

Binary Apple Tree

題目描述

Let's imagine how apple tree looks in binary computer world. You're right, it looks just like a binary tree, i.e. any biparous branch splits up to exactly two new branches. We will enumerate by integers the root of binary apple tree, points of branching and the ends of twigs. This way we may distinguish different branches by their ending points. We will assume that root of tree always is numbered by \(1\)

and all numbers used for enumerating are numbered in range from \(1\) to \(N\), where \(N\) is the total number of all enumerated points. For instance in the picture below \(N\) is equal to \(5\). Here is an example of an enumerated tree with four branches:

2 5
\ /
3 4
\ /
1
As you may know it's not convenient to pick an apples from a tree when there are too much of branches. That's why some of them should be removed from a tree. But you are interested in removing branches in the way of minimal loss of apples. So your are given amounts of apples on a branches and amount of branches that should be preserved. Your task is to determine how many apples can remain on a tree after removing of excessive branches. ### 輸入格式 First line of input contains two numbers: $N$ and $Q$ ($2 \le N \le 100$;$1 \le Q \le N-1$).$N$ denotes the number of enumerated points in a tree. $Q$ denotes amount of branches that should be preserved. Next $N-1$ lines contains descriptions of branches. Each description consists of a three integer numbers divided by spaces. The first two of them define branch by it's ending points. The third number defines the number of apples on this branch. You may assume that no branch contains more than $30000$ apples. ### 輸出格式 Output should contain the only number — amount of apples that can be preserved. And don't forget to preserve tree's root ;-) ### 樣例輸入
5 2
1 3 1
1 4 10
2 3 20
3 5 20
### 樣例輸出
21
## 題解 題意:有一棵樹,每條邊都有一個權值,求包含根的有$Q$條邊的聯通塊的權值之和最大。 那麼我們考慮樹上dp $dp[i][j]$表示以$i$為根,保留$j$條邊最大的權值之和。 那麼轉移方程如下: $dp[u][i]=max$($dp[u][i],dp[u][i-k-1]+dp[son][k]$) $dp[u][0]=val[u][fa]$ 記得把$dp[u][0]$的值初始化為$u$和它父親的邊的權值,如果$u$不是根結點。 上程式碼: ```cpp #include using namespace std; int n,q; int u,v,w; struct aa{ int to,nxt,v; }p[209]; int h[109],len=1; void add(int u,int v,int w){ p[++len].to=v; p[len].v=w; p[len].nxt=h[u]; h[u]=len; } int ss[109]; int dp[109][109]; void dfs(int u,int fa,int us){ ss[u]=0; for(int j=h[u];j;j=p[j].nxt){ if(p[j].to==fa) continue; dfs(p[j].to,u,p[j].v); ss[u]+=1+ss[p[j].to];//記錄以u為根的子樹的節點數 } dp[u][0]=us;//別忘了u節點和父親的邊 for(int j=h[u];j;j=p[j].nxt){ if(p[j].to==fa) continue; for(int i=q;i>
=1;i--){//從大到小列舉防止重複計算 for(int o=0;i-o-1>=0 && o<=ss[p[j].to];o++){ dp[u][i]=max(dp[u][i],dp[u][i-o-1]+dp[p[j].to][o]); } } } } int main(){ scanf("%d%d",&n,&q); for(int j=1;j