给定n个点坐标,输出可以组成多少个平行四边形(C++)
请大家先看问题:
You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points. Input The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points. Each of the next n lines contains two integers (xi, yi) (0 ≤ xi, yi ≤ 109) — the coordinates of the i-th point. Output Print the only integer c — the number of parallelograms with the vertices at the given points. Example Input 4 0 1 1 0 1 1 2 0 Output 1
这个题我的思路是定义结构体来表示一个点的纵横坐标,然后把给定n个点的坐标录入后,每次对4个点坐标进行比较。
比较方法原来是想从平行四边形定义:不相邻两边平行证,难以实现。队友指出直接用对角线中点坐标相等即可。雀食可以实现,但是我的想法是四重循环,肯定超时啊!
遂上网,看到大佬利用的方法是ans=(num+1)*num/2,想了很久终于想到了:若两个对角线中点重合,说明有一个平行四边形;若三条对角线中点都重合呢?那就有1+2=3个平行四边形了!由此可推,若n条对角线中点重合,则有1+2+3+......+n-1个平行四边形,也就是(n+1)*n/2个。这是整个实现过程的关键。
此外,在计算ans前的排序也很重要,这样保证计算是从坐标系左下开始逐渐向坐标增大的方向寻找点的,每次先寻找最近的点,可以减少麻烦。
此外值得一提的是看大佬的博客,学到了sort()函数的第三个参数是用来自己定义排序规则的,若不写则默认从小到大排列;若自己写则自定义函数遵循如下规则:
对于sort(起点地址,终点地址,cmp),cmp(a,b)来说:
若cmp返回值为true,则排序是a b;
若cmp返回值为false,则排序是b a;
明白这个规则再看大佬的几段源代码,就知道为什么这么写可以实现从大到小/从小到大的排序。链接如下:
C++中sort函数使用方法 - 俊宝贝 - 博客园 (cnblogs.com)
粘贴大佬源码如下:
#include<iostream> #include<algorithm> using namespace std; bool cmp(int a,int b); main(){ //sort函数第三个参数自己定义,实现从大到小 int a[]={45,12,34,77,90,11,2,4,5,55}; sort(a,a+10,cmp); for(int i=0;i<10;i++) cout<<a[i]<<" "; } //自定义函数 bool cmp(int a,int b){ return a>b; }
1 #include<iostream> 2 #include<algorithm> 3 #include"cstring" 4 using namespace std; 5 typedef struct student{ 6 char name[20]; 7 int math; 8 int english; 9 }Student; 10 bool cmp(Student a,Student b); 11 main(){ 12 //先按math从小到大排序,math相等,按english从大到小排序 13 Student a[4]={{"apple",67,89},{"limei",90,56},{"apple",90,99}}; 14 sort(a,a+3,cmp); 15 for(int i=0;i<3;i++) 16 cout<<a[i].name <<" "<<a[i].math <<" "<<a[i].english <<endl; 17 } 18 bool cmp(Student a,Student b){ 19 if(a.math >b.math ) 20 return a.math <b.math ;//按math从小到大排序 21 else if(a.math ==b.math ) 22 return a.english>b.english ; //math相等,按endlish从大到小排序23 24 }

浙公网安备 33010602011771号