hdu 3333 Turing Tree


按右端点排序

#include <cstdio>
#include <map>
#include <cstring>
using namespace std;
const int MAXN = 50010;
const int MAXM = 200000 + 123;
struct Edge
{
    int id, next, v;
}edge[MAXM];
int head[MAXN];
long long tree[MAXN];
long long ans[MAXM];
int a[MAXN];
int n, m;
int cnt;
map<int, int> q;
void addedge(int u, int v, int id)
{
    edge[cnt].v = v;
    edge[cnt].id = id;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
void init()
{
    cnt = 0;
    memset(head, -1, sizeof(head));

    scanf("%d", &n);
    for(int i = 1; i <= n; i++)  scanf("%d", &a[i]);

    scanf("%d", &m);
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        addedge(y, x, i);
    }

    memset(tree, 0, sizeof(tree));
    q.clear();
}

inline int lowbit(int x)
{
    return x&(-x);
}

void update(int x, int c)
{
    for(int i = x; i <= n; i+=lowbit(i))
    tree[i] += c;
}

long long getsum(int x)
{
    long long sum = 0;
    for(int i = x; i >= 1; i -= lowbit(i))
    sum += tree[i];
    return sum;
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        init();
        long long sum = 0;
        for(int i = 1; i <= n; i++)
        {
            if(q.find(a[i]) != q.end()) update(q[a[i]], -a[i]);
            else sum += a[i];

            update(i, a[i]);
            q[a[i]] = i;

            for(int p = head[i]; p != -1; p = edge[p].next)
            {
               // printf("v==%d\n",edge[p].v);
                ans[edge[p].id] = sum - getsum(edge[p].v - 1) ;
            }
        }
        for(int i = 1; i <= m; i++)  printf("%I64d\n", ans[i]);
    }
    return 0;
}


你可能感兴趣的:(hdu 3333 Turing Tree)