算法:离散化模板

原理

离散化是把无限空间中有限的个体映射到有限的连续区间 ,核心作用:去重 + 压缩坐标

当题目中数据范围很大,但是数据的总量不是很大,**并且我们需要用数据的值来映射数组的下标时,**我们就可以用离散化的思想先预处理一下所有的数据,使的每一个数据都映射成一个范围较小的值。

比如: 9, 99, 9999, 9999999 离散之后就变成 1, 2, 3, 4。

细节:离散化后只是让对应位置的元素有了新的下标

离散化模板

1.静态数组实现

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

#define int long long 
#define endl '\n'

const int N = 2e5 + 10; 
int n;
int a[N];
int t[N];
int pos; // 离散化后的大小
int find(int x)
{
	return lower_bound(t + 1, t + 1 + pos, x) - t; // 让下标从1开始
}

void solve()
{
	cin >> n;
	for(int i = 1; i <= n; i++)
	{
		cin >> a[i];
		t[i] = a[i];
	}
	// 排序 + 去重 
	sort(t + 1, t + 1 + n); // 排序 
	pos = unique(t + 1, t + 1 + n) - t - 1; // 去重
	for(int i = 1; i <= n; i++)
	{
		cout << find(a[i]) << endl; // 离散化后的结果 
	}
}

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int _ = 1;
	cin >> _;
	while(_--)
	{
		solve();
	}
	return 0;
}

不建议用unordered_map来离散化,有时候效率低,有被卡TLE

2.动态数组实现

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

#define int long long 
#define endl '\n'

void solve()
{
	int n; cin >> n;
	vector<int> a(n + 1);
	for(int i = 1; i <= n; i++)
	{
		cin >> a[i];
	}
	vector<int> t = a;
	sort(t.begin(), t.end()); // 排序 
	t.erase(unique(t.begin(), t.end()), t.end()); // 去重 	
	int pos = t.size();
	for(int i = 1; i <= n; i++)
	{
		cout << lower_bound(t.begin(), t.end(), a[i]) - t.begin() + 1 << endl;
	}
	
}

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int _ = 1;
	cin >> _;
	while(_--)
	{
		solve();
	}
	return 0;
}
相关推荐
青少儿编程课堂2 小时前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
geovindu3 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗5 小时前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
凌冰_5 小时前
数据结构 - 队列(五)
数据结构·算法·软件工程
让我们一起加油好吗7 小时前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
让我们一起加油好吗7 小时前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
lisw0518 小时前
稀疏算法概述!
算法·机器人·无人机
YLCHUP19 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴20 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl