【77.78%】【codeforces 625C】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.
Examples
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
【题目链接】: http://codeforces.com/contest/625/problem/C
【题解】
贪心.
尽量让小的数字先在前k-1列出现.剩下的数按顺序每一行从左往右安排就可以了.;
看样例也能看出来了.
【完整代码】
#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%I64d",&x)
typedef pair<int,int> pii;
typedef pair<LL,LL> pll;
const int MAXN = 500+10;
const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
int n,k;
int a[MAXN][MAXN];
int main()
{
//freopen("F:\\rush.txt","r",stdin);
rei(n);rei(k);
int now = 0;
rep1(i,1,n)
rep1(j,1,k-1)
a[i][j] = ++now;
rep1(i,1,n)
rep1(j,k,n)
a[i][j] = ++now;
LL temp = 0;
rep1(i,1,n)
temp += a[i][k];
cout << temp << endl;
rep1(i,1,n)
rep1(j,1,n)
{
printf("%d",a[i][j]);
if (j==n)
puts("");
else
putchar(' ');
}
return 0;
}