首先我们来判断无法修改成 次重复字符串的情况,只要给的字符串的长度除以 有余数,就说明这个字符串肯定不能重复 次,输出 -1。
然后我们统计每一段字符串中出现的最多的字母,最后答案加上 每一段字符串中出现的最多的字母的数量。因为我们肯定是改少的而不是改多的。
#include <bits/stdc++.h>
#define int long long
using namespace std;
map <int , int> cnt;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int k;
string s;
cin >> k >> s;
int lens = s.size();
if (lens % k != 0) // 判断能不能改为k次重复字符串
{
cout << -1;
return 0;
}
if (k == 1)
{
cout << 0;
return 0;
}
int ans = 0;
int ping = lens / k;
for (int i = 0; i < ping; i++)
{
for (int j = i; j < lens; j += ping)
{
cnt[s[j]]++; // 统计当前字母的出现次数
}
int maxn = 0;
for (int j = 'a'; j <= 'z'; j++)
{
maxn = max(maxn , cnt[j]); // 找出最多的出现次数
cnt[j] = 0;
}
ans += k - maxn; // 统计需要修改多少个字母
}
cout << ans;
return 0;
}我们可以来找找规律……找规律的过程不给了哈
通过我们找的规律可以知道,其实我们要求的第 项,其实就是把 转换为 进制。
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int k , n;
cin >> k >> n;
int ans = 0 , cnt = 1;
while (n != 0)
{
int x = n % 2; // 先转换为2进制
n = n / 2;
if (x == 1)
{
ans += cnt; // 转换为k进制
}
cnt *= k;
}
cout << ans;
return 0;
}模拟题。。。
我们从0开始枚举,一直枚举到 ,然后一一判断满不满足题目给的要求。
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5 + 5;
int get(int x , int j)
{
int p = pow(10 , j);
return x / p % 10;
}
bool check(int x , int y)
{
if (x == y)
return 1;
else if (x == 0 && y == 9)
return 1;
else if (x == 9 && y == 0)
return 1;
else if (abs(x - y) <= 1)
return 1;
return 0;
}
signed main()
{
int n , a , k;
cin >> n >> a >> k;
for (int i = 0; i <= pow(10 , n) - 1; i++) // 枚举
{
int cnt = 0;
bool flag = 0;
for (int j = 0; j < n; j++)
{
int t1 = get(a , j) , t2 = get(i , j); //
if (t1 == t2)
continue;
else if(check(t1 , t2) == 1)
cnt++;
else
{
flag = 1;
break;
}
}
if (flag == 1)
continue;
if (cnt <= k)
cout << i << "\n";
}
return 0;
}我们先使用二维前缀和,然后使用双指针……
#include<bits/stdc++.h>
using namespace std;
const int N=505;
#define int long long
int a[N][N],s[N][N],b[N];
signed main()
{
int n , m , k;
cin >> n >> m >> k;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> a[i];
}
}
for (int j = 1; j <= m; j++)
{
for (int i = 1; i <= n; i++)
{
s[i][j] = s[i - 1][j] + a[i][j]; // 计算二维前缀和
}
}
int ans = 0;
for (int x = 1; x <= n; x++)
{
for (int y = x; y <= n; y++)
{
for (int j = 1; j <= m; j++)
{
b[j] = s[y][j] - s[x - 1][j];
}
int l = 1 , r = 1 , sum = b[1];
while (r <= m) // 双指针
{
while (sum <= k && r <= m)
{
ans += r - l + 1;
r++;
sum += b[r];
}
while (sum > k && l <= r)
{
sum -= b[l];
l++;
}
}
}
}
cout << ans;
return 0;
}