Find the answer
Time Limit: 4000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2428 Accepted Submission(s): 829
Problem Description
Given a sequence of n integers called W and an integer m. For each i (1 <= i <= n), you can choose some elements Wk (1 <= k < i), and change them to zero to make ∑ij=1Wj<=m. So what’s the minimum number of chosen elements to meet the requirements above?.
Input
The first line contains an integer Q — the number of test cases.
For each test case:
The first line contains two integers n and m — n represents the number of elemens in sequence W and m is as described above.
The second line contains n integers, which means the sequence W.
1 <= Q <= 15
1 <= n <= 2*105
1 <= m <= 109
For each i, 1 <= Wi <= m
Output
For each test case, you should output n integers in one line: i-th integer means the minimum number of chosen elements Wk (1 <= k < i), and change them to zero to make ∑ij=1Wj<=m.
Sample Input
2
7 15
1 2 3 4 5 6 7
5 100
80 40 40 40 60
Sample Output
0 0 0 0 0 2 3
0 1 1 2 3
题意
给出一个 n 个数组和一个数 m,对于每个数 a[i] 求前 i - 1 个最少要去掉几个数时剩下的数加上 a[i] 的和小于等于 m。
思路
要使去掉的数最少,肯定要去掉最大的几个数,但我们每次去找最前几个大的数必然会 T,这题反过来想,就是前 i - 1 个数要凑出 m - a[i],尽可能的多,所以就去取最小的几个数。这题可以用权值线段树来做。因为 n 为 2 * 1e5,数是 1e9,所以先离线化,每个节点维护一个值域的数的总和,和数的个数。查询的时候因为左子树的数比较小,所以在左子数的大于等于足够查询 val 值时就直接递归查询左子树;当左子树的总和不够时就取左子树的全部,再去递归查询右子树(用 val - tree[root<<1].val 去查询)。当 tree[root].l == tree[root].r 时说明该 val 只能用 b[tree[root].l] 这个数来凑,那么直接取 val / (b[tree[root].l]) 即这个数该取的数量。
另外每次要先查询,再把 a[i] 更新进线段树,防止后面的数影响前面。
代码
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define maxn 200100
using namespace std;
typedef long long ll;
int a[maxn], b[maxn];
struct node{
ll val;
int num, l, r;
}tree[maxn * 4];
void build(int root, int l, int r){
tree[root].l = l;
tree[root].r = r;
tree[root].val = 0;
tree[root].num = 0;
if(l == r) return;
int mid = (l + r) >> 1;
build(root<<1, l, mid);
build(root<<1|1, mid+1, r);
}
void update(int root, int pos){
if(tree[root].l == tree[root].r){
tree[root].val += b[pos];
tree[root].num++;
return;
}
int mid = (tree[root].l + tree[root].r) >> 1;
if(pos <= mid) update(root<<1, pos);
else update(root<<1|1, pos);
tree[root].val = tree[root<<1].val + tree[root<<1|1].val;
tree[root].num = tree[root<<1].num + tree[root<<1|1].num;
}
int query(int root, int val){
if(tree[root].val <= val) return tree[root].num;
if(tree[root].l == tree[root].r) return val/(b[tree[root].l]);
if(tree[root<<1].val >= val) return query(root<<1, val);
else return tree[root<<1].num + query(root<<1|1, val - tree[root<<1].val);
}
int main(){
int t, n, m;
while(~scanf("%d", &t)){
while(t--){
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
b[i] = a[i];
}
sort(b + 1, b + 1 + n);
build(1, 1, n);
for(int i = 1; i <= n; i++){
if(i == 1)
printf("0 ");
else
printf("%d ",i - 1 - query(1, m - a[i]));
int pos = lower_bound(b + 1, b + 1 + n, a[i]) - b;
update(1, pos);
}
printf("\n");
}
}
}