Knowledge Test about Match
生活随笔
收集整理的這篇文章主要介紹了
Knowledge Test about Match
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Knowledge Test about Match
題意:
給你一個(gè)B數(shù)組,要求你去匹配A數(shù)組[0,N-1],計(jì)算公式f(a,b)=∑i=0n?1∣ai?bi∣f(a,b)=\sum_{i=0}^{n-1}\sqrt{|a_{i}-b_{i}|}f(a,b)=∑i=0n?1?∣ai??bi?∣?,使得結(jié)果盡量小。最終結(jié)果與標(biāo)準(zhǔn)結(jié)果相差<=4%即可。
題解:
第一反應(yīng)就是直接排序sort,這樣讓大的和大的在一起匹配,小的和小的一起匹配,但是這樣不行。因?yàn)槠ヅ浜瘮?shù)是sqrt,sqrt的導(dǎo)函數(shù)隨著x的增加越來(lái)越小,直接sort后可能造成層次不齊,反而增大了函數(shù)和。
比如:
{1,2,3}
{0,1,2}
sort排序后:(1,1)(2,2)(0,3)會(huì)比sort的結(jié)果更優(yōu)
std做法是直接貪心:從小到大枚舉d,每次去看cal(i,a[i])+cal(j,a[j])是否比cal(i,a[j])+cal(j,a[i])優(yōu),然后亂搞就可以了
因?yàn)轭}目不要求求出最佳答案,只要與最佳答案在一定范圍即可,所以不用求最佳答案,可以貪心
代碼:
// 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 LOCALstartTime= clock();freopen("in.txt", "r", stdin); #endif } void Time_test() { #ifdef LOCALendTime= 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(); }總結(jié)
以上是生活随笔為你收集整理的Knowledge Test about Match的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。