[C++] 백준 1292 - 쉽게 푸는 문제

메르센고수·2023년 8월 11일
0

Baekjoon

목록 보기
12/48
post-thumbnail

문제 - 쉽게 푸는 문제 (Bronze 1)

[백준 1292] https://www.acmicpc.net/problem/1292

풀이 전략

  • vector STL을 이용해서 이중 for문을 통해 index를 vector에 저장하고 A~B까지 for문을 돌려서 내부 원소를 출력
  • Index를 출력하기 때문에 출력하는 for문을 돌릴 때 index-1을 해야함

소스 코드

#include <iostream>
#include <vector>
using namespace std;

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int A,B;
    cin>>A>>B;

    vector<int> V;
    for(int i=1;i<1000;i++){
        for(int j=0;j<i;j++){
           V.push_back(i);
        }
    } // index의 수 만큼 for문을 돌림
    int sum=0;
    for(int i=A-1;i<B;i++){
        sum+=V[i];
    } // index이기 때문에 i=A;i<=B가 아니라 index-1을 해줘야 함
    cout<<sum<<endl;
    return 0;
}

결과

확인

실제로 vector에 문제에서 요구하는 대로 값이 저장되었는지 확인하기 위해 sum 출력문을 주석 처리하고 A부터 B까지 모든 원소를 출력하는 출력문 추가

#include <iostream>
#include <vector>
using namespace std;

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int A,B;
    cin>>A>>B;

    vector<int> V;
    for(int i=1;i<1000;i++){
        for(int j=0;j<i;j++){
           V.push_back(i);
        }
    }
    int sum=0;
    for(int i=A-1;i<B;i++){
        sum+=V[i];
        cout<<V[i]<<" "; // 모든 원소 출력
    }
    // cout<<sum<<endl;
    return 0;
}

결과를 보면 A=1, B=10일 때 값이 제대로 출력되는 것을 확인할 수 있다.

profile
블로그 이전했습니다 (https://phj6724.tistory.com/)

0개의 댓글