백준 문제/DP

[백준] 11659번 구간 합 구하기 4

dubu0721 2025. 2. 16. 15:01

문제: 11659번: 구간 합 구하기 4

basic-algo-lecture/workbook/0x10.md at master · encrypted-def/basic-algo-lecture

 

basic-algo-lecture/workbook/0x10.md at master · encrypted-def/basic-algo-lecture

바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.

github.com

 

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <limits>
//#include <bits/stdc++.h>

using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n, m;
	cin >> n >> m;
	vector<int> table(n);
	cin >> table[0];
	for (int i = 1; i < n; i++) {
		int tmp;
		cin >> tmp;
		table[i] = table[i - 1] + tmp;
	}
	
	while (m-- > 0) {
		int i, j;
		cin >> i >> j;
		i--;
		j--;

		if (i == 0) cout << table[j] << "\n";
		else {
			cout << table[j] - table[i - 1] << "\n";
		}
	}

	return 0;
}

 

처음에 어렵게 생각했는데 그냥 j 까지 합에 i-1 까지의 합을 빼주면 쉽게 해결할 수 있는 문제였다.