Now N days have passed and he is sobered. He is surprised to find that there are exactly N×M bottles around him. Another amazing fact is that there are N bottles with height 1 and N bottles with height 2 … N bottles with height M.
Now he is interested in playing with these bottles. He wants to arrange all these bottles in a rectangle with M rows and N columns which satisfied:
(1)In any column, there are no bottles with same height;
(2)In any row, the height difference between any two adjacent bottles is no more than 1.
He defined a strange function Y which equals the maximum value of the total height of any single row. He is addicted in arranging these rubbish bottles to find the minimal Y. You know that he cannot solve it with his pour IQ. You are his friend and can’t endure his decadence any more. So you decide to help him solve this problem and then bring him back to study.
The input will finish with the end of file.
3 3 3 5
8 11HintFor the first case the solution is: 1 2 3 2 1 1 3 3 2
题意:
给你n个1,n个2,n个3,... ...n个m,让你组成一个矩阵,要满足:
1.在同一行里,相邻的两个数的差值不能超过1;
2.在同一列中,不能有相同的数字;
现在需要你找出所有情况的矩阵中最大行的最小值。
解:
(为了方便叙述以 3 5 进行分析)
最糟糕的情况是:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
那么这样的最大值为15,这显然不是我们需要的矩阵,那么我们需要替换最大行的3。
那么我们来考虑下这个,一个3,需要符合行的条件的话,放在中间位置需要两个2或者3(像这样:2 3 2 3 3 3)
现在我们需要尽可能小,肯定是选 2 3 2 ,但如果每一行都将3放在中间位置,2是不够用的,那么只能将3放在行的两边,这样一个3能对应一个2,同理,2也将进行排列2 1 2.
那么组成这样3 2 _ 2 3,为了能让行小就变成3 2 1 2 3。
自己按规定组织下,得出矩阵:
3 3 2 1 1
2 1 1 2 3
最大行为3 3 2 2 1.
再看3 3的情况:
最糟糕的是3 3 3,替换的话是3 2 3,如果是:3 2 1的话,按照列的规则应该完善的矩阵是:
3 2 1,
_ 3 _
_ _ 3
按照行的规则完善:
3 2 1,
2 3 2
_ 2 3
显然不符合条件(3 2 2)同理。
那么我们可以得出最大行道的排列应该是等差的一个数列,m , m,m-1,m-1,m-2,m-2.....m-(n+1)/2.
求这个数列的和就行了。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
int n,m;
while(~scanf("%d%d",&m,&n))
{
int sum=0;
int temp=m-n/2;
int k=(n+1)/2;
while(k--)
{
if(m!=temp)
sum+=m;
sum+=m;
m--;
}
printf("%d\n",sum);
}
return 0;
}