codeforces 1929A. Sasha and the Beautiful Array
题目如下
Sasha decided to give his girlfriend an array 𝑎1,𝑎2,…,𝑎𝑛. He found out that his girlfriend evaluates the beauty of the array as the sum of the values (𝑎𝑖−𝑎𝑖−1) for all integers 𝑖 from 2 to 𝑛.
Help Sasha and tell him the maximum beauty of the array 𝑎 that he can obtain, if he can rearrange its elements in any way.
Input
Each test consists of multiple test cases. The first line contains a single integer 𝑡 (1≤𝑡≤500) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer 𝑛 (2≤𝑛≤100) — the length of the array 𝑎.
The second line of each test case contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤109) — the elements of the array 𝑎.
Output
For each test case, output a single integer — the maximum beauty of the array 𝑎 that can be obtained.
题目大意
题目中定义了数组美丽值的含义是数组中所有𝑎𝑖−𝑎𝑖−1的总和,希望我们找出最大美丽值通过改变数组的排列顺序
解题思路
要使得美丽值最大,也就是说使得所有𝑎𝑖−𝑎𝑖−1的总和最大,我们可以通过排序的方式,现将数组进行一个升序的排序,得到从小到大依次排列的数使得每项之间的差值都大于等于0,使得美丽值最大
实现
用qsort进行快速的排序
点击查看代码
int compare(const void *a,const void *b){
return (*(int*)a - *(int *)b);
}
qsort(arr, n, sizeof(int), compare);
点击查看代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a,const void *b){
return (*(int*)a - *(int *)b);
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,sum = 0;
scanf("%d",&n);
int arr[101];
for(int i = 0; i < n; i++){
scanf("%d",&arr[i]);
}
qsort(arr, n, sizeof(int), compare);
for(int i = 1; i < n; i++){
sum += arr[i] - arr[i - 1];
}
printf("%d\n",sum);
}
return 0;
}

浙公网安备 33010602011771号