codeforces723 D. Lakes in Berland(并查集)

时间:2021-01-10 14:52:04

题目链接:codeforces723 D. Lakes in Berland

参考博客:http://www.cnblogs.com/Geek-xiyang/p/5930245.html

 #include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#define CLR(a,b) memset((a),(b),sizeof((a)))
using namespace std;
const int N = ;
const int M = ;
int n, m, k;
char ch[N][N];
int val[N][N];
int fa[M], num[M];
bool vis[M];
int dx[] = {,,,-};
int dy[] = {,-,,};
void init(){
CLR(ch,'.');
int cnt = ;
for(int i = ; i <= n+; ++i)
for(int j = ; j <= m+; ++j)
val[i][j] = ++cnt;
for(int i = ; i <= cnt; ++i){
fa[i] = i;
num[i] = ;
}
}
int fin(int x){
if(x != fa[x])
fa[x] = fin(fa[x]);
return fa[x];
}
void uni(int x, int y){
if((x = fin(x)) == (y = fin(y))) return;
else {
fa[x] = y;
num[y] += num[x];
}
}
void make(int i, int j){
for(int k = ; k < ; ++k){
if(ch[dx[k]+i][dy[k]+j] == '.')
uni(val[i][j], val[dx[k]+i][dy[k]+j]);
}
}
bool cmp(int x, int y){
return num[x] < num[y];
}
vector<int>v;
int main(){
int i, j, kk, rt, t;
scanf("%d%d%d", &n, &m, &k);
init();
for(i = ; i <= n+; ++i){
uni(val[][], val[i][]);
uni(val[][], val[i][m+]);
}
for(i = ; i <= m+; ++i){
uni(val[][], val[][i]);
uni(val[][], val[n+][i]);
}
for(i = ; i <= n; ++i){
scanf("%s", ch[i]+);
ch[i][m+] = '.';//第二遍改时把这句漏了继续WA
}
for(i = ; i <= n; ++i)
for(j = ; j <= m; ++j)
if(ch[i][j] == '.')
make(i, j);
for(i = ; i <= n; ++i){
for(j = ; j <= m; ++j){
rt = fin(val[i][j]);
if(ch[i][j] == '.' && fin(val[][]) != rt){
if(vis[rt]) continue;
else vis[rt] = true;
v.push_back(rt);
}
}
}
sort(v.begin(), v.end(), cmp);
int len = v.size();
t = len;
int ans = ;
if(t > k){
for(i = ; i < len; ++i){
rt = fin(v[i]);
if(vis[rt]){
vis[rt] = false;
t--;
for(j = ; j <= n; ++j)
for(kk = ; kk <= m; ++kk)//我第一遍把这里写成k导致WA死
if(fin(val[j][kk]) == rt) {ch[j][kk] = '*'; ans++;}
}
if(t == k) break;
}
}
printf("%d\n", ans);
for(i = ; i <= n; ++i){
for(j = ; j <= m; ++j)
printf("%c", ch[i][j]);
puts("");
}
return ;
}