牛客第一場 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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章