HDU 1166 敌兵布阵
近似于裸的线段树
#include <stdio.h>
#include <string>
#include <string.h>
#include <cmath>
#include <iostream>
using namespace std;
const int MAX_N = 50010;
int s[4*MAX_N];
void up(int p){
s[p]=s[p*2]+s[p*2+1];
}
void modify(int p,int l,int r,int x,int v){
if(l==r) {
s[p]+=v;
return ;
}
int mid=(l+r)/2;
if(x<=mid) {
modify(p*2,l,mid,x,v);
}
else {
modify(p*2+1,mid+1,r,x,v);
}
up(p);
}
int query(int p,int l,int r,int x,int y){
if(x<=l&&r<=y) return s[p];
int mid=(l+r)/2,res=0;
if(x<=mid) res+=query(p*2,l,mid,x,y);
if(y>mid) res+=query(p*2+1,mid+1,r,x,y);
return res;
}
int main(){
int t,Case=1;
scanf("%d",&t);
while(t--){
memset(s,0,sizeof(s));
printf("Case %d:\n",Case++);
int n;
scanf("%d",&n);
for(int i = 1;i<=n;i++){
int d;
scanf("%d",&d);
modify(1,1,n,i,d);
}
while(1){
string s;
cin >> s;
if(s=="End") {
break;
}
else {
if(s=="Add"){
int a,b;
scanf("%d%d",&a,&b);
modify(1,1,n,a,b);
}
if(s=="Sub"){
int a,b;
scanf("%d%d",&a,&b);
modify(1,1,n,a,-b);
}
if(s=="Query"){
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",query(1,1,n,a,b));
}
}
}
}
return 0;
}

本文介绍了一个基于线段树的数据结构解决HDU1166敌兵布阵问题的方法。通过实现线段树的增删查询操作,有效解决了区间更新和查询的问题。文中详细展示了线段树的构建、更新及查询过程。
1万+

被折叠的 条评论
为什么被折叠?



