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 (n2n+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 (1t1001 \le t \le 100) — the number of test cases.

The only line of each test case contains a single integer nn (1n1001 \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)=(i1)n+ja(i,j)=(i-1)n+j

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

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

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

x=a(n1,n1)=n2n1x=a(n-1,n-1)=n^2-n-1 则其代价为 x+(x+1)+(x+n)+x+(x1)=5x=5n25n5x+(x+1)+(x+n)+x+(x-1)=5x=5n^2-5n-5

y=a(n,n1)=n21y=a(n,n-1)=n^2-1 则其代价为 y+(y+1)+y+(yn)=4yn+1=4n2n4y+(y+1)+y+(y-n)=4y-n+1=4n^2-n-4

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

比较差值 (5n25n5)(4n2n4)=n24n1(5n^2-5n-5)-(4n^2-n-4)=n^2-4n-1
因此 n{3,4}n\in\{3,4\} 时答案为 4n2n44n^2-n-4n5n\ge 5 时答案为 5n25n55n^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