关于一种做法
查看原帖
关于一种做法
1049265
EityDawn楼主2024/8/15 10:33

每次随机打乱序列,然后通过不断交换元素位置确定最优解,跑得贼快,目前洛谷最优解

#include<iostream>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<climits>
#include<queue>
#include<vector>
#include<map>
#include<set>
#define int long long
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N=50;
const ll inf=1e16;
int n;
ll a[N],Ans;
ll calc()
{
    ll res=0;
    for(int i=1;i<=n/2;i++) res+=a[i];
    for(int i=n/2+1;i<=n;i++) res-=a[i];
    return abs(res);
}
bool increase()
{
    for(int i=1;i<=n/2;i++)
        for(int j=n/2+1;j<=n;j++)
        {
            swap(a[i],a[j]);
            ll res=calc();
            if(res<Ans){Ans=res;return true;}
            else swap(a[i],a[j]);
        }
    return false;
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    srand(time(0));
    int T=1;
    cin>>T;
    while(T--)
    {
        cin>>n;Ans=inf;
        for(int i=1;i<=n;i++) cin>>a[i];
        sort(a+1,a+1+n);Ans=calc();
        while(increase());
        int t=50;
        while(t--) {
            random_shuffle(a+1,a+1+n);
            while(increase());
        }
        cout<<Ans<<'\n';
    }
    return 0;
}
2024/8/15 10:33
加载中...