hrbust 2362 Aggie’s Tasks【树状数组】

Aggie面临着一系列任务选择,每个任务都有难度和预期利润。为了最大化收益同时避免浪费时间在简单任务上,Aggie采取了一种策略:一旦接受了某个难度的任务,她就不会再接受更简单的任务。本篇介绍了一个算法解决方案,利用树状数组来帮助Aggie找到最大可能的利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Aggie’s Tasks
Time Limit: 1000 MSMemory Limit: 262144 K
Total Submit: 83(34 users)Total Accepted: 26(20 users)Rating: Special Judge: No
Description

Aggie is faced with a sequence of tasks, each of which with a difficulty value di and an expected profit pi. For each task, Aggie must decide whether or not to complete it. As Aggie doesn’t want to waste her time on easy tasks, once she takes a task with a difficulty di, she won’t take any task whose difficulty value is less than or equal to di.

Now Aggie needs to know the largest profits that she may gain.

Input

The first lineconsists of onepositive integer t (t 10), which denotes the number of test cases.

For each test case, the first line consists one positive integer n (n 100000), which denotes the number of tasks. The second line consists of n positive integers, d1, d2, …, dn (di  100000), which is the difficulty value of each task. The third line consists of n positive integers, p1, p2, …, pn (pi  100), which is the profit that each task may bring to Aggie.

Output

For each test case, output a single numberwhich is the largest profits that Aggie may gain.

Sample Input

1

5

3 4 5 1 2

1 1 1 2 2

Sample Output

4

看数据范围显然不能用lcs,这里用到树状数组;

具体看代码中注释;

#include<bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 7;
int c[MAX];
struct node
{
    int x, y;
} a[MAX];
int lowbit(int i)
{
    return i & (-i);
}
void add(int i, int num) ///更新区间值,将当前价值更新到树状数组中;
{
    while(i < MAX)  ///注意此处是MAX,不是n
    {
        c[i] = max(c[i], num);  /// 比较得出最佳方案后将其在树状数组中向上将更新的值传递上去;
        i += lowbit(i);
    }
}
int Sum(int i) ///得到该节点的当前最优解;
{
    int sum = -0x3f3f3f3f;
    while(i > 0)
    {
        sum = max(sum, c[i]); /// 从该节点向下遍历子节点寻找最优解;
        i -= lowbit(i);
    }
    return sum;
}
int main()
{
    int N, n;
    scanf("%d", &N);
    while(N--)
    {
        memset(c, 0, sizeof c);
        scanf("%d", &n);
        for(int i = 0; i < n; i++)
        {
            scanf("%d", &a[i].x);
            a[i].x++; /// 因为下面要查询前一元素的最优解,并且数据范围可以等于0,所以++以避免(0-1)的情况
        }
        for(int i = 0; i < n; i++)
            scanf("%d", &a[i].y);
        int ans = -0x3f3f3f3f;
        for(int i = 0; i < n; i++)
        {
            int maxn = Sum(a[i].x - 1); /// 查询下一子节点的最优解;
            add(a[i].x, maxn + a[i].y); ///将(刚查过得最优解+当前价值)更新到区间中;
            ans = max(ans, maxn + a[i].y);  /// 遍历寻找最优解;
        }
        printf("%d\n", ans);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值