原题链接:http://poj.org/problem?id=2826
这道题要的思路很容易,但把代码写丑也很容易。
接到的水的截面体积为0的情况有:
1. 两条线段不相交;
2. 其中任意一条线段水平;
3. 两条线段重合;
4. 相交的情况下,最高的端点遮住了次高的端点
这道题断断续续搞了一周才搞定,POJ上wa了几个版面。几何题,同样的功能不同的写法是wa与ac的鸿沟,唉~~~

1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <algorithm> 5 #include <math.h> 6 #define INF 1e7 7 const double eps=1e-8; 8 9 struct point 10 { 11 double x, y; 12 point(){} 13 point(double _x, double _y):x(_x), y(_y){} 14 }; 15 16 double min(double a, double b){return a < b ? a : b;} 17 double max(double a, double b){return a > b ? a : b;} 18 19 bool inter(point a, point b, point c, point d) 20 { 21 if ( min(a.x, b.x) > max(c.x, d.x) || 22 min(a.y, b.y) > max(c.y, d.y) || 23 min(c.x, d.x) > max(a.x, b.x) || 24 min(c.y, d.y) > max(a.y, b.y) ) return 0; 25 double h, i, j, k; 26 h = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); 27 i = (b.x - a.x) * (d.y - a.y) - (b.y - a.y) * (d.x - a.x); 28 j = (d.x - c.x) * (a.y - c.y) - (d.y - c.y) * (a.x - c.x); 29 k = (d.x - c.x) * (b.y - c.y) - (d.y - c.y) * (b.x - c.x); 30 return h * i <= eps && j * k <= eps; 31 } 32 33 point intersection(point u1,point u2,point v1,point v2) 34 { 35 point ret=u1; 36 double t=((u1.x-v1.x)*(v1.y-v2.y)-(u1.y-v1.y)*(v1.x-v2.x)) 37 /((u1.x-u2.x)*(v1.y-v2.y)-(u1.y-u2.y)*(v1.x-v2.x)); 38 ret.x+=(u2.x-u1.x)*t; 39 ret.y+=(u2.y-u1.y)*t; 40 return ret; 41 } 42 43 double dot(point a, point b, point c, point d) 44 {return (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);} 45 void swapPoint(point &a, point &b) 46 { 47 std::swap(a.x, b.x); 48 std::swap(a.y, b.y); 49 } 50 51 int main() 52 { 53 int n; 54 bool flag; 55 point a, b, c, d; 56 scanf("%d", &n); 57 while(n --) 58 { 59 scanf("%lf%lf%lf%lf", &a.x, &a.y, &b.x, &b.y); 60 scanf("%lf%lf%lf%lf", &c.x, &c.y, &d.x, &d.y); 61 if((int)a.y == (int)b.y || (int)c.y == (int)d.y || fabs(dot(a, b, c, d)) < eps || !inter(a, b, c, d)) 62 puts("0.00"); 63 else 64 { 65 point cp = intersection(a, b, c, d); 66 67 point lowp, upp, tmp; 68 if(a.y < b.y) swapPoint(a, b); 69 if(c.y < d.y) swapPoint(c, d); 70 bool flag; 71 if(a.y < c.y) 72 { 73 lowp.x = a.x, lowp.y = a.y; 74 upp.x = c.x, upp.y = c.y; 75 tmp = intersection(c, d, *new point(-INF, lowp.y), *new point(INF, lowp.y)); 76 flag = inter(a, *new point(a.x, INF), c, d); 77 } 78 else 79 { 80 lowp.x = c.x, lowp.y = c.y; 81 upp.x = a.x, upp.y = a.y; 82 tmp = intersection(a, b, *new point(-INF, lowp.y), *new point(INF, lowp.y)); 83 flag = inter(c, *new point(c.x, INF), a, b); 84 } 85 if(flag) 86 printf("0.00\n"); 87 else 88 printf("%.2f\n", fabs(dot(lowp, cp, tmp, cp)) / 2.0); 89 } 90 } 91 return 0; 92 }