HDU 1166 soldats ennemis ont mis fin à la résolution des problèmes arbre segment de rapport
idées de résolution de problèmes: la ligne d'arbre. Cette question ne concerne que une structure de données, pas tant avec l'algorithme, sera en mesure de regarder directement le code pour comprendre. Si vous ne comprenez pas, expliquer à la recherche de la ligne d'arbre.
#include<iostream>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<string.h>
#include<map>
#include<stack>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<fstream>
#include<sstream>
#include<set>
#pragma warning(disable:4996)
#define INF 0x3f3f3f3f
#define ll long long
#define PI acos(-1.0)
const int N = 100005;
const int maxn = 1e9;
using namespace std;
int n, t;
int a[50005];
int tree[200020];//tree里放区间和
void build(int id, int l, int r)
{
if (l == r)
{
tree[id] = a[l];
return;
}
int mid = (l + r) >> 1;
build(id << 1, l, mid);
build(id << 1 | 1, mid + 1, r);
tree[id] = tree[id << 1] + tree[id << 1 | 1];
}
int query(int id, int l, int r, int x, int y)
{
if (x <= l && y >= r)
{
return tree[id];
}
int mid = (l + r) >> 1;
int sum = 0;
if (x <= mid)
sum += query(id << 1, l, mid, x, y);
if (y > mid)
sum += query(id << 1 | 1, mid + 1, r, x, y);
return sum;
}
void Add(int id, int l, int r, int x, int y)
{
if (l == r)
{
tree[id] += y;
return;
}
int mid = (l + r) >> 1;
if (x <= mid)
Add(id << 1, l, mid, x, y);
else
Add(id << 1 | 1, mid + 1, r, x, y);
tree[id] += y;
}
void sub(int id, int l, int r, int x, int y)
{
if (l == r)
{
tree[id] -= y;
return;
}
int mid = (l + r) >> 1;
if (x <= mid)
sub(id << 1, l, mid, x, y);
else
sub(id << 1 | 1, mid + 1, r, x, y);
tree[id] -= y;
}
int main()
{
int cnt = 0;
scanf("%d", &t);
while (t--)
{
cnt++;
memset(a, 0, sizeof(a));
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
build(1, 1, n);
printf("Case %d:\n", cnt);
char ch[10] = "";
while (scanf("%s", ch))
{
if (strcmp(ch, "Query") == 0)
{
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", query(1, 1, n, x, y));
}
else if (strcmp(ch, "Add") == 0)
{
int x, y;
scanf("%d%d", &x, &y);
Add(1, 1, n, x, y);
}
else if (strcmp(ch, "Sub") == 0)
{
int x, y;
scanf("%d%d", &x, &y);
sub(1, 1, n, x, y);
}
else if (strcmp(ch, "End") == 0)
break;
memset(ch, 0, sizeof(0));
}
}
}