Stay Hungry,Stay Foolish!

C - Rotate and Palindrome

C - Rotate and Palindrome

https://atcoder.jp/contests/abc286/tasks/abc286_c

 

思路

从原始字符串开始, rotate第一次, rotate第二次, ... , rotate最后一次

对于每种情况得到的字符串:

判断如果转换成回文,需要替换多少个字符串,

计算每种情况的cost

选取最少的cost

 

Code

long long n, a, b;
string s;
 
int main()
{
    cin >> n >> a >> b;
 
    cin >> s;
    
    // Now try all rotations one by one
    long long cost_min = LLONG_MAX;
    
    int n = s.length();
    for (long long i = -1; i < n - 1; i++) {
//        cout << "i=" << i << endl;
        
        long long costi = 0;
        costi += (i+1) * a;
        
        string str1 = s.substr(i + 1, n - i - 1);
        string str2 = s.substr(0, i + 1);
 
        string rstr = str1.append(str2);
        
//        cout << "rstr=" << rstr << endl;
 
        int diff_count = 0;
        
        // Start from leftmost and rightmost corners of str
        int l = 0;
        int h = rstr.length() - 1;
 
        // Keep comparing characters while they are same
        while (h > l){
            if (rstr[l++] != rstr[h--])
                diff_count ++;
        }
        
//        cout << "diff_count=" << diff_count << endl;
        
        costi += (long long)diff_count * b;
        
        cost_min = min(cost_min, costi);
    }
 
    cout << cost_min << endl;
 
    return 0;
}
 

 

posted @ 2023-01-22 13:38  lightsong  阅读(44)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel