1. 程式人生 > >洛谷P2202 [USACO13JAN]方塊重疊Square Overlap

洛谷P2202 [USACO13JAN]方塊重疊Square Overlap

pan enter event ase for sticky str lan log

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>=0)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 0;
        int d=y2-y1;
        return k*(k-d);
    }
    if(y1==y2){
        if(x2-x1>=k)return 0;
        int d=x2-x1;
        return k*(k-d);
    }
    if(Abs(x1-x2)>=k&&Abs(y1-y2)>=k)return 0;
    int mx1=max(x1-k/2,x2-k/2),mn1=min(x1+k/2,x2+k/2);
    int mx2=max(y1-k/2,y2-k/2),mn2=min(y1+k/2,y2+k/2);
    return (mx1-mn1)*(mx2-mn2);
}
int main(){
    freopen("Cola.txt","r",stdin);
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)scanf("%d%d",&p[i].x,&p[i].y);
    sort(p+1,p+n+1,cmp);
    int t=0;
    for(int i=1;i<=n;i++){
        for(int j=i+1;j<=n;j++){
            int now=check(i,j);
            if(now>0){
                if(t>=2){
                    puts("-1");return 0;
                }
                ans+=now;
                t++;
            }
        }
    }
    if(ans)printf("%d\n",ans);
    else puts("0");
}
60分 暴力

洛谷P2202 [USACO13JAN]方塊重疊Square Overlap