Description
You are observing a distant galaxy using a telescope above the Astronomy Tower, and you think that a rectangle drawn in that galaxy whose edges are parallel to coordinate axes and contain maximum star systems on its edges has a great deal to do with the mysteries of universe. However you do not have the laptop with you, thus you have written the coordinates of all star systems down on a piece of paper and decide to work out the result later. Can you finish this task?
Input
There are multiple test cases in the input file. Each test case starts with one integer N , (1N100) , the number of star systems on the telescope. N lines follow, each line consists of two integers: the X and Ycoordinates of the K -th planet system. The absolute value of any coordinate is no more than 109 , and you can assume that the planets are arbitrarily distributed in the universe.
N = 0 indicates the end of input file and should not be processed by your program.
Output
For each test case, output the maximum value you have found on a single line in the format as indicated in the sample output.
Sample Output
10 2 3 9 2 7 4 3 4 5 7 1 5 10 4 10 6 11 4 4 6 0
Sample Input
Case 1: 7
这道题与最大子矩阵的题有些相似,仍然采取扫描法。先确定矩形的上下界,然后再用一条线从左到右扫描,每扫描完一次求一下能包含的最多的点的个数,,求个数时用维护最大值的方法做。这道题还用到了unique去重函数,该函数是对相邻的数进行去重,一般要先排好顺序,同时该函数并不是把重复的数删掉而是把它们挪到后面,return:An iterator to the element that follows the last element not removed
代码如下:
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
int Y[103],on[103],on2[103],Left[103],N;
struct Node
{
int x,y;
bool operator<(const Node &a)const
{
return x<a.x;
}
}zb[103];
int solve()
{
int m,ans=0;
sort(zb,zb+N);
sort(Y,Y+N);
m=unique(Y,Y+N)-Y;
if(m<=2) return N;
for(int i=0;i<m;i++)
{
for(int j=i+1;j<m;j++)
{
int ymin=Y[i],ymax=Y[j],k=0;
Left[k]=0,on[k]=0,on2[k]=0;
if(zb[k].y>ymin&&zb[k].y<ymax) on[k]++;
if(zb[k].y>=ymin&&zb[k].y<=ymax) on2[k]++;
for(int t=1;t<N;t++)
{
if(zb[t].x!=zb[t-1].x)
{
k++;
on[k]=0;on2[k]=0; //每扫描到新的位置,一定要清零
Left[k]=Left[k-1]+on2[k-1]-on[k-1];
}
if(zb[t].y>ymin&&zb[t].y<ymax) on[k]++;
if(zb[t].y>=ymin&&zb[t].y<=ymax) on2[k]++;
}
if(k<=1) return N;
int s=0;
for(int t=0;t<=k;t++)
{
ans=max(ans,Left[t]+on2[t]+s);
s=max(s,on[t]-Left[t]);
}
}
}
return ans;
}
int main()
{
int count=0;
while(scanf("%d",&N)==1&&N)
{
int x,y;
for(int i=0;i<N;i++)
{
cin>>zb[i].x>>zb[i].y;
Y[i]=zb[i].y;
}
printf("Case %d: %d\n",++count,solve());
}
return 0;
}
这道题我犯了两个错误:
1.数组on【】,on2【】没有赋初值就直接进行加一操作。
2.输出格式有错误。