SGU 532 Building Foundation(枚举)

来源:互联网 发布:阿里云服务器架设sf 编辑:程序博客网 时间:2024/05/14 20:06

给出n条与x轴或y轴平行的线段,然后求这些线段能组成多少个矩形。

上来就n^4先枚举了一发,果断TLE了。。。

然后反思:由于n条线段与x轴或y轴平行,所以组成的矩形一定是两条于x轴平行,两条与y轴平行的。这样的话,我们先n^2枚举所有两条y值不相等的与x轴平行的线段,然后就会发现能与这两条线段都有交点的平行于y轴的线段的x跟y都会有一个范围,然后在O(n)枚举所有与y轴平行的线段,求和就行了。

#include<algorithm>#include<iostream>#include<cstring>#include<fstream>#include<sstream>#include<cstdlib>#include<vector>#include<string>#include<cstdio>#include<bitset>#include<queue>#include<stack>#include<cmath>#include<map>#include<set>#define FF(i, a, b) for(int i=a; i<b; i++)#define FD(i, a, b) for(int i=a; i>=b; i--)#define REP(i, n) for(int i=0; i<n; i++)#define CLR(a, b) memset(a, b, sizeof(a))#define debug puts("**debug**")#define LL long long#define PB push_back#define MP make_pairusing namespace std;const int maxn = 666;int n;struct Seg{    int x1, y1, x2, y2;    Seg(){}    Seg(int a, int b, int c, int d) :x1(a), y1(b), x2(c), y2(d){}}px[maxn], py[maxn];bool cmpy(const Seg a, const Seg b){    return a.y1 < b.y1;}bool judge(int i, int j, int& l, int& r){    if(px[i].y1 == px[j].y1) return 0;    if(px[i].x1 < px[j].x2 || px[j].x1 < px[i].x2) l = max(px[i].x1, px[j].x1), r = min(px[i].x2, px[j].x2);    else return 0;    return r > l;}bool ok(int y1, int y2, Seg a, int l, int r){    if(a.x1 >= l && a.x1 <= r && a.y1 <= y1 && a.y2 >= y2) return 1;    return 0;}int main(){    while(~scanf("%d", &n))    {        int cnt1 = 0, cnt2 = 0;        int a, b, c, d;        REP(i, n)        {            scanf("%d%d%d%d", &a, &b, &c, &d);            if(a == c)            {                if(b > d) swap(d, b);                py[cnt2++] = Seg(a, b, c, d);            }            else            {                if(a > c) swap(a, c);                px[cnt1++] = Seg(a, b, c, d);            }        }        sort(px, px+cnt1, cmpy);        LL ans = 0;        REP(i, cnt1) FF(j, i+1, cnt1)        {            int l, r;            if(judge(i, j, l, r))            {                int tmp = 0;                REP(k, cnt2)                {                    if(ok(px[i].y1, px[j].y1, py[k], l, r)) tmp++;                }                ans += ((LL)tmp*(tmp-1)) / 2;            }        }        printf("%I64d\n", ans);    }    return 0;}


原创粉丝点击