fragment-header
fragment-markdown
홈
로그인
로그아웃
내 블로그
설정
로그인
AtCoder Beginner Contest 421-C (C++) Alternated
최초 업로드: 2025-08-30 14:24:37
최근 수정 시간: 2025-08-30 14:24:52
게시자: rlatjwls3333
카테고리: Atcoder
조회수: 4
# C - Alternated [문제 링크](https://atcoder.jp/contests/abc421/tasks/abc421_c) ## Problem Statement You are given a string \$S\$ of length \$2N\$. \$S\$ contains exactly \$N\$ occurrences of `A` and \$N\$ occurrences of `B`. Find the minimum number of operations (possibly zero) needed to make \$S\$ have no adjacent identical characters, where an operation consists of swapping two adjacent characters in \$S\$. ## Constraints * \$1 \le N \le 5 \times 10^5\$ * \$N\$ is an integer. * \$S\$ is a string of length \$2N\$ consisting of \$N\$ occurrences of `A` and \$N\$ occurrences of `B`. ## Input The input is given from Standard Input in the following format: $N$ $S$ ## Output Print the answer. ## 풀이 A를 짝수번째에 차례대로 매핑했을 때의 비용, 홀수번째에 차례대로 매핑했을 때의 비용 중 최소를 출력하면 된다. ``` c++ #include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; string s; cin >> n >> s; ll evenCost=0, oddCost=0; ll cnt=0; for(int i=0;i<n*2;i++) { if(s[i]=='A') { evenCost += abs(cnt*2-i); oddCost += abs(cnt*2+1-i); cnt++; } } cout << min(evenCost, oddCost); } ```