幾個島-滴滴出行程式設計題
阿新 • • 發佈:2019-01-11
題目連結
思路
- 比較直接,就是用vector去儲存每個連通區域,連通區域內的畫素點用unordered_set儲存,方便之後的查詢
- 每次新來一個畫素點的時候,就在所有列表中找他是否屬於某個鄰域,如果是的話,則將所有的這些鄰域進行合併。否則就新建一個unordered_set,儲存這個新的land即可。
- 總結:滴滴的題目主要是有了思路就得立馬寫,流程比較複雜,但是一些技巧性的演算法可能涉及的不太多。
程式碼
#include <cstdlib> #include <string> #include <iostream> #include <fstream> #include <vector> #include <sstream> #include <unordered_map> #include <unordered_set> #include <map> #include <set> #include <stdio.h> #include <numeric> #include <algorithm> #include <functional> #include <stack> #include <queue> #include <cmath> #include <assert.h> #include <vector> #include <memory> #include <memory.h> using namespace std; typedef long long ll; const int MOD = 1e9 + 7; typedef unsigned char uchar; //#define G_DEBUG int dirs4[5][2] = { -1, 0, 1, 0, 0, 0, 0, 1, 0, -1 }; struct pairhash { public: template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const { return std::hash<T>()(x.first) ^ std::hash<U>()(x.second); } }; int main() { #ifdef G_DEBUG // 除錯使用 int N = 2; string str1 = "abab"; string str2 = "ababab"; #else int rows = 0, cols = 0; int count = 0; cin >> rows >> cols >> count; #endif vector<unordered_set<pair<int, int>, pairhash>> pairs; int curr_r = 0, curr_c = 0; int result = 0; for (int i = 0; i < count; i++) { cin >> curr_r >> curr_c; if ((curr_r < 0 || curr_r >= rows) || (curr_c < 0 || curr_c >= cols)) { if (i == 0) cout << pairs.size(); else cout << " " << pairs.size(); continue; } vector<int> need_cmb; for (int k = 0; k < pairs.size(); k++) { bool found = false; auto& curr_pair = pairs[k]; for (int j = 0; j < 5; j++) { int tmp_r = curr_r + dirs4[j][0]; int tmp_c = curr_c + dirs4[j][1]; if ((tmp_r < 0 || tmp_r >= rows) || (tmp_c < 0 || tmp_c >= cols)) continue; if (curr_pair.find(pair<int, int>(tmp_r, tmp_c)) != curr_pair.end()) { curr_pair.insert(pair<int, int>(curr_r, curr_c)); found = true; break; } } if (found) { need_cmb.push_back( k ); } } if (need_cmb.empty()) { pairs.resize( pairs.size()+1 ); pairs.back().insert( pair<int,int>(curr_r, curr_c) ); } else if (need_cmb.size() > 1) { for (int k = need_cmb.size() - 1; k >= 1; k--) { for (auto c : pairs[need_cmb[k]]) { pairs[need_cmb[0]].insert( c ); } pairs.erase( pairs.begin()+need_cmb[k] ); } } if (i == 0) cout << pairs.size(); else cout << " " << pairs.size(); } cout << endl; system("pause"); return 0; }