HDU题目地址:HDU 1828 POJ题目地址:POJ 1177
这题是求周长并,我用的方法可能有点麻烦。。是先求横着的线,再求竖着的线。每次只要求出每次的总区间覆盖长度,然后每次累加这次的总区间覆盖与上次的总区间覆盖长度的差的绝对值。因为只有长度发生变化时,才会产生一段新的周长。
待会再试试只扫描一次的方法。此博客有待更新。
代码如下:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1
int sum[50000], c[50000], cnt, a[6000], b[5000], d1[6000], d2[6000], lazy[50000];
struct node
{
int l, r, h, f;
} edge[100000];
void add(int l, int r, int h, int f)
{
edge[cnt].l=l;
edge[cnt].r=r;
edge[cnt].h=h;
edge[cnt++].f=f;
}
int cmp(node x, node y)
{
return x.h<y.h;
}
void PushUp(int rt, int l, int r)
{
if(lazy[rt])
sum[rt]=c[r+1]-c[l];
else if(l==r)
sum[rt]=0;
else
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void update(int ll, int rr, int x, int l, int r, int rt)
{
if(ll<=l&&rr>=r)
{
lazy[rt]+=x;
PushUp(rt,l,r);
return ;
}
int mid=l+r>>1;
if(ll<=mid) update(ll,rr,x,lson);
if(rr>mid) update(ll,rr,x,rson);
PushUp(rt,l,r);
}
int erfen(int x, int high)
{
int low=0, mid;
while(low<=high)
{
mid=low+high>>1;
if(c[mid]==x) return mid;
else if(c[mid]>x) high=mid-1;
else low=mid+1;
}
}
int main()
{
int n, i, j, last, ans, tmp, k;
while(scanf("%d",&n)!=EOF)
{
cnt=0;
k=0;
memset(sum,0,sizeof(sum));
memset(lazy,0,sizeof(lazy));
for(i=0; i<n; i++)
{
scanf("%d%d%d%d",&a[i],&d1[i],&b[i],&d2[i]);
c[k++]=a[i];
c[k++]=b[i];
add(a[i],b[i],d1[i],1);
add(a[i],b[i],d2[i],-1);
}
sort(edge,edge+2*n,cmp);
sort(c,c+2*n);
last=ans=0;
for(i=0; i<2*n; i++)
{
int l=erfen(edge[i].l,2*n-1);
int r=erfen(edge[i].r,2*n-1);
update(l,r-1,edge[i].f,0,2*n-1,1);
//printf("%d %d %d\n",l,r,sum[1]);
ans+=abs(sum[1]-last);
last=sum[1];
}
cnt=0;
k=0;
memset(sum,0,sizeof(sum));
memset(lazy,0,sizeof(lazy));
for(i=0; i<n; i++)
{
c[k++]=d1[i];
c[k++]=d2[i];
add(d1[i],d2[i],a[i],1);
add(d1[i],d2[i],b[i],-1);
}
sort(edge,edge+2*n,cmp);
sort(c,c+2*n);
last=0;
for(i=0; i<2*n; i++)
{
int l=erfen(edge[i].l,2*n-1);
int r=erfen(edge[i].r,2*n-1);
update(l,r-1,edge[i].f,0,2*n-1,1);
ans+=abs(sum[1]-last);
last=sum[1];
}
printf("%d\n",ans);
}
return 0;
}