Revenge of Collinearity
Time Limit: 8000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
In geometry, collinearity is a property of a set of points, specifically, the property of lying on a single line. A set of points with this property is said to be collinear (often misspelled as colinear).
---Wikipedia
Today, Collinearity takes revenge on you. Given a set of N points in two-dimensional coordinate system, you have to find how many set of <Pi, Pj, Pk> from these N points are collinear. Note that <Pi, Pj,
Pk> cannot contains same point, and <Pi, Pj, Pk> and <Pi, Pk, Pj> are considered as the same set, i.e. the order in the set doesn’t matter.
Input
The first line contains a single integer T, indicating the number of test cases.
Each test case begins with an integer N, following N lines, each line contains two integers Xi and Yi, describing a point.
[Technical Specification]
1. 1 <= T <= 33
2. 3 <= N <= 1 000
3. -1 000 000 000 <= Xi, Yi <= 1 000 000 000, and no two points are identical.
4. The ratio of test cases with N > 100 is less than 25%.
Output
For each query, output the number of three points set which are collinear.
Sample Input
2 3 1 1 2 2 3 3 4 0 0 1 0 0 1 1 1
Sample Output
1 0
Source
题目大意:给出n个二维平面的点,问有多少对三点共线。
解题思路:既然是三点共线,不妨设为A,B,C三点,如果我们纯粹暴力枚举A,B,C三点,为了ABC三点之间不相互重复,我们可以先对点排个序,按照x优先非递减,y次之非递减。但是纯粹暴力必然TLE,如果减少枚举的点数,那么就可以减少时间复杂度,假如我们只枚举点A,那么对于其他点中的每一个都会与A点形成一条直线,如果某一条直线出现的不止一次,那么就意味着至少有另外两对与A点在同一直线上,那么就相应的存在三点共线。假设有k个点与A点共线(注意:这里共线是说这k+1个点都在同一直线上)(另外,还要注意这k个点是不重复的,何为不重复呢?举例说明:有(1,0),(2,0),(3,0),(4,0),(5,0)五个点,当A=(1,0)时,k=4;当A=(2,0)时,k=3而不是k=4;当A=(3,0)时,k=2,……)。因为枚举的是A点,其中A点必包括,那么就有k*(k-1)/2对三点共线,枚举完所有的A点,总和就是答案。
对于共线数目k的求解………………………………
代码如下:
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <iostream> #include <algorithm> #include <string> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <stack> #include <queue> #include <numeric> #include <iomanip> #include <bitset> #include <sstream> #include <fstream> #include <limits.h> #define debug "output for debug\n" #define pi (acos(-1.0)) #define eps (1e-6) #define inf (1<<28) #define sqr(x) (x) * (x) #define mod 1000000007 using namespace std; typedef long long ll; typedef unsigned long long ULL; typedef pair<ll,ll> p; map<p,ll> m; struct point { ll x,y; }a[1005]; ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; } bool cmp(point a,point b) { if(a.x==b.x) return a.y<b.y; return a.x<b.x; } int main() { ll i,j,k,n,t; scanf("%I64d",&t); while(t--) { scanf("%I64d",&n); for(i=0;i<n;i++) scanf("%I64d%I64d",&a[i].x,&a[i].y); sort(a,a+n,cmp); ll ans=0; for(i=0;i<n;i++) { m.clear(); for(j=i+1;j<n;j++) { ll dx=a[j].x-a[i].x; ll dy=a[j].y-a[i].y; ll d=gcd(dx,dy); dx=dx/d; dy=dy/d; m[make_pair(dx,dy)]++; } map<p,ll>::iterator it; for(it=m.begin();it!=m.end();it++) { k=it->second; if(k>=2) ans=ans+k*(k-1)/2; } } printf("%I64d\n",ans); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。