ZOJ Monthly, January 2014 E Diagonal (浙江大学月赛)

Diagonal

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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
Submit    Status


题意:就是给出一个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;
}

 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值