이번 문제는 for문을 이중으로 사용하여 풀었다.
#include <iostream>
#define MAX 10001
using namespace std;
int n, m;
int A[MAX];
int cnt=0;
int result=0;
void Input(){
cin>>n>>m;
for(int i=0; i<n; i++){
cin>>A[i];
}
}
void Solution(){
for(int i=0; i<n; i++){
cnt=A[i];
if(A[i]==m){
result++;
}
for(int j=i+1; j<n; j++){
cnt+=A[j];
if(cnt==m){
result++;
}
else if(cnt<m){
continue;
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
Input();
Solution();
cout<<result<<endl;
return 0;
}
문제는 풀었지만 알고리즘 분류에 두 포인터로 명시되어 있었고 두 포인터로 푸는 법도 찾아보았다.
Code
#include <iostream>
#define MAX 10001
using namespace std;
int n, m;
int A[MAX];
int low=0, high=0;
int cnt=0;
int result=0;
void Input(){
cin>>n>>m;
for(int i=0; i<n; i++){
cin>>A[i];
}
}
void Solution(){
while(1){
if(cnt>=m)
cnt-=A[low++];
else if(high==n)
break;
else
cnt+=A[high++];
if(cnt==m)
result++;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
Input();
Solution();
cout<<result<<endl;
return 0;
}
이러한 문제는 두 포인터 알고리즘을 사용하면 시간이 단축된다는 사실을 알 수 있었다.