forked from marioyc/Online-Judge-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3164 - Command Network.cpp
143 lines (108 loc) · 2.98 KB
/
3164 - Command Network.cpp
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define MAX_V 100
typedef double edge_cost;
edge_cost INF = 1e10;
int V,E,root,prev[MAX_V];
bool adj[MAX_V][MAX_V];
edge_cost G[MAX_V][MAX_V],MCA;
bool visited[MAX_V],circle[MAX_V];
void add_edge(int u, int v, edge_cost c){
if(adj[u][v]) G[u][v] = min(G[u][v],c);
else G[u][v] = c;
adj[u][v] = true;
}
void dfs(int v){
visited[v] = true;
for(int i = 0;i<V;++i)
if(!visited[i] && adj[v][i])
dfs(i);
}
bool check(){
memset(visited,false,sizeof(visited));
dfs(root);
for(int i = 0;i<V;++i)
if(!visited[i])
return false;
return true;
}
int exist_circle(){
prev[root] = root;
for(int i = 0;i<V;++i){
if(!circle[i] && i!=root){
prev[i] = i; G[i][i] = INF;
for(int j = 0;j<V;++j)
if(!circle[j] && adj[j][i] && G[j][i]<G[prev[i]][i])
prev[i] = j;
}
}
for(int i = 0,j;i<V;++i){
if(circle[i]) continue;
memset(visited,false,sizeof(visited));
j = i;
while(!visited[j]){
visited[j] = true;
j = prev[j];
}
if(j==root) continue;
return j;
}
return -1;
}
void update(int v){
MCA += G[prev[v]][v];
for(int i = prev[v];i!=v;i = prev[i]){
MCA += G[prev[i]][i];
circle[i] = true;
}
for(int i = 0;i<V;++i)
if(!circle[i] && adj[i][v])
G[i][v] -= G[prev[v]][v];
for(int j = prev[v];j!=v;j = prev[j]){
for(int i = 0;i<V;++i){
if(circle[i]) continue;
if(adj[i][j]){
if(adj[i][v]) G[i][v] = min(G[i][v],G[i][j]-G[prev[j]][j]);
else G[i][v] = G[i][j]-G[prev[j]][j];
adj[i][v] = true;
}
if(adj[j][i]){
if(adj[v][i]) G[v][i] = min(G[v][i],G[j][i]);
else G[v][i] = G[j][i];
adj[v][i] = true;
}
}
}
}
bool min_cost_arborescence(int _root){
root = _root;
if(!check()) return false;
memset(circle,false,sizeof(circle));
MCA = 0;
int v;
while((v = exist_circle())!=-1)
update(v);
for(int i = 0;i<V;++i)
if(i!=root && !circle[i])
MCA += G[prev[i]][i];
return true;
}
int main(){
int M,a,b;
double x[100],y[100];
while(scanf("%d %d",&V,&M)==2){
for(int i = 0;i<V;++i) scanf("%lf %lf",&x[i],&y[i]);
memset(adj,false,sizeof(adj));
for(int i = 0;i<M;++i){
scanf("%d %d",&a,&b);
--a; --b;
add_edge(a,b,sqrt((x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b])));
}
if(!min_cost_arborescence(0)) printf("poor snoopy\n");
else printf("%.2lf\n",MCA);
}
return 0;
}