分析:
给你N个不重叠(边会重复)的矩形,让你算出共有多少个正方形。
先不考虑公共部分的。把N个矩形自己内部的正方形算出来,再考虑公共部分的,容斥一下把重复的减掉就可以了。
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <string>
#include <numeric>
#include <algorithm>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <complex>
#include <ctime>
typedef long long LL;
const double pi = acos(-1.0);
const long long mod = 1e9 + 7;
using namespace std;
typedef struct
{
LL x1,y1,x2,y2;
}Rect;
Rect rects[1005];
LL numSquares(LL n, LL m)
{
if(n < m)
swap(n,m);
return (3 * n - m + 1) * m * (m + 1) / 6;
}
bool intersection(LL a, LL b, LL c, LL d, LL& len)
{
len = 0;
if (c >= a && c <= b)
len = min(b,d) - c;
else if (a >= c && a <= d)
len = min(b,d) - a;
len -= 2;
return (len > 1);
}
LL crossSquares(int r1, int r2)
{
LL len;
if (intersection(rects[r1].x1, rects[r1].x2, rects[r2].x1, rects[r2].x2, len))
{
if (rects[r1].y2 == rects[r2].y1)
{
return numSquares(len, rects[r2].y2 - rects[r1].y1) -
numSquares(len, rects[r2].y2 - rects[r2].y1) -
numSquares(len, rects[r1].y2 - rects[r1].y1);
}
else if (rects[r2].y2 == rects[r1].y1)
{
return numSquares(len, rects[r1].y2 - rects[r2].y1) -
numSquares(len, rects[r2].y2 - rects[r2].y1) -
numSquares(len, rects[r1].y2 - rects[r1].y1);
}
}
else if (intersection(rects[r1].y1, rects[r1].y2, rects[r2].y1, rects[r2].y2, len))
{
if (rects[r1].x2 == rects[r2].x1)
{
return numSquares(len, rects[r2].x2 - rects[r1].x1) -
numSquares(len, rects[r2].x2 - rects[r2].x1) -
numSquares(len, rects[r1].x2 - rects[r1].x1);
}
else if (rects[r2].x2 == rects[r1].x1)
{
return numSquares(len, rects[r1].x2 - rects[r2].x1) -
numSquares(len, rects[r2].x2 - rects[r2].x1) -
numSquares(len, rects[r1].x2 - rects[r1].x1);
}
}
return 0;
}
int main()
{
//freopen("int.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n;
int t = 0;
while(scanf("%d",&n) && n)
{
LL sum = 0;
for(int i = 0; i < n; i++)
{
scanf("%I64d %I64d %I64d %I64d",&rects[i].x1,&rects[i].y1,&rects[i].x2,&rects[i].y2);
if (rects[i].x1 > rects[i].x2)
swap(rects[i].x1 , rects[i].x2);
if (rects[i].y1 > rects[i].y2)
swap(rects[i].y1 , rects[i].y2);
sum += numSquares(rects[i].x2 - rects[i].x1, rects[i].y2 - rects[i].y1);
}
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
sum += crossSquares(i, j);
printf("Case %d: %I64d\n",++t,sum);
}
return 0;
}