标签:code bing iostream abs lines sam blog pac nes
Description
Input
Output
Sample Input
7 1 6 3 3 4 6 4 9 4 5 6 7 1 4 3 5 3 5 5 5 5 2 6 3 5 4 7 2 1 4 1 6 3 3 6 7 2 3 1 3 0 0 2 0 2 0 0 0 0 0 1 1 1 2 2 1 2 0 0 0
Sample Output
CONNECTED NOT CONNECTED CONNECTED CONNECTED NOT CONNECTED CONNECTED CONNECTED CONNECTED CONNECTED
给定n个木棒,两端分别是(x1,y1),(x2,y2),但1木棒与2木棒相交,2木棒与3木棒相交时,说明1木棒与3木棒也相交
有若干个询问a和b,求a与b是否相交。判断两个木棒是否相交,可以想判断他们是否平行,平行的话直接其中一个木棒的一点在另一木棒上就是相交,不平行的话,求两个直线的交点,看这个交点是否在这两个木棒上在的话就是相交了。
下面是代码,根据挑战程序设计上的计算几何基础写的。
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <cmath> 5 using namespace std; 6 const int N = 20; 7 const int M = 110; 8 double EPS = 1e-10; 9 double add(double a,double b) { 10 if(abs(a+b) < EPS * (abs(a) + abs(b))) return 0; 11 return a + b; 12 } 13 struct Point{ 14 double x, y; 15 Point(){} 16 Point(double x, double y) :x(x), y(y) {} 17 Point operator + (Point p) { 18 return Point(add(x, p.x), add(y, p.y)); 19 } 20 Point operator - (Point p) { 21 return Point(add(x, -p.x), add(y, -p.y)); 22 } 23 Point operator * (double d) { 24 return Point(x*d, y*d); 25 } 26 double dot(Point p) { //内积 27 return add(x * p.x, y * p.y); 28 } 29 double det(Point p) { //外积 30 return add(x * p.y, -y * p.x); 31 } 32 }; 33 34 bool on_seg(Point p1, Point p2, Point q) { //判断点q是否在线段p1-p2上 35 return (p1 - q).det(p2 - q) == 0 && (p1 - q).dot(p2 - q) <= 0; 36 } 37 Point intersection(Point p1, Point p2, Point q1, Point q2) { //计算直线p1-p2与直接q1-q2的交点 38 return p1 + (p2 - p1) * ((q2 - q1).det(q1 - p1) / (q2 - q1).det(p2 - p1)); 39 } 40 int n; 41 Point p[N], q[N]; 42 int m; 43 bool g[N][N]; 44 void solve() { 45 for(int i = 1; i <= n; i ++) { 46 g[i][i] = true; 47 for(int j = 1; j < i; j ++) { 48 if((p[i] - q[i]).det(p[j] - q[j]) == 0) { 49 g[i][j] = g[j][i] = on_seg(p[i], q[i], q[j]) 50 || on_seg(p[i], q[i], p[j]) 51 || on_seg(p[j], q[j], q[i]) 52 || on_seg(p[j], q[j], p[i]); 53 } else { 54 Point r = intersection(p[i], q[i], p[j], q[j]); 55 g[i][j] = g[j][i] = on_seg(p[i], q[i], r) && on_seg(p[j], q[j], r); 56 } 57 } 58 } 59 for(int k = 1; k <= n; k ++) { 60 for(int i = 1; i <= n; i ++) { 61 for(int j = 1; j <= n; j ++) { 62 g[i][j] |= g[i][k] && g[k][j]; 63 } 64 } 65 } 66 } 67 int main() { 68 while(cin >> n && n) { 69 memset(g, false, sizeof(g)); 70 for(int i = 1; i <= n; i ++) { 71 cin >> p[i].x >> p[i].y >> q[i].x >> q[i].y; 72 } 73 int a, b; 74 solve(); 75 while(cin >> a >> b && (a+b)) { 76 if(g[a][b]) printf("CONNECTED\n"); 77 else printf("NOT CONNECTED\n"); 78 } 79 } 80 return 0; 81 }
标签:code bing iostream abs lines sam blog pac nes
原文地址:http://www.cnblogs.com/xingkongyihao/p/7298851.html