[CodeForces Round #784] B. Triple (C++)

2022. 5. 1. 05:43

백준문제풀이 스터디 9주차

CodeForces에서 오랜만에 Div.4 수준 (백준 기준 Gold 1 이하 수준이라고 함) 문제들로 구성된 대화가 개최되었다.

해당 대회 문제를 풀고싶어서 이번 스터디에는 대회 가상 참여 (virtual participation)을 하게 되었다. 혹시 관심 있으면

아래 사이트에서 "start virtual contest"버튼을 눌러 참가해보시죠.

 

간단하게 설명드리자면 채점 방식은 ICPC와 같고, 2시간동안 진행이 된다.

 

https://codeforces.com/contest/1669

 

https://codeforces.com/contest/1669

 

codeforces.com


문제

Given an array aa of nn elements, print any value that appears at least three times or print -1 if there is no such value.

입력

The first line contains an integer tt (1≤t≤10^4) — the number of test cases.

The first line of each test case contains an integer nn (1≤n≤2⋅10^5) — the length of the array.

The second line of each test case contains nn integers a1,a2,…,an (1≤ai≤n) — the elements of the array.

It is guaranteed that the sum of nn over all test cases does not exceed 2⋅10^5.

출력

For each test case, print any value that appears at least three times or print -1 if there is no such value.


풀이 방식

1. 테스트케이스 갯수인 t 입력받기

for문 t 번 반복 {

  2. 테스트케이스의 array 길이 n 입력

  3. n 크기 array 생성하고 0으로 초기화

  for문 n번 반복 {

    4. array 요소인 x 받기

    5. array[x]++

    6. array[x]가 3 이상이 되면 answer에 x값 넣고, flag 1로

  }

  flag 1이면 answer 출력

}


코드

#include <iostream>
using namespace std;

int main()
{
    int t;      // the number of testcases
    int n;      // the length of the array
    cin >> t;

    int flag;
    int x;
    int answer;
    for (int i = 0; i < t; i++) {
        cin >> n;
        flag = 0;
        int * array = new int[n]();
        
        for (int j = 0; j < n; j++) {
            cin >> x;
            array[x-1]++;
            // cout << x << " " << array[x-1] << endl;
            
            if (array[x-1] >= 3) {
                flag = 1;
                answer = x;
            }
        }

        if (flag == 1) {
            cout << answer << endl;
        } else {
            cout << -1 << endl;
        }
        free(array);
    }

    return 0;
}

https://codeforces.com/contest/1669/problem/B

 

https://codeforces.com/contest/1669/problem/B

 

codeforces.com

 

BELATED ARTICLES

more