Luckyleaves's Blog

stay hungry,stay foolish greedy and lucky

P2538 城堡

退火模板题

solution

  • 对于这道题, 也没什么好说的,退火那些建立城堡,对于单次询问,跑一边最短路就结束了。

代码

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include<bits/stdc++.h>
#define LL long long
#define PII pair<int, int>
using namespace std;
template <class T>
inline void read(T& res)
{
res = 0; bool flag = 0;
char c = getchar();
while(c < '0' || '9' < c)
{
if(c == '-') flag = 1;
c = getchar();
}
while('0' <= c && c <= '9')
res = (res << 3) + (res << 1) + c - '0', c = getchar();
if(flag) res = -res;
}
const int N = 55;
const int Inf = 0x3f3f3f3f;
uniform_int_distribution<unsigned> p;
default_random_engine mu{time(0)};
int idx;
int e[N << 1], ne[N << 1], h[N], w[N];
void add(int x, int y, int z)
{
idx ++;
e[idx] = y, ne[idx] = h[x], h[x] = idx, w[idx] = z;
}
int r[N];
int n, m, k;
bool vis[N];
int b[N], tot;
int ans = Inf;
int dist[N];
bool d[N];
priority_queue<PII, vector<PII>, greater<PII> > q;
int calc()
{
for(int i = 0;i < n;i ++)
{
d[i] = 0;
dist[i] = Inf;
if(vis[i])
{
dist[i] = 0;
q.push(make_pair(0, i));
}
}
while(!q.empty())
{
int o = q.top().second;
q.pop();
if(d[o]) continue;
d[o] = 1;
for(int i = h[o]; ~i;i = ne[i])
{
int j = e[i];
if(dist[j] > dist[o] + w[i])
{
dist[j] = dist[o] + w[i];
q.push(make_pair(dist[j], j));
}
}
}
int res = 0;
for(int i = 0;i < n;i ++) res = max(res, dist[i]);
ans = min(ans, res);
return res;
}
void sim()
{
for(int i = 1;i <= tot;i ++) vis[b[i]] = 0;
shuffle(b + 1, b + tot + 1, mu);
for(int i = 1;i <= k;i ++) vis[b[i]] = 1;
int o = calc();
for(double t = 1e4;t > 1e-4;t *= 0.997)
{
int x = p(mu), y = p(mu);
swap(vis[b[x]], vis[b[y]]);
int u = calc();
int delte = u - o;
if(exp(-delte / t) < (double)rand() / RAND_MAX) swap(vis[b[x]], vis[b[y]]);
else o = u;
}
}
int main()
{
memset(h, -1, sizeof(h));
read(n), read(m), read(k);
if(m + k == n)
{
cout << 0 << endl;
return 0;
}
for(int i = 0;i < n;i ++)
read(r[i]);
for(int i = 0;i < n;i ++)
{
int o;
read(o);
if(i == r[i]) continue;
add(i, r[i], o);
add(r[i], i, o);
}
for(int j = 1;j <= m;j ++)
{
int o;
read(o);
vis[o] = 1;
}
for(int i = 0;i < n;i ++)
if(!vis[i]) b[++ tot] = i;
p.param(uniform_int_distribution<unsigned>::param_type{1, tot});
while((double)clock() / CLOCKS_PER_SEC < 0.6) sim();
cout << ans << endl;
return 0;
}