几何概型,《训练指南》的题。分类讨论太神啦我不会,我只会萌萌哒的simpson强上~这里用正方形在y=x-w的左上方的面积减去在y=x+w左上方的面积就是两条直线之间的面积,然后切出来的每一小段肯定是梯形或三角形,所以可以写得和一般的Simpson有点区别。
#include<cstdio> const double eps=1e-8; int a1,a2,b1,b2,w; double f1(double x){ if(x+w<=b1)return b2-b1; return (x+w<=b2&&x+w>=b1)?(b2-(x+w)):0; } double f2(double x){ if(x-w<=b1)return b2-b1; return (x-w<=b2&&x-w>=b1)?(b2-(x-w)):0; } bool equal(double x,double y){ return x-y<eps&&x-y>-eps; } double simpson(double l,double r,double f(double x)){ double fl=f(l),fr=f(r); // printf("simpson%f %f %f %f ",l,r,fl,fr);getchar(); if(fl==0&&fr!=0&&r-l<eps)return 0; if(fr==0&&fl!=0&&r-l<eps)return 0; if(equal(fl-fr,r-l)||equal(fl-fr,l-r))return (fl+fr)*(r-l)/2.0; if(fl==fr)return fl*(r-l); return simpson(l,(l+r)/2.0,f)+simpson((l+r)/2.0,r,f); } double area1(){//area that is left up of y=x+w return simpson(a1,a2,f1); } double area2(){//area that is left up of y=x-w return simpson(a1,a2,f2); } int main(){ freopen("joining.in","r",stdin); freopen("joining.out","w",stdout); int tests,cases=0;scanf("%d",&tests); while(tests--){ scanf("%d%d%d%d%d",&a1,&a2,&b1,&b2,&w); ++cases; // printf("%.8f %.8f ",area2(),area1()); printf("Case #%d: %.8f ",cases,(area2()-area1())/double(a2-a1)/double(b2-b1)); } fclose(stdin);fclose(stdout); return 0; } /*378 1035 488 1063 12*/