티스토리 뷰
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const int MAX_N = 100010;
int sqrtN;
struct Query {
int idx, s, e;
bool operator < (Query &x) {
if (s / sqrtN != x.s / sqrtN) return s / sqrtN < x.s / sqrtN;
return e < x.e;
}
};
vector<Query> query;
int arr[MAX_N], cnt[MAX_N*10];
LL ret = 0, ans[MAX_N];
void add(int x)
{
ret += (LL)(2 * ++cnt[x] - 1)*x;
}
void sub(int x)
{
ret -= (LL)(2 * --cnt[x] + 1)*x;
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
int n, q;
cin >> n; sqrtN = (int)sqrt(n);
cin >> q;
for (int i = 1; i <= n; i++) cin >> arr[i];
for (int i = 0; i < q; i++) {
int s, e; cin >> s >> e;
query.push_back({ i,s,e });
}
sort(query.begin(), query.end());
int s = 0, e = 0;
for (int i = 0; i < q; i++) {
while (s < query[i].s) sub(arr[s++]);
while (s > query[i].s) add(arr[--s]);
while (e < query[i].e) add(arr[++e]);
while (e > query[i].e) sub(arr[e--]);
ans[query[i].idx] = ret;
}
for (int i = 0; i < q; i++)
cout << ans[i] << "\n";
return 0;
}
모스 알고리즘(MO's algorithm) 공부하다 푼 문제중 인상깊었다.
'백준 문제풀이' 카테고리의 다른 글
백준[baekjoon] 11333 (0) | 2021.02.11 |
---|---|
백준[baekjoon] 8201 (0) | 2020.07.17 |
백준[baekjoon] 14728 (0) | 2020.05.02 |
백준[baekjoon] 12865 (0) | 2020.04.20 |
백준[baekjoon] 10165 (0) | 2020.02.26 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- ICPC 후기
- 백준
- 정보올림피아드
- 초등부
- tetris
- unreal enigne
- C++게임개발
- 언리얼 프로젝트 재생성 자동화
- 백준 2365
- opengl
- OpenVDB
- 홍정모의 게임 만들기 연습 문제 패키지
- Unreal Engine
- Codeforces
- 언리얼 프로젝트 재생성
- C++게임
- 브레젠험 알고리즘
- 숫자판 만들기
- pygame
- 코드포스
- BOJ 27469
- DP
- UE5.3
- 퀸 움직이기
- BOJ 2365
- 테트리스
- 언리얼 자동화
- ndisplay
- 백준 27469
- Python
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함