SGU 532 Building Foundation(枚举)

给出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_pair
using 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;
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值