Alice is very interested in the algorithm. He finds a interesting book called "Algorithmic puzzles" which contains more than 100 puzzles. The puzzles included many typical algorithmic thinking in the programming. He likes the grid puzzles most. The grid puzzle is which the puzzle is based on the grids.
On the page 173, Alice is attracted by a grid puzzle. There is a N * N grids. Each grid should be filled with a number from 1, 2, .., N * N. No two girds share the same number. For any two adjacent numbers X and X + 1, the grids they filled in should also be adjacent. The problem is to find the maximum sum of the numbers in the main diagonal (the ith grid in the ith row). Alice wants you to help him solve the problem.
Input
There are multiple test cases. For each test case:
There is an integer N (1 <= N <= 1000) which described above.
Output
For each test case, output the maximum sum of the numbers in the main diagonal.
Sample Input
2 3
Sample Output
6 19
Author: GAN, Tiansheng
Source: ZOJ Monthly, January 2014
题意:就是给出一个n*n的矩阵然后在里面填1~n*n的数,使任意两个相邻的数在矩阵的位置也是相邻的,求所有情况中主对角线之和最大,并输出最大值。
题解:这道题是纯找规律。。居然要最大主对角线,那我们就从最大开始摆。从n*n,n*n-2,n*n-4……n*n-2*(n-2),因为对角线不是直接能到达的,所以就只能跳一个转弯到达。之后不能主对角线的n个元素全封了,这就不能填满了,所以留一个出口。之后就是找出对角线最后一个元素的规律。1 ,2,3,6,9可以看出规律为:(n-1)*n/2-(n-1)/2+1
最后套公式——(这还是赛后在q群上看人家的解题思路。。惭愧。。)
#include<stdio.h> #include<cstring> int main() { int n,i; while(~scanf("%d",&n)) { int ans = (n-1)*n/2+1-(n-1)/2; for(i=0;i<n-1;i++) ans+=(n*n-2*i); printf("%d\n",ans); } return 0; }