CF1367E Necklace Assembly

题目传送门

思路

提供一种比现有的两篇题解都简单的方法。

我们枚举答案,发现最终的答案数组一定是由多个完全相同的块组成的,并且块长必定是 \(k\) 的因数。

然后我们考虑枚举答案 \(i\),那么此时的块长必然是 \(\gcd(i,k)\),那么可以得到块的数量为 \(\frac{i}{\gcd(i,k)}\),每个字母在每个块中的数量也可以简单地计算出来,为 \(\sum \frac{a_i}{\frac{i}{\gcd(i,k)}}\),最后比较这个值与块长 \(\gcd(i,k)\) 的大小即可。

代码

#include<bits/stdc++.h>
using namespace std;
int const N=2e3+10;
int a[30];
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int t;cin>>t;
    while (t--){
        memset(a,0,sizeof a);
        int n,k;string s;cin>>n>>k>>s;
        s=" "+s;int ans=0;
        for (int i=1;i<=n;++i) ++a[s[i]-'a'];
        for (int i=1;i<=n;++i){
            int len=i/__gcd(i,k),sum=0;
            for (int j=0;j<26;++j) sum+=a[j]/len;
            if (sum>=__gcd(i,k)) ans=max(ans,i);
        }
        cout<<ans<<'\n';
    }
    return 0;
}
posted @ 2022-10-24 15:36  Tx_Lcy  阅读(63)  评论(0)    收藏  举报