Knowledge Test about Match

这篇博客探讨了一个数组匹配问题,其中目标是最小化计算公式f(a,b)=∑i=0n−1∣ai−bi∣的平方根之和。虽然直觉上排序可能会有所帮助,但实际情况是,由于sqrt函数的特性,直接排序可能不是最优解。作者提出了一个贪心策略,即从小到大枚举并比较元素对的组合,以减少函数和。代码展示了如何实现这个贪心算法,并指出只要结果与最佳答案相差小于4%,即为有效解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Knowledge Test about Match

题意:

给你一个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=0n1aibi ,使得结果尽量小。最终结果与标准结果相差<=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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值