백준13550 수열과 쿼리7

문제 링크

  • http://icpc.me/13550

사용 알고리즘

  • Mo’s Algorithm
  • Sqrt Decomposition
  • Prefix Sum

풀이

수열과 쿼리0(풀이)에서 누적합을 구할 때 mod K를 취해주면 똑같은 코드로 풀리게 됩니다.

전체 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <bits/stdc++.h>
using namespace std;

const int sq = 400;
const int sz = 1010101/sq + 10;

struct Query{
	int s, e, x;
	Query(){}
	Query(int s, int e, int x) : s(s), e(e), x(x) {}
	bool operator < (const Query &t) const {
		if(s/sq != t.s/sq) return s < t.s;
		return e < t.e;
	}
};

int n, k, q;
int arr[1010101];
vector<Query> qry;

list<int> pos[1010101];
int cnt[1010101], bucket[sz];
int ans[1010101];

void Plus(int x, int dir){
	int now = 0;
	auto &dq = pos[arr[x]];
	if(!dq.empty()){
		now = dq.back() - dq.front();
		cnt[now]--;
		bucket[now/sq]--;
	}
	if(!dir) dq.push_front(x);
	else dq.push_back(x);
	now = dq.back() - dq.front();
	cnt[now]++; bucket[now/sq]++;
}

void Minus(int x, int dir){
	auto &dq = pos[arr[x]];
	int now = dq.back() - dq.front();
	cnt[now]--; bucket[now/sq]--;
	if(!dir) dq.pop_front();
	else dq.pop_back();
	if(!dq.empty()){
		now = dq.back() - dq.front();
		cnt[now]++; bucket[now/sq]++;
	}
}

int query(){
	for(int i=sz-1; i>=0; i--){
		if(bucket[i] == 0) continue;
		for(int j=sq-1; j>=0; j--){
			if(cnt[i*sq+j] > 0){
				return i*sq+j;
			}
		}
	}
	return 0;
}

int main(){
	ios_base::sync_with_stdio(0); cin.tie(0);
	cin >> n >> k;
	for(int i=1; i<=n; i++) cin >> arr[i];
	for(int i=1; i<=n; i++){
		arr[i] += arr[i-1];
		arr[i] %= k;
		arr[i] += k;
		arr[i] %= k;
	}
	cin >> q;
	for(int i=0; i<q; i++){
		int s, e; cin >> s >> e;
		qry.push_back({s-1, e, i});
	}
	sort(qry.begin(), qry.end());

	int s = qry[0].s, e = qry[0].e, x = qry[0].x;
	for(int i=s; i<=e; i++){
		Plus(i, 1);
	}
	ans[x] = query();

	for(int i=1; i<q; i++){
		x = qry[i].x;
		while(qry[i].s < s) Plus(--s, 0);
		while(e < qry[i].e) Plus(++e, 1);
		while(s < qry[i].s) Minus(s++, 0);
		while(qry[i].e < e) Minus(e--, 1);
		ans[x] = query();
	}

	for(int i=0; i<q; i++) cout << ans[i] << "\n";
}