| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 15494 | Accepted: 4916 |
Description
Given n segments in the two dimensional space, write a program, which determines if there exists a line such that after projecting these segments on it, all projected segments have at least one point in common.
Input
Input begins with a number T showing the number of test cases and then, T test cases follow. Each test case begins with a line containing a positive integer n ≤ 100 showing the number of segments. After that, nlines containing four real numbers x1 y1 x2 y2 follow, in which (x1, y1) and (x2, y2) are the coordinates of the two endpoints for one of the segments.
Output
For each test case, your program must output "Yes!", if a line with desired property exists and must output "No!" otherwise. You must assume that two floating point numbers a and b are equal if |a - b| < 10-8.
Sample Input
3 2 1.0 2.0 3.0 4.0 4.0 5.0 6.0 7.0 3 0.0 0.0 0.0 1.0 0.0 1.0 0.0 2.0 1.0 1.0 2.0 1.0 3 0.0 0.0 0.0 1.0 0.0 2.0 0.0 3.0 1.0 1.0 2.0 1.0
Sample Output
Yes! Yes! No!
Source
分析详见代码 :
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const double eps = 1e-8;
const int maxn = 111;
int n;
struct Point {
double x, y;
};
struct Line {
Point a, b;
} line[maxn];
double Multi(Point p1, Point p2, Point p0) {
return (p1.x - p0.x) * (p2.y - p0.y) - (p1.y - p0.y) * (p2.x - p0.x);
}
bool Check(Point a, Point b) {
if (fabs(a.x-b.x) < eps && fabs(a.y-b.y) < eps) return false;//注意题干中说的小于1e-8就认为是重合
for (int i = 0; i < n; i++)
if (Multi(line[i].a, b, a) * Multi(line[i].b, b, a) > 0) return false;
//当叉乘的结果是两正或两负的时候,也就是第三条边两个点都在直线的一侧,公式同为逆时针带入,或顺时针(本人博客poj2318)
return true;
}
int main()
{
int t, i, j;
bool flag;
//如果n条线段投影到一条直线上,有一个公共点,那么这条直线上必定存在一条垂线,过所有的线段
scanf ("%d", &t);
while (t--) {
scanf ("%d", &n);
for (i = 0; i < n; i++)
scanf ("%lf%lf%lf%lf", &line[i].a.x, &line[i].a.y, &line[i].b.x, &line[i].b.y);
flag = false;
if (n < 3) flag = true; //两点确定一条直线,如果只有两条线段,任选俩点都能找到那条垂线
for (i = 0; i < n && !flag; i++) {
if (Check(line[i].a, line[i].b)) flag = true; //枚举线段自身的两个点
for (j = i + 1; j < n && !flag; j++) { //枚举当前线段两对和其他线段两点的组合情况
if (Check(line[i].a, line[j].a) ||
Check(line[i].a, line[j].b) ||
Check(line[i].b, line[j].a) ||
Check(line[i].b, line[j].b))
flag = true;
}
}
if (flag) printf ("Yes!\n");
else printf ("No!\n");
}
return 0;
}
本文介绍了一种算法,用于判断二维空间中的多个线段是否能够投影到一条直线上,并且该投影线段上是否存在至少一个公共点。通过枚举线段的端点并检查这些端点是否位于所有线段的同一侧来实现。
261

被折叠的 条评论
为什么被折叠?



