P1653 [USACO04DEC] Cow Ski Area G
题意概括
每个格子可以向高度不高于自己的相邻格子滑行。现在可以添加若干条连接任意两个格子的双向缆车,求使所有格子两两可达所需的最少缆车数。
算法分析
把每个格子看成一个点。若相邻格子 满足 ,就加入有向边 。问题转化为:至少添加多少条双向边,才能使整张有向图强连通。
先用 Tarjan 算法求强连通分量。同一强连通分量中的格子本来就可以互相到达,将每个强连通分量缩成一个点后得到一张 DAG。
设缩点后入度为 的点有 个,出度为 的点有 个。
- 每个入度为 的点必须与外界新增的边相连,否则其他分量仍无法到达它,所以至少需要 条缆车。
- 每个出度为 的点也必须与外界新增的边相连,否则它仍无法到达其他分量,所以至少需要 条缆车。
因此答案至少是 。另一方面,可以把各个源点和汇点按拓扑关系配对,用一条双向缆车同时补上“从汇点离开”和“进入源点”的能力;数量较少的一侧用完后,把剩余端点接到任意另一侧端点即可。这样恰好使用 条缆车。
若缩点后只有一个点,原图已经强连通,答案为 。
正确性证明
缩点不会改变不同强连通分量之间的可达关系。
对任意入度为 的缩点,如果没有缆车与它相连,则其他缩点不可能到达它,因此每个源点都至少需要关联一条缆车。同理,每个出度为 的缩点都至少需要关联一条缆车。所以任意方案至少需要 条缆车。
按照上述配对方式连接源点和汇点后,每个源点都获得了来自其他部分的入口,每个汇点也获得了通往其他部分的出口。DAG 中任意点都能从某个源点到达,也都能到达某个汇点;借助新增的双向缆车,各部分被串联成一个强连通图。因此 条缆车足够。
下界与构造上界相同,算法得到的答案最优。
复杂度分析
格子数为 ,相邻格子产生的有向边数为 。时间复杂度为 ,空间复杂度为 。
参考代码
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int W, L;
cin >> W >> L;
int n = W * L;
vector<int> h(n);
for (int i = 0; i < n; ++i) cin >> h[i];
vector<vector<int>> graph(n);
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
for (int x = 0; x < L; ++x) {
for (int y = 0; y < W; ++y) {
int u = x * W + y;
for (int k = 0; k < 4; ++k) {
int nx = x + dx[k], ny = y + dy[k];
if (nx < 0 || nx >= L || ny < 0 || ny >= W) continue;
int v = nx * W + ny;
if (h[v] <= h[u]) graph[u].push_back(v);
}
}
}
vector<int> dfn(n), low(n), scc(n), stk;
vector<char> inStack(n, false);
int timer = 0, sccCount = 0;
function<void(int)> tarjan = [&](int u) {
dfn[u] = low[u] = ++timer;
stk.push_back(u);
inStack[u] = true;
for (int v : graph[u]) {
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (inStack[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (low[u] == dfn[u]) {
while (true) {
int v = stk.back();
stk.pop_back();
inStack[v] = false;
scc[v] = sccCount;
if (v == u) break;
}
++sccCount;
}
};
for (int i = 0; i < n; ++i) {
if (!dfn[i]) tarjan(i);
}
if (sccCount == 1) {
cout << 0 << '\n';
return 0;
}
vector<int> indegree(sccCount), outdegree(sccCount);
for (int u = 0; u < n; ++u) {
for (int v : graph[u]) {
if (scc[u] != scc[v]) {
++outdegree[scc[u]];
++indegree[scc[v]];
}
}
}
int sources = 0, sinks = 0;
for (int i = 0; i < sccCount; ++i) {
sources += (indegree[i] == 0);
sinks += (outdegree[i] == 0);
}
cout << max(sources, sinks) << '\n';
return 0;
}