题意:
给你一个B数组,要求你去匹配A数组[0,N-1],计算公式 f ( a , b ) = ∑ i = 0 n − 1 ∣ a i − b i ∣ f(a,b)=\sum_{i=0}^{n-1}\sqrt{|a_{i}-b_{i}|} f(a,b)=∑i=0n−1∣ai−bi∣,使得结果尽量小。最终结果与标准结果相差<=4%即可。
题解:
第一反应就是直接排序sort,这样让大的和大的在一起匹配,小的和小的一起匹配,但是这样不行。因为匹配函数是sqrt,sqrt的导函数随着x的增加越来越小,直接sort后可能造成层次不齐,反而增大了函数和。
比如:
{1,2,3}
{0,1,2}
sort排序后:(1,1)(2,2)(0,3)会比sort的结果更优
std做法是直接贪心:从小到大枚举d,每次去看cal(i,a[i])+cal(j,a[j])是否比cal(i,a[j])+cal(j,a[i])优,然后乱搞就可以了
因为题目不要求求出最佳答案,只要与最佳答案在一定范围即可,所以不用求最佳答案,可以贪心
代码:
// Problem: Knowledge Test about Match
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/contest/11166/K
// Memory Limit: 524288 MB
// Time Limit: 2000 ms
// Data:2021-08-24 12:48:46
// By Jozky
#include <bits/stdc++.h>
#include <unordered_map>
#define debug(a, b) printf("%s = %d\n", a, b);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
clock_t startTime, endTime;
//Fe~Jozky
const ll INF_ll= 1e18;
const int INF_int= 0x3f3f3f3f;
void read(){};
template <typename _Tp, typename... _Tps> void read(_Tp& x, _Tps&... Ar)
{
x= 0;
char c= getchar();
bool flag= 0;
while (c < '0' || c > '9')
flag|= (c == '-'), c= getchar();
while (c >= '0' && c <= '9')
x= (x << 3) + (x << 1) + (c ^ 48), c= getchar();
if (flag)
x= -x;
read(Ar...);
}
template <typename T> inline void write(T x)
{
if (x < 0) {
x= ~(x - 1);
putchar('-');
}
if (x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
void rd_test()
{
#ifdef LOCAL
startTime= clock();
freopen("in.txt", "r", stdin);
#endif
}
void Time_test()
{
#ifdef LOCAL
endTime= clock();
printf("\nRun Time:%lfs\n", (double)(endTime - startTime) / CLOCKS_PER_SEC);
#endif
}
const int maxn= 2000;
int a[maxn];
double cal(int a, int b)
{
return sqrt(abs(a - b));
}
int main()
{
//rd_test();
int t;
read(t);
while (t--) {
int n;
read(n);
for (int i= 0; i < n; i++)
read(a[i]);
int cnt= 5;
while (cnt--) {
for (int i= 0; i < n; i++) {
for (int j= i + 1; j < n; j++) {
if (cal(i, a[i]) + cal(j, a[j]) > cal(i, a[j]) + cal(j, a[i])) {
swap(a[i], a[j]);
}
}
}
}
for (int i= 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
//Time_test();
}