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
| struct edge {
int from,to;
int cost;
edge(int t,int c) : to(t),cost(c) {}
edge(int f,int t,int c) : from(f),to(t),cost(c) {}
bool operator<(const edge &e) const {
return cost < e.cost;
}
};
struct SCC {
int n;
vector<vector<int> > g, rg, ng, scc; // rg: 逆グラフ, ng: 分解後のグラフ
vector<int> res; // scc: 強連結成分に属する頂点, res:強連結成分の番号
bool used[100005];
SCC(int _n) {
n = _n;
g.resize(n); rg.resize(n) ; scc.resize(n); res.resize(n);
}
SCC(const vector<vector<int> > &g) : n(g.size()), g(g), rg(n), scc(n), res(n) {
rep(i, n) {
rep(j, g[i].size()) rg[g[i][j]].push_back(i);
}
}
// i-jに辺を追加する
void add(int i, int j) {
g[i].push_back(j);
rg[j].push_back(i);
}
vector<int> vs;
void dfs(int v) {
used[v] = true;
rep(i, g[v].size()) {
if(!used[ g[v][i] ]) dfs(g[v][i]);
}
vs.push_back(v);
}
void rdfs(int v, int k) {
used[v] = true;
res[v] = k;
scc[k].push_back(v);
rep(i, rg[v].size()) {
if(!used[ rg[v][i] ]) rdfs(rg[v][i], k);
}
}
void ng_make(int k) {
ng.resize(k);
rep(i, n) {
set<int> S;
rep(j, g[i].size()) {
int to = g[i][j];
if(res[i] == res[to]) continue;
if(S.find(res[to]) != S.end()) continue;
ng[res[i]].push_back(res[to]);
S.insert(res[to]);
}
}
}
int build() {
memset(used, 0, sizeof(used));
rep(i, n) {
if (!used[i]) dfs(i);
}
memset(used, 0, sizeof(used));
int k = 0;
for (int i = vs.size()-1; i >= 0; i--) {
if (!used[vs[i]]) rdfs(vs[i], k++);
}
// ng_make(k);
return k;
}
};
class HardProof {
public:
int minimumCost(vector<int> D) {
int n = sqrt(D.size());
int k = -1;
map<int, vector<P> > m;
rep(i, n) {
rep(j, n) {
k++;
if(i == j) continue;
m[D[k]].push_back(mp(i, j));
}
}
int ans = INF;
map<int, vector<P> >::iterator l = m.begin(), r = m.begin(), ite;
for(r = m.begin(); r != m.end(); r++) {
k = 1;
while(k == 1) {
SCC scc(n);
ite = l;
while(ite != m.end() && ite->first <= r->first) {
vector<P> v = ite->second;
rep(i, v.size()) {
int a = v[i].first, b = v[i].second;
scc.add(a, b);
}
if(ite == r) break;
ite++;
}
k = scc.build();
if(k == 1) {
ans = min(ans, r->first - l->first);
l++;
continue;
}
break;
}
}
if(ans == INF) return 0;
return ans;
}
};
|