Aggie’s Tasks | ||||||
| ||||||
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);
}
}