Test SRM Level Three: LargestCircle, Brute F

系统 1456 0

题目来源: http://community.topcoder.com/stat?c=problem_statement&pm=3005&rd=5858


思路:

如果直接用Brute Force搜索所有可能的圆的话,那么搜索空间将很大,所以我用了一个priority_queue结构,将搜索的顺序变为按圆的半径从大到小搜索,所以当搜索到符合条件的圆时,即可停止搜索。这样可以大大减少搜索范围,不过对于最坏的情况,也就是没有符合条件的圆时,还是会将所有的可能情况都搜索到。


代码如下:

 

    #include <iostream>

#include <algorithm>

#include <vector>

#include <queue>

#include <utility>

#include <cmath>



using namespace std;



typedef pair <int, pair<int, int> > entry;

#define make_entry(radius, row, col) ( make_pair( (radius), make_pair( (row), (col) ) ) )



class LargestCircle

{

public:

	int radius(vector <string> grid);

};



bool checkCircle(int cusRadius, int cus_row, int cus_col, vector<string> & grid);

int LargestCircle::radius(vector<string> grid)

{

	int i, j;

	int rows, cols, cus_row, cus_col;

	priority_queue <entry> PQ;

	int maxRadius, cusRadius;



	rows = grid.size();

	cols = grid[0].size();

	for (i = 0; i < rows - 1; i++) {

		for (j = 0; j < cols - 1; j++) {

			PQ.push(make_pair(min(min(i + 1, j + 1), min(rows - i - 1, cols - j - 1)), 

				make_pair(i, j)));

		}

	}



	maxRadius = 0;



	while ( !PQ.empty() ) {

		cusRadius = PQ.top().first;

		cus_row = PQ.top().second.first;

		cus_col = PQ.top().second.second;

		PQ.pop();



		if ( checkCircle(cusRadius, cus_row, cus_col, grid) ) {

			maxRadius = cusRadius;

			break;

		}

		--cusRadius;

		if (cusRadius > 0) {

			PQ.push(make_entry(cusRadius, cus_row, cus_col));

		}

	}



	return maxRadius;

}



/**

 * 检查该圆是否合法

 */

bool checkCircle(int cusRadius, int cus_row, int cus_col, vector<string> & grid)

{

	int i, j;

	double pre_bias, next_bias;

	int pre_cell, next_cell;

	int next_row, next_col;



	next_bias = 0;

	for (i = 0; i < cusRadius; i++) {

		pre_bias = next_bias;	/* pre_bias值与上一个循环中的 next_bias值相等 */

		next_bias = sqrt( pow( (double)cusRadius, 2 ) - pow( (double)(cusRadius-i - 1), 2 ) );



		pre_cell = (int)pre_bias;

		next_cell = (int)next_bias;

		if ( abs( next_bias - next_cell > 0.00001)) {

			++next_cell;

		}



		for (j = 0; j < next_cell - pre_cell; j++) {

			next_row = cus_row - (cusRadius - i) + 1;

			next_col = cus_col - pre_cell - j;

			if ('#' == grid[next_row][next_col] ||

			    '#' == grid[next_row][2 * cus_col + 1 - next_col] ||	// 右对称点

			    '#' == grid[2 * cus_row + 1 - next_row][next_col] ||	// 下对称点

			    '#' == grid[2 * cus_row + 1 - next_row][2 * cus_col + 1 - next_col]) {	//中心对称

				return false;

			}

		}

	}



	return true;

}


  


 

 

Test SRM Level Three: LargestCircle, Brute Force


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论