Top

模拟退火


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
48
49
50
51
52
53
54
#include <stdio.h>
#include <bits/stdc++.h>
#define fst first
#define sed second
using namespace std;
typedef long long ll;

const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int N = 110;
int x[N], y[N], z[N];
int n;
double X, Y, Z, ans;

double dis(double X, double Y, double Z)
{
double res = 0;
for (int i = 0; i < n; ++i)
res = max(res, sqrt((x[i] - X) * (x[i] - X) + (y[i] - Y) * (y[i] - Y) + (z[i] - Z) * (z[i] - Z)));
return res;
}
void SA()
{
double T = 4, D = 0.995; //初始温度 退火率
while (T > 1e-8) //灭了
{
double x = X + ((rand() << 1) - RAND_MAX) * T; //根据最优解随机一个变动值随着T缩小范围
double y = Y + ((rand() << 1) - RAND_MAX) * T;
double z = Z + ((rand() << 1) - RAND_MAX) * T;
double res = dis(x, y, z);
if (res < ans) //更新最优解
ans = res, X = x, Y = y, Z = z;
else if (exp((ans - res) / T) * RAND_MAX > rand()) //概率接受当前解
X = x, Y = y, Z = z;
T *= D; //退火
}
}
int main()
{
#ifdef LOCAL
freopen("C:/input.txt", "r", stdin);
#endif
srand(time(NULL) * 11);
rand();
cin >> n;
for (int i = 0; i < n; ++i)
scanf("%d%d%d", &x[i], &y[i], &z[i]), X += x[i], Y += y[i], Z += z[i];
X /= n, Y /= n, Z /= n; //取平均值
ans = dis(X, Y, Z);
SA();
printf("%.10f\n", ans);

return 0;
}

<模拟退火>
http://codeforces.com/gym/101981/attachments
Problem D. Country Meow
Input file: standard input
Output file: standard output
In the 24th century, there is a country somewhere in the universe, namely Country Meow. Due to advanced
technology, people can easily travel in the 3-dimensional space.
There are N cities in Country Meow. The i-th city is located at (xi, yi, zi) in Cartesian coordinate.
Due to the increasing threat from Country Woof, the president decided to build a new combatant
command, so that troops in different cities can easily communicate. Hence, the Euclidean distance between
the combatant command and any city should be minimized.
Your task is to calculate the minimum Euclidean distance between the combatant command and the
farthest city.
Input
The first line contains an integer N (1 ≤ N ≤ 100).
The following N lines describe the i-th city located.Each line contains three integers xi, yi, zi

(100000 ≤ xi, yi, zi ≤ 100000).
Output
Print a real number — the minimum Euclidean distance between the combatant command and the farthest
city. Your answer is considered correct if its absolute or relative error does not exceed 10?3
. Formally, let your answer be a, and the jury’s answer be b. Your answer is considered correct if |a?b|
max(1,|b|) ≤ 10^3
.
Examples
standard input standard output
3
0 0 0
3 0 0
0 4 0
2.500000590252103
4
0 0 0
1 0 0
0 1 0
0 0 1
0.816496631812619

文章版权为Anoyer博客所有,转载请以链接形式标明本文地址