Submission #1062365

#TimeUsernameProblemLanguageResultExecution timeMemory
1062365danielzhuTracks in the Snow (BOI13_tracks)C++17
100 / 100
437 ms28312 KiB
#include <bits/stdc++.h>
using namespace std;
#define MX 4001
typedef long long LL;
typedef pair<int, int> PR;
typedef tuple<int, int, int> TP;
const int MOD = (int)1e9 + 7;
const int INF = (int)1e9 + 5;
const LL MAXV = (LL)1e18; 
using vi = vector<int>;
using vii = vector<vi>;

int H, W;
string md[MX]; //snow meadow
//idea: the footprints (not all) of an animal can be covered by all its successors' footprints.
//Also can be solved using Disjoint Sets instead of BFS/DFS?  
int solve() {
	cin >> H >> W;
	//read the snow meadow info
	for (int i = 0; i < H; i++)
		cin >> md[i]; 
	queue<PR> Q[2]; //two queues for BFS responding to R and F
	int ans = 0; 
  if (md[0][0] == '.')
    return ans;
  vector<char> animal(1, md[0][0]);
  animal.push_back(md[0][0] == 'F' ? 'R' : 'F'); //alternate animal's footprints to discover
  int cur = 0; //an index of animial to reveal the current animal in backward order
  Q[cur].push({0, 0});
	md[0][0] = 'X'; //visited 
  while (!Q[cur].empty()) {
		ans++;
		//BFS to find the CC for current animal's footprints
		while (!Q[cur].empty()) {
			int r = Q[cur].front().first, c = Q[cur].front().second;
			Q[cur].pop();
			int dr = 0, dc = 1;
			for (int k = 0; k < 4; k++) { //4 directions
				int nr = r + dr, nc = c + dc;
				if (nr >= 0 && nr < H && nc >= 0 && nc < W && md[nr][nc] != '.' && md[nr][nc] != 'X') {
					if (md[nr][nc] == animal[cur]) { //current animial footprint
						Q[cur].push({nr, nc});
					} else { //immediately preceding animial footprint
						Q[cur^1].push({nr, nc}); //different use
						// Or you can do: Q[1-cur].emplace_back(nr, nc);
					}
					md[nr][nc] = 'X'; //visited
				}
				//the following 2 statements for iterating thru 4 directions
				// you can use: int dr[] = {0, 1, 0, -1}, dc[] = {1, 0, -1, 0};
				swap(dr, dc);
				dc = -dc;
			}
		}
		cur ^= 1; //for immediately preceding animal. or cur = 1 - cur;
	}	
	return ans;
}   


int main() {
	ios::sync_with_stdio(false);
  cin.tie(nullptr);
	cin.exceptions(cin.failbit);
  cout << solve() << endl;
  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...