【洛谷 P4302】[JLOI2011]不重复数字【哈希表】

题目描述

给定 nn 个数,要求把其中重复的去掉,只保留第一次出现的数。

输入格式

本题有多组数据。
第一行一个整数 TT,表示数据组数。
对于每组数据:
第一行一个整数 nn。
第二行 nn 个数,表示给定的数。

输出格式

对于每组数据,输出一行,为去重后剩下的数,两个数之间用一个空格隔开。

输入输出样例

输入

#1

2
11
1 2 18 3 3 19 2 3 6 5 4
6
1 2 3 4 5 6

输出

#1

1 2 18 3 19 6 5 4
1 2 3 4 5 6

分析:

哈希表 思想很简单
用哈希表判断是否出现过

CODE:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define p 1808504320951916825
#pragma GCC optimize(2)
using namespace std;
long long n,m;
long long hash[4698571+123456];
bool found(int x){
	long long place=abs(x%p); //哈希%
	while(hash[place]!=p)  
	{
		if(hash[place]==x)  //相同
			return true;
		else 
			++place;  //后移
	}
	hash[place]=x;
	return false;	
}
int main(){
	scanf("%lld",&n);
	while(n--){
		memset(hash,25,sizeof(hash));  //注意每次清空hash
		scanf("%lld",&m);
		for(int i=1;i<=m;i++)
		{
			long long k;
			scanf("%lld",&k);
			if(!found(k)) cout<<k<<" ";  //直接输出
		}
		cout<<endl;
	}
	return 0;
} 

被luogu管理员加了两个ex数据 100分没了

猜你喜欢

转载自blog.csdn.net/dgssl_xhy/article/details/107467245
今日推荐