P1496 火烧赤壁(离散化)
这是我的第一道离散化题,虽然只是一道普及-的题,但我理解起来还是有点吃力,看完视频后我我觉的离散化,就是将一堆数据用他们的相对大小表示 例如 1,99,100,1000,可以表示为1,2,3,4.
55 100 300 1,可以表示为 2 3 4 1;这道题目就是先把各个区间的两个端点存储到c数组,对c进行排序后中然后用二分查找各个数据在c中的相对位置
这里要注意,标记f数组时应该<b[i],应为我们是用后一个数减前一个数,如果不这样的话,例如,1 5,8 10,两个区间,答案就会加上8-5这是不正确的
#include<iostream>
#include<set>
#include<map>
#include<algorithm>
#include<vector>
#include<cmath>
#include<climits>
#include<cstring>
#define int long long
const int N = 1e6+5;
using namespace std;
char* p1, * p2, buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int read()
{
int x = 0, f = 1;
char ch = nc();
while (ch < 48 || ch>57)
{
if (ch == '-')
f = -1;
ch = nc();
}
while (ch >= 48 && ch <= 57)
x = x * 10 + ch - 48, ch = nc();
return x * f;
}
int a[N], b[N], c[N],f[N];
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int>v;
int k = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i] >> b[i];
c[++k] = a[i];
c[++k] = b[i];
}
sort(c + 1, c + 1 + 2 * n);
for (int i = 1; i <= n; i++) {
a[i] = lower_bound(c + 1, c + 1 + 2 * n, a[i])-c;
b[i] = lower_bound(c + 1, c + 1 + 2 * n, b[i]) - c;
for (int j = a[i]; j < b[i]; j++)f[j] = 1;
}
int cnt = 0;
for (int i = 1; i < 2 * n; i++) {
if (f[i] == 1)cnt += c[i+1] - c[i];
}
cout << cnt;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理