您的位置:首页 > 其它

hdu 1166_敌兵布阵_线段树版

2010-01-24 20:29 225 查看
刚才用树状数组做了下,发现可以用线段树,试着写了写,果然可以。。。。。。。

/*
* File: main.cpp
* Author: Administrator
*
* Created on 2010年1月24日, 下午7:26
*/

#include <stdlib.h>
#include<iostream>
#include<string>
using namespace std;
#define N 50005

struct Node {
int l, r, num;
} Tree[N * 3];
int A
;

void Build_Tree(int l, int r, int k) {
Tree[k].l = l;
Tree[k].r = r;
if (l == r) {
Tree[k].num = A[l];
return;
}
int mid = (l + r) / 2;
Build_Tree(l, mid, 2 * k);
Build_Tree(mid + 1, r, 2 * k + 1);
Tree[k].num = Tree[2 * k].num + Tree[2 * k + 1].num;
}

int Find_Num(int l, int r, int k) {
if (Tree[k].l == l && Tree[k].r == r) {
return Tree[k].num;
}
int mid = (Tree[k].l + Tree[k].r) / 2;
if (r <= mid)return Find_Num(l, r, 2 * k);
else if (l > mid)return Find_Num(l, r, 2 * k + 1);
else {
int a, b;
a = Find_Num(l, mid, 2 * k);
b = Find_Num(mid + 1, r, 2 * k + 1);
return a + b;
}
}

void Insert_Tree(int k, int i) {
if (Tree[k].r == Tree[k].l && (i == Tree[k].l)) {
Tree[k].num = A[Tree[k].l];
return ;
}
int mid = (Tree[k].l + Tree[k].r) / 2;
if (i <= mid)Insert_Tree(2 * k, i);
else if (i > mid)Insert_Tree(2 * k + 1, i);
Tree[k].num = Tree[2 * k].num + Tree[2 * k + 1].num;
}

/*
*
*/
int main(int argc, char** argv) {

int n, i, j, k, a1, a2;
char ch[20];
int ca, c;
cin >> ca;
for (c = 1; c <= ca; c++) {
cin >> n;
for (i = 1; i <= n; i++) {
cin >> A[i];
}//system("pause");
Build_Tree(1, n, 1);
cout << "Case " << c << ":" << endl;
while (cin >> ch) {
if (strcmp(ch, "End") == 0)break;
if (strcmp(ch, "Query") == 0) {
cin >> a1 >> a2;
cout << Find_Num(a1, a2, 1) << endl;
}
if (strcmp(ch, "Add") == 0) {
cin >> a1 >> a2;
A[a1] += a2;
Insert_Tree(1, a1);
}
if (strcmp(ch, "Sub") == 0) {
cin >> a1 >> a2;
A[a1] -= a2;
Insert_Tree(1, a1);
}

}
}
return (EXIT_SUCCESS);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: