微软编程之美热身赛-长方形

Time Limit:
2000ms Case Time Limit:
1000ms Memory Limit:
256MB

Description

在 N 条水平线与 M 条竖直线构成的网格中,放 K 枚石子,每个石子都只能放在网格的交叉点上。问在最优的摆放方式下,最多能找到多少四边平行于坐标轴的长方形,它的四个角上都恰好放着一枚石子。

Input

输入文件包含多组测试数据。
第一行,给出一个整数T,为数据组数。接下来依次给出每组测试数据。
每组数据为三个用空格隔开的整数 N,M,K。

1 ≤ T ≤ 100
0 ≤ K ≤ N * M
小数据:0 < N, M ≤ 30
大数据:0 < N, M ≤ 30000

Output

对于每组测试数据,输出一行”Case #X: Y”,其中X表示测试数据编号,Y表示最多能找到的符合条件的长方形数量。所有数据按读入顺序从1开始编号。

Sample Input

3
3 3 8
4 5 13
7 14 86

Sample Output

Case #1: 5
Case #2: 18
Case #3: 1398

完整代码:

//#include "header.h"	//AnycodeX includes the header.h by default, needn't cancle the notation.
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <cmath>

using namespace std;

void calculate(int *ptr, int index, int N, int M, int K);
void printResult(int N, int *ptr);

int main()
{   
	int K;         //K stones in total
	int N, M;      //N lines, M columns
	int T;      //T groups of data

	cin >> T;
	int *result = new int[T];         //saving results, T groups in total
	for (int i = 0; i < T; i++)
	{
		cin >> N;
		cin >> M;
		cin >> K;
		calculate(result, i, N, M, K);
	}
	printResult(T, result);
} 

void calculate(int *ptr, int index, int N, int M, int K)
{
	int result = 0;
	int temp1 = sqrt(K);
	int temp2 = K - temp1 * temp1;
	int lines = 0;
	int coloum = 0;
	int small = 0;
	int flag = 0;
	if (temp1 < min(N, M))
	{
		if (temp2 > temp1)
		{
			
			coloum = temp1;
			if (temp1 <= N - 2 || temp1 <= M - 2)
			{
				lines = temp1 + temp2/temp1;     //按行优先排或者按列排
				small = temp2 - temp2/temp1 * temp1;
				flag = 1;
			}
			else
			{
				lines = temp1 + 1; 
				small = temp2 - temp1;
				flag = 0;
			}
		}
		else
		{
			lines = temp1;
			coloum = temp1;
			small = temp2;
		}
	}
	else
	{
		coloum = min(N, M);
		lines = K / coloum;
		small = K % coloum;
		flag = 1;
	}
	result = lines*(lines-1)*coloum*(coloum-1)/4;
	if (flag == 1)
		result += small*(small-1)*lines/2;
	else
		result += small*(small-1)*coloum/2;

		ptr[index] = result;
}

void printResult(int N, int *ptr)
{
	for (int i = 0; i < N; i++)
		cout << "case #" << i+1 << ": " << ptr[i] << endl;
}

    原文作者:爱上健身的菇凉
    原文地址: https://blog.csdn.net/XIAXIA__/article/details/23194667
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞