https://www.acmicpc.net/problem/1522
1522번: 문자열 교환
a와 b로만 이루어진 문자열이 주어질 때, a를 모두 연속으로 만들기 위해서 필요한 교환의 회수를 최소로 하는 프로그램을 작성하시오. 이 문자열은 원형이기 때문에, 처음과 끝은 서로 인접해
www.acmicpc.net
생각해보기
- a가 모두 연속이면 되므로 a혹은 b를 기준으로 잡고 기준이 아닌 친구를 스왑하면 된다.
- 슬라이딩 윈도우를 사용하자.
코드
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string input;
void solution(){
cin>>input;
int acnt = count(input.begin(), input.end(), 'a');
int ans = 987'654'321;
for(int i=0;i<input.length();++i){
int cnt = 0;
for(int j=0;j<acnt;++j){
int idx = (i+j)%input.length();
cnt += input[idx] == 'b';
}
ans = min(ans, cnt);
}
cout<<ans<<'\n';
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie();
cout.tie();
solution();
return 0;
}

728x90
'알고리즘 > 백준 문제' 카테고리의 다른 글
| 1138 - 한 줄로 서기 (0) | 2023.07.19 |
|---|---|
| 24042 - 횡단보도 (0) | 2023.07.19 |
| 1911 - 흙길 보수하기 (0) | 2023.07.18 |
| 2098 - 외판원 순회 (0) | 2023.07.18 |
| 2631 - 줄세우기 (0) | 2023.07.17 |
댓글