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 line consists of one positive 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 number which 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 |
第一眼LIS变形;时间复杂度O(n^2) 淘汰
for(int i=0;i<n;i++){
dp[i]=p[i];
for(int j=0;j<i;j++){
if(d[i]>d[j]){
dp[i]=max(dp[i],dp[j]+p[i]);
}
}
}
第二眼对难度dp:时间复杂度O(n*dmax)淘汰
for(int i=0;i<n;i++){
for(int j=0;j<d[i];j++){
dp[d[i]]=max(ddp[d[i]],dp[j]+p[i]);
}
}
由第二个状态转移得出可以实用线段树/树状数组更新区间最大值:时间复杂度O(n*log(d))满足题干。。
for(int i=0;i<n;i++){
int Max = Query(d[i]-1);
update(d[i],Max+p[i]);
res = max(res, Max+p[i]);
}
全部代码。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 100005
int c[N+5];
int d[N+5],p[N+5];
int lowbit(int x){
return x&-x;
}
void update(int x,int p){
while(x<=N){
c[x]=max(c[x],p);
x+=lowbit(x);
}
}
int Query(int pos){
int res=-N*100;
while(pos>0){
res = max(res,c[pos]);
pos-=lowbit(pos);
}
return res;
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
int n;
memset(c,0,sizeof(c));
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&d[i]);
d[i]++;
}
for(int i=0;i<n;i++){
scanf("%d",&p[i]);
}
int res = 0;
for(int i=0;i<n;i++){
int Max = Query(d[i]-1);
update(d[i],Max+p[i]);
res = max(res, Max+p[i]);
}
printf("%d\n",res);
}
}