跳到正文

题解

题解:CF1624D Palindromes Coloring

LQR16421948约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年11月16日
收录
2026年11月16日
更新
2026年11月16日
篇幅
约 2 分钟
获赞
1
题目
CF1624D

版本

  1. v1当前

思路

  1. 因为回文串越长越难构造出具有单调性,所以可以二分二分答案。
  2. 通过回文串的特性发现一个长度为奇数的回文串一定是若干个相同的字符在加一个字符。而一个长度为偶数的回文串一定是若干个相同的字符。
  3. 定义 xx 表示回文串的串的长度,cnt\mathrm{cnt} 表示一对相同字符的个数,cntt\mathrm{cntt} 表示还剩下的数字个数。
  4. 长度为偶数是如果 cnt≥x2×k\mathrm{cnt}\ge \frac{x}{2}\times k 就返回 11 表示可以 否则不行,否则返回 00 表示不行。
  5. 长度为奇数是如果 cnt≥⌊x2⌋×k\mathrm{cnt}\ge \left\lfloor\frac{x}{2}\right\rfloor\times k 并且 cntt≥k−cnt\mathrm{cntt}\ge k-\mathrm{cnt} 就返回 11 表示可以,否则返回 00 表示不行。

代码

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5;
int n,k;
string s;
int check(int x){
	map<char,int>mp;
	if(x==1) return 1;
    int cnt=0,cntt=0;
    for(int i=1;i<=n;i++) mp[s[i]]++;
    for(int i=1;i<=n;i++){
    	if(mp[s[i]]>=2) cnt++,mp[s[i]]-=2;
    	if(mp[s[i]]==1) cntt++;
	}
    if(x%2==0){
    	if(cnt>=x/2*k) return 1;
    	return 0;
	}else if(x%2==1){
		if(cnt>=(x/2)*k&&cntt>=k-cnt) return 1;
		return 0;
	}
}
void solve(){
    cin>>n>>k>>s;
    sort(s.begin(),s.end());
    s=' '+s;
    int l=0,r=n/k+1;
    while(l+1<r){
        int mid=l+r>>1;
        if(check(mid)) l=mid;
        else r=mid;
    }
    cout<<l<<'\n';
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int T;
    cin>>T;
    while(T--) solve();
    return 0;
}
原文