欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

P1884 [USACO12FEB]Overplanting S——洛谷

程序员文章站 2024-01-05 19:55:52
...

P1884 [USACO12FEB]Overplanting S——洛谷
解题思路: 离散化 + 差分矩阵
解题步骤:
P1884 [USACO12FEB]Overplanting S——洛谷
因为原始坐标系与差分的坐标系不同,所以要进行坐标系的变换
P1884 [USACO12FEB]Overplanting S——洛谷
离散化处理缩小查找空间
P1884 [USACO12FEB]Overplanting S——洛谷
图中坐标离散化后,再转化为格子的坐标,因为之前存贮的坐标是点的坐标,每个格子存储一个矩形
P1884 [USACO12FEB]Overplanting S——洛谷

#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
typedef pair<int, int> PII;
typedef long long LL;
const int N = 2020;
vector<int> allx, ally;//存放所有点的横纵坐标
map<int, int> mapx, mapy;//映射坐标对应的下标
vector<PII> rec[2];//存放矩形
int a[N][N], b[N][N];
void insert(int x1, int y1, int x2, int y2, int c)
{
    b[x1][y1] += c;
    b[x2 + 1][y1] -= c;
    b[x1][y2 + 1] -= c;
    b[x2 + 1][y2 + 1] += c;
}
int main()
{
    int n; 
    cin >> n;
    //输入所有的x, y 坐标到数组allx和ally中, 准备离散化
    allx.push_back(0);
    ally.push_back(0);
    for(int i = 0; i < n; i++)
    {
        int x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        rec[0].push_back({y2, x1}); //注意坐标系的转换
        rec[1].push_back({y1, x2});
        allx.push_back(y1);
        allx.push_back(y2);
        ally.push_back(x1);
        ally.push_back(x2);
    }
    //排序, 去重
    sort(allx.begin() + 1, allx.end());
    allx.erase(unique(allx.begin() + 1, allx.end()), allx.end());
    sort(ally.begin() + 1, ally.end());
    ally.erase(unique(ally.begin() + 1, ally.end()), ally.end());
    
    //建立x 和y坐标的map映射
    for(int i = 1; i < allx.size(); i++) mapx[allx[i]] = i;
    for(int i = 1; i < ally.size(); i++) mapy[ally[i]] = i;
    
    //差分矩阵
    for(int i = 0; i < n; i++)
    {
        int x1, y1 , x2, y2;
        x1 = rec[0][i].first;//点的实际坐标
        y1 = rec[0][i].second;
        x2 = rec[1][i].first;
        y2 = rec[1][i].second;
        
        insert(mapx[x1], mapy[y1], mapx[x2] - 1, mapy[y2] - 1, 1);//映射为格子下标
    }
    
    //求前缀和矩阵
    for(int i = 1; i <= allx.size(); i++)
      for(int j = 1; j <= ally.size(); j++)
        a[i][j] = a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1] + b[i][j];
        
        //将前缀和矩阵中被覆盖的格子,还原成原坐标系中的矩阵,进行面积求和
        LL area = 0;
        for(int i = 1; i <= allx.size(); i++)
          for(int j = 1; j <= ally.size(); j++)
            {
                if(a[i][j])
                {
                    int x1, y1, x2, y2;
                    x1 = allx[i];
                    y1 = ally[j];
                    x2 = allx[i + 1];
                    y2 = ally[j + 1];
                    area += (LL)(x2 - x1) * (y2 - y1);
                }
            }
            cout << area << endl;
            return 0;
}

相关标签: 算法习题