P2210
能量函数题目已经给你了。
如何生成新解?
我们可以每次随机两个变量 ,,设 为奶牛的排列,则生成新解的方式就是:
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 55;
int n;
const double d = 0.997;
int a[N][N];
int ans;
int pos[N];
int calc()
{
int res = 0;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= 3; j ++)
res += abs(pos[i] - pos[a[i][j]]);
return res >> 1;
}
void SA()
{
double T = 2000;
while (T > 1e-8)
{
int x = rand() % n + 1;
int y = rand() % n + 1;
swap(pos[x], pos[y]);
int Num = calc();
if (Num < ans) ans = Num;
else if (exp(ans - Num) / T < double(rand()) / RAND_MAX) swap(pos[x], pos[y]);
T *= h;
}
}
void work()
{
for (int i = 1; i <= 50; i ++) SA();
cout << ans << endl;
}
int main()
{
srand(time(0));
cin >> n;
for (int i = 1; i <= n; i ++)
{
scanf("%d", &a[i][1]);
scanf("%d", &a[i][2]);
scanf("%d", &a[i][3]);
pos[i] = i;
}
ans = 1e9;
work();
return 0;
}P2503
设三个数组,,它们有以下意义:
- 表示输入的数组。
- 表示每个数对应组的编号。
- 表示每组里数字的和。
能量函数为:
其中 表示数组 的平均值。
#include <bits/stdc++.h>
using namespace std;
const int N = 25;
int n, m, a[N], grp[N], sum[N]; //a表示数字,grp表示对应的组的编号,sum表示组里数字的和
double ans, avg; //avg表示平均值
const double d = 0.997;
double calc() //能量函数
{
double val = 0;
for (int i = 1;i <= m;i++)
val += (sum[i] - avg) * (sum[i] - avg);
return val / m; //最后开方
}
void change(int pos, int target) //将第pos个数的分组改为target
{
sum[grp[pos]] -= a[pos];
sum[target] += a[pos];
grp[pos] = target;
}
void SA() //模拟退火
{
double T = 3000, nowans = ans;
while (T > 1e-10)
{
int pos = rand() % n + 1;
int target = rand() % m + 1;
int p = grp[pos];
change(pos, target);
double nans = calc();
double delta = nans - nowans;
if (delta < 0)
{
nowans = nans;
if (nowans < ans) ans = nowans;
}
else if (RAND_MAX * exp(-delta / T) <= rand()) change(pos, p); //如果取新解失败就舍弃
T *= d;
}
}
int main()
{
srand(time(0));
cin >> n >> m;
for (int i = 1; i <= n; i ++)
{
scanf("%d", &a[i]);
avg += a[i];
}
avg /= m;
for (int i = 1; i <= n; i ++)
{
grp[i] = rand() % m + 1;
sum[grp[i]] += a[i];
}
ans = calc();
for (int i = 1; i <= 1000; i ++) SA();
cout << fixed << setprecision(2) << sqrt(ans);
return 0;
}P3878
能量函数为:
#include <bits/stdc++.h>
using namespace std;
const int inf = 2147483647;
int n, ans = inf, a[1005];
int calc()
{
int sum1 = 0, sum2 = 0;
for (int i = 1; i <= (n + 1) / 2; i ++)
sum1 += a[i];
for (int i = (n + 1) / 2 + 1; i <= n; i ++)
sum2 += a[i];
return abs(sum1 - sum2);
}
void SA()
{
double T = 2000, d = 0.995;
while (T >= 1e-10)
{
int x = rand() % n + 1;
int y = rand() % n + 1;
swap(a[x], a[y]);
int sum = calc();
if (sum < ans)
ans = sum;
else if (exp((ans - sum) / T) < (double(rand()) / RAND_MAX))
swap(a[x], a[y]);
T *= d;
}
}
int main()
{
srand(time(0));
int T;
cin >> T;
while (T --)
{
cin >> n;
for (int i = 1; i <= n; i ++)
cin >> a[i];
for (int i = 1; i <= 200; i ++) SA();
cout << ans << endl;
ans = inf;
}
return 0;
}