POJ1151(求矩阵的并面积) 离散化

find函数直接用了线性搜索,居然没有TLE。

#include <iostream>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;

struct rec
{
	double x1;
	double y1;
	double x2;
	double y2;
};

int find(double aim,double* arr,int T)
{
	int i;
	for (i=0;i<=T-1;i++)
	{
		if (aim==arr[i])
		  return i;
	}
}

int main()
{
  int T;
	int num=0;
	while (1)
	{
		num++;
		int i;
		int j;
		int k;
		double ans=0;
		int posx1;
		int posx2;
		int posy1;
		int posy2;
		int counterx=0;
		int countery=0;
		int total=0;
		int cover[200][200]={{0}};
		double x[200];
		double y[200];
		rec rectangle[100];
		map<double,bool> rx,ry;
		map<double,bool>::iterator iter;
		
		cin >> T;
		if (num!=1 && T!=0)
			cout << endl << endl;
		if (T==0)
			break;
		for (i=0;i<=T-1;i++)
		{
			cin >> rectangle[i].x1 >> rectangle[i].y1;
			cin >> rectangle[i].x2 >> rectangle[i].y2;
			//重复的坐标不应该添加进数组
			//true表示已存在,flase表示不存在
			iter=rx.find(rectangle[i].x1);
			if (iter==rx.end() || iter->second==false)
			{
		    x[counterx]=rectangle[i].x1;
				rx[rectangle[i].x1]=true;
				counterx++;
			}
			iter=ry.find(rectangle[i].y1);
			if (iter==ry.end() || iter->second==false)
			{
			  y[countery]=rectangle[i].y1;
				ry[rectangle[i].y1]=true;
				countery++;
			}
			iter=rx.find(rectangle[i].x2);
			if (iter==rx.end() || iter->second==false)
			{
			  x[counterx]=rectangle[i].x2;
				rx[rectangle[i].x2]=true;
				counterx++;
			}
			iter=ry.find(rectangle[i].y2);
			if (iter==ry.end() || iter->second==false)
			{
			  y[countery]=rectangle[i].y2;
				ry[rectangle[i].y2]=true;
				countery++;
			}
		}
		sort(x,x+counterx);
		sort(y,y+countery);
		for (i=0;i<=T-1;i++)
		{
			//对于每个矩阵找到坐标在数组中的位置
		  posx1=find(rectangle[i].x1,x,counterx);
			posx2=find(rectangle[i].x2,x,counterx);
			posy1=find(rectangle[i].y1,y,countery);
			posy2=find(rectangle[i].y2,y,countery);
			for (j=posx1;j<posx2;j++)
				for (k=posy1;k<posy2;k++)
				{
					//第j行第k列的矩阵,1表示已覆盖
					cover[j][k]=1;
				}
		}
		
		for (i=0;i<=counterx-1;i++)
			for (j=0;j<=countery-1;j++)
			{
			  if (cover[i][j]==1)
				{
					ans+=(x[i+1]-x[i])*(y[j+1]-y[j]);
				}
			}
		
		cout << "Test case #" << num << endl;
		cout << "Total explored area: ";
		printf("%.2f",ans);
	}
	return 0;
}


你可能感兴趣的:(POJ1151(求矩阵的并面积) 离散化)