Codeforces 723D. Lakes in Berland

解题思路:

  1.dfs所有的水,顺便计数大小并判断是不是湖。

  2.如果是湖,将大小和坐标存下来。

  3.对湖按大小从小到大排序。

  4.dfs前(湖的数量-k)个湖,用*填充这些湖。

代码:

  

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

struct lake{
    int x;int y;
    int size;
    bool islake;
};
vector <lake> l;

char a[55][55];
bool used[55][55];
int n,m,k;
int dir[4][2] = {1,0,-1,0,0,1,0,-1};

bool cmp(lake p,lake q){
    return p.size < q.size;
}


void dfs(int x,int y,lake &t){
//    cout << x << " " << y << " l" << endl;
    if(x == 1 or y == 1 or x == n or y == m) t.islake = false;
    t.size++;
    used[x][y] = true;
    for(int i = 0;i < 4; ++i){
        int conx = x+dir[i][0];
        int cony = y+dir[i][1];
        if(!used[conx][cony] and a[conx][cony] == '.'){
            dfs(conx, cony, t);
        }
    }
}

void dfsfill(int x,int y){
    a[x][y] = '*';
    for(int i = 0;i < 4; ++i){
        int conx = x+dir[i][0];
        int cony = y+dir[i][1];
        if(a[conx][cony] == '.'){
            dfsfill(conx, cony);
        }
    }
}

int main(){
       ios::sync_with_stdio(false);
       cin >> n >> m >> k;
     for(int i = 1;i <= n; ++i) cin >> a[i]+1;     
     for(int i = 1;i <= n; ++i){
         for(int j = 1;j <= m; ++j){
            if(!used[i][j] and a[i][j] == '.'){
                lake t;
                t.x = i;t.y = j;
                t.size = 0;
                t.islake = true;
                dfs(i, j, t);
                if(t.islake){
//                    cout << t.x << " " << t.y <<" " << t.size << endl;
                    l.push_back(t);
                }
            }
        }
    }
    sort(l.begin(),l.end(),cmp);
    int s = l.size() - k;
    int ans = 0;
    for(int i = 0;i < s; ++i){
        ans += l[i].size;
        dfsfill(l[i].x, l[i].y);
    }
    cout << ans << endl;
    for(int i = 1;i <= n; ++i) cout << a[i]+1 << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhangjiuding/p/9121021.html