백준13546 수열과 쿼리4

문제 링크

  • http://icpc.me/13546

사용 알고리즘

  • 모스 알고리즘
  • 평방 분할

풀이

수열 A의 값은 모두 1 이상 k이하입니다.
모스 알고리즘을 돌리면서 값이 K인 인덱스를 K개의 deque(혹은 list)로 관리해주고, deque를 monotone하게 유지해주면서 문제를 풉니다.
deque를 monotone하게 유지해준다면, 각 숫자마다 |x-y|의 max는 |back - front|로 쉽게 구할 수 있습니다.
그러나 모든 K개의 덱 중에서 |back - front|의 최댓값을 구할 방법은 쉽게 떠오르지 않습니다.

K개의 덱에서 뽑아낸 |back - front|의 값들에 대해서 sqrt decomposition을 해줄겁니다.
덱에 삽입/삭제 연산을 하면 |back - front|의 값이 변하게 됩니다. 기존 |back - front|를 prv, 삽입/삭제 연산으로 인해 새로 바뀐 |back - front|를 now라고 합시다.
prv가 등장한 횟수가 1 감소하고, now가 등장한 횟수가 1 증가합니다.
등장할 수 있는 횟수는 0~N이므로, 0~N을 sqrt(N)개의 버킷으로 분할했다면, prv/now의 등장횟수가 1씩 변하는 것은 단순한 update이기 때문에 O(1)만에 할 수 있습니다.

최댓값을 구하는 것은 제일 뒤에있는 버킷부터 하나씩 보면서, 0보다 큰 값이 있는 버킷 하나만 뒤져보면 sqrt(N)만에 구할 수 있습니다.

전체 코드

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
#include <bits/stdc++.h>
using namespace std;

const int sq = 300;
const int sz = 101010/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[101010];
Query qry[101010];

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

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];
	cin >> q;
	for(int i=0; i<q; i++){
		cin >> qry[i].s >> qry[i].e; qry[i].x = i;
	}
	sort(qry, qry+q);

	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";
}