• hash表--[JLOI2011]不重复数字



    给出N个数,要求把其中重复的去掉,只保留第一次出现的数。
    例如,给出的数为1 2 18 3 3 19 2 3 6 5 4,其中2和3有重复,去除后的结果为1 2 18 3 19 6 5 4。
    Input
    输入第一行为正整数T,表示有T组数据。
    接下来每组数据包括两行,第一行为正整数N,表示有N个数。第二行为要去重的N个正整数。
    对于30%的数据,1 <= N <= 100,给出的数不大于100,均为非负整数;
    对于50%的数据,1 <= N <= 10000,给出的数不大于10000,均为非负整数;
    对于100%的数据,1 <= N <= 50000,给出的数在32位有符号整数范围内。
    提示:
    由于数据量很大,使用C++的同学请使用scanf和printf来进行输入输出操作,以免浪费不必要的时间。

    Output
    对于每组数据,输出一行,为去重后剩下的数字,任两个数字之间有一个空格
    Sample Input
    2
    11
    1 2 18 3 3 19 2 3 6 5 4
    6
    1 2 3 4 5 6
    Sample Output
    1 2 18 3 19 6 5 4
    1 2 3 4 5 6

    Sol:使用Set

    #include<bits/stdc++.h>
    using namespace std;
    set<int> S;
    int main()
    {
    	int t;
    	cin>>t;
    	while(t--){
    		S.clear();
    		int n;
    		scanf("%d",&n);
    		for(int i=1;i<=n;i++){
    			int x;
    			scanf("%d",&x);
    			if(!S.count(x))
    			{
    				if(i==1)
    				    cout<<x;
    				else
    			         printf(" %d",x);
    				 S.insert(x);	
    			}
    		}
    		printf("
    ");
    	}
    }
    

      Sol2:使用Hash表

    #include<algorithm>
    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #define maxn 50005
    #define int long long
    using namespace std;
    const int p = 13331, q = 10101;
    int read() {
        int x = 0, f = 1, ch = getchar();
        while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();}
        while(isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar();
        return x * f;
    }
     
    struct node {int a, nxt;} Hash[maxn];
    int head[p + 10], cnt = 0;
    void insert(int x) {
        register int key = (x + q) % p;
        Hash[++cnt].a = x, Hash[cnt].nxt = head[key]; head[key] = cnt;
    }
     
    bool search(int x) {
        register int key = (x + q) % p;
        for(int i = head[key]; i; i = Hash[i].nxt) {
            if(Hash[i].a == x) return true;
        }
        return false;
    }
     
    int T, n, a;
    signed main() {
        T = read();
        while(T--) {
            memset(Hash, 0, sizeof Hash);
            memset(head, 0, sizeof head); cnt = 0;
            n = read();
            for(int i = 1; i <= n; i++) {
                a = read();
                if(search(a)) continue;
                insert(a);
                if(i == 1) printf("%lld", a);
                else printf(" %lld", a);
            }
            puts("");
        }
        return 0;
    }
    

      

  • 相关阅读:
    优化MyBatis配置文件中的配置
    Java多线程---同步与锁
    Runtime.getRuntime().exec()
    java ---线程wait/notify/sleep/yield/join
    redis配置详情
    httpcline
    线程
    Bootstrap学习(一)
    springmvc注解配置
    salesforce上上传和导出.csv格式文件
  • 原文地址:https://www.cnblogs.com/cutemush/p/12296109.html
Copyright © 2020-2023  润新知