In the game of DotA, Pudge’s meat hook is actually the most horrible thing for most of the heroes. The hook is made up of several consecutive metallic sticks which are of the same length.
Now Pudge wants to do some operations on the hook.
Let us number the consecutive metallic sticks of the hook from 1 to N. For each operation, Pudge can change the consecutive metallic sticks, numbered from X to Y, into cupreous sticks, silver sticks or golden sticks.
The total value of the hook is calculated as the sum of values of N metallic sticks. More precisely, the value for each kind of stick is calculated as follows:
For each cupreous stick, the value is 1.
For each silver stick, the value is 2.
For each golden stick, the value is 3.
Pudge wants to know the total value of the hook after performing the operations.
You may consider the original hook is made up of cupreous sticks.
题意:
n
个点,起始值为
使用数组存放的做法参考了下面这位巨巨的文章
HDU - 1698 - Just a Hook (线段树-成段更新)http://blog.youkuaiyun.com/u014355480/article/details/45726057
最开始我用的是自己定义的节点类,但是代码只会超时,参考了网上的文章以后发现,完全二叉树的性质使得所有数据用数组就能存放下来。
#include <stdio.h>
#include<string.h>
#define maxn 100000
#define fath(i) (i>>1)
#define left(i) (i<<1)
#define right(i) ((i<<1)+1)
#define mid(l,r) (l+ ((r -l) >> 1))
//完全二叉树用数组存放
int l[(maxn << 2) + 5];
int r[(maxn << 2) + 5];
int k[(maxn << 2) + 5];
int lzy[(maxn << 2) + 5];
int n;
void build(int cl, int cr, int i) {
l[i] = cl; r[i] = cr;
k[i] = 1;
if (cl != cr) {
build(cl, mid(cl, cr), left(i));
build(mid(cl, cr) + 1, cr, right(i));
}
}
int setk;
void update(int cl, int cr, int i) {
if (cl == l[i] && cr == r[i]) {
k[i] = setk;
lzy[i] = setk;
return;
}
if (lzy[i]) {
lzy[left(i)] = lzy[right(i)] = lzy[i];
k[left(i)] = k[right(i)] = lzy[i];
lzy[i] = 0;
}
k[i] = -1;
int m = mid(l[i], r[i]);
if (cr <= m)
{
update(cl, cr, left(i));
}
else if (cl >= (m + 1)) {
update(cl, cr, right(i));
}
else {
update(cl, m, left(i));
update(m + 1, cr, right(i));
}
}
int ans;
void sol(int i) {
if (k[i] > 0) {
if (lzy[i] > 0) {
ans += (r[i] - l[i] + 1)*lzy[i];
return;
}
ans += (r[i] - l[i] + 1)*k[i];
return;
}
sol(left(i));
sol(right(i));
}
//#define tst
int main() {
int kase, q;
int a1, a2, a3;
#ifdef tst
FILE* fin = fopen("D:\\CB_projects\\TapToUse\\data.txt", "r");
fscanf(fin, "%d", &kase);
#else
scanf("%d", &kase);
#endif // tst
for (int t = 1; t <= kase;++t) {
#ifdef tst
fscanf(fin, "%d", &n);
#else
scanf("%d", &n);
#endif // tst
build(1, n, 1);
int q;
#ifdef tst
fscanf(fin, "%d", &q);
#else
scanf("%d", &q);
#endif // tst
for (int i = 0; i < q; ++i) {
#ifdef tst
fscanf(fin, "%d %d %d", &a1, &a2, &a3);
#else
scanf("%d %d %d", &a1, &a2, &a3);
#endif // tst
setk = a3;
update(a1, a2, 1);
}
ans = 0;
sol(1);
printf("Case %d: The total value of the hook is %d.\n", t,ans);
memset(l, 0, sizeof(l));
memset(r, 0, sizeof(r));
memset(k, 0, sizeof(k));
memset(lzy, 0, sizeof(lzy));
}
}
(居然在数据结构上面卡时间,小声BB