Find the answer HDU6609(线段树)

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=6609
题面:
Given a sequence of n integers called W and an integer m. For each i (1 <= i <= n), you can choose some elements W k W_{k} Wk (1 <= k < i), and change them to zero to make ∑ i = 1 j W j &lt; = m ∑_{i=1}^{j}W_{j}&lt;=m i=1jWj<=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 <= 2e5
1 <= m <= 1e9
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.
题意: 给你一个数组,满足这样 W k W_{k} Wk (1 <= k < i), 可以使一些 W k W_{k} Wk为0,使得 ∑ i = 1 j W j &lt; = m ∑_{i=1}^{j}W_{j}&lt;=m i=1jWj<=m,最少需要使多少个W为0
思路: ∑ i = 1 j W j &gt; m ∑_{i=1}^{j}W_{j}&gt;m i=1jWj>m,则我们最优的策略就是使越大的元素为0,直到 ∑ i = 1 j W j &lt; = m ∑_{i=1}^{j}W_{j}&lt;=m i=1jWj<=m,所以我们用线段树来维护,建一颗线段树,来储存前i个元素的区间和与个数。维护区间和不是普通的区间和,而是从小到大有序的区间和,每个叶子代表一种元素与个数,这样就能在 O ( l o g ) O(log) O(log)的时间里找出需要减去较大的数量,总时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn)

#include<bits/stdc++.h>
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
using namespace std;
typedef long long ll;
const int N=2e5+5;
ll sum[N*4];
int cnt[N*4],a[N],b[N];
void update(int l,int r,int root,int x)
{
	if(l==r)
	{
		sum[root]+=b[x];
		cnt[root]++;
		return ;
	}
	int mid=(l+r)>>1;
	if(x<=mid)
		update(lson,x);
	else
		update(rson,x);
	sum[root]=sum[root<<1]+sum[root<<1|1];
	cnt[root]=cnt[root<<1]+cnt[root<<1|1];
}

int query(int l,int r,int root,ll x)
{
	if(l==r)
	{
		return (x+b[l]-1)/b[l];
	}
	int mid=(l+r)>>1;
	if(sum[root<<1|1]<x)
		return query(lson,x-sum[root<<1|1])+cnt[root<<1|1];
	return query(rson,x);
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int n,m;
		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);
		int tot=unique(b+1,b+1+n)-b-1;
		for(int i=1;i<=4*tot;i++)
			sum[i]=cnt[i]=0;
		ll res=0;
		for(int i=1;i<=n;i++)
		{
			res+=a[i];
			int ans=0;
			if(res>m)
				ans=query(1,tot,1,res-m);
			int x=lower_bound(b+1,b+1+tot,a[i])-b;
			update(1,tot,1,x);
			printf("%d ",ans);
		}
		puts("");
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值