in
3
1 1
1 2
1 3
out
3
in
4
1 3
2 1
3 4
4 2
out
0
穷举法可以,然而会超时
void exhaustion(queen* q, int n)
{
int count = 0;
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
if(q[i].x == q[j].x || q[i].y == q[j].y ||
( abs(q[i].x - q[j].x) == abs(q[i].y - q[j].y)) )
count++;
}
}
cout << count << endl;
}
所以开数组记录每行每列每对角的皇后数量
再根据组合数计算即可
注意从上到左是 x+y
上到右是x-y,为了避免越界要+n保证是整数
#includeusing namespace std; struct queen{ int x; int y; }; long long combination_2(long long n) { if(n < 2) return 0; else { return n * (n-1) / 2; } } void statstics(queen *q, int n) { int* row = new int[n + 1]; int* column = new int[n + 1]; int * upleft = new int[2 * n + 1]; int * upright = new int[2 * n + 1]; for(int i = 0; i < n + 1; i++) row[i] = column[i] = 0; for(int i = 0; i < 2 * n + 1; i++) upleft[i] = upright[i] = 0; for(int i = 0; i < n; i++) { row[q[i].x ]++; column[q[i].y ]++; upleft[q[i].x + q[i].y ]++; upright[q[i].x - q[i].y + n]++; } long long count = 0; for(int i = 0; i < n + 1; i++) count += combination_2(row[i]) + combination_2(column[i]); for(int i = 0; i < 2 * n + 1; i++) count += combination_2(upright[i]) + combination_2(upleft[i]); cout << count << endl; } int main() { int n; cin >> n; queen* q = new queen[n]; for(int i = 0; i < n ;i++) cin >> q[i].x >> q[i].y; //exhaustion(q,n); statstics(q,n); }



