K-special Tables

C. K-special Tables
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.

Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:

  • every integer from 1 to n2 appears in the table exactly once;
  • in each row numbers are situated in increasing order;
  • the sum of numbers in the k-th column is maximum possible.

Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.

Input

The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.

Output

First print the sum of the integers in the k-th column of the required table.

Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.

If there are multiple suitable table, you are allowed to print any.

Sample test(s)
input
4 1
output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
input
5 3
output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13


题意:输出一个n*n的矩阵,要求有三个。

 1、1~n*n各个数有且只有一个。

2、每一行都要递增。
 3、保证第k列,在所有可能答案中最大。
思路:k=1时,直接按1~n*n输出。当k!=1时,按1~n*n存入二维数组,到k-1列就换行,再从第一行的第k列依次存入二维数组中即可。最后算出第k列的和。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
    int i,j,k,n;
    int mp[505][505];
    int a=1,ans=0;
    scanf("%d%d",&n,&k);
    if(k==1)
    {
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
                mp[i][j]=a++;

        for(i=1;i<=n;i++)
            ans+=mp[i][k];
    }
    else
    {
        for(i=1;i<=n;i++)
            for(j=1;j<k;j++)
                mp[i][j]=a++;

        for(i=1;i<=n;i++)
            for(j=k;j<=n;j++)
                mp[i][j]=a++;

        for(i=1;i<=n;i++)
            ans+=mp[i][k];
    }

    printf("%d\n",ans);
    for(i=1;i<=n;i++)
    {
        for(j=1;j<n;j++)
        {
            printf("%d ",mp[i][j]);
        }
        printf("%d\n",mp[i][n]);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值