[BOJ][C++] λ°±μ€ 2003λ²: μλ€μ ν© 2
https://www.acmicpc.net/problem/2003
2003λ²: μλ€μ ν© 2
첫째 μ€μ N(1 ≤ N ≤ 10,000), M(1 ≤ M ≤ 300,000,000)μ΄ μ£Όμ΄μ§λ€. λ€μ μ€μλ A[1], A[2], …, A[N]μ΄ κ³΅λ°±μΌλ‘ λΆλ¦¬λμ΄ μ£Όμ΄μ§λ€. κ°κ°μ A[x]λ 30,000μ λμ§ μλ μμ°μμ΄λ€.
www.acmicpc.net
λ¬Έμ
Nκ°μ μλ‘ λ μμ΄ A[1], A[2], …, A[N] μ΄ μλ€. μ΄ μμ΄μ iλ²μ§Έ μλΆν° jλ²μ§Έ μκΉμ§μ ν© A[i] + A[i+1] + … + A[j-1] + A[j]κ° Mμ΄ λλ κ²½μ°μ μλ₯Ό ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€.
μ λ ₯
첫째 μ€μ N(1 ≤ N ≤ 10,000), M(1 ≤ M ≤ 300,000,000)μ΄ μ£Όμ΄μ§λ€. λ€μ μ€μλ A[1], A[2], …, A[N]μ΄ κ³΅λ°±μΌλ‘ λΆλ¦¬λμ΄ μ£Όμ΄μ§λ€. κ°κ°μ A[x]λ 30,000μ λμ§ μλ μμ°μμ΄λ€.
μΆλ ₯
첫째 μ€μ κ²½μ°μ μλ₯Ό μΆλ ₯νλ€.
νμ΄
ν¬ν¬μΈν° μ΄μ©
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> v(n);
for(int i=0; i<n; i++) {
cin >> v[i];
}
int ans=0;
int tmp = v[0];
for(int start=0, end=0; end<n;) {
while(tmp>m && start<end) {
tmp -= v[start];
start++;
}
if(tmp==m) {
ans++;
}
end++;
tmp += v[end];
}
cout << ans;
return 0;
}
λΆλΆν© μ΄μ©
// νμ΄ : https://whkakrkr.tistory.com
#include <bits/stdc++.h>
using namespace std;
int solution(int n, int m, vector<int>&a) {
vector<int>prefix(n+1, 0);
for(int i=1; i<=n; i++) {
prefix[i] = prefix[i-1] + a[i-1];
}
int ans = 0;
for(int right=n; right>0; right--) {
for(int left=0; left<right; left++) {
if(prefix[right] - prefix[left] == m) {
ans++;
break;
}
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
int n,m;
cin >> n >> m;
vector<int>a(n);
for(int i=0; i<n; i++) {
cin >> a[i];
}
cout << solution(n,m,a);
return 0;
}