题意解析
设点 A 坐标 ( a , b ) (a, b) (a,b),点 B 坐标 ( c , d ) (c, d) (c,d)。
满足:
- ∣ a − c ∣ = ∣ b − d ∣ |a - c| = |b - d| ∣a−c∣=∣b−d∣。
- w a , b = w c , d w_{a, b} = w_{c, d} wa,b=wc,d。
那么 AB 就是一对满足条件的格子。
20pts
- 枚举点 A 可能的情况,时间复杂度 O ( n 2 ) O(n^2) O(n2)。
- 枚举点 B 可能的情况,时间复杂度 O ( n 2 ) O(n^2) O(n2)。
- 判断是否满足上述条件 1 , 2 1, 2 1,2,时间复杂度 O ( 1 ) O(1) O(1)。
总的时间复杂度 O ( n 4 ) O(n^4) O(n4)。
100pts(法一)
要优化时间复杂度,必须从条件 1 1 1 或条件 2 2 2 入手。
条件 1 1 1 等价于,AB 两点在同一条斜线上。
如下图的棕色方块,均为在一条斜线上(本条件类似于八皇后的车)。
优化 <条件 1>:
在每一条斜线上进行枚举,判断条件 2 2 2,这样时间复杂度约为 n 3 n^3 n3。
优化 <条件 2>:
先预处理出所有值的位置,例如 v a l u e = 3 value = 3 value=3 的点位于 ( 1 , 2 ) (1, 2) (1,2), ( 3 , 4 ) (3, 4) (3,4), … \dots …。
再进行二重循环枚举,判断点是否在一条斜线上,在数据随机的情况下时间复杂度有较大优化,但当所有点的 v a l u s valus valus 均相等时,时间复杂度为 n 4 n^4 n4。
结合上述两个优化
遍历每一条斜线( k = 1 k = 1 k=1 或 k = − 1 k = -1 k=−1),在一条斜线上维护之前的值的出现的次数,例如我现在遍历到斜线的第 5 5 5 个点, v a l u e = 3 value = 3 value=3,前 4 4 4 个点中, v a l u e = 3 value = 3 value=3 的点,均可以与本点进行配对。
由于若 AB 配对,那么一定有 BA 配对,故答案需 × 2 \times 2 ×2。
100pts(法二)
我们对所有的对角线进行枚举(同法一),这样只要在这个数组上的两个数的值是相同的,那么他俩就可以组成两个对子,所以我们建立一个临时数组,将整条对角线上的点都放入一个数组中,随后对数组进行排序。
在一个有序数组中,统计每个数的出现次数,我们可以用双指针进行计算。
- Python(法一)
n, m = map(int, input().split())
g = []
for i in range(n):
lis = list(map(int, input().split()))
g.append(lis)
dx = [1, 1]
dy = [1, -1]
def get_ans(x, y, d):
res = 0
h = {}
while x >= 0 and y >= 0 and x < n and y < m:
v = g[x][y]
if v in h:
res += h[v]
else:
h[v] = 0
h[v] += 1
x += dx[d]
y += dy[d]
return res
res = 0
for j in range(m):
res += get_ans(0, j, 0)
for i in range(1, n):
res += get_ans(i, 0, 0)
for j in range(m):
res += get_ans(0, j, 1)
for i in range(1, n):
res += get_ans(i, m - 1, 1)
print(res * 2)
- C++(法二)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
const int N = 1e3 + 10;
int dx[] = {1, 1}, dy[] = {1, -1};
int n, m;
int g[N][N];
int get_ans(int x, int y, int d)
{
vector<int> p;
while (x >= 0 && y >= 0 && x < n && y < m)
{
p.push_back(g[x][y]);
x += dx[d], y += dy[d];
}
sort(p.begin(), p.end());
int res = 0;
for (int i = 0; i < p.size(); ++ i )
{
int j = i + 1;
while (j < p.size() && p[i] == p[j])
j ++;
int cnt = j - i;
res += cnt * (cnt - 1);
i = j - 1;
}
return res;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; ++ i )
for (int j = 0; j < m; ++ j )
cin >> g[i][j];
int res = 0;
for (int j = 0; j < m; ++ j )
res += get_ans(0, j, 0);
for (int i = 1; i < n; ++ i )
res += get_ans(i, 0, 0);
for (int j = 0; j < m; ++ j )
res += get_ans(0, j, 1);
for (int i = 1; i < n; ++ i )
res += get_ans(i, m - 1, 1);
cout << res << endl;
return 0;
}