2024年第二场蓝桥杯小白赛 房顶漏水啦 知识点:思维题

71 阅读1分钟

2.房顶漏水啦【算法赛】 - 蓝桥云课 (lanqiao.cn)

思想

根据提供的样例图我们可以发现选的木板至少要把上下行,左右列全部覆盖掉。

那么我们至少要把最小行(最上面的行),最大行(最下面的行)覆盖,即maxrow-maxcol+1(+1是包括右区间)

同理,列也一样,maxcol-mincol+1;

因为木板只能是正方形,所以只能在maxcol-mincol+1和maxrow-minrow+1中选一个较大的,这样就可以即把行覆盖又把列覆盖: image.png

code

#include <bits/stdc++.h>
using namespace std;

int main() {
    int maxcol = -1e9, maxrow = -1e9;
    int mincol = 1e9, minrow = 1e9;


    int n, m;
    cin >> n >> m;

    while (m--) {
        int x, y;
        cin >> x >> y;

        maxrow = max(maxrow, x);
        maxcol = max(maxcol, y);

        minrow = min(minrow, x);
        mincol = min(mincol, y);
    }

    cout << max(maxrow - minrow + 1, maxcol - mincol + 1);


    return 0;

image.png 注意x,y最大都是1e10,可能会溢出int,所以要开long long,那么最大值应该开1e12而不是1e9:

#include <bits/stdc++.h>
using namespace std;
#define int long long
signed main() {
    int maxcol = -1e12, maxrow = -1e12;
    int mincol = 1e12, minrow = 1e12;


    int n, m;
    cin >> n >> m;

    while (m--) {
        int x, y;
        cin >> x >> y;

        maxrow = max(maxrow, x);
        maxcol = max(maxcol, y);

        minrow = min(minrow, x);
        mincol = min(mincol, y);
    }

    cout << max(maxrow - minrow + 1, maxcol - mincol + 1);


    return 0;
}

image.png