题目连接: http://hihocoder.com/problemset/problem/1687
思路就是找到一个最右下(左上,右上,左下都可以)的点,然后以这个点遍历其他的每个点,然后找到斜率最大或者最小的那个点就是符合题意的点。用结构体去存坐标和点的编号,然后sort排序,把最右下的点放到第一个,然后从第二个开始遍历就好了。注意在求k值得时候,x1和x2可能相等,然后除以0就会Runtime Error。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct Node{
int x,y;
int num;
}Edge[100005];
int n;
bool cmp(Node a,Node b){
if(a.x == b.x){
return a.y < b.y;
}
return a.x > b.x;
}
double k(int x1,int y1,int x2,int y2){
if(x1 == x2)return 0;
else return (y1-y2)/(x1-x2);
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&Edge[i].x,&Edge[i].y);
Edge[i].num = i;
}
sort(Edge + 1, Edge + 1 + n, cmp);
int flag1;
double Max = -0x3f3f3f3f;
for(int i=2;i<=n;i++){
double ans = k(Edge[1].x,Edge[1].y,Edge[i].x,Edge[i].y);
if(ans > Max){
Max = ans;
flag1 = Edge[i].num;
}
}
cout<<Edge[1].num<<" "<<flag1<<endl;
return 0;
}