This can be done with both DFS or BSF graph traversal.
#include <iostream> #include <sstream> #include <cstring> #include <cstdio> #include <cstdlib> #include <algorithm> #include <ctime> #include <cctype> #include <cmath> #include <vector> #include <map> #include <set> #include <queue> #include<bitset> #define foreach(it, l) for (typeof(l.begin()) it = l.begin(); it != l.end(); it++) #define db(a) \ cout << #a << " = " << a << endl #define db2(a, b) \ cout << #a << " = " << a << " " << #b << " = " << b << endl #define inf (1<<30) using namespace std; vector<string> lista; int h, w; void dfs(int i, int j, char cur) { if (i >= 0 && i < h && j >= 0 && j < w && lista[i][j] == cur) { lista[i][j] = '-'; dfs(i + 1, j, cur); dfs(i - 1, j, cur); dfs(i, j - 1, cur); dfs(i, j + 1, cur); } } bool def(int i, int j, char cur) { if (i > 0 && lista[i - 1][j] == cur) return true; if (i < h - 1 && lista[i + 1][j] == cur) return true; if (j > 0 && lista[i][j - 1] == cur) return true; if (j < w - 1 && lista[i][j + 1] == cur) return true; return false; } bool cmp(const pair<char, int>& a, const pair<char, int>& b) { if (a.second > b.second) return true; return a.first < b.first; } int main() { #ifdef dennisbot freopen("in.in", "r", stdin); freopen("ou.out", "w", stdout); #endif int t; string s; set<char> sc; cin >> t; int start = t; while (t--) { cin >> h >> w; lista.resize(h); for (int i = 0; i < h; i++) { cin >> lista[i]; } map<char, int> mapa; sc.clear(); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (lista[i][j] != '-' && def(i, j, lista[i][j])) { char cur = lista[i][j]; mapa[cur]++; sc.insert(cur); dfs(i, j, cur); } } } printf("World #%d\n", start - t); vector< pair<char,int> > res; foreach(it, mapa) { res.push_back(make_pair(it->first, it->second)); } sort(res.begin(), res.end(), cmp); for (int i = 0; i < res.size(); i++) { cout << res[i].first << ": " << res[i].second << endl; } } return 0; }
No hay comentarios:
Publicar un comentario