题目链接:​​这里​

题意:给你一个n*m的矩阵,然后你们有不少于k条河流,然后你需要使得一些河流变成陆地,使得河流的数量恰好等于k,问你至少填多少个水。河流的定义是水塘,且不与外界相连的地方。

解法:直接dfs搜出每一条河流,然后贪心排序,从小到大去填满就好了。

//CF 723D

#include <bits/stdc++.h>
using namespace std;
int n, m, k, vis[55][55], cnt, flag, area;
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
char s[55][55];
void dfs1(int x, int y){
area++;
vis[x][y] = 1;
if(x == 0 || x == n-1 || y == 0 || y== m-1) flag = 1;
for(int i = 0; i < 4; i++){
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 0 || tx >= n) continue;
if(ty < 0 || ty >= m) continue;
if(s[tx][ty] == '*') continue;
if(vis[tx][ty]) continue;
dfs1(tx, ty);
}
}
struct node{
int a, b, c;
node(){}
node(int a, int b, int c) : a(a), b(b), c(c){}
bool operator <(const node &rhs) const{
return a < rhs.a;
}
}t[5000];

void dfs2(int x, int y)
{
s[x][y] = '*';
for(int i = 0; i < 4; i++){
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 0 || tx >= n) continue;
if(ty < 0 || ty >= m) continue;
if(s[tx][ty] == '*') continue;
dfs2(tx, ty);
}
}

int main(){
scanf("%d%d%d", &n, &m, &k);
for(int i = 0; i < n; i++) scanf("%s", s[i]);
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!vis[i][j] && s[i][j] == '.'){
area = 0;
flag = 0;
dfs1(i, j);
if(flag == 1) continue;
t[cnt++] = node(area, i, j);
}
}
}
sort(t, t + cnt);
int ans =0;
for(int i = 0; i < cnt - k; i++){
ans = ans + t[i].a;
dfs2(t[i].b, t[i].c);
}
printf("%d\n", ans);
for(int i = 0; i < n; i++){
printf("%s\n", s[i]);
}
return 0;
}