[BOJ/C+]2003番号の和2


この問題には2つのfor文が使われています.
  • の連続した値を増加し続け、cntがmに等しい場合、結果を増加させる.
  • cntがmより小さい場合、繰り返しが続く.
  • Code

    #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;
    }
    解題したが,アルゴリズム分類では2つのポインタとして明確に規定されており,2つのポインタで解題する方法も調べた.
  • low、highは2つのポインタを設定します.
  • cntの大きさに合わせてlow,highの位置を調整します.
  • highがnより大きい場合、while文は終了する.
  • while文では、cntがmより大きい場合、lowが指す値を削除し、highが指す値を追加します.
  • 簡単に言えば、低く減らして、高くします.
  • 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;
    }

    これらの問題は,2つのポインタアルゴリズムを用いることで時間を短縮できることを示している.