413 字
2 分钟
Maximum-Neighborhood

题面#

Consider an n×nn \times n grid filled with numbers as follows:

  • the first row contains integers from 11 to nn from left to right;
  • the second row contains integers from (n+1)(n+1) to 2n2n from left to right;
  • this pattern continues until the nn-th row, which contains integers from (n2−n+1)(n^2-n+1) to n2n^2 from left to right.

Let’s define the cost of a cell as its value plus the sum of its neighboring cells’ values. Two cells are considered neighboring if they share a side.

Your task is to calculate the maximum cost among all cells in the grid.

The grid for n=4n = 4 and the optimal answer for it. The yellow cell has the maximum possible cost; the green cells are its neighbors. The cost of the cell is 15+11+14+16=5615+11+14+16=56.

Input

The first line contains a single integer tt (1≤t≤1001 \le t \le 100) — the number of test cases.

The only line of each test case contains a single integer nn (1≤n≤1001 \le n \le 100).

Output

For each test case, print a single integer — the maximum cost among all cells in the grid.

思路#

设位置为第 ii 行第 jj 列则值为 a(i,j)=(i−1)n+ja(i,j)=(i-1)n+j

相邻格共享边因此最多 44 个邻居且每个邻居与自身相差 11 或 nn

最大值一定出现在靠右下的位置因为邻居与自身都更大

  • 当 n≤2n\le 2 可直接得答案为 n=1⇒1n=1\Rightarrow 1 以及 n=2⇒9n=2\Rightarrow 9
  • 当 n≥3n\ge 3 只需比较右下角 2×22\times 2 内的候选

令 x=a(n−1,n−1)=n2−n−1x=a(n-1,n-1)=n^2-n-1 则其代价为 x+(x+1)+(x+n)+x+(x−1)=5x=5n2−5n−5x+(x+1)+(x+n)+x+(x-1)=5x=5n^2-5n-5

令 y=a(n,n−1)=n2−1y=a(n,n-1)=n^2-1 则其代价为 y+(y+1)+y+(y−n)=4y−n+1=4n2−n−4y+(y+1)+y+(y-n)=4y-n+1=4n^2-n-4

其余两格的邻居数更少且代价更小因此最大值为 max⁡(5n2−5n−5, 4n2−n−4)\max(5n^2-5n-5,\ 4n^2-n-4)

比较差值 (5n2−5n−5)−(4n2−n−4)=n2−4n−1(5n^2-5n-5)-(4n^2-n-4)=n^2-4n-1
因此 n∈{3,4}n\in\{3,4\} 时答案为 4n2−n−44n^2-n-4 且 n≥5n\ge 5 时答案为 5n2−5n−55n^2-5n-5

代码#

#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t --) {
long long n;
cin >> n;
if (n == 1) cout << 1 << endl;
else if (n == 2) cout << 9 << endl;
else if (n == 3 || n == 4) cout << 4*pow(n, 2) - n - 4 << endl;
else cout << 5*pow(n, 2) - 5 * n - 5 << endl;
}
}
Maximum-Neighborhood
https://github.com/posts/算法/maximum-neighborhood/
作者
FZSGBall
发布于
2026-05-27
许可协议
CC BY-NC-SA 4.0