[随机算法]爬山算法和模拟退火

本文介绍了爬山算法和模拟退火两种随机算法,并通过分析洛谷平台上的数道算法题目,如[P3878]分金币、[P1337]平衡点等,探讨了这两种算法在解决实际问题中的应用。同时,文中提到了Floyd算法在最外层的重要性,以及可能存在的多次运行模拟退火算法的写法。
摘要由CSDN通过智能技术生成

洛谷 – P3878 – [TJOI2010]分金币
https://www.luogu.org/problem/P3878

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n, a[55];
vector<int> ansa, ansb;
ll suma, sumb, ans = 0x3f3f3f3f3f3f3f3f;
void init()
{
   
    suma = sumb = 0;
    ansa.clear(); ansb.clear();
    for (int i = 0; i < n; ++i){
   
        if (rand() & 1) ansa.push_back(a[i]);
        else ansb.push_back(a[i]);
    }
    if (abs((int)ansa.size() - (int)ansb.size()) > 1){
   
        while ((int)ansa.size() > (int)ansb.size() + 1){
   
            ansb.push_back(ansa.back());
            ansa.pop_back();
        }
        while ((int)ansb.size() > (int)ansa.size() + 1){
   
            ansa.push_back(ansb.back());
            ansb.pop_back();
        }
    }
    for (int e : ansa) suma += e;
    for (int e : ansb) sumb += e;
    ans = min(ans, abs(suma - sumb));
}
int suiji()
{
   
    init();
    for (int i = 0; i < 900; ++i){
   
        ll sa = suma, sb = sumb;
        int x = rand() % (int)ansa.size(), y = rand() % (int)ansb.size();
        sa = sa - ansa[x] + ansb[y];
        sb = sb - ansb[y] + ansa[x];
        if (abs(sa - sb) < ans){
   
            swap(ansa[x], ansb[y]);
            ans = abs(sa - sb);
            suma = sa, sumb = sb;
        }
    }
    return ans;
}
int main()
{
   
    ios::sync_with_stdio(0); cin.tie(0);
    srand(19990627);
    int t;
    cin >> t;
    while (t--){
   
        cin >> n;
        for (int i = 0; i < n; ++i) cin >> a[i];
        if (n == 1){
   
            cout << a[0] << endl;
            continue;
        }
        for (int i = 0; i < 900; ++i) suiji();
        cout << ans << endl;
        ans = 0x3f3f3f3f;
    }
    return 0;
}

洛谷 – P1337 – [JSOI2004]平衡点 / 吊打XXX
https://www.luogu.org/problem/P1337

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e3 + 10, mod =  1e9 + 7;

int n;
struct e{
   
    int x, y, z;
}a[maxn];
double ansx, ansy, ans = 0;

double cal(double x, double y)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值