Moo Volume
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 22151 | Accepted: 6712 |
Description
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.
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).
* 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:
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.
看了这个题目,开始不明白什么意思,后来看了HINT的解释才明白。简单点,就是求n个数两两之差的和,第一想到的是暴力法解,但又怕10000*10000=10^8会超时,压界(希望北大的服务器厉害)。下面是我的代码
#include <stdio.h>
#include <stdlib.h>
#define MAX 10100
int main ()
{
int n;
long long num[MAX];
long long sum = 0;
scanf ("%d", &n);
for (int i = 1; i <= n; i++)
scanf ("%lld", &num[i]);
for (int i = 1; i < n; i++)
for (int j = i + 1; j <= n; j++)
sum += abs(num[i] - num[j]);
printf ("%lld\n", sum * 2);
return 0;
}
就这样AC了,就这样AC了,就这样AC了!!但老师把这一题归在了递推题里面,我就尝试着用递推写,草稿纸浪费了不少,规律矩阵我能找出来,但是用代码实现起来很复杂。我就去大佬的CSDN看他们的解题思路,结果发现他们的规律矩阵跟我的完全不同,看了几天我也不知道这种思路,无奈只好拿别人的规律来了
#include <stdio.h>
#include <stdlib.h>
int cmp(const void* a,const void* b)
{
return *(int*)a-*(int*)b;
}
int main()
{
long long ans = 0;
int n,m,arr[10010];
scanf("%d",&n);
for(int i = 0; i < n; ++i)
scanf("%d",&arr[i]);
qsort(arr,n,sizeof(int),cmp);
for(int i = 0; i < n; ++i)
ans += (n-1-i) * (arr[n-1-i] - arr[i]);
printf("%lld\n",2*ans);
return 0;
}