CF377A Maze題解

2020-10-04 11:00:15

CF377A Maze

題意:有一個地圖,有空地和牆,空地是一個連通塊,問要再添k堵牆,使得空地還是一個連通塊,輸出改變後的地圖。
解法:這題的思維很新穎,沒想到啊,如果正面搜尋,需要考慮的情況比較多,所以逆向思維,先把所有’.‘變成’X’,然後,再找出一個大小為ans-k數量的連通塊,記得dfs的時候計數器要定義為全域性變數,害,下次我還寫bfs。
程式碼

#include  <algorithm>
#include  <iostream>
#include  <cstring>
#include  <vector>
#include  <cstdio>
#include  <queue>
#include  <cmath>
#include  <set>
#include  <map>
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define _for(n,m,i) for (register int i = (n); i < (m); ++i)
#define _rep(n,m,i) for (register int i = (n); i <= (m); ++i)
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define PI acos(-1)
#define eps 1e-9
#define rint register int
#define F(x) ((x)/3+((x)%3==1?0:tb))
#define G(x) ((x)<tb?(x)*3+1:((x)-tb)*3+2)
using namespace std;
typedef long long LL;
typedef pair<LL, int> pli;
typedef pair<int, int> pii;
typedef pair<double, int> pdi;
typedef pair<LL, LL> pll;
typedef pair<double, double> pdd;
typedef map<int, int> mii;
typedef map<char, int> mci;
typedef map<string, int> msi;
template<class T>
void read(T &res) {
  int f = 1; res = 0;
  char c = getchar();
  while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); }
  while(c >= '0' && c <= '9') { res = res * 10 + c - '0'; c = getchar(); }
  res *= f;
}
const int ne[8][2] = {1, 0, -1, 0, 0, 1, 0, -1, -1, -1, -1, 1, 1, -1, 1, 1};
const int INF = 0x3f3f3f3f;
const int N = 510;
const LL Mod = 1e9+7;
const int M = 1e6+10;
char tu[N][N];
int n, m, k, ans, cnt;
void dfs(int x, int y) {
  //cout << x << " " << y << " " << cnt << " " << ans-k << endl;
  for(int i = 0, tx, ty; i < 4; ++i) {
    tx = x + ne[i][0], ty = y + ne[i][1];
    if(tx >=1 && ty >= 1 && tx <= n && ty <= m && tu[tx][ty] == 'X') {
      if(cnt == ans-k) return;
      tu[tx][ty] = '.'; ++cnt;
      dfs(tx, ty);
    }
  }
}
int main() {
  scanf("%d %d %d", &n, &m, &k);
  int fx, fy;
  _rep(1, n, i) {
    scanf("%s", tu[i]+1);
    _rep(1, m, j) if(tu[i][j] == '.') {
      tu[i][j] = 'X', ++ans;
      fx = i; fy = j;
    }
  }
  tu[fx][fy] = '.'; ++cnt; dfs(fx, fy);
  _rep(1, n, i) printf("%s\n", tu[i]+1);
  return 0;
}