题解:P16694 [CSPro 29] 田地丈量

· · 题解

P16694 [CSPro 29] 田地丈量 题解

核心公式

  1. 交集边界计算:

    \begin{cases} x_1' = \max(x_1, 0) \\ x_2' = \min(x_2, a) \\ y_1' = \max(y_1, 0) \\ y_2' = \min(y_2, b) \end{cases}

    其中 x_1, y_1 为田地左下角坐标,x_2, y_2 为田地右上角坐标,a, b 为目标区域右上角坐标。

  2. 单块田地有效面积:

    S_i = \begin{cases} (x_2' - x_1') \times (y_2' - y_1') & \text{if } x_1' < x_2' \land y_1' < y_2' \\ 0 & \text{otherwise} \end{cases}
  3. 总答案:

    ans = \sum_{i=1}^n S_i

    其中 n 为田地总块数。

AC代码

# include <bits/stdc++.h>
using namespace std;
int n,x,y,ans,t[10005][10005];
int main () {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> n >> x >> y;
    while (n --) {
        int x1,x2,y1,y2;
        cin >> x1 >> y1 >> x2 >> y2;
        x1 = max(x1,0); x2 = min(x2,x); y1 = max(y1,0); y2 = min(y2,y);
        if (x1 <= x2 && y1 <= y2) ans += (x2 - x1) * (y2 - y1);
    }
    cout << ans;
    return 0;
}

AI使用声明

本文使用豆包进行了公式排版和格式优化,核心思路、算法逻辑与代码均为本人原创。