旋转函数(移位加密)
题目:
给定一个长度为 n 的整数数组A。假设Bk是数组A顺时针旋转k个位置后的数组,我们定义A的“旋转函数”F为:
F(k) = 0 * Bk[0] + 1 * Bk[1] + … + (n-1) * Bk[n-1]。
计算F(0), F(1), …, F(n-1)中的最大值。
示例:
A = [4, 3, 2, 6]
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
所以F(0),F(1),F(2),F(3)中的最大值是F(3) =26。
代码分享:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int a[100];
int i,j,k,x,N,s;
int C[100]={0};
int max=C[0];
int R[100]={0};//定义多个数组作为中间变量
int z[100]={0};
int v[100]={0};
int m[100] = {0};
printf("请输入数组元素个数:\n");
scanf("%d",&N);
printf("请输入数组元素:\n");
for(i=0;i<N;i++)//循环录入
{
scanf("%d",&a[i]);
}
printf("用户录入数组元素个数为:%d\n",N);
printf("用户录入元素如下:\n");
for(i=0;i<N;i++)//循环打印
{
if(i<N)
printf("%d,",a[i]);
else
{
printf("%d",a[i]);
}
}
printf("\n*********************************\n");
for(x=0,i=0;x<N;x++,i++)
{
m[x]=a[i];
}
for(x=0;x<N;x++)//打印新数组值 替代a[i]
{
printf("%d\t",m[x]);
}
printf("\n*********************************\n");
for(i=0;i < N;i++)
{
for(j = 0; j < N; j++)
{
z[j] = m[(i + j) % N];
//printf("%d",z[j]);
}
for(j=0;j<N;j++)//计算
{
v[j] = (j * z[j]);
//v[j]=v[j]+z[j];
R[i] += v[j];
}
/*for(s=0;s<N;s++)
{
printf("\n%d",v[s]);
}*/
printf("\n*%d",R[i]);
if(max<R[i])
{
max=R[i];
}
printf("\n%d",max);
}
printf("\n*********************************\n");
for(j=0;j<N;j++)
{
printf("F(%d)=",j) ; //j*a[N]+j*a[N-1]
for(k=0;k<N;k++)
{
if(k == 0)
{
printf("(%d * %d)",k,a[(k+j)%(N)]);
}
if(k>0 && k<N)
{
printf("+(%d * %d)",k,a[(k+j)%(N)]);
}
}
printf("=%d.",R[j]);
printf("\n");
}
printf("\n*********************************\n");
printf("\n最大值为:%d",max);
return 0;
}
运行结果:
备注:解决本题目时,作者将题目示例的解题过程,打印了出来,在第二张图片****之间显示,但该部分对解决移位加密并无实际用途,只是解题思路的直观体现。
总结:
希望对该题目的代码分享能够帮助到需要的人,也望大佬给出改进意见。