1. 程式人生 > >hdu 5020(判斷三點共線)

hdu 5020(判斷三點共線)

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解題思路:判斷三點共線首先想到的是列舉O(n³),顯然超時。這裡採用的是尋找相同斜率的方法,斜率相同,自然就會出現共線。首先對x進行排序,這樣就可以使複雜度降為O(n²),我們可以採用map來記錄斜率。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;

const int maxn = 1005;
struct Point
{
	int x,y;
}p[maxn];
int n;
map<pair<int,int>,int> Map;

bool cmp(Point a,Point b)
{
	if(a.x == b.x) return a.y < b.y;
	return a.x < b.x;
}

int gcd(int a,int b)
{
    if(a == 0) return b;
    if(b == 0) return a;
    if(a > b) swap(a,b);
    while(b)
    {
        int temp=a % b;
        a = b;
        b = temp;
    }
    return a;
}

int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(int i = 1; i <= n; i++)
			scanf("%d%d",&p[i].x,&p[i].y);
		sort(p+1,p+1+n,cmp);
		int ans = 0;
		for(int i = 1; i <= n; i++)
		{
			Map.clear();
			for(int j = i + 1; j <= n; j++)
			{
				int cx = p[j].x - p[i].x;
				int cy = p[j].y - p[i].y;
				int d = gcd(cx,cy);
				if(d < 0) d = -d;
				cx /= d; cy /= d;
				Map[make_pair(cx,cy)]++;
			}
			for(map<pair<int,int>,int>::iterator it = Map.begin(); it != Map.end(); it++)
			{
				if(it->second >= 2)
					ans += (it->second) * (it->second - 1) / 2; //組合數:C(n,2)
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}