[백준 30156] Malvika is peculiar about color of balloons (C#, C++) - soo:bak
작성일 :
문제 링크
30156번 - Malvika is peculiar about color of balloons
설명
두 가지 색의 풍선이 있을 때, 모든 풍선을 한 색으로 통일하기 위해 뒤집어야 할 최소 개수를 구하는 문제입니다.
접근법
모든 풍선을 한 색으로 만들려면, 한 쪽 색을 전부 다른 색으로 바꿔야 합니다.
a를 모두 b로 바꾸면 a의 개수만큼, b를 모두 a로 바꾸면 b의 개수만큼 뒤집어야 합니다. 따라서 두 개수 중 더 작은 값이 답입니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
class Program {
static void Main() {
var t = int.Parse(Console.ReadLine()!);
for (var tc = 0; tc < t; tc++) {
var s = Console.ReadLine()!;
var cntA = 0;
var cntB = 0;
foreach (var c in s) {
if (c == 'a') cntA++;
else if (c == 'b') cntB++;
}
Console.WriteLine(Math.Min(cntA, cntB));
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while (t--) {
string s; cin >> s;
int cntA = 0, cntB = 0;
for (char c : s) {
if (c == 'a') cntA++;
else if (c == 'b') cntB++;
}
cout << min(cntA, cntB) << "\n";
}
return 0;
}