[算法刷题题解笔记] 洛谷 P1003 [NOIP2011 提高组] 铺地毯 [枚举]

题目链接

题目大意

  • 先将若干个地毯铺在地面上,然后给你任一一个点,判断出这个点在覆盖地面最上面的那张地毯的编号

解题思路

  • 由于这些地毯按照编号从小到大的顺序平行于坐标轴先后铺设,后铺的地毯覆盖在前面已经铺好的地毯之上。
  • 所以我们要判断给定的点在那个地毯上,我们只需要从编号最大的开始向编号小的地毯逐个枚举进行判断即可,只要一判断出在某个地毯上,就可以退出枚举,输出地毯编号(从1开始)
  • 注意:在矩形地毯边界和四个顶点上的点也算被地毯覆盖。

解题代码

// package luogu.orange;

import java.io.*;

/**
 * ClassName: P1003
 * Package: luogu.orange
 * Description:
 *
 * @Author tcw
 * @Create 2023-06-08 19:47
 * @Version 1.0
 */
public class Main {
    
    
    
    // 快读
    private static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    // 快写
    private static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    
    /**
     * 私有内部类,地毯类
     * 用于存储地毯的左下角坐标和地毯在x轴和y轴的长度
     * 同时可以用于判断点是否在该地毯内
     */
    private static class Carpet {
    
    
        int a; // 左下角横坐标
        int b; // 左下角纵坐标
        int g; // 地毯在x轴的长度
        int k; // 地毯在y轴的长度
    
        public Carpet(int a, int b, int g, int k) {
    
    
            this.a = a;
            this.b = b;
            this.g = g;
            this.k = k;
        }
    
        /**
         * 根据需要进行判断的点的坐标判断该点是否在地毯内
         *
         * @param x
         * @param y
         * @return 布尔值,true在,false不在
         */
        public boolean isInternal(int x, int y) {
    
    
            // 计算地毯的右上角坐标
            int rA = a + g;
            int rB = b + k;
            // 判断点是否在地毯内
            if (x >= a && x <= rA && y >= b && y <= rB) return true;
            return false;
        }
    }
    
    public static void main(String[] args) {
    
    
        // 地毯个数
        int n = readInt();
        // 存储所有地毯信息的数组
        Carpet[] carpets = new Carpet[n];
        // 读入地毯的数据
        for (int i=0; i<n; i++) {
    
    
            carpets[i] = new Carpet(readInt(), readInt(), readInt(), readInt());
        }
        // 要进行判断的点的坐标
        int x = readInt();
        int y = readInt();
        // 由于后面铺的地毯会覆盖前面的
        // 所以从最后一个开始逐个枚举判断
        for (int i=n-1; i>=0; i--) {
    
    
            if (carpets[i].isInternal(x, y)) {
    
    
                out.print(i+1); // 输出地毯编号
                out.flush();
                return;
            }
        }
        out.println(-1);
        out.flush();
    }
    
    /**
     * 读取整数数据
     *
     * @return 整数
     */
    private static int readInt() {
    
    
        int in = Integer.MIN_VALUE;
        try {
    
    
            st.nextToken();
            in = (int) st.nval;
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return in;
    }
    
}

猜你喜欢

转载自blog.csdn.net/m0_53022813/article/details/131115262
今日推荐