AC代码①:
#include <iostream>
using namespace std;
int a[510];
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int main()
{
ios::sync_with_stdio(false);//解放输入效率
int t, n, i, sum, temp;
cin >> t;
while (t--)
{
temp = sum = 0;
cin >> n;
for (i = 0; i < n; i++)
cin >> a[i];
qsort(a, n, sizeof(int), cmp);
//先计算n/2点为出发点,然后比较n/2 + 1的sum值
for (i = 0; i < n; i++)
sum += abs(a[i] - a[n / 2]);
if (n % 2 == 0)
{
for (i = 0; i < n; i++)
temp += abs(a[i] - a[n / 2 - 1]);
sum = sum > temp ? temp : sum;
}
cout << sum << endl;
}
return 0;
}
AC代码②:DP
#include<bits/stdc++.h>
using namespace std;
int v[510];
int dp[510];
int main() {
ios::sync_with_stdio(false);
int t, m;
cin >> t;
while (t--) {
memset(dp, 0, sizeof(dp));
cin >> m;
for (int i = 0; i < m; ++i)cin >> v[i];
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
dp[i] += abs(v[j] - v[i]);//一定是绝对值啊
long long minn = 99999999999;
for (int i = 0; i < m; ++i)
minn = minn < dp[i] ? minn : dp[i];
cout << minn << endl;
}
return 0;
}
Ps:DP的时间消耗会更大,因为相对第一种代码还是做了很多无用计算