728x90
반응형
GitHub - xhaktmchl/Algorithm_study: 알고리즘 이론 및 문제풀이
알고리즘 이론 및 문제풀이. Contribute to xhaktmchl/Algorithm_study development by creating an account on GitHub.
github.com
#include <iostream>
#include <algorithm>
using namespace std;
/*
[백준 2167 c++ O] 2차원 배열의 합
문제:
접근1: 완탐 -> 시간 초과
접근2: 행 마다 누적합 저장해놓으면 -> 배열의 구간 합 계산 가능
풀이:
//1.입력
//배열
//범위
//2.행 누적합 구하기
//3.각 구간의 배열 합 구하기
//4.출력: 구간 합
*/
int n, m, k,xs,ys,xe,ye;
int a[310][310];
int pSum[310][310];
int calSum() {
//i,j까지 구간합
int sum1 = 0, sum2 = 0;
/*for (int i = 1; i <= y1; i++) {
sum1 += pSum[i][x1] - pSum[i][0];
}*/
//x,y까지 구간합
for (int i = ys; i <= ye; i++) {
sum2 += pSum[i][xe] - pSum[i][xs - 1];
//cout << sum2 << '\n';
}
//두개의 차 + (i,j)원소 합
return sum2;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
//1.입력
//배열
//범위
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
//2.행 누적합 구하기
pSum[i][j] = pSum[i][j - 1] + a[i][j];
}
}
//3.각 구간의 배열 합 구하기
cin >> k;
for (int i = 0; i < k; i++) {
cin >> ys >> xs >> ye >> xe;
//4.출력: 구간 합
cout << calSum() << '\n';
}
}
- 풀이2 :
GitHub - xhaktmchl/Algorithm_study: 알고리즘 이론 및 문제풀이
알고리즘 이론 및 문제풀이. Contribute to xhaktmchl/Algorithm_study development by creating an account on GitHub.
github.com
#include <iostream>
#include <algorithm>
using namespace std;
/*
[백준 2167 c++ OO] 2차원 배열의 합
문제:
접근1: 완탐 -> 시간 초과
접근2: 행 마다 누적합 저장해놓으면 -> 배열의 구간 합 계산 가능
시간복잡도:
풀이:
//1.입력
//배열
//범위
//2.행 누적합 구하기
//3.각 구간의 배열 합 구하기
//4.출력: 구간 합
풀이2:
//pSum =누적합
sum(2,2~4,4) = pSum[4][4] -pSum[4][1] -pSum[1][4] + pSum[1][1]
*/
int n, m, k, xs, ys, xe, ye;
int a[310][310];
int pSum[310][310];
int calSum() {
//i,j까지 구간합
int sum = 0;
//x,y까지 구간합
for (int i = ys; i <= ye; i++) {
sum += pSum[i][xe] - pSum[i][xs - 1];
}
//두개의 차 + (i,j)원소 합
return sum;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
//1.입력
//배열
//범위
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
// 누적합
pSum[i][j] = a[i][j]+ pSum[i][j - 1] + pSum[i - 1][j] - pSum[i - 1][j - 1];
}
}
//3.각 구간의 배열 합 구하기
cin >> k;
for (int i = 0; i < k; i++) {
cin >> ys >> xs >> ye >> xe;
//4.출력: 구간 합
cout << pSum[ye][xe] - pSum[ys-1][xe] - pSum[ye][xs-1] + pSum[ys-1][xs-1] << '\n';
}
}
반응형
'Algorithm_BOJ(백준) > 누적합' 카테고리의 다른 글
[백준 21318 c++ V] 피아노 체조 (0) | 2023.01.06 |
---|---|
[백준 16139 c++ O] 인간-컴퓨터 상호작용 (0) | 2023.01.06 |
[백준 11659 c++ O] 구간 합 구하기 4 (0) | 2023.01.03 |
[백준 14929 c++ V] 귀찮아 (SIB) (0) | 2023.01.03 |