Can you answer these queries? 【HDU - 4027】【线段树】【RE的好伤心~】

题目链接


题意:就是给你一串数,让你对一段区间操作,要么是询问,要么是把这段区间的每个点开根号。

比赛看到这道题的时候,我还真高兴呢,终于有线段树了,我推了下,发现前期单点更新就行,后期的时候判断是否为1,也就是此时节点的权值是否等于(r-l+1),于是我兴高采烈的敲完了,并且过了测试样例就交了,想必也应该没什么问题,但是RE了,那时候距离比赛结束还有近一小时,我开始debug,看到是“ACCESS_VIOLATION”,我以为是数组开小了,然后改了数组再交,有RE,然后我在想是不是我线段树哪里写飙了,然后开始疯狂找,疯狂交题,然后看到有人过了这题,然而心态就炸了,再也没想明白哪里的问题。。。

然后比赛结束后,看了下评论,发现是查询区间[l, r]中,题目给的l不一定大于r的,哇!!!心都凉了。。。


果然,我还是题做的太少,线段树的基本坑点都没想到。。。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN=100005;
int N, M;
ll tree[maxN<<2], a[maxN];
void buildTree(int rt, int l, int r)
{
    if(l==r)
    {
        tree[rt]=a[l];
        return;
    }
    int mid=(l+r)>>1;
    buildTree(rt<<1, l, mid);
    buildTree(rt<<1|1, mid+1, r);
    tree[rt] = tree[rt<<1] + tree[rt<<1|1];
}
void update(int rt, int l, int r, int ql, int qr)
{
    if(tree[rt] == (r-l+1)) return;
    if(l==r)
    {
        tree[rt] = (ll)sqrt(tree[rt]);
        return;
    }
    int mid=(l+r)>>1;
    if(ql<=mid) update(rt<<1, l, mid, ql, qr);
    if(qr>mid) update(rt<<1|1, mid+1, r, ql, qr);
    tree[rt] = tree[rt<<1] + tree[rt<<1|1];
}
ll query(int rt, int l, int r, int ql, int qr)
{
    if(tree[rt] == (r-l+1)) return min(r, qr)-max(l, ql)+1;
    if(ql<=l && qr>=r) return tree[rt];
    int mid=(l+r)>>1;
    ll ans=0;
    if(ql>mid) return query(rt<<1|1, mid+1, r, ql, qr);
    else if(qr<=mid) return query(rt<<1, l, mid, ql, qr);
    else
    {
        ans = query(rt<<1, l, mid, ql, qr);
        ans += query(rt<<1|1, mid+1, r, ql, qr);
        return ans;
    }
}
int main()
{
    int Cas=0;
    while(scanf("%d", &N)!=EOF)
    {
        for(int i=1; i<=N; i++) scanf("%lld", &a[i]);
        buildTree(1, 1, N);
        scanf("%d", &M);
        printf("Case #%d:\n", ++Cas);
        while(M--)
        {
            int e1, e2, e3; scanf("%d%d%d", &e1, &e2, &e3);
            if(e2 > e3) swap(e2, e3);
            if(e1)
            {
                printf("%lld\n", query(1, 1, N, e2, e3));
            }
            else
            {
                update(1, 1, N, e2, e3);
            }
        }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41730082/article/details/83477321