http://codeforces.com/problemset/problem/371/A
一个序列只含有0和1,令循环节的长度为k,要使每k个循环节对应数字都相等,最少要改变几个数字。水题。
#include<stdio.h>
#include<string.h>
int main()
{
int n,k;
int a[110];
while(~scanf("%d %d",&n,&k))
{
int num1;
int num2;
int flag = 1;
int c = 0;
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
for(int i = 1; i <= k; i++)
{
num1 = 0;
num2 = 0;
for(int j = i; j <= n; j += k)
{
if(a[j] == 1)
num1++;
else num2++;
}
if(num1 != 0 && num2 != 0)
{
flag = 0;
if(num1 > num2)
c += num2;
else if(num1 < num2)
c += num1;
else c += num1;
}
}
if(flag)
printf("0\n");
else printf("%d\n",c);
}
return 0;
}
http://codeforces.com/problemset/problem/371/B
有两个数,每次取一个数除以2或3或5(必须能整除),问至少需要几步使这两个数相等。若永远不会相等输出-1,永远相等输出0。
先求出两个数最小公约数,如48和3,最小公约数是4,同除以4得到12和1,再对这两数除以5或3或2直到它们为1。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int gcd(int a, int b)
{
int t;
if(a < b)
{
t = a;
a = b;
b = t;
}
while(b!=0)
{
t = a%b;
a = b;
b = t;
}
return a;
}
int main()
{
int a,b;
int ans;
while(~scanf("%d %d",&a,&b))
{
if(a == b)
{
printf("0\n");
continue;
}
int t = gcd(a,b);
a = a/t;
b = b/t;
ans = 0;
while(a!=1)
{
if(a%3!=0 && a%5!=0 && a%2!=0)
{
ans = -1;
break;
}
if(a%5 == 0)
{
a = a/5;
ans++;
}
else if(a%3 == 0)
{
a = a/3;
ans++;
}
else if(a%2 == 0)
{
a = a/2;
ans++;
}
}
if(ans == -1)
{
printf("-1\n");
continue;
}
while(b!=1)
{
if(b%2!=0 && b%3!=0 && b%5!=0)
{
ans = -1;
break;
}
if(b%5==0)
{
b = b/5;
ans++;
}
else if(b%2==0)
{
b =b/2;
ans++;
}
else if(b%3==0)
{
b = b/3;
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}