HDU

来源:互联网 发布:剪辑音乐软件手机 编辑:程序博客网 时间:2024/06/14 21:52

Counting Squares

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2163    Accepted Submission(s): 1082


Problem Description
Your input is a series of rectangles, one per line. Each rectangle is specified as two points(X,Y) that specify the opposite corners of a rectangle. All coordinates will be integers in the range 0 to 100. For example, the line
5 8 7 10
specifies the rectangle who's corners are(5,8),(7,8),(7,10),(5,10).
If drawn on graph paper, that rectangle would cover four squares. Your job is to count the number of unit(i.e.,1*1) squares that are covered by any one of the rectangles given as input. Any square covered by more than one rectangle should only be counted once.
 

Input
The input format is a series of lines, each containing 4 integers. Four -1's are used to separate problems, and four -2's are used to end the last problem. Otherwise, the numbers are the x-ycoordinates of two points that are opposite corners of a rectangle.
 

Output
Your output should be the number of squares covered by each set of rectangles. Each number should be printed on a separate line.
 

Sample Input
5 8 7 106 9 7 86 8 8 11-1 -1 -1 -10 0 100 10050 75 12 9039 42 57 73-2 -2 -2 -2
 

Sample Output
810000
 

Source
浙江工业大学第四届大学生程序设计竞赛 
 

题意:给许多矩形,求所有矩形框住的总面积,重合部分只算一次。


求总面积,被覆盖多次的只按一次来计算,就是线段树扫描线的用法,从左往右扫,每次遇到矩形边界进行判断,若该点为矩形左边界,则接下来又有一段线段覆盖的次数+1,若为矩形右边界,则覆盖次数-1,然后计算面积,S +=(覆盖的线段长度)*(该点水平位置-上一点水平位置)。
#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int x1,x2,y1,y2,sum[450],cover[150],len,x,ans,cnt;struct node {int x,l,r,in;}line[1010];bool cmp(node a,node b) {return a.x<b.x;}void Cover(int L,int R,int l,int r,int x,int C){    if(l==r)    {        cover[l]+=C;        sum[x] = min(1,cover[l]);        return ;    }    int m = (l+r)>>1;    if(L<=m) Cover(L, R, l, m, x<<1, C);    if(R>m) Cover(L, R, m+1, r, x<<1|1, C);    sum[x] = sum[x<<1] + sum[x<<1|1];}void init(){    ans = cnt = len = x = 0;    memset(cover,0,sizeof cover);    memset(sum,0,sizeof sum);    memset(line,0,sizeof line);}int main(){    init();    while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2)!=EOF)    {        if(x1+x2+y1+y2<0)        {            sort(line, line+cnt, cmp);            for(int i=0;i<cnt;i++)            {                ans += len*(line[i].x-x);                x = line[i].x;                Cover(line[i].l+1, line[i].r, 0, 100, 1, line[i].in);                len = sum[1];            }            printf("%d\n",ans);            init();            if(x1+x2+y1+y2==-4) continue;            else break;        }               if(x1>x2) swap(x1,x2);        if(y1>y2) swap(y1,y2);        line[cnt].x = x1, line[cnt].l = y1, line[cnt].r = y2, line[cnt++].in = 1;        line[cnt].x = x2, line[cnt].l = y1, line[cnt].r = y2, line[cnt++].in = -1;    }    return 0;}




原创粉丝点击