算法竞赛中超过 1000×1000 的整型二维数组如何处理?
【大容量 int 型二维数组处理方法】
● 由于算法竞赛中的典型内存限制一般为 64MB,所以 int 型二维数组理论最大约开到 4096×4096(约占用 67MB),否则就会 MLE(爆空间)。同时还要注意在使用时要预留缓冲空间,即数组实际大小应比理论最大值小 10%-20%,避免因其他变量的使用导致内存超限。
● 在算法竞赛实践中,超过 1000×1000 的整型二维数组推荐使用动态容器 STL vector 或 STL map。此思路,本质上是利用 STL vector 及 STL map 进行离散化,或称之为映射。
(1)使用 STL vector 进行离散化的 C++ 代码,如下所示。
★ 命令 unique(v.begin(), v.end()) 返回指向容器中不重复序列末尾后一个位置的迭代器。
★ 命令 lower_bound(v.begin(), v.end(), x) 实现在有序容器 v 中查找第一个不小于 x 的元素位置。它的值减去 v.begin() 得到的是从 0 开始的下标值。
#include <bits/stdc++.h>
using namespace std;int main() {int n;cin>>n;vector<int> nums(n), v;for(int i=0; i<n; i++) {cin>>nums[i];v.push_back(nums[i]);}sort(v.begin(), v.end());v.erase(unique(v.begin(), v.end()), v.end());for(int x:nums) {int pos=lower_bound(v.begin(),v.end(),x)-v.begin();cout<<pos+1<<" ";}return 0;
}/*
in:
5
8 2 6 9 4out:
4 1 3 5 2
*/
(2)使用 STL map 进行离散化的 C++ 代码,如下所示。
#include <bits/stdc++.h>
using namespace std;const int maxn=1e5+5;
int a[maxn];
map<int,int> mp;
int n,id=1;int main() {cin>>n;for(int i=0; i<n; i++) cin>>a[i];sort(a,a+n);for(int i=0; i<n; i++) {if(mp.find(a[i])==mp.end()) {mp[a[i]]=id++;}}for(auto x:mp) { //输出离散化结果cout<<x.first<<" -> "<<x.second<<endl;}return 0;
}/*
in:
5
1000 30 1000 -5 30out:
-5 -> 1
30 -> 2
1000 -> 3
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/148998565
https://blog.csdn.net/hnjzsyjyj/article/details/130179373