跳到正文

题解

题解:AT_abc377_f [ABC377F] Avoid Queen Attack

cbcyh约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年1月6日
收录
2026年1月6日
更新
2026年11月10日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1

为什么别的题解都说是容斥?感觉这个题和容斥也没啥大关系呀。

题意

给定一个 N×NN \times N 的棋盘,上面有 MM 个棋子,每个棋子都能攻击和它同一行、同一列和同一斜线上的棋子。问还有多少个位置能放棋子。

思路

不同行直接肯定是平行的,没有交点,不同列也是。根据小学学过的数学知识,我们可以把这些有棋子的行、列统一移到棋盘右上角,设有 c1c1 行有棋子,有 c2c2 列有棋子,那么剩下的格子数就是 (N−c1)×(N−c2)(N - c1) \times (N - c2)。如下图。 光考虑这些是不够的,还要考虑每个棋子的两条斜线。对于每条从左下到右上斜线,我们可以 O(Mlog⁡M)O(M \log M) 时间以内算出以前的横线和竖线有多少交点。同样也可以把从左上到右下的斜线与它们的交点算出来。 那么,如何计算这两种斜线的交点呢?设第一条直线满足 x+y=kx+y=k,第二条直线满足 x−y=zx-y=z。那么解 k=zk=z 这个方程,可得:

x=k+z2y=k−xx= \frac{k+z}{2}\\ y= k-x

算出来的 x,yx,y 要满足 1≤x≤N,1≤y≤N1 \le x \le N,1 \le y \le N 且 x,yx,y 都为整数。 那么我们也就可以在 O(Mlog⁡M)O(M\log M) 时间复杂度以内解决。注意我们只需要算一遍。

时间复杂度

枚举线段是 O(M)O(M) 的,计算交点是 O(Mlog⁡M)O(M \log M) 的。总时间复杂度为 O(M2log⁡M)O(M^2 \log M)。 有棋子的行、列都是要去重的。可以直接使用 set,当然也可以用 vector,把时间复杂度做到 O(M2)O(M^2)。

代码实现

AC link

C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define unll unsigned long long
#define bint __int128
#define set_q priority_queue
#define unmp unordered_map
mt19937_64 mrand((unll) std::chrono::steady_clock::now().time_since_epoch().count());

inline ll in () {
	ll x = 0; bool f = false; char ch = getchar();
	while (ch < '0' || ch > '9') {f |= ch == '-'; ch = getchar();}
	while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
	return f ? -x : x;
}

const ll p = 1000000007, inf = 1ll << 60ll, infless = -(1ll << 60ll);

inline ll quickpow (const ll &a, const ll &n) {
	ll res = 1ll, t = a;
	for (ll y = n; y > 0; y >>= 1) {
		if (y & 1) {
			res *= t;
			res %= p;
		}
		t *= t;
		t %= p;
	}
	return res;
}

const int N = 1010, M = 520;

int test, n, m;
set<int> a, b, c, d;
ll ans = 0ll;

inline void solve () {
	ans = 0ll;
	//solve clear !
	n = in(), m = in();
	for (int i = 1; i <= m; i++) {
		int x = in(), y = in();
		a.insert(x);
		b.insert(y);
		c.insert(x + y);
		d.insert(x - y);
	}
	ans = 1ll * (n - (int)(a.size())) * (n - (int)(b.size()));
	for (auto z : c) {
		set<int> r;
		for (auto x : a) {
			int y = z - x;
			if (y >= 1 && y <= n) {
				r.insert(x);
			}
		}
		for (auto y : b) {
			int x = z - y;
			if (x >= 1 && x <= n) {
				r.insert(x);
			}
		}
		ll s = 0ll;
		if (z <= n + 1) {
			s = z - 1;
		} else {
			s = n - (z - n) + 1;
		}
		ans -= (s - (ll)r.size());
	}
	for (auto z : d) {
		set<int> r;
		for (auto x : a) {
			int y = x - z;
			if (y >= 1 && y <= n) {
				r.insert(x);
			}
		}
		for (auto y : b) {
			int x = z + y;
			if (x >= 1 && x <= n) {
				r.insert(x);
			}
		}
		for (auto k : c) {
			if (!((k + z) & 1)) {
				ll x = (k + z) / 2, y;
				y = k - x;
				if (x >= 1 && x <= n && y >= 1 && y <= n) {
					r.insert(x);
				}
			}
		}
		ll s = 0ll;
		if (z >= 0) {
			s = n - z;
		} else {
			s = n + z;
		}
		ans -= (s - (ll)r.size());
	}
	printf("%lld\n", ans);
	return;
}

int main() {
	for (test = 1; test--; solve());
	return 0;
}
原文