티스토리 뷰

백준

백준 소스코드 [C++] 14413 Poklon

Hani_Levenshtein 2020. 12. 25. 10:05

www.acmicpc.net/problem/14413

 

14413번: Poklon

The output must consist of Q lines, each line containing the answer to a query, respectively.

www.acmicpc.net

백준 소스코드 [C++] 14413 Poklon

#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
#include <vector>
#include <math.h>
#include <stack>
#include <bitset>
#include <string>
#define all(v) v.begin(), v.end()
#define pii pair<int,int>
#define make_unique(v) v.erase(unique(v.begin(), v.end()), v.end())
typedef long long ll;
using namespace std;
int n, m,sqrtn;

int cnt[500001];
int two=0;
void add(int a) {
	if (cnt[a] == 2) two--;
	cnt[a]++;
	if (cnt[a] == 2) two++;
}

void sub(int a) {
	if (cnt[a] == 2) two--;
	cnt[a]--;
	if (cnt[a] == 2) two++;
}

struct query {
	int idx, i, j;
};
bool compare(query& x,query& y) {
	if (x.i / sqrtn != y.i / sqrtn) return x.i / sqrtn < y.i / sqrtn;
	return x.j < y.j;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n>>m;
	sqrtn = (int)sqrt(n);
	vector<int> arr(n);
	vector<int> brr(n);
	for (int i = 0;i < n;i++)cin >> arr[i];
	brr = arr;
	sort(all(brr));
	make_unique(brr);
	for (int i = 0;i < n;i++)arr[i]=lower_bound(all(brr),arr[i])-brr.begin();

	int x, y;
	vector<query> q(m);
	vector<int>res(m);
	for (int a = 0;a < m;a++) {
		cin >> x >> y;
		q[a] = { a,x - 1,y - 1 };
	}

	sort(q.begin(), q.end(), compare);

	int s = q[0].i, e = q[0].j;
	for (int a = s;a <= e;a++) add(arr[a]);
	res[q[0].idx] = two;

	for (int a = 1;a < m;a++) {
		while (q[a].i < s)add(arr[--s]);
		while (q[a].j > e)add(arr[++e]);
		while (q[a].i > s)sub(arr[s++]);
		while (q[a].j < e)sub(arr[e--]);
		res[q[a].idx] = two;
	}
	for (int i = 0;i < m;i++)  cout << res[i] << '\n';

	return 0;
}
댓글