๐Ÿ“ Coding Test Study/C++

[10์ฃผ ์™„์„ฑ C++ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ๋ˆ„์ ํ•ฉ, Prefix Sum

ibelieveinme 2023. 8. 11. 01:33
728x90

* ๋ˆ„์ ํ•ฉ: ์–ด๋–ค ๋ฐฐ์—ด์˜ ์•ž ์š”์†Œ๋ถ€ํ„ฐ ๋ˆ„์ ๋œ ํ•ฉ์„ ์ €์žฅํ•œ ๋ฐฐ์—ด.

               ์•ž์—์„œ๋ถ€ํ„ฐ ๋”ํ•˜๋Š” prefix sum๊ณผ ๋’ค์—์„œ ๋ถ€ํ„ฐ ๋”ํ•˜๋Š” suffix sum ์ด ์žˆ๋‹ค.

               ๋ฐฐ์—ด์˜ ๊ฐ’์ด ๋ณ€ํ•˜์ง€ ์•Š๋Š” ์ •์  ๋ณ€์ˆ˜์—๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

* ๋ˆ„์ ํ•ฉ์ด ํ•„์š”ํ•œ ์˜ˆ์‹œ๋ฌธ์ œ

๋ฌธ์ œ
์Šน์ฒ ์ด๋Š” ๋‡Œ๋ฅผ ์žƒ์–ด๋ฒ„๋ ธ๋‹ค. ํ•™๊ต์— ๊ฐ”๋”๋‹ˆ ์„ ์ƒ๋‹˜์ด ์ž์—ฐ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ N๊ฐœ์˜ ์นด๋“œ๋ฅผ ์ฃผ๋ฉฐ M๊ฐœ์˜ ์งˆ๋ฌธ์„ ๋˜์ง„๋‹ค. ๊ทธ ์งˆ๋ฌธ์€ ๋‚˜์—ดํ•œ ์นด๋“œ ์ค‘ A๋ฒˆ์งธ๋ถ€ํ„ฐ B๋ฒˆ์งธ๊นŒ์ง€์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ๋‡Œ๋ฅผ ์žƒ์–ด๋ฒ„๋ ธ๊ธฐ ๋•Œ๋ฌธ์— ์Šน์ฒ ์ด๋Š” ์ด ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜๊ฐ€ ์—†๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•ด๋ณด์ž.

์ž…๋ ฅ
์ˆ˜์˜ ๊ฐœ์ˆ˜N, ํ•ฉ์„ ๊ตฌํ•ด์•ผ ํ•˜๋Š” ํšŸ์ˆ˜ M, ๊ทธ ์ดํ›„ N๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ˆ˜๋Š” 100์ดํ•˜์˜ ์ž์—ฐ์ˆ˜. ๊ทธ ์ดํ›„ M๊ฐœ์˜ ์ค„์—๋Š” ํ•ฉ์„ ๊ตฌํ•ด์•ผ ํ•˜๋Š” ๊ตฌ๊ฐ„ A, B๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

์ถœ๋ ฅ
M๊ฐœ์˜ ์ค„์— A๋ถ€ํ„ฐ B๊นŒ์ง€์˜ ํ•ฉ์„ ๊ตฌํ•˜๋ผ.

๋ฒ”์œ„
1 <= N <= 100,000
1 <= M <= 100,000
1 <= A <= B <= N

์˜ˆ์ œ์ž…๋ ฅ
8 3
1 2 3 4 5 6 7 8
1 4
1 5
3 5

์˜ˆ์ œ์ถœ๋ ฅ
10
15
12

์œ„ ๋ฌธ์ œ๋ฅผ ๋‹จ์ˆœ 2์ค‘ for๋ฌธ์œผ๋กœ ํ’€๋ฉด ๋ฌธ์ œ์˜ ์ตœ๋Œ€ ๋ฒ”์œ„ 100,000 * 100,000 ๋ฒˆ์œผ๋กœ 10,000,000,000๋ฒˆ(100์–ต๋ฒˆ) ์˜ ์ˆ˜๊ฐ€ ๋‚˜์™€์„œ ์‹œ๊ฐ„๋ณต์žก๋„์˜ ๋ฒ”์œ„๋ฅผ ๋„˜์–ด์„ ๋‹ค.

 

๋”ฐ๋ผ์„œ ๋‹ค๋ฅธ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ƒ๊ฐํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค. ์ด๋ ‡๊ฒŒ ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง€๊ณ  ๊ทธ ๋ฐฐ์—ด์˜ ์—ฐ์†๋œ ํ•ฉ์„ ๋ˆ„์ ํ•ด์„œ ๊ฐ–๊ณ  ์žˆ๋Š” ํ˜•ํƒœ๊ฐ€ ํ•„์š”ํ•  ๋•Œ '๋ˆ„์ ํ•ฉ' ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•œ๋‹ค.

 

//๊ทธ๋ƒฅ 2์ค‘ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ํ’€์—ˆ์„ ๋•Œ

#include <iostream>
#include <vector>
using namespace std;

int main() {
	int n, m, a, b;
	cin >> n >> m;

	vector<int> v(n+1);
	for (int i = 1; i <= n; i++){
		cin >> v[i];
	}

	for (int i = 0; i < m; i++) {
		int sum = 0;
		cin >> a >> b;
		for (int j = a; j <= b; j++) {
			sum += v[j];
		}
		cout << sum << '\n';
	}
	return 0;
}

 

//๋ˆ„์ ํ•ฉ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•œ ๊ฒฝ์šฐ

#include <iostream>
#include <vector>
using namespace std;

int main() {
	int n, m, a, b;
	cin >> n >> m;

	vector<int> v(n+1);
	for (int i = 1; i <= n; i++){
		cin >> v[i];
		v[i] += v[i - 1];
	}

	for (int i = 0; i < m; i++) {
		cin >> a >> b;
		cout << v[b] - v[a - 1] << '\n';
	}
	return 0;
}

 

 

๋ˆ„์ ํ•ฉ์„ ์ด์šฉํ•˜๋ฉด ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(n)์œผ๋กœ ์ค„์–ด๋“ ๋‹ค.

 

728x90