Given an array of N integers. Your task is to write a program to find the maximum value of ∑arr[i]*i, where i = 0, 1, 2,…., n – 1.
You are allowed to rearrange the element of the array
Examples:
Input : N = 4, arr[] = { 3, 5, 6, 1 } Output : 31 If we arrange arr[] as { 1, 3, 5, 6 }. Sum of arr[i]*i is 1*0 + 3*1 + 5*2 + 6*3 = 31, which is maximum Input : N = 2, arr[] = { 19, 20 } Output : 20
Note: Since output could be large, hence module 10^9+7 and then print answer.
Input:
First line of the input contains an integer T, denoting the number of test cases. Then T test case follows. First line of each test case contains an integer N, denoting the size of the array. Next line contains N space separated integers denoting the elements of the array.
Output:
For each test case print the required answer on a new line.
Constraints:
1<=T<=103
1<=N<=103
Example:
Input:
2
5
5 3 2 4 1
3
1 2 3
Output:
40
8
下面是我的代码实现:思路:先对数组进行升序排列,然后按着公式即是最大值。我就奇了怪了,我的代码应该是没问题的,在OJ上出现了不可理解的错误:
代码如下:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int num,i;
cin>>num;
for(i=0;i<num;i++)
{
int N,j,k,temp;
long sum=0;
cin>>N;
int *Arr=new int[N];
for(j=0;j<N;j++)
cin>>Arr[j];
for(j=0;j<N;j++)
{
for(k=0;k<N;k++)
{
if(Arr[k]>Arr[k+1])
{
temp=Arr[k];
Arr[k]=Arr[k+1];
Arr[k+1]=temp;
}
}
}
for(j=0;j<N;j++)
sum=sum+j*Arr[j];
cout<<sum<<endl;
}
return 0;
}
然后提交,反馈是:
Wrong Answer. !!!Wrong Answer Possibly your code doesn't work correctly for multiple test-cases (TCs). The first test case where your code failed: Input: 84 87 78 16 94 36 87 93 50 22 63 28 91 60 64 27 41 27 73 37 12 69 68 30 83 31 63 24 68 36 30 3 23 59 70 68 94 57 12 43 30 74 22 20 85 38 99 25 16 71 14 27 92 81 57 74 63 71 97 82 6 26 85 28 37 6 47 30 14 58 25 96 83 46 15 68 35 65 44 51 88 9 77 79 89 Its Correct output is: 237220 And Your Code's output is: 233266
但是我在本地运行的这个例子的答案是:237220
就是不明白为什么在OJ上就是233266,好气哦