C - Segments
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 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 x1y1 x2 y2 follow, in which (x1, y1) and (x2, y2) are the coordinates of the two endpoints for one of the segments.
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.
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
Yes! Yes! No!
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
using namespace std;
const int MX = 105;
const int mod = 1e9 + 7;
const int INF = 2e9 + 5;
const double eps = 1e-8;
int n;
struct Point{
double x, y;
Point(){}
Point(double _x, double _y){
x = _x;
y = _y;
}
};
struct Line{
Point s, e;
Line(){}
Line(Point x, Point y){
s = x;
e = y;
}
}line[MX];
int sgn(double x){
if(fabs(x) < eps) return 0;
if(x < 0) return -1;
return 1;
}
double multi(Point p0, Point p1, Point p2){
return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y);
}
double dis(Point a, Point b){
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
bool intersect(Line l1, Line l2){
return sgn(multi(l2.s, l1.s, l1.e)) * sgn(multi(l2.e, l1.s, l1.e)) <= 0;
}
int check(Line l){
if(sgn(dis(l.e, l.s)) == 0) return 0;
for(int i = 0; i < n; i++){
if(!intersect(l, line[i])) return 0;
}
return 1;
}
int main(){
int t;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
double x1, y1, x2, y2;
for(int i = 0; i < n; i++){
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
line[i] = Line(Point(x1, y1), Point(x2, y2));
}
int flag = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(check(Line(line[i].s, line[j].s)) || check(Line(line[i].s, line[j].e)) ||
check(Line(line[i].e, line[j].s)) || check(Line(line[i].e, line[j].e))){
flag = 1;
break;
}
}
if(flag) break;
}
if(flag) printf("Yes!\n");
else printf("No!\n");
}
return 0;
}