codeforces 670c 离散化

第二场
C:经典的离散化题目

离散化就是 当数据 个数 过大 已经超出了数组存放的范围时 用来优化数据的一种方法 若此时 我们只需要这些数据的相对位置 或者 大小关系 而不需要具体数值的时候 就可以采取离散化的方法。
例如: 5 ,21,955555555;这三个数 只考虑其大小关系我们可以把它们
记作 1,2,3来表示相对的位置关系
离散化 的具体步骤 a[ i ] 原数组 lsh[ i ] 离散化之后的数组 cnt 用来记录个数
具体分为三步:
1.存入数据之后 sort 排序
2.对排好序的数组 进行unique去重 注意unique只是 把重复的元素放到数组后面而不是 删除
3.利用low_bound函数二分查找

int lsh[];int cnt;
sort(lsh + 1,lsh + 1 + cnt);
cnt = unique(lsh + 1,lsh + 1 + cnt) - lsh - 1;返回的数据的个数
low_bound(lsh + 1,lsh + 1+ cnt, x ) - lsh;// 即可找到数据的相对位置

codeforces 670C 看电影:经典离散化排序
代码实现过程:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
// 数据离散化 的经典 题目
using namespace std;
typedef long long ll;
const int N = 2e5;
int num[3*N];int lsh[3*N];int cnt;
int a[N],b[N],c[N];// num数组用来存放离散化后的答案 lsh数组来存放离散化数据 cnt用来记录离散化数据的个数
int n,m;

void d()//离散化数据
{
    
    
    cnt = 0;
    for(int i = 1;i <= n;i ++)
        lsh[++cnt] = a[i];
    for(int i = 1;i <= m;i ++)
        lsh[++cnt] = b[i];
    for(int i = 1;i <= m;i ++)
        lsh[++cnt] = c[i];
    sort(lsh+1,lsh+cnt+1);// 把数据 从小到大排序之后 才能进行 去重操作
    cnt = unique(lsh+1,lsh+1+cnt) - lsh - 1;//此时cnt记录得就是 最终 完成离散化之后 留有的数据个数 别忘了最后减一
}

int tofind(int n)
{
    
    
    return lower_bound(lsh+1,lsh+1+cnt,n) - lsh;// 二分查找 离散化之后的数据位置
}

int main()
{
    
    
    while(scanf("%d",&n)!=EOF)
    {
    
    
        for(int i = 1;i <= n;i ++)
            scanf("%d",&a[i]);
        scanf("%d",&m);
        for(int i = 1;i <= m;i ++)
        {
    
    
            scanf("%d",&b[i]);
        }
        for(int i = 1;i <= m;i ++)
        {
    
    
            scanf("%d",&c[i]);
        }
        d();
        for(int i = 1;i <= n;i ++)
            num[tofind(a[i])]++;//记录个数
        int num1;int num2;
        int pos = 1;
        int nm1;int nm2;
        nm1 = nm2 = 0;
        for(int i = 1;i <= m;i ++)
        {
    
    
            num1 = num[tofind(b[i])];
            num2 = num[tofind(c[i])];
            if(nm1 < num1 || (nm1 == num1 && nm2 < num2))
            {
    
    
                nm1 = num1;
                nm2 = num2;
                pos = i;// 电影院的位置
            }
        }
        printf("%d\n",pos);
    }
    return 0;
}

这个题为什么 lsh 数组 要把a,b,c全部放入而不是单独放入a
我的理解是 数据的输入时并不一定会保持一致 应该存入的是全部的数据
(好吧 其实还是不是很懂qwq)```

猜你喜欢

转载自blog.csdn.net/weixin_45672411/article/details/104138630