Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 다이나믹프로그래밍
- 우선순위큐
- int
- priority_queue
- 유클리드호제법
- 오블완
- vector
- C++
- 분할정복
- 배열
- 티스토리챌린지
- 에라토스테네스의 체
- 최소공배수
- Set
- stoi
- BFS
- 그래프
- N과M
- 정렬
- 문자열
- Sort
- DP
- DFS
- 깊이우선탐색
- 프로그래머스
- 백트래킹
- 알고리즘
- 백준
- 이분탐색
- map
Archives
- Today
- Total
안녕 세상아,
[c++/백준] 11659 구간 합 구하기 4 본문
https://www.acmicpc.net/problem/11659
11659번: 구간 합 구하기 4
첫째 줄에 수의 개수 N과 합을 구해야 하는 횟수 M이 주어진다. 둘째 줄에는 N개의 수가 주어진다. 수는 1,000보다 작거나 같은 자연수이다. 셋째 줄부터 M개의 줄에는 합을 구해야 하는 구간 i와 j
www.acmicpc.net
그냥 쉽게 생각해서 2중 for문 사용했는데 역시나 시간초과로 틀림 ㅎㅎ;;
<시간초과 된 코드> 틀리는게 당연함 입력값 최대가 N, M 둘다 100,000임
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
vector<int> v;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v.push_back(x);
}
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
long long int sum = 0;
for (int i = a-1; i < b; i++) {
sum = sum + v[i];
}
cout << sum << '\n';
}
}
<맞는 답>
dp를 사용해서 풀면 시간초과 되지 않고 풀린다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
int* arr = new int[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int* sum = new int[n + 1];
sum[0] = 0;
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1] + arr[i - 1];
}
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
int ans = sum[b] - sum[a - 1];
cout << ans << '\n';
}
}
이중 for문을 사용해서 풀지 않는게 핵심인 것 같다. 또한
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
이것들도 잊지않고 넣어주기!
'백준' 카테고리의 다른 글
[c++/백준] 15651 N과 M (3) (1) | 2023.05.10 |
---|---|
[c++/백준] 1021 회전하는 큐 (0) | 2023.05.09 |
[c++/백준] 2108 통계학 (1) | 2023.05.08 |
[c++/백준] 14501 퇴사 (0) | 2023.05.08 |
[c++/백준] 15650 N과 M(2) (0) | 2023.05.08 |