Official

C - Rotate and Palindrome Editorial by en_translator


An important observation to solve this problem is that you may assume that the \(A\)-yen operation is performed several times, then \(B\)-yen operation several times. You may also assume that the \(A\)-yen operation is performed at most \(N\) times (because performing it \(N\) times makes it in the original state).

With this observation, you realize that the small constraints allow us to check all possible numbers of performing the \(A\)-yen operation. The minimum number of performing the \(B\)-yen operation required is found as the number of pairs of characters that should match to make it a palindrome but do not currently match.

Thus, the problem has been solved in a total of \(\mathrm{O}(N^2)\) time.


Sample code (C++):

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    long long a, b;
    string s;
    cin >> n >> a >> b >> s;
    s += s;
    long long ans = 1ll << 60;
    for(int i = 0; i < n; i++) {
        long long tmp = a * i;
        for(int j = 0; j < n / 2; j++) {
            int l = i + j;
            int r = i + n - 1 - j;
            if(s[l] != s[r]) tmp += b;
        }
        ans = min(ans, tmp);
    }
    cout << ans << endl;
}

Sample code (Python):

n, a, b = map(int, input().split())
s = input()
s += s
ans = 1 << 60
for i in range(n):
    tmp = a * i
    for j in range(n // 2):
        if s[i + j] != s[i + n - 1 - j]:
            tmp += b
    ans = min(ans, tmp)
print(ans)

posted:
last update: