POJ 1127 Jack Straws (线段不规范相交&&图的连通性&&Floyd-Warshall算法)

http://poj.org/problem?id=1127


/*16ms,376KB*/

#include<cstdio>
#include<cstring>

struct P
{
	int x, y;
	P(int x = 0, int y = 0): 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);
	}
	int dot(P p)
	{
		return x * p.x + y * p.y;
	}
	int det(P p)
	{
		return x * p.y - y * p.x;
	}
} p1[15], p2[15];

bool c[15][15];

inline int cross_product(P p1, P p2, P p)
{
	return (p2.x - p1.x) * (p.y - p1.y) - (p2.y - p1.y) * (p.x - p1.x);
}

inline bool is_intersect(P p1, P p2, P pp1, P pp2)
{
	///先看是不是共基线,是的话测试端点是否在另一线段内部
	if ((p2.x - p1.x) * (pp2.y - pp1.y) - (p2.y - p1.y) * (pp2.x - pp1.x) == 0)
		return (p1 - pp1).dot(p1 - pp2) <= 0 || (p2 - pp1).dot(p2 - pp2) <= 0;
	return cross_product(p1, p2, pp1) * cross_product(p1, p2, pp2) <= 0 && cross_product(pp1, pp2, p1) * cross_product(pp1, pp2, p2) <= 0;
}

void Floyd_Warshall(int n)
{
	int k, i, j;
	for (k = 1; k <= n; ++k)
		for (i = 1; i <= n; ++i)
			for (j = 1; j <= n; ++j)
				c[i][j] |= c[i][k] && c[k][j];
}

int main()
{
	int n, i, j, a, b;
	while (scanf("%d", &n), n)
	{
		for (i = 1; i <= n; ++i)
			scanf("%d%d%d%d", &p1[i].x, &p1[i].y, &p2[i].x, &p2[i].y);
		memset(c, 0, sizeof(c));
		for (i = 1; i <= n; ++i)
		{
			c[i][i] = true;
			for (j = 1; j < i; ++j)
				if (is_intersect(p1[i], p2[i], p1[j], p2[j]))
					c[i][j] = c[j][i] = true;
		}
		Floyd_Warshall(n);
		while (scanf("%d%d", &a, &b), a)
			puts(c[a][b] ? "CONNECTED" : "NOT CONNECTED");
	}
	return 0;
}

附:另一道判断线段相交(含不规范相交)的题:UVa 191 Intersection

你可能感兴趣的:(C++,ACM,poj,Floyd-Warshall)