P2202 [USACO13JAN]方块重叠Square Overlap

题目描述

Farmer John is planning to build N (2 <= N <= 50,000) square fenced-in pastures on his farm, each of size exactly K x K (1 <= K <= 1,000,000). Pasture i is centered at point (x_i, y_i) with integer coordinates in the range -1,000,000...1,000,000. However, in his haste to complete his plans, FJ realizes that he may have accidentally placed two pastures in locations that overlap (by overlap, this means the two pastures share a positive area in common). No two pastures share the exact same center point.

Given the locations of each of the planned square pastures, please help FJ compute the area shared by the two overlapping pastures. Output zero if no two squares overlap, and -1 if overlap occurs between more than a single pair of pastures.

在一个直角坐标系中,有N个边长为K的正方形。

给出每一个正方形的中心,请判断所有的正方形是否有重叠。

输入数据保证每一个正方形的中心不重合

输入输出格式

输入格式:

  • 第1行 :两个正整数: N , K

其中:2 <= N <= 50 000 ,1 <= K <= 1 000 000 ,K保证是偶数

*第2 .. i+1行:每行有两个整数xi,yi,描述了第i个正方形的中心。

其中:xi,yi均在[-1 000 000,1 000 000]内

输出格式:

只输出一行:

如果没有正方形重叠,输出“0”;如果有且只有一对正方形重叠,输出它们重叠的面积;如果有两对及以上的正方形重合,输出"-1";

注意:在输出答案后一定要输换行符!

输入输出样例

输入样例#1: 

4 6
0 0
8 4
-2 1
0 7
输出样例#1: 

20
#include<cstdio>
#include<iostream>
#include<algorithm>
#define maxn 50010
using namespace std;
int n,k,ans;
struct node{
int x,y;
}p[maxn];
bool cmp(node a,node b){
if(a.x!=b.x)return a.x<b.x;
return a.y<b.y;
}
int Abs(int x){
if(x>=)return x;
return -x;
}
int check(int x,int y){
int x1=p[x].x,x2=p[y].x;
int y1=p[x].y,y2=p[y].y;
if(x1==x2){
if(y2-y1>=k)return ;
int d=y2-y1;
return k*(k-d);
}
if(y1==y2){
if(x2-x1>=k)return ;
int d=x2-x1;
return k*(k-d);
}
if(Abs(x1-x2)>=k&&Abs(y1-y2)>=k)return ;
int mx1=max(x1-k/,x2-k/),mn1=min(x1+k/,x2+k/);
int mx2=max(y1-k/,y2-k/),mn2=min(y1+k/,y2+k/);
return (mx1-mn1)*(mx2-mn2);
}
int main(){
freopen("Cola.txt","r",stdin);
scanf("%d%d",&n,&k);
for(int i=;i<=n;i++)scanf("%d%d",&p[i].x,&p[i].y);
sort(p+,p+n+,cmp);
int t=;
for(int i=;i<=n;i++){
for(int j=i+;j<=n;j++){
int now=check(i,j);
if(now>){
if(t>=){
puts("-1");return ;
}
ans+=now;
t++;
}
}
}
if(ans)printf("%d\n",ans);
else puts("");
}

70分 暴力

/*
用一个bool变量have记录之前是否已经找到重叠正方形
对于第一个中心i:对横坐标从小到大进行排序后再按横坐标从小到大枚举
对于第二个中心j:枚举范围为[1,i-1],并且从后往前进行枚举,我们设一个变量temp为点j到点i的距离,那么当temp>=K时就直接跳出对j的枚举过程。如果temp<K 并且满足 |Yi-Yj|<K 且 have=false 就更新ans并标记have , 否则have=true直接输出-1即可。
*/
#include<iostream>
#include<algorithm>
#include<cstdio>
#define maxn 50010
using namespace std;
int n,k;
struct node{int x,y;}s[maxn];
int ans=,have;
bool cmp(node a,node b){return a.x<b.x;}
int abs(int x){
if(x>=)return x;
return -x;
}
int main(){
scanf("%d%d",&n,&k);
for(int i=;i<=n;i++)scanf("%d%d",&s[i].x,&s[i].y);
sort(s+,s+n+,cmp);
for(int i=;i<=n;i++){
int tmp=;
for(int j=i-;j>=;j--){
tmp+=(s[j+].x-s[j].x);
if(tmp>=k)break;
if(abs(s[i].y-s[j].y)<k){
if(have){puts("-1");return ;}
have=;
ans=(k-tmp)*(k-abs(s[i].y-s[j].y));
}
}
}
printf("%d\n",ans);
return ;
}

100分

05-22 02:10