P1884 [USACO12FEB]Overplanting S——洛谷
程序员文章站
2024-01-05 19:55:52
...
解题思路: 离散化 + 差分矩阵
解题步骤:
因为原始坐标系与差分的坐标系不同,所以要进行坐标系的变换
离散化处理缩小查找空间
图中坐标离散化后,再转化为格子的坐标,因为之前存贮的坐标是点的坐标,每个格子存储一个矩形
#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;
}
推荐阅读
-
洛谷 - P5836 [USACO19DEC]Milk Visits S (并查集+连通块或者LCA)
-
洛谷:P2926 [USACO08DEC]Patting Heads S(数学。普及/提高-)
-
洛谷 P2895 [USACO08FEB]Meteor Shower S(bfs
-
Java实现 洛谷 P6183 [USACO10MAR]The Rock Game S(DFS)
-
洛谷:P2853 [USACO06DEC]Cow Picnic S(图,普及/提高-,)
-
洛谷P2871-[USACO07DEC]Charm Bracelet S(01背包模板题)
-
洛谷P1825-[USACO11OPEN]Corn Maze S(BFS)
-
洛谷P2639-[USACO09OCT]Bessie‘s Weight Problem G(01背包)
-
P1884 [USACO12FEB]Overplanting S——洛谷
-
洛谷CSP-J/S2020初赛模拟部分题解