题目链接:http://poj.org/problem?id=1127
题意:给出n条线段,判断两条线段是否相交(此处的相交也满足传递性,即若a与b相交并且b与c相交,那么a与c也相交)
思路:对于相交的传递性,用floyd算法求解即可。线段相交的代码摘自入门经典。
#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 13 + 5;
struct Point {
double x, y;
Point(double x=0, double y=0):x(x),y(y) {}
}a[maxn], b[maxn];
typedef Point Vector;
Vector operator + (Vector A, Vector B) { return Vector(A.x+B.x, A.y+B.y); }
Vector operator - (Vector A, Vector B) { return Vector(A.x-B.x, A.y-B.y); }
Vector operator * (Vector A, double p) { return Vector(A.x*p, A.y*p); }
Vector operator / (Vector A, double p) { return Vector(A.x/p, A.y/p); }
const double eps = 1e-10;
int dcmp(double x) {
if(fabs(x) < eps) return 0; else return x < 0 ? -1 : 1;
}
bool operator == (const Point& a, const Point& b) {
return dcmp(a.x-b.x) == 0 && dcmp(a.y-b.y) == 0;
}
double Dot(Vector A, Vector B) { return A.x*B.x + A.y*B.y; }
double Cross(Vector A, Vector B) { return A.x*B.y - A.y*B.x; }
bool OnSegment(Point p, Point a1, Point a2) {
return dcmp(Cross(a1-p, a2-p)) == 0 && dcmp(Dot(a1-p, a2-p)) <= 0;
}
bool SegmentProperIntersection(Point a1, Point a2, Point b1, Point b2) {
double c1 = Cross(a2-a1, b1-a1), c2 = Cross(a2-a1, b2-a1),
c3 = Cross(b2-b1, a1-b1), c4 = Cross(b2-b1, a2-b1);
if(dcmp(c1)*dcmp(c2) < 0 && dcmp(c3)*dcmp(c4) < 0) return true;
if(OnSegment(a1, b1, b2) || OnSegment(a2, b1, b2) || OnSegment(b1, a1, a2) || OnSegment(b2, a1, a2)) return true;
return false;
}
int main() {
bool dp[15][15]; int n;
while(scanf("%d", &n) && n) {
memset(dp, false, sizeof dp);
for(int i = 1; i <= n; i++) scanf("%lf%lf%lf%lf", &a[i].x, &a[i].y, &b[i].x, &b[i].y);
for(int i = 1; i <= n; i++)
for(int j = i; j <= n; j++)
if(i == j || SegmentProperIntersection(a[i], b[i], a[j], b[j]))
dp[i][j] = dp[j][i] = true;
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
dp[i][j] |= dp[i][k] & dp[k][j];
int a, b;
while(scanf("%d%d", &a, &b) && a+b) {
if(dp[a][b] || dp[b][a]) printf("CONNECTED\n");
else printf("NOT CONNECTED\n");
}
}
return 0;
}
2万+



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



