poj2826(垃圾精度题)

求两块木板能装雨水的面积,垃圾题WA了几十发,随机数造了几十万组数据过了还是WA,最后用上long double加特判过的,特判了一块木板水平的情况,我也不知道为什么要特判,按我的做法这种情况不特判也会输出0的,数据是真的坑。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define double long double
using namespace std;
const double eps = 1e-8;


double cross(double x1, double y1, double x2, double y2) {
	//printf("%.0f %.0f %.0f %.0f", x1, y1, x2, y2);
    return 1.0*x1*y2 - x2*y1;
}

bool judge(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
	if (fabs(y1-y2) <= eps) return false;
	if (fabs(y3-y4) <= eps) return false;
    if (min(x1, x2) <= max(x3, x4)
        && min(x3, x4) <= max(x1, x2)
        && min(y1, y2) <= max(y3, y4)
        && min(y3, y4) <= max(y1, y2)
        && cross(x1-x3,y1-y3,x4-x3,y4-y3)*cross(x2-x3,y2-y3,x4-x3,y4-y3) <= eps
        && cross(x3-x2,y3-y2,x1-x2,y1-y2)*cross(x4-x2,y4-y2,x1-x2,y1-y2) <= eps)
        return true;
    return false;
}

double area(double x1, double y1, double x2, double y2) {
    return fabs(x1*y2 - x2*y1) / 2.0;
}

void calc(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, double & ans_x, double & ans_y) {
    ans_x = 1.0*((x1*y2-x2*y1)*(x3-x4) - (x3*y4-x4*y3)*(x1-x2)) / ((y2-y1)*(x3-x4) - (x2-x1)*(y3-y4));
	ans_y = 1.0*((y2-y1)*(x3*y4-x4*y3) - (y4-y3)*(x1*y2-x2*y1)) / ((y2-y1)*(x3-x4) - (x2-x1)*(y3-y4));
}

double solve(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
    if (!judge(x1,y1,x2,y2,x3,y3,x4,y4)) return .0;
    if (y1 < y2) {swap(y1, y2); swap(x1, x2);}
    if (y3 < y4) {swap(y3, y4); swap(x3, x4);}
    if (x3 < x1) {swap(y1, y3); swap(x1, x3); swap(y2, y4); swap(x2, x4);}
    //printf("%Lf %Lf %Lf %Lf\n",x1, y1, x2, y2);
    //printf("%Lf %Lf %Lf %Lf\n",x3, y3, x4, y4);
    if (x1 < x3 && cross(x3-x4,y3-y4,x1-x2,y1-y2) <= eps || x1 == x3) return .0;
    
    double ans_x1, ans_y1, ans_x2, ans_y2, ans_x3, ans_y3;
    if (y1 <= y3) {ans_x2 = x3; ans_y2 = y3; ans_x3 = x1; ans_y3 = y1;}
    else {ans_x2 = x1; ans_y2 = y1; ans_x3 = x3; ans_y3 = y3;}
    
    calc(x1,y1,x2,y2,x3,y3,x4,y4,ans_x1,ans_y1);
    calc(-1000,min(y1,y3),100,min(y1,y3), ans_x2, ans_y2, ans_x1, ans_y1, ans_x2, ans_y2);
    //printf("ans_x1 = %Lf ans_y1 = %Lf\n", ans_x1, ans_y1);
    //printf("ans_x2 = %Lf ans_y2 = %Lf\n", ans_x2, ans_y2);
    //printf("ans_x3 = %Lf ans_y3 = %Lf\n", ans_x3, ans_y3);
    return area(ans_x3-ans_x1, ans_y3-ans_y1, ans_x2-ans_x1, ans_y2-ans_y1);
}


int main() {
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
    int T, kase = 0;
    scanf("%d", &T);

    while (T--) {
    	++kase;
    	
    	double x1, y1, x2, y2, x3, y3, x4, y4;
        scanf("%Lf %Lf %Lf %Lf", &x1, &y1, &x2, &y2);
        scanf("%Lf %Lf %Lf %Lf", &x3, &y3, &x4, &y4);

        printf("%.2Lf\n",solve(x1,y1,x2,y2,x3,y3,x4,y4));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/bpdwn2017/article/details/81634655