Description
“We need a programmer to help us for some projects. If you show us that you or one of your friends is able to program, you can pass the first hurdle.
I will give you a problem to solve. Since this is the first hurdle, it is very simple.”
We all know that the simplest program is the “Hello World!” program. This is a problem just as simple as the “Hello World!”
In a large matrix, there are some elements has been marked. For every marked element, return a marked element whose row and column are larger than the showed element’s row and column respectively. If there are multiple solutions, return the element whose row is the smallest; and if there are still multiple solutions, return the element whose column is the smallest. If there is no solution, return -1 -1.
Saya is not a programmer, so she comes to you for help
Can you solve this problem for her?
Input
The first line of input in each test case contains one integer N (0<N≤1000), which represents the number of marked element.
Each of the next N lines containing two integers r and c, represent the element’s row and column. You can assume that 0<r, c≤300. A marked element can be repeatedly showed.
The last case is followed by a line containing one zero.
Output
Sample Input
3 1 2 2 3 2 3 0
Sample Output
Case 1: 2 3 -1 -1 -1 -1
作为一名计算机专业的学生,Hello World可以说是我们最为熟悉的了,是这两个单词领我们走进计算机领域,一切就此打开,而在ACMer的AC道路上,这两个单词也几乎就是水题的代名词,这不,在2010年山东ACM省赛上,我们就见识了一个Hello World。
这道题的大意:在一个大小未知的矩阵中有N个被标记的元素,然后针对每一个被标记的元素e(x,y),你要在所有被标记的元素中找到一个元素E(X,Y),使得X>x并且Y>y,如果存在多个满足条件的元素,先比较X,选择X最小的那个,如果还是有很多满足条件的元素,再比较Y,选择Y最小的元素,如果不存在就输出两个-1,每一组测试数据都要输出一个Case n。
解题的方法可以说有很多,如果对STL熟悉,就用set,只不过元素要换成pair<int,int>,因为要同时记录x,y坐标,或者用结构体数组,最差也可以用一个真实的矩阵,不过因为矩阵大小未知,定义和搜索的时候可能会超内存或者超时,推荐前两种方法,这里我选择了第二种。
1.结构体中只存储行列坐标信息
2.建立结构体数组,将数据存入其中
3.以横坐标为第一顺序,纵坐标为第二顺序进行递增排序,这样做是为了符合题意并有利于后续处理
4.对每一个元素,从排好序的数据中遍历查找,第一个遇到的符合条件的数据即为符合题意得数据,如果没有找到则输出-1
5.最后不要忘了每组测试数据之后有一个空行,表示每次做完题都会忘记,然后华丽的PE了
#include<iostream>
#include<algorithm>
using namespace std;
struct E
{
int r,c;
};
bool cmp(const E &a,const E &b)
{
if(a.r<b.r)
return 1;
if((a.r==b.r)&&(a.c<b.c))
return 1;
return 0;
}
int main()
{
int n,i,j,cas=0,r,c;
while(cin>>n,n)
{
E *e=new E[n];
E *e0=new E[n];
for(i=0;i<n;i++)
{
cin>>r>>c;
e[i].r=r;
e[i].c=c;
e0[i].r=r;
e0[i].c=c;
}
sort(e0,e0+n,cmp);
//for(i=0;i<n;i++)
//cout<<e0[i].r<<' '<<e0[i].c<<endl;
cout<<"Case "<<++cas<<":"<<endl;
for(i=0;i<n;i++)
{
r=e[i].r;
c=e[i].c;
for(j=0;j<n;j++)
{
if(e0[j].r>r&&e0[j].c>c)
{
cout<<e0[j].r<<' '<<e0[j].c<<endl;
break;
}
}
if(j==n)
cout<<-1<<' '<<-1<<endl;
}
cout<<endl;
}
return 0;
}