一个长度为n的数组a[0],a[1],...,a[n-1]。现在更新数组的名个元素,即a[0]变为a[1]到a[n-1]的积
a[1]变为a[0]和a[2]到a[n-1]的积,...,a[n-1]为a[0]到a[n-2]的积。
程序要求:
要求具有线性复杂度。
不能使用除法运算符。
算法思想:
设共有N个数(N=7), 建立一个数组backToFront,从数组最后开始分别保存a[6], a[6]*a[5], a[6]*a[5]*a[4],.......a[6]*a[5]*a[4]*a[3]*a[2]*a[1].
然后再设一个变量 frontToBack用来保存,从前到后的乘积.
#include <iostream>
using namespace std;
void print(long a[], int len)
{
int i;
for (i = 0; i < len; i++)
cout << a[i] << " ";
cout << endl;
}
void change(long a[], int len)
{
long *backToFront = new long(len);
long frontToBack;
int i;
backToFront[len - 1] = 1;
for(i = len - 2; i >= 0; i--)
backToFront[i] = backToFront[i + 1] * a[i + 1];
frontToBack = 1;
for(i = 0; i < len; i++)
{
int tmp;
tmp = a[i];
a[i] = frontToBack * backToFront[i];
frontToBack *= tmp;
}
delete [] backToFront;
}
int main()
{
long a[MAX];
int i;
for (i = 0; i < MAX; i++)
a[i] = i + 1;
print(a, MAX);
change(a, MAX);
print(a, MAX);
system("PAUSE");
return 0;
}
using namespace std;
void print(long a[], int len)
{
int i;
for (i = 0; i < len; i++)
cout << a[i] << " ";
cout << endl;
}
void change(long a[], int len)
{
long *backToFront = new long(len);
long frontToBack;
int i;
backToFront[len - 1] = 1;
for(i = len - 2; i >= 0; i--)
backToFront[i] = backToFront[i + 1] * a[i + 1];
frontToBack = 1;
for(i = 0; i < len; i++)
{
int tmp;
tmp = a[i];
a[i] = frontToBack * backToFront[i];
frontToBack *= tmp;
}
delete [] backToFront;
}
int main()
{
long a[MAX];
int i;
for (i = 0; i < MAX; i++)
a[i] = i + 1;
print(a, MAX);
change(a, MAX);
print(a, MAX);
system("PAUSE");
return 0;
}