Segments
Time Limit: 1000MS Memory Limit: 65536K
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, n lines 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!
题意:
题目给出n条线段,问是否有一条直线可以是n条直线的投影都落在这条直线上,并且有公共点。
思路:
此题最难的地方应该是如何确定这条直线,就是求与所有线段相交的直线了,因为过投影相交区域作直线的垂线,该垂线必定与每条线段相交,然后就是枚举两个点就行了,过两个端点的直线的垂线肯定会有公共点,因为离散化的思维,所有的n条线段中,只要找到两个端点然后枚举就行了。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn = 110;
const double eps = 1e-8;
struct P {
double x;
double y;
P () {}
P (double x, double y) : x(x), y(y) {}
P operator + (P p) {
return P(x + p.x, y + p.y);
}
P operator - (P p) {
return P(x - p.x, y - p.y);
}
P operator * (double d) {
return P(x * d, y * d);
}
double det(P p) {
return x * p.y - y * p.x;
}
double dot(P p) {
return x * p.x + y * p.y;
}
};
struct Line {
P s;
P e;
Line() {};
Line(P s, P e) : s(s), e(e) {};
};
Line line[maxn];
int t, n, m;
int check(double x) {
if (fabs(x) < eps) return 0;
else if (x < 0) return -1;
else return 1;
}
double getdis(P a, P b) {
return sqrt((b - a).dot(b - a));
}
double xmult(P p1, P p2, P p0) {
return (p1 - p0).det(p2 - p0);
}
bool intersection(Line L1, Line L2) {
return check(xmult(L1.s, L1.e, L2.s)) * check(xmult(L1.s, L1.e, L2.e)) <= 0;
}
bool judge(Line L) {
if (check(getdis(L.s, L.e)) == 0) return false;
for (int i = 1; i <= n; i++) {
if (intersection(L, line[i]) == false) return false;
}
return true;
}
int main() {
double x1, x2, y1, y2;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
line[i] = Line(P(x1, y1), P(x2, y2));
}
bool flag = false;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (judge(Line(line[i].s, line[j].s)) || judge(Line(line[i].s, line[j].e))
|| judge(Line(line[i].e, line[j].s)) || judge(Line(line[i].e, line[j].e))) {
flag = true;
break;
}
}
if (flag) break;
}
if (flag) printf("Yes!\n");
else printf("No!\n");
}
return 0;
}