T2-26D4T4
题意:
有 n 行 m 列的地形网格,a[i][j]代表该位置海拔高度。
只能在第一行修建水库;水只能流向相邻、海拔严格更低的格子。
底部第 n 行是城市。
判断是否能让底部全部城市都得到水源。
可行:输出1,再输出最少需要修建多少水库
不可行:输出0,再输出底部有多少城市无法供水
思路:
在第一层选择建不建水库
暴力枚举第一行所有建水库的组合,模拟水流,统计底部能覆盖的城市数量,记录最优答案
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 500 + 10;
const int M = 1e6 + 10;
int dx[] = {0, 0, 1, -1},dy[] = {1, -1, 0, 0};
int n,m,a[N][N],t, z = M;
bool sh[N],vis[N][N]; // 流水标记
struct node
{
int x, y;
};
// 根据选定的水库位置,模拟水往下流,标记所有可以到达的格子
void hhh()
{
queue<node> q;
// 把第一行所有修水库的点入队,标记水
for (int i = 1; i <= m; i++)
{
if (sh[i] == true)
{
vis[1][i] = true;
q.push({1, i});
}
}
while (!q.empty())
{
node w = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = w.x + dx[i],ny = w.y + dy[i];
// 下一格高度>=当前,水不能流过去
if (nx < 1 || nx > n || ny < 1 || ny > m || vis[nx][ny] == true || a[nx][ny] >= a[w.x][w.y])
{
continue;
}
// 可以流到,入队并标记
q.push({nx, ny});
vis[nx][ny] = true;
}
}
}
// x为当前枚举层数;fa为当前方案已经修建的水库数量
void hh(int x, int fa)
{
// 第一行所有列全部枚举完毕,得到一种水库修建方案
if (x > m)
{
memset(vis, 0, sizeof vis); // 清空访问标记
hhh();// 模拟水流扩散
int p = 0; // p统计最后一行被水覆盖的城市数量
for (int i = 1; i <= m; i++)
{
if (vis[n][i] == true)
{
p++;
}
}
// 更新最大覆盖城市数量t
if (t < p)
{
t = max(t, p);
// 如果全部m个城市都覆盖,更新最小水库数量z
if (t == m)
{
z = min(z, fa);
}
}
return;
}
// 不要
hh(x + 1, fa);
// 要
sh[x] = true;
hh(x + 1, fa + 1);
sh[x] = false; // 回溯
}
signed main()
{
// 读入行数n,列数m
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> a[i][j];
}
}
// 开始递归枚举:从第1列开始,初始修建水库数量0
hh(1, 0);
if (t == m)
{
// 可以全部覆盖:输出1,输出最少水库数量z
cout << 1 << endl << z;
}
else
{
// 无法全部覆盖:输出0,输出不能供水的城市数目
cout << 0 << endl << m - t;
}
return 0;
}