Several islands - didi trip programming
Title Link
thinking
- It is more direct to use vector to store each connected area, and the pixel points in the connected area are stored in unordered set, which is convenient for later search
- Every time a pixel is newly added, it will find out whether it belongs to a neighborhood in all the lists. If so, all these neighborhoods will be merged. Otherwise, create a new unordered set and save the new land.
- Conclusion: Didi's topic is mainly to write immediately when he has ideas. The process is relatively complex, but some technical algorithms may not involve much.
Code
#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
// Debugging use
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;
}
Posted by buildakicker on Sun, 05 Jan 2020 04:36:03 -0800