牛客第一场 Different Integers

链接:https://www.nowcoder.com/acm/contest/139/J
来源:牛客网
 

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld

题目描述

Given a sequence of integers a1, a2, ..., an and q pairs of integers (l1, r1), (l2, r2), ..., (lq, rq), find count(l1, r1), count(l2, r2), ..., count(lq, rq) where count(i, j) is the number of different integers among a1, a2, ..., ai, aj, aj + 1, ..., an.

输入描述:

The input consists of several test cases and is terminated by end-of-file.
The first line of each test cases contains two integers n and q.
The second line contains n integers a1, a2, ..., an.
The i-th of the following q lines contains two integers li and ri.

输出描述:

For each test case, print q integers which denote the result.

示例1

输入

复制

3 2
1 2 1
1 2
1 3
4 1
1 2 3 4
1 3

输出

复制

2
1
3

备注:

* 1 ≤ n, q ≤ 105
* 1 ≤ ai ≤ n
* 1 ≤ li, ri ≤ n
* The number of test cases does not exceed 10.

题意:给你一个长度为n的序列和q次询问,问1-l和r-n有多少种不同的数;

思路:在序列后添加原序列,将两个区间转化成一个区间,然后树状数组离线处理(或者线段树or主席树?);

下面附上我的代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
struct node
{
    int l, r;
    int id;
}q[100005];
int last[maxn];
int c[maxn];
int a[maxn];
int lowbit(int x)
{
    return x & (-x);    
}
void add(int x, int v, int n)
{
    for(int i = x; i <= n * 2; i += lowbit(i))
        c[i] += v;
}
int sum(int l)
{
    int ret = 0;
    for(int i = l; i > 0  ;i -= lowbit(i))
    {
        ret += c[i]; 
    }
    return ret;
}
bool cmp(node a, node b)
{
    return a.r < b.r;
}
int ans[100005];
int main()
{
    int n, m;
    while(cin >> n >> m)
    {
    	memset(a, 0, sizeof(a));
        memset(last, -1, sizeof(last));
        memset(c, 0, sizeof(c));
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i]);
            a[i + n] = a[i];
        }
        for(int i = 0; i < m; i++)
        {
            scanf("%d %d", &q[i].l, &q[i].r);
            int t = q[i].l;
            q[i].l = q[i].r;
            q[i].r = t + n;
            q[i].id = i;
        }
        sort(q, q + m, cmp);
        for(int i = 0, j = 1; i < m; i++)
        {
            for(; j <= q[i].r; j++)
            {
                if(~last[a[j]])
                    add(last[a[j]], -1, n);
                add(j, 1, n);
                last[a[j]] = j;
            }
//            for(int k = 1; k <= 2 * n; k++)
//            	printf("%d ", c[k]);
//            puts("");
            ans[q[i].id] = sum(q[i].r) - sum(q[i].l-1);
        }
        for(int i = 0; i < m; i++)
            printf("%d\n", ans[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/gtuif/article/details/81474642