http://codeforces.com/problemset/problem/723/D
dfs找出每个湖,保存坐标和大小,按大小排序,填充湖即可,注意湖的数量最多会有1250个。
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f using namespace std; int n,m,k,dir[][2] = {-1,0,0,-1,1,0,0,1},ok,cnt = 0,sizee,vis[55][55] = {0}; char mp[55][55]; struct lake { int x,y,cnt; }l[1300]; bool cmp(struct lake a,struct lake b) { return a.cnt < b.cnt; } void dfs1(int x,int y) { vis[x][y] = 1; sizee++; for(int i = 0;i < 4;i++) { int xx = x+dir[i][0],yy = y+dir[i][1]; if(xx < 0 || yy < 0 || xx >= n || yy >= m) { ok = 0; continue; } if(mp[xx][yy] == '*' || vis[xx][yy]) continue; dfs1(xx,yy); } } void dfs2(int x,int y) { mp[x][y] = '*'; for(int i = 0;i < 4;i++) { int xx = x+dir[i][0],yy = y+dir[i][1]; if(xx < 0 || yy < 0 || xx >= n || yy >= m) continue; if(!vis[xx][yy]) continue; vis[xx][yy] = 0; dfs2(xx,yy); } } int main() { scanf("%d%d%d",&n,&m,&k); getchar(); int x = 0; while(gets(mp[x++])); for(int i = 0;i < n;i++) { for(int j = 0;j < m;j++) { sizee = 0; ok = 1; if(mp[i][j] == '.' && !vis[i][j]) { dfs1(i,j); if(ok) { l[cnt].x = i; l[cnt].y = j; l[cnt++].cnt = sizee; } } } } sort(l,l+cnt,cmp); int endd = cnt-k,ans = 0; for(int i = 0;i < endd;i++) { ans += l[i].cnt; dfs2(l[i].x,l[i].y); } printf("%d ",ans); for(int i = 0;i < n;i++) puts(mp[i]); return 0; }