ACM题解——贪心——奶牛场
题目描述
Farmer John has received a noise complaint from his neighbor, Farmer Bob, stating that his cows are making too much noise.
FJ's N cows (1 <= N <= 10,000) all graze at various locations on a long one-dimensional pasture. The cows are very chatty animals. Every pair of cows simultaneously carries on a conversation (so every cow is simultaneously MOOing at all of the N-1 other cows). When cow i MOOs at cow j, the volume of this MOO must be equal to the distance between i and j, in order for j to be able to hear the MOO at all. Please help FJ compute the total volume of sound being generated by all N*(N-1) simultaneous MOOing sessions.
Input
* Line 1: N
* Lines 2..N+1: The location of each cow (in the range 0..1,000,000,000).
Output
There are five cows at locations 1, 5, 3, 2, and 4.
Sample Input
5 1 5 3 2 4
Sample Output
40
Hint
INPUT DETAILS:
There are five cows at locations 1, 5, 3, 2, and 4.
OUTPUT DETAILS:
Cow at 1 contributes 1+2+3+4=10, cow at 5 contributes 4+3+2+1=10, cow at 3 contributes 2+1+1+2=6, cow at 2 contributes 1+1+2+3=7, and cow at 4 contributes 3+2+1+1=7. The total volume is (10+10+6+7+7) = 40.
题意
给定n个点,求每个点到其他点的距离,将这些距离全部相加得出结果。
题解
拿到题目常规想法就是开双层for循环,外层i:[0-n),内层j:[0-i);,算出距离相加即可,但是观察数据范围是10^4,该算法时间复杂度为O(n²),就是10^8次方,会造成TLE,所以需要优化算法降低时间复杂度。
用一个例子来说明这个巧妙的算法:把一长段距离划分成一段段来计算
1 2 5 8 10
可以发现任一个间隙被加的次数都等于 其前面的元素个数×(总数-前面的元素个数);因此只需遍历一遍,求出sum即可,这个sum要用long long类型。
代码
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main()
{
int n=0;
cin>>n;
long long int* a=new long long int[n];
long long int sum=0;
for(int i=0;i<n;i++)
scanf("%lld",&a[i]);
sort(a,a+n);
for(int i=0;i<n-1;i++)
sum+=(n-i-1)*(i+1)*(a[i+1]-a[i]);
sum=sum*2; //从前往后算的是前面到后面的点的距离,后面点到前面的距离都没算,关系为2倍,所以结果×2
printf("%lld\n",sum);
return 0;
}