洛谷 – 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)