题意:
给n个数,m个操作,每次把区间[l,r]的数用它们都的它们的平均值替代,当它们的平均值不是整数时,若前n个数的和小于最初n个数的和就向上取整,不然就向下取整,最后输出每个数
思路:
线段树区间更新,区间求和。
易错点是:关于正数和负数的整除问题,正数整除是自动向下取整的,但负数是向上取整的。即13/3 = 4.3舍为4, 但-13/3 = -4.3 舍为-4
注意:两个int相乘要强制类型转化为long long!!,错了无数次
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
#define lson root<<1, l, mid
#define rson root<<1 | 1, mid+1, r
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 30000+50;
using namespace std;
LL Tree[maxn<<2], lazy[maxn<<2], sum_org;
// 线段树
void push_up(int root){ Tree[root] = Tree[root<<1] + Tree[root<<1 | 1];}
void Stree_build(int root, int l, int r){
if(l == r){
scanf("%lld", &Tree[root]);
sum_org+= Tree[root];
return;
}
int mid = (l+r) >> 1;
Stree_build(lson);
Stree_build(rson);
push_up(root);
}
void push_down(int root, int len){
if(0 == lazy[root]) return;
lazy[root<<1] = lazy[root];
lazy[root<<1 | 1] = lazy[root];
Tree[root<<1] = lazy[root] * (len - (len>>1));
Tree[root<<1 | 1] = lazy[root] * (len>>1);
lazy[root] = 0;
}
void update(int la, int rb, int l, int r, int root, int val){
if(la > r||l > rb) return;
if(la <= l&&rb >= r){
Tree[root] = (LL)val * (r-l+1); // 注意强制类型转化!!!
lazy[root] = val;
//if(l == r) A[l] = Tree[root];
return;
}
push_down(root, r-l+1);
int mid = (l+r) >> 1;
if(la <= mid)
update(la, rb, l, mid, root<<1, val);
if(rb > mid)
update(la, rb, mid+1, r, root<<1 | 1, val);
push_up(root);
}
void Query(int la, int rb, int l, int r, int root, LL& ans){
if(la > r||l > rb) return;
if(la <= l&&rb >= r){
ans+= Tree[root];
return;
}
push_down(root, r-l+1);
int mid = (l+r) >> 1;
if(la <= mid)
Query(la, rb, l, mid, root<<1, ans);
if(rb > mid)
Query(la, rb, mid+1, r, root<<1 | 1, ans);
//push_up(root);
}
void print(int root, int l,int r){
if(l == r){
if(l == 1) printf("%lld", Tree[root]);
else printf(" %lld", Tree[root]);
return;
}
push_down(root, r-l+1);
int mid = (l+r) >> 1;
print(lson);
print(rson);
}
int main()
{
freopen("in.txt","r",stdin);
int n, m, a, b;
while(scanf("%d%d",&n,&m) == 2){
memset(lazy, 0, sizeof(lazy));
memset(Tree, 0, sizeof(Tree));
sum_org = 0;
Stree_build(1, 1, n);
while(m--){
scanf("%d%d", &a,&b);
LL sum = 0;
Query(a, b, 1, n, 1, sum);
int ave = sum / (b-a+1);
if(sum > 0&&Tree[1] <= sum_org){
if(sum%(b-a+1)) ++ave;
}
else if(sum < 0&&Tree[1] > sum_org){
if(sum%(b-a+1)) --ave;
}
update(a, b, 1, n, 1, ave);
}
print(1, 1, n);
printf("\n\n");
}
fclose(stdin);
return 0;
}