HDU 5583 Kingdom of Black and White 暴力

本文介绍了一种通过改变字符串中最多一个字符来最大化特定数值的算法。该数值定义为字符串中连续相同字符出现次数平方和。文章详细阐述了枚举转折点的方法,并提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

改最多一个位置,使得值最大。值是 连续相同数字个数的平方和

思路:

枚举转折点

#include<cstdio>
#include<algorithm>
#include<string>
#include<iostream>
#include<cstring>
using namespace std;

typedef long long ll;
const int N = 1e5 + 5;
string s;
ll a[N], tot, ans, cnt, cal;

ll get(ll k){
    return k * k;
}

int main(){
    ios::sync_with_stdio(0);
    int T;
    cin >> T;
    for(int kase = 1; kase <= T; kase++){
        cin >> s;
        cnt = 1; 
        memset(a, 0, sizeof(a));
        tot = cal = 0;
        int len = s.length();
        for(int i = 0; i < len; i++){
            if(i + 1 == len || s[i] != s[i + 1]){
                a[++tot] = cnt;
                cal += cnt * cnt;
                cnt = 1;
            }else cnt++;
        }    
        ans = cal;
        for(int i = 1; i < tot; i++) {
            if(a[i] == 1) {
                ans = max(ans, cal - get(a[i - 1]) - get(a[i + 1]) - 1 + get(a[i - 1] + a[i + 1] + 1));
            }else {
                if(a[i + 1] != 1 || i == tot - 1) {
                    ans = max(ans, cal - get(a[i]) - get(a[i + 1]) + get(a[i] + 1) + get(a[i + 1] - 1));
                }
                ans = max(ans, cal - get(a[i]) - get(a[i + 1]) + get(a[i] - 1) + get(a[i + 1] + 1));
            }
        }
        printf("Case #%d: %lld\n", kase, ans);
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值