GYM-100952-Palindrome Again !!【模拟】

23 篇文章 0 订阅
4 篇文章 0 订阅

这里写图片描述

题目链接:gym-100952-C

题目大意:给出字符串a,将该字符串变成回文串

1.字符串向左边或右边移动一步(0往前移一格为n-1看成环),花费为1
2.当前字母变幻为相邻字母,例如a -> b 或 a -> z, 花费为1

题目思路:模拟

以下是代码:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#include <deque>
#include <list>

using namespace std;
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n, p;
        cin >> n >> p;
        p--;
        string s;
        cin >> s;
        int len = s.size();
        int minpos = 999999, maxpos = 0;
        int ans = 0;
        int flag = 0;
        for (int i = 0, j = len - 1; i < len / 2; i++, j--)
        {
            if (s[i] != s[j])
            {
                int a = min(s[i], s[j]) - 'a';
                int b = max(s[i], s[j]) - 'a';
                ans += min(b - a, a + 26 - b);
                minpos = min(minpos, i);
                maxpos = max(maxpos, i);
                flag = 1;
            }
        }
        if (!flag)  //判断本身是否为回文串
        {
            cout << 0 << endl;
            continue;
        }
        if (len % 2 && p == len / 2)
        {
            ans += abs(p - minpos);
            cout << ans << endl;
            continue;
        }
        if (p >= len / 2)
        {
            p = len - p - 1;  //注意这里是对称,不能直接减len/2
        }
        int a = abs(minpos - p);
        int b = abs(maxpos - p);
        ans += min(a, b);
        ans += maxpos - minpos;
        cout << ans << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值