使用unordered_set,对pair类型写一个哈希函数,查找操作的时间复杂度为平均 O(1),可AC
#include <iostream>
#include <unordered_set>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 55, M = 1010;
int n, l, s;
int b[N][N];
PII tree[M];
// 提供哈希函数
struct pair_hash {
template <class T1, class T2>
std::size_t operator() (const std::pair<T1, T2>& p) const {
auto hash1 = std::hash<T1>{}(p.first);
auto hash2 = std::hash<T2>{}(p.second);
return hash1 ^ (hash2 << 1); // 组合两个哈希值
}
};
unordered_set<PII, pair_hash> st;
int main()
{
cin >> n >> l >> s;
for (int i = 0; i < n; i ++) cin >> tree[i].x >> tree[i].y, st.insert(tree[i]);
for (int i = s; i >= 0; i --)
for (int j = 0; j <= s; j ++)
cin >> b[i][j];
int res = 0;
for (int k = 0; k < n; k ++) {
int tx = tree[k].x, ty = tree[k].y;
if (tx + s <= l && ty + s <= l) {
bool flag = true;
for (int i = tx; i <= tx + s; i ++) {
for (int j = ty; j <= ty + s; j ++) {
int bx = i - tx, by = j - ty;
int temp = 0;
if (st.find({i, j}) != st.end()) temp = 1;
if (temp != b[bx][by]) {
flag = false;
break;
}
}
if (!flag) break;
}
if (flag) res ++;
}
}
cout << res << endl;
return 0;
}
用set,查找操作的时间复杂度为 O(log n),大数据TLE
#include <iostream>
#include <set>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 55, M = 1010;
int n, l, s;
int b[N][N];
PII tree[M];
set<pair<int, int>> st;
int main()
{
cin >> n >> l >> s;
for (int i = 0; i < n; i ++) cin >> tree[i].x >> tree[i].y, st.insert(tree[i]);
for (int i = s; i >= 0; i --)
for (int j = 0; j <= s; j ++)
cin >> b[i][j];
int res = 0;
for (int k = 0; k < n; k ++) {
int tx = tree[k].x, ty = tree[k].y;
if (tx + s <= l && ty + s <= l) {
bool flag = true;
for (int i = tx; i <= tx + s; i ++) {
for (int j = ty; j <= ty + s; j ++) {
int bx = i - tx, by = j - ty;
int temp = 0;
if (st.count({i, j})) temp = 1;
if (temp != b[bx][by]) {
flag = false;
break;
}
}
if (!flag) break;
}
if (flag) res ++;
}
}
cout << res << endl;
return 0;
}