离散化

离散化:把大数据排序,然后对应排序前的顺序,并把排序后数据的下标记录到排序前数据相对应的位置

注意:lower_bound 和 upper_bound 的区别在于,  离散后 前者是从0-n-1;   后面是 1-n; 离散坐标的时候,如果相邻两个数不为1,则插入一个小于当前值,大于前一个位置的数;

思路:排序->删除重复元素->索引数据离散化后对应得值

STL 中 unique函数的功能是元素去重。就是将重复的元素保留一个在前面,其余的移动到最后。由于”删除”的是相邻的重复元素,所以在使用unique函数之前,一般都会将目标序列进行排序。

//一维离散化
//dis[]=now[] = 输入 
sort(now+1,now+1+n);
len = unique(now+1,now+1+n)-now;
for(int i=1;i<=n;i++)
    dis[i] = lower_bound(now+1,now+1+len,dia[i])-now;

//结构体
    bool operator < (const node &a) const {
        return x< a.x;
    }
for
(int i=1;i<=n;i++) { cin>>node[i].x; node[i].id = i; } sort(node+1,node+1+n); for(int i=1;i<n;i++) rank[node[i].id] = i;

二维离散化

#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
#define mem(s,t) memset(s,t,sizeof(s))
#define pq priority_queue
#define pb push_back
#define fi first
#define se second
#define ac return 0;
#define ll long long
#define rep(xx,yy) for(int i=xx;i<=yy;i++)
#define TLE std::ios::sync_with_stdio(false);   cin.tie(NULL);   cout.tie(NULL);   cout.precision(10);
const double eps = 1e-14;
const int maxn = 1e9;
const int mxn = 1e3;
int x[mxn],y[mxn],nx[mxn],ny[mxn],dis[mxn][mxn];
struct node{    int x,y;}node[mxn];
int main()
{
    mem(dis,0);
    int n,pos=1;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>node[i].x>>node[i].y;
        x[i] = node[i].x;
        y[i] = node[i].y;
    }
    x[n+1]=y[n+1] = maxn;
    sort(x+1,x+1+n);
    int lenx=unique(x+1,x+1+n)-x;

    sort(y+1,y+1+n);
    int leny=unique(y+1,y+1+n)-y;

    pos = 1;
    for(int i=1; i<=lenx; i++)
    {
        if(i==1)
            nx[pos++] = x[i];
        else if(x[i]!=x[i-1]+1)
            nx[pos++] = x[i]-1,nx[pos++] = x[i];
    }
    pos = 1;
    for(int i=1; i<=leny; i++)
    {
        if(i==1)
            ny[pos++] = y[i];
        else if(x[i]!=x[i-1]+1)
            ny[pos++] = y[i]-1,ny[pos++] = y[i];
    }
    for(int i=1;i<=n;i++)
    {
        int posx = lower_bound(nx+1,nx+1+n,node[i].x)-nx;
        int posy = lower_bound(ny+1,ny+1+n,node[i].y)-ny;
        cout<<posx<<" "<<posy<<endl;
        dis[posx][posy] = 1;
    }

    for(int i=1;i<=n+1;i++)
    {
        for(int j=1;j<=n+1;j++)
            cout<<dis[i][j];
        cout<<endl;
    }
    return 0;
}
 
所遇皆星河
原文地址:https://www.cnblogs.com/Shallow-dream/p/11443813.html