1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include <bits/stdc++.h>
using namespace std;
int calc() {
//用dp,最短路,贪心,模拟等算法求出当前解。
}
int SA() {
double beginT = , endT = , delT = ;
for (double T = beginT; T > endT; T *= delT) {
//对于序列,枚举两个数并进行交换,得出当前解
//对于坐标,随机生成一个点进行计算
//对于网格图,随机枚举两个格点进行交换
//...
if () // 当前解优于最优解
// 更新最优解
else if (exp(-当前 / T) * RAND_MAX < rand()) //还原之前的状态
}
}
int main() {
srand(rand());
while((double)clock()/CLOCKS_PER_SEC<=0.8) SA();// 卡时
return 0;
}
|
例题
P3878 [TJOI2010] 分金币
程序(傻缺都能看懂)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int n, a[maxn], ans = 0x3f3f3f3f;
int get_diff() {
int s1 = 0, s2 = 0;
for (int i = 1; i <= (n + 1) / 2; i++) {
s1 += a[i];
}
for (int i = (n + 1) / 2 + 1; i <= n; i++) {
s2 += a[i];
}
return abs(s1 - s2);
}
void SA(int times) {
while (times--) {
double beginT = 10000, endT = 1e-10, delT = 0.95;
for (double T = beginT; T > endT; T *= delT) {
int x = rand() % n + 1, y = rand() % n + 1;
swap(a[x], a[y]);
int sum = get_diff();
if (sum < ans)
ans = sum;
else {
if (exp((ans - sum) / T) < (double(rand()) / RAND_MAX))
swap(a[x], a[y]);
}
}
}
}
int main() {
srand(rand());
int T;
cin >> T;
while (T--) {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
SA(1000);
cout << ans << endl;
ans = 0x3f3f3f3f;
}
return 0;
}
|