(2017多校训练第六场)HDU - 6103 Kirinriki 尺取法

官方题解:

(2017多校训练第六场)HDU - 6103 Kirinriki 尺取法_第1张图片

代码如下:

#include 

using namespace std;
const int N = 5005;
char str[N];
int len;
int ans;
int m;

void solve(int x, int y)
{
    int l = 0, r = 0, sum = 0;
    while (x - r >= 1 && y + r <= len)
    {
        int tmp = abs(str[y + r] - str[x - r]);
        if (sum + tmp <= m)
        {
            sum += tmp;
            r++;
        }
        else
        {
            sum -= abs(str[y + l] - str[x - l]);
            l++;
        }
        ans = max(ans, r - l);
    }
}

int main()
{
    //freopen("test.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int T;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d%s", &m, str + 1);
        len = strlen(str + 1);
        ans = -1;
        for (int i = 1; i <= len; i++)
        {
            solve(i, i + 1); //两个字符串间隔为偶数
            solve(i - 1, i + 1); //两个字符串间隔为奇数
        }
        printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(ACM-其它)