算法与数据结构实验题 7.22 索隆的难题

实验任务

索隆是有名的路痴,为了不让索隆走丢,娜美给了索隆一本地图。该地图有N个城市,编号从1到N。每个城市有个代号,索隆每到一个城市只能知道该城市的代号而不知道该城市的编号,现有一份编号与代号对应的清单,你能帮索隆尽快地找到所在城市的编号吗?

数据输入

输入第一行为两个正整数N (1< =N < =1000000),M(1<=M<=10000) 表示有N个城市,M个询问

接下来N行,每行一个整数ai(0<=ai<=100000000),第i行表示编号i的城市的代号为ai。这N个整数各不相同。

接下来M行,每行一个整数b(0<=b<=100000000),表示当前所在城市的代号。

数据输出

输入示例

6 3
4
5
7
10
8
2
4
5
8

输出示例

1
2
5

代码一

#include<bits/stdc++.h>
using namespace std;
 
int n,m,x;
unordered_map<int,int>mp;
 
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++) {
		scanf("%d",&x);
		mp[x]=i;
	}
	for(int i=1;i<=m;i++) {
		scanf("%d",&x);
		printf("%d\n",mp[x]);
	}
	return 0;
}

代码二

#include<bits/stdc++.h> 
using namespace std;
typedef long long ll;
const int N=5000;

int n,m,x;
vector<pair<int,int>>G[N];
int query(int x) {
	for(auto& it:G[x%N]) if(it.first==x) return it.second;
}

int main()  
{
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	
	cin>>n>>m;
	for(int i=1;i<=n;i++) {  
		cin>>x;
		G[x%N].push_back({x,i});
	}  
	while(m--) {
		cin>>x;
		cout<<query(x)<<'\n';
	}
	return 0;
}

思路

哈希表板子题,第一个采用STL中的哈希表,也就是unordered_map来实现,第二份采用常规的哈希来做,效率更高

posted @ 2024-11-25 23:33  Severj  阅读(180)  评论(0)    收藏  举报