[ BAPC 2016 ] Target Practice 简单几何

题目链接:Target Practice

题意

给你n个笛卡尔积点,问是否可以用最多两条直线穿过所有的点,可以输出“success”,否则输出“failure”。

题解

分析本题,如果确定了一条直线,那么其它点无非在该条直线上或者另一条直线,进而我们很容易可以确定两条直线来判断剩下点是否符合条件。
但本题的难点在于无法确定第一条直线是哪条,如果用O(n)时间复杂度去枚举,会发现总的时间复杂度为 O ( n 2 ) {O(n^2)} O(n2),不合理。
但其实“两点确定一条直线”,我们枚举三个点所连成的三条直线就可。每条直线O(n)的时间复杂度去判断其它的点是否符合条件,总共时间复杂度O(3n)=O(n)。
注意题中可能有直线斜率不存在,所以需要用乘积去判断其它点是否在该条直线上,还有需要注意long long 问题。

代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define lowbit(x) x&-x

const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=1e5+10;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

struct Node
{
    
    
	ll x,y;
}node[maxn];
int book[maxn],n;
vector<int> tt;

bool check(Node a,Node b,Node c)
{
    
    
	ll t1=(c.y-a.y)*(b.x-a.x);
	ll t2=(b.y-a.y)*(c.x-a.x);
	return (t1==t2)? true:false;
}

bool solve(int pos1,int pos2)
{
    
    
	tt.clear();
	for(int i=0;i<n;i++)
	{
    
    
		if(i==pos1 || i==pos2) continue;
		if(!check(node[pos1], node[pos2], node[i])) tt.pb(i);
	}
	if(tt.size()<=2) return true;
	int p1=tt[0],p2=tt[1];
	for(int i=2;i<tt.size();i++)
	{
    
    
		if(!check(node[p1], node[p2], node[tt[i]])) return false;
	}
	return true;
}
int main()
{
    
    
	cin >> n;
	for(int i=0;i<n;i++) cin >> node[i].x >> node[i].y;
	if(n<5 || solve(0,1) || solve(1,2) || solve(0,2)) 
		cout << "success" << endl;
	else 
		cout << "failure" << endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_44235989/article/details/108013729
今日推荐