习题4-10 洪水! UVa815

1.题目描述:点击打开链接

2.解题思路:本题给了一个m*n的矩形区域,每个格子的高度不一,长和宽均为10米,输入每个格子的高度和这个网格中洪水的总体积,输出洪水的高度和多少格子被淹没了。可以利用二分搜索解决:把洪水看成一个底面面积为100的长方体,计算出这个长方体的高,然后二分查找洪水的高度即可。

3.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

#define N 30+5
#define INF 100000000
int g[N][N];
int n, m;
int vol;
int _min, _max;
double sum(double h)
{
	double ans = 0.0;
	for (int i = 0; i < m;i++)
	for (int j = 0; j < n;j++)
	if (g[i][j]<h)
		ans += (double)h - g[i][j];
	return ans;
}
void solve(double sumh)
{
	double eps = 1e-5;
	double L = _min, R = INF;
	while (R - L > eps)//二分查找洪水的高度
	{
		double M = L + (R - L) / 2;
		if (sum(M) < sumh)L = M;
		else R = M;
	}
	int cnt = 0;
	for (int i = 0; i < m;i++)
	for (int j = 0; j < n;j++)
	if (g[i][j] < L)cnt++;
	printf("Water level is %.2lf meters.\n", L);
	printf("%.2lf percent of the region is under water.\n", (double)100*cnt / (m*n));
}
int main()
{
	//freopen("t.txt", "r", stdin);
	int rnd = 0;
	while (~scanf("%d%d", &m, &n)&&(m||n))
	{
		memset(g, 0, sizeof(g));
		_min = INF, _max = 0;
		for (int i = 0; i < m;i++)
		for (int j = 0; j < n; j++)
		{
			cin >> g[i][j];
			_min = min(_min, g[i][j]); 
			_max = max(_max, g[i][j]);
		}
		cin >> vol;
		double sumh = (double)vol / 100;
		printf("Region %d\n", ++rnd);
		solve(sumh);
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(二分查找)