티스토리 뷰
8462번: 배열의 힘
자연수 \(n\)개로 이루어진 배열 \(a_1,a_2,a_3,\dots ,a_n\)이 있다. \(l\)부터 \(r\)까지 부분 배열은 \(a_l,a_{l+1},\dots , a_r\) 이다. \(K_s\)는 부분 배열 안에 있는 자연수 \(s\)의 개수이다. 부분 배열의 힘이란
www.acmicpc.net
백준 소스코드 [C++] 8462 배열의 힘
#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>
typedef long long ll;
using namespace std;
int n, m,sqrtn;
ll arr[100001];
ll cnt[1000001];
ll sum = 0;
void add(ll a) {
sum = sum - cnt[a] * cnt[a] * a;
cnt[a]++;
sum = sum + cnt[a] * cnt[a] * a;
}
void sub(ll a) {
sum = sum - cnt[a] * cnt[a] * a;
cnt[a]--;
sum = sum + cnt[a] * cnt[a] * a;
}
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);
for (int i = 0;i < n;i++)cin >> arr[i];
vector<query> q(m);
vector<ll>res(m);
int x, y;
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] = sum;
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] = sum;
}
for (int i = 0;i < m;i++) cout << res[i] << '\n';
return 0;
}
'백준' 카테고리의 다른 글
백준 소스코드 [C++] 12986 화려한 마을 2 (2) | 2020.12.24 |
---|---|
백준 소스코드 [C++] 12999 화려한 마을 3 (0) | 2020.12.24 |
백준 소스코드 [C++] 13548 수열과 쿼리 6 (0) | 2020.12.23 |
백준 소스코드 [C++] 13547 수열과 쿼리 5 (0) | 2020.12.23 |
백준 소스코드 [C++] 1958 LCS 3 (0) | 2020.12.20 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 최단경로 알고리즘
- WWDC19
- 최대 매칭
- 네트워크 유량
- 최단경로 문제
- observeOn
- WWDC17
- WWDC21
- 다익스트라 시간복잡도
- 코딩대회
- 최단경로문제
- 강한 순환 참조
- State Restoration
- 컴퓨터 추상화
- CompositionalLayout
- 포드 풀커슨 알고리즘
- CPU와 Memory
- mach-o
- test coverage
- IOS
- 벨만포드 시간복잡도
- rxswift
- 벨만포드 알고리즘
- HIG
- 부스트캠프 6기
- 에드몬드 카프 알고리즘
- 네트워크 플로우
- Testable
- WWDC16
- MeTal
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함