[백준 11637] 인기 투표 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
각 테스트케이스에서 후보자의 득표 수가 주어졌을 때,
최다 득표자가 과반수인지, 혹은 최다 득표자가 여러 명인지를 판단하는 문제입니다.
출력은 다음 중 하나입니다:
- 한 명이 과반 이상을 득표한 경우:
majority winner 후보번호
- 한 명이 최다 득표를 했지만 과반은 아닌 경우:
minority winner 후보번호
- 최다 득표자가 두 명 이상인 경우:
no winner
접근법
- 각 테스트케이스마다
후보자 수
와투표 수
를 입력받습니다. - 총합과 함께 최다 득표 수를 구하면서 동시에 해당 후보자의 번호를 기록합니다.
- 동일한 득표 수가 여러 번 등장할 경우, 최다 득표자 수를 따로 카운팅하여
no winner
를 판단합니다. - 최종적으로 과반수 여부를 판단해 출력 형식을 결정합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Linq;
class Program {
static void Main() {
int t = int.Parse(Console.ReadLine());
for (int k = 0; k < t; k++) {
int n = int.Parse(Console.ReadLine());
int[] votes = new int[n];
int total = 0, maxVote = 0, maxIndex = -1, countMax = 0;
for (int i = 0; i < n; i++) {
votes[i] = int.Parse(Console.ReadLine());
total += votes[i];
if (votes[i] > maxVote) {
maxVote = votes[i];
maxIndex = i;
countMax = 1;
} else if (votes[i] == maxVote)
countMax++;
}
if (countMax > 1)
Console.WriteLine("no winner");
else
Console.WriteLine((maxVote > total / 2 ? "majority" : "minority") + $" winner {maxIndex + 1}");
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while (t--) {
int n; cin >> n;
vi votes(n);
int total = 0, maxVote = 0, winner = 0, maxCount = 0;
for (int i = 0; i < n; i++) {
cin >> votes[i];
total += votes[i];
if (votes[i] > maxVote) {
maxVote = votes[i];
winner = i + 1;
maxCount = 1;
} else if (votes[i] == maxVote)
maxCount++;
}
if (maxCount > 1) cout << "no winner\n";
else cout << (maxVote > total / 2 ? "majority" : "minority") << " winner " << winner << "\n";
}
return 0;
}