标签:des style blog class code java
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2461
2 2 0 0 2 2 1 1 3 3 1 1 2 1 2 2 1 0 1 1 2 2 1 3 2 2 1 2 0 0
Case 1: Query 1: 4 Query 2: 7 Case 2: Query 1: 2
题目意思:
给n(n<=20)个矩形,有m(m<=100000)个询问,每个询问求给定矩形的并的面积。
解题思路:
简单容斥原理
对于指定的矩形并面积,先求出所有单个矩形的和,再减去两个矩形的交,再加上三个矩形的交,以此类推。
问题就转化为求多个矩形的交,这个转化为求两个矩形的交。
代码:
//#include<CSpreadSheet.h> #include<iostream> #include<cmath> #include<cstdio> #include<sstream> #include<cstdlib> #include<string> #include<string.h> #include<cstring> #include<algorithm> #include<vector> #include<map> #include<set> #include<stack> #include<list> #include<queue> #include<ctime> #include<bitset> #include<cmath> #define eps 1e-6 #define INF 0x3f3f3f3f #define PI acos(-1.0) #define ll __int64 #define LL long long #define lson l,m,(rt<<1) #define rson m+1,r,(rt<<1)|1 #define M 1000000007 //#pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; #define Maxn 33 struct Rec { int x1,y1,x2,y2; bool vv; }rec[Maxn]; int n,m,num,pp[Maxn],ans; Rec cal(Rec a,Rec b) //求两个矩形的交的矩形 { Rec res; if(a.x1>b.x1) swap(a,b); if(b.x1>=a.x2||b.y1>=a.y2||b.y2<=a.y1) { res.vv=false; //说明交的面积为0 return res; } res.vv=true; //注意要置为true res.x1=b.x1; res.y1=max(a.y1,b.y1); res.x2=min(a.x2,b.x2); res.y2=min(a.y2,b.y2); return res; } int area(Rec cur) { return (cur.x2-cur.x1)*(cur.y2-cur.y1); } void dfs(Rec hav,int cur,int cn) { if(cur>num) return ; for(int i=cur;i<=num;i++) { Rec temp=cal(hav,rec[pp[i]]); if(!temp.vv) //没有公共部分 continue; if(cn&1) ans+=area(temp); //求公共部分面积 else ans-=area(temp); dfs(temp,i+1,cn^1); } } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int ca=0; while(scanf("%d%d",&n,&m)&&n+m) { printf("Case %d:\n",++ca); for(int i=1;i<=n;i++) scanf("%d%d%d%d",&rec[i].x1,&rec[i].y1,&rec[i].x2,&rec[i].y2); for(int qu=1;qu<=m;qu++) { ans=0; scanf("%d",&num); for(int i=1;i<=num;i++) scanf("%d",&pp[i]); for(int i=1;i<=num;i++) { ans+=area(rec[pp[i]]); dfs(rec[pp[i]],i+1,0); } printf("Query %d: %d\n",qu,ans); } putchar(‘\n‘); } return 0; }
[容斥原理] hdu 2461 Rectangles,布布扣,bubuko.com
标签:des style blog class code java
原文地址:http://blog.csdn.net/cc_again/article/details/25377597