This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.
Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly times consecutively. In other words, array a is k-periodic, if it has period of length k.
For example, any array is n-periodic, where n is the array length. Array [2, 1, 2, 1, 2, 1] is at the same time 2-periodic and 6-periodic and array [1, 2, 1, 1, 2, 1, 1, 2, 1] is at the same time 3-periodic and 9-periodic.
For the given array a, consisting only of numbers one and two, find the minimum number of elements to change to make the array k-periodic. If the array already is k-periodic, then the required value equals 0.
The first line of the input contains a pair of integers n, k (1 ≤ k ≤ n ≤ 100), where n is the length of the array and the value n is divisible by k. The second line contains the sequence of elements of the given array a1, a2, ..., an (1 ≤ ai ≤ 2), ai is the i-th element of the array.
Print the minimum number of array elements we need to change to make the array k-periodic. If the array already is k-periodic, then print0.
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int main()
{
int n,k,t;
int i,j,l;
int ans=0;
int a[105];
int b[105]={};
int c[105];
for(i=0;i<105;i++)
{
c[i]=999999999;
}
cin>>n>>k;
t=n/k;
for(i=1;i<=n;i++)
{
cin>>a[i];
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i%k==j%k&&a[i]!=a[j])
{
b[i]++;
}
}
}
for(i=1;i<=n;i++)
{
for(j=0;j<k;j++)
{
if(i%k==j&&b[i]<c[j])
{
c[j]=b[i];
}
}
}
for(i=0;i<k;i++)
{
ans+=c[i];
}
cout<<ans<<endl;
return 0;
}
这种解法比较粗暴,做完比赛后感觉没有用到题目中给到的只有1,2两个元素的条件,思考以后写出了第二个符合提议的较简单解法
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
int n,k,t;
int i,j;
int a[105];
int b[105];
int s,sum;
while(cin>>n>>k)
{
sum=0;
memset(b,0,sizeof(b));
t=n/k;
for(i=1;i<=n;i++)
{
cin>>a[i];
}
for(i=1;i<=n;i++)
{
b[i%k]+=a[i];
}
for(i=0;i<k;i++)
{
if(b[i]-t<2*t-b[i])
{
sum+=b[i]-t;
}
else
{
sum+=2*t-b[i];
}
}
cout<<sum<<endl;
}
return 0;
}