ABC259Ex
考虑两种暴力。
- 直接枚举同颜色的点,枚举起点和终点,组合数计算路径数即可,复杂度 \(\mathcal O(k^2)\),其中 \(k\) 为该颜色的点的个数。
- 做一遍 \(\mathcal O(n^2)\) DP,遇到该颜色的点就统计答案。
根号分治,若 \(k\le n\),采用暴力一,易知复杂度不超过 \(\mathcal O(n^3)\),否则采用暴力二,因为这样的颜色至多 \(n\) 种,所以复杂度也不超过 \(\mathcal O(n^3)\)。
Code:
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef pair <int, int> pii;
const int N = 805, mod = 998244353;
int n;
int fac[N*2], inv[N*2];
vector <pii> pos[N*N];
int f[N][N], vis[N][N];
int qpow(int x, int y) {
int res = 1;
while (y) {
if (y & 1) res = 1ll * res * x % mod;
x = 1ll * x * x % mod;
y >>= 1;
}
return res;
}
void init(int maxn) {
fac[0] = 1;
for (int i = 1; i <= maxn; ++i) fac[i] = 1ll * fac[i - 1] * i % mod;
inv[maxn] = qpow(fac[maxn], mod - 2);
for (int i = maxn - 1; ~i; --i) inv[i] = 1ll * inv[i + 1] * (i + 1) % mod;
}
int C(int n, int m) {
if (n < 0 || m < 0 || n < m) return 0;
return 1ll * fac[n] * inv[m] % mod * inv[n - m] % mod;
}
void add(int &a, int b) {
a += b;
if (a >= mod) a -= mod;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
for (int j = 1, x; j <= n; ++j)
scanf("%d", &x), pos[x].push_back(pii(i, j));
init(n * 2);
int ans = 0;
for (int x = 1; x <= n * n; ++x) if (pos[x].size()) {
if (pos[x].size() <= n) {
for (int i = 0; i < pos[x].size(); ++i)
for (int j = i; j < pos[x].size(); ++j) {
int x1 = pos[x][i].fi, y1 = pos[x][i].se, x2 = pos[x][j].fi, y2 = pos[x][j].se;
add(ans, C(x2 - x1 + y2 - y1, x2 - x1));
}
}
else {
memset(vis, 0, sizeof vis);
for (auto i : pos[x]) vis[i.fi][i.se] = 1;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j) {
f[i][j] = (f[i - 1][j] + f[i][j - 1]) % mod;
if (vis[i][j] == 1) ++f[i][j], f[i][j] %= mod, add(ans, f[i][j]);
}
}
}
printf("%d", ans);
return 0;
}