您的位置:首页 > 产品设计 > UI/UE

UESTC 4 Complete Building the Houses 树状数组

2014-07-27 21:13 134 查看
题目来源:

http://acm.uestc.edu.cn/#/problem/show/4

分析:就是一个很普通的区间修改,单点查询的树状数组,但是今天忘记吃药了,一直写不对,中午迷迷糊糊地,直接把数据读入到数组里而不是update,然后又总是考虑后面的数被减到0以下要怎么处理,其实根本不用考虑,直接判断大于0就行了,要是修改那些值,就无法满足数组a[]的性质了(a[]是原式的做差,a[i] = x[i] - x[i-1], a[1] = x[1])。想想还是贴出来纪念一下(这有什么好纪念的?!)

#include<cstdio>
#include<cstring>
using namespace std;

int n, m, T;
long long a[100100];
long long ans;
int lowbit(int x)
{
return x & -x;
}
void update(int x, long long val)
{
for (int i = x; i <= n; i += lowbit(i))
a[i] += val;
}
long long query(int x)
{
long long ans = 0;
for (int i = x; i > 0; i -= lowbit(i))
ans += a[i];
return ans;
}
int main()
{
int cas = 0;
scanf("%d", &T);
while(T--)
{
memset(a, 0, sizeof(a));
scanf("%d %d", &n, &m);
long long x;
for (int i = 1; i <= n; i++){
scanf("%lld", &x);
update(i, x);
update(i+1, -x);
}
ans = 0;
for (int i = 1; i <= n; i++){
int tmp = query(i);
if (tmp > 0){
ans += tmp;
update(i, -tmp);
update(i+m, tmp);
}
}
cas++;
printf("Case #%d: %lld\n", cas, ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐