HDU5534 Partial Tree

题目:
给n个点,给定度为i的点有一个权值w[i],问如何组成一棵树(n-1条边),使得权值和最小
分析:
总共有2(n-1)个度,先给每一个点分配一个度(保证每个点有1个度),剩余n-2个度,还是分配给这n个点。
问题转化为:空间为n-2的一个背包,如何分配给n个物品,使得价值最大
问题再转化为:每个物品可以取0,1,2,3…..n-2个(对应每个点有多少度),即每个物品可取无限件,在一个空间为n-2的背包中,怎样取得最大价值
问题最终转化为:一个完全背包问题
(这道题想了好久好久才明白,也写了好久好久!!!)
代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int Tmax=2020;
int n,w[Tmax],f[Tmax];
void dp()
{
    int i,j;
    f[0]=n*w[1];
    for(i=0;i<=n-2;i++)
      for(j=i;j<=n-2;j++)
        f[j]=max(f[j],f[j-i]+w[i+1]-w[1]);
    return;
}
int main()
{
    int T,i;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(i=1;i<n;i++)
          scanf("%d",&w[i]);
        memset(f,0,sizeof(f));
        dp();
        printf("%d\n",f[n-2]);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,这是一道关于二叉树的问题,需要输出每个二叉树的层序遍历。如果二叉树没有完全给出,则输出“not complete”。而且,这道题目是一个ACM竞赛的题目,需要使用Java语言进行编写。 以下是Java语言的代码实现: ```java import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String s = sc.nextLine(); if (s.equals("")) { continue; } String[] arr = s.split(" "); int len = arr.length; int[] tree = new int[len]; boolean[] flag = new boolean[len]; for (int i = 0; i < len; i++) { if (arr[i].equals("()")) { tree[i] = -1; flag[i] = true; } else { tree[i] = Integer.parseInt(arr[i].substring(1, arr[i].length() - 1)); } } int root = 0; for (int i = 0; i < len; i++) { if (!flag[i]) { root = i; break; } } boolean isComplete = true; Queue<Integer> queue = new LinkedList<>(); queue.offer(root); int index = 1; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { int cur = queue.poll(); if (tree[cur] == -1) { if (index < len && !flag[index]) { isComplete = false; } } else { if (cur * 2 + 1 < len) { queue.offer(cur * 2 + 1); if (tree[cur * 2 + 1] != -1) { flag[cur * 2 + 1] = true; } } if (cur * 2 + 2 < len) { queue.offer(cur * 2 + 2); if (tree[cur * 2 + 2] != -1) { flag[cur * 2 + 2] = true; } } } index++; } } if (!isComplete) { System.out.println("not complete"); continue; } queue.offer(root); StringBuilder sb = new StringBuilder(); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { int cur = queue.poll(); sb.append(tree[cur]).append(" "); if (cur * 2 + 1 < len && tree[cur * 2 + 1] != -1) { queue.offer(cur * 2 + 1); } if (cur * 2 + 2 < len && tree[cur * 2 + 2] != -1) { queue.offer(cur * 2 + 2); } } } System.out.println(sb.toString().trim()); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值