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 <P i, P j, P k> from these N points are collinear. Note that <P i, P j, P k> cannot contains same point, and <P i, P j, P k> and <P i, P k, P j> 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;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值