http://acm.hdu.edu.cn/showproblem.php?pid=4027
題目是標準的線段樹,由於要對區間內的每個數進行開方操作,所以每次update都要update到葉子節點那裏。
這樣很明顯沒有體現線段樹的lazy update,稍微分析也可知道必定TLE。。。
改進:
首先,題目中要求開方後向下取整。然後,由於sum最大不超過2^63,所以每個數最多開方7次,等到變成1的時候,數值就不會再變化了,也就是,如果某個區間內所有數都變成1了,那麼就不需要再update了。
最後,注意,x有可能大於y的。。。若無注意到此處,會RE滴~
代碼:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 100000 + 10;
struct SegTree
{
int left, right;
ll sum;
bool allone; /**這裏是重點,標記是否區間內全爲1**/
};
SegTree st[N*3];
ll num[N];
void build(int left, int right, int idx)
{
st[idx].left = left;
st[idx].right = right;
if (left == right)
{
st[idx].sum = num[left];
if (st[idx].sum == 1)
st[idx].allone = true;
else st[idx].allone = false;
return;
}
int mid = (left + right) / 2;
build(left, mid, idx*2);
build(mid+1, right, idx*2+1);
st[idx].sum = st[idx*2].sum + st[idx*2+1].sum;
if (st[idx*2].allone && st[idx*2+1].allone)
st[idx].allone = true;
else st[idx].allone = false;
}
void update(int left, int right, int idx)
{
if (st[idx].left == st[idx].right)
{
st[idx].sum = (ll)sqrt(st[idx].sum * 1.0);
if (st[idx].sum == 1)
st[idx].allone = true;
return;
}
if (st[idx].allone && st[idx].left <= left && right <= st[idx].right)
return;
int mid = (st[idx].left + st[idx].right) / 2;
if (right <= mid)
update(left, right, idx*2);
else if (left > mid)
update(left, right, idx*2+1);
else
{
update(left, mid, idx*2);
update(mid+1, right, idx*2+1);
}
st[idx].sum = st[idx*2].sum + st[idx*2+1].sum;
if (st[idx*2].allone && st[idx*2+1].allone)
st[idx].allone = true;
}
ll query(int left, int right, int idx)
{
if (st[idx].left == left && st[idx].right == right)
return st[idx].sum;
int mid = (st[idx].left + st[idx].right) / 2;
if (left > mid)
return query(left, right, idx*2+1);
else if (right <= mid)
return query(left, right, idx*2);
else return query(left, mid, idx*2) + query(mid+1, right, idx*2+1);
}
int main()
{
// freopen("in.txt", "r", stdin);
int n, m, k = 1;
while (scanf("%d", &n) != EOF)
{
printf("Case #%d:\n", k++);
for (int i = 1; i <= n; i++)
scanf("%I64d", &num[i]);
build(1, n, 1);
int t, a, b;
scanf("%d", &m);
for (int i = 1; i <= m; i++)
{
scanf("%d%d%d", &t, &a, &b);
if (a > b)
swap(a, b);
if (t == 0)
update(a, b, 1);
else printf("%I64d\n", query(a, b, 1));
}
printf("\n");
}
return 0;
}