洛谷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

/*
   用一个bool变量have记录是否找到了重叠正方形。
   先枚举第一个中心i 然后(按照x坐标)从小到大排序 这样就保证其相邻
   再枚举第二个中心j 枚举范围[1,i-1]并从后到前枚举(不会T)
   其他的根据题意模拟即可
   题解:我们设一个变量temp为点j到点i的距离,那么当temp>=K时就直接跳出对j的枚举过程。如果temp<K 并且满足 |Yi-Yj|<K 且 have=false 就更新ans并标记have , 否则have=true直接输出-1即可。
*/

#include <bits/stdc++.h>

using namespace std;

const int maxn = 50005;

struct node{
    int x,y;
}p[maxn];

bool cmp(node a,node b){
    return a.x < b.x;
}

int n,k,ans;
bool have = false;

int main(){
    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);
    for(int i = 2;i <= n;i++){
        int tmp = 0;
        for(int j = i-1;j >= 1;j--){
            tmp += (p[j+1].x-p[j].x);
            if(tmp >= k) break;
            if(abs(p[i].y-p[j].y) < k){
                if(have) {printf("-1");return 0;}
                have = 1;
                ans = (k-tmp) * (k-abs(p[i].y-p[j].y));
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}

 

 

posted @ 2018-11-07 11:41  bryce02  阅读(160)  评论(0编辑  收藏  举报
Live2D