离散化+例题(AcWing 103. 电影)

离散化

什么叫做离散化?就是把一个较大的数字映射成为一个较小的数字!列如给你200个1-1e100范围内的数字,那么最大1e100能否用一个1-200内的数字表示呢?答案是可以的!因为只有200个数字,那么把给出的所有数字按照输入顺序映射成为1,2…200,当然数字重复映射也会重复!

那么如何实现这部操作呢??STL中学过容器就知道,map就是映射的一种实现方式!!

以下是一个简单的离散化模板,可以得知离散化后的数字和出实现的个数

#include<bits/stdc++.h>

using namespace std;
const int N=1e5;
int cnt[N]; 
map<int,int> p,sum;
int main(){
	int n;
	scanf("%d",&n);
	int pos=0;//离散化的数字
	for(int i=1;i<=n;i++){
		int x;
		scanf("%d",&x);
		if(!p[x])	p[x]=++pos;//离散化	,pos从1到最多n 
		cnt[i]=p[x];//储存离散化后的数字 
		sum[p[x]]++;//记录个数		
	}
	return 0;
} 

AcWing 103. 电影

题目大意:请你帮忙选择一部电影,可以让观影很开心的人最多。如果有多部电影满足条件,则在这些电影中挑选观影比较开心的人最多的那一部。

思路:这道题目是一道离散化的好题,因为我们这里的语言,是非常的分散,所以我们可以把他们汇聚在一起,也就是重新定义这些语言,重新标号1,2,3,…,n。

注意:这道题目统计方面,因为时间限制非常严格,所以动用了C++11的哈希级别map,unordered_map<int,int>,优点就是在读取存入会比map快很多!!!

#include<bits/stdc++.h>
/* //我的版本不能直接用 unordered_map ,所以加了一些 
#if(__cplusplus == 201103L)
#include <unordered_map>
#include <unordered_set>
#else
#include <tr1/unordered_map>
#include <tr1/unordered_set>
namespace std
{
    using std::tr1::unordered_map;
    using std::tr1::unordered_set;
}
#endif
*/ 
using namespace std;
const int N=2*1e5+5;
struct node{//结构体mv,用来储存1-m部电影,a,b表示离散化后的语言个数,x表示第x部电影 
	int a,b,x;
}mv[N];
int per[N];//用来储存离散化后的数 

unordered_map<int,int> p,sum;//p表示离散化数字,sum表示离散化后的数字的个数 
//map<int,int> p,sum; 
bool cmp(node x,node y){//sort排序 
	if(x.a!=y.a) return x.a>y.a;
	else return x.b>y.b;
} 



int main(){
	int n;
	scanf("%d",&n);
	int pos=0;
	for(int i=1;i<=n;i++){
		int x;
		scanf("%d",&x);
		if(!p[x])	p[x]=++pos;//离散化	,pos从0到最多n+m 
		per[i]=p[x];//储存离散化后的数字 
		sum[p[x]]++;//记录个数		
	}
	
	int m;
	scanf("%d",&m);
	for(int i=1;i<=m;i++){
		int x;
		scanf("%d",&x);
		x=p[x];//离散化 
		mv[i].a=sum[x]; //a的人数的个数 
		
	} 
	for(int i=1;i<=m;i++){//同理 
		int x;
		scanf("%d",&x);
		x=p[x];
		mv[i].b=sum[x];
		mv[i].x=i;
	} 
	
	sort(mv+1,mv+m+1,cmp);
	printf("%d\n",mv[1].x);//输出第一个就是答案 
	return 0;
} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值