HDU - 4027 Can you answer these queries?(线段树)

题目链接

思路:
1.查询:区间查询板子
2.修改: 要将线段树区间修改稍微改一下,因为每次区间修改都把该区间所有的数修改为向下取整的原值开根号,所以一个1e18次方的数修改超过50次(我猜的)大概就会变成1,而 1修改的话值不变,所以当修改区间的所有值都为1时就不用再修改该区间了直接return,我判断所有值为1的条件是节点的值w等于区间长度,也可以用区间最大值来判断。
注意:输入的区间值不保证l <= r,要判一下;还有就是每组样例之间要有一个空格。

代码:

#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl
#define lson idx << 1
#define rson idx << 1 | 1

using namespace std;

typedef long long ll;
typedef pair<ll, ll> PII;

const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int n, m;
struct node
{
    int l, r;
    ll w;
} tree[N << 2];
ll a[N];

inline void PushUp(int idx)
{
    tree[idx].w = tree[lson].w + tree[rson].w;
}

void Build(int idx, int l, int r)
{
    tree[idx].l = l;
    tree[idx].r = r;
    if (l == r)
    {
        tree[idx].w = a[l];
        return;
    }
    int mid = l + r >> 1;
    Build(lson, l, mid);
    Build(rson, mid + 1, r);
    PushUp(idx);
}

inline void Update(int idx, int l, int r)
{
    if (tree[idx].l >= l && tree[idx].r <= r && tree[idx].w == tree[idx].r - tree[idx].l + 1)
    {
        return;
    }
    else if (tree[idx].l == tree[idx].r)
    {
        if (tree[idx].w > 1)
        {
            tree[idx].w = floor(sqrt(tree[idx].w));
        }
        return;
    }
    if (tree[lson].r >= l)
        Update(lson, l, r);
    if (tree[rson].l <= r)
        Update(rson, l, r);
    PushUp(idx);
}

inline ll Query(int idx, int l, int r)
{
    if (tree[idx].l >= l && tree[idx].r <= r)
        return tree[idx].w;
    ll sum = 0;
    if (tree[lson].r >= l)
        sum += Query(lson, l, r);
    if (tree[rson].l <= r)
        sum += Query(rson, l, r);
    return sum;
}

int main()
{
    int k = 1;
    while (cin >> n && n != EOF)
    {
        printf("Case #%d:\n", k);
        k++;
        for (int i = 1; i <= n; i++)
            scanf("%lld", &a[i]);
        Build(1, 1, n);
        cin >> m;
        while (m--)
        {
            int op, l, r;
            scanf("%d%d%d", &op, &l, &r);
            if (l > r)
                swap(l, r);
            if (op)
                printf("%lld\n", Query(1, l, r));
            else
                Update(1, l, r);
        }
        printf("\n");
    }
    return 0;
}
上一篇:LG 题解 P4041 [AHOI2014/JSOI2014]奇怪的计算器


下一篇:043、Java中逻辑运算之实现位与操作