ssl1063-统计数字【哈希表】
生活随笔
收集整理的這篇文章主要介紹了
ssl1063-统计数字【哈希表】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
先做賭徒的,結果發現這道題太TM簡單了,然后就先做這道題了。
正題
給出n(1<=n<=200000)個數字,每個數字不超過1500000000。求每個數字出現的次數
輸入輸出(建議無視)
Input
輸入包含n+1行;
第一行是整數n,表示自然數的個數;
第2~n+1每行一個自然數。
Output
輸出包含m行(m為n個自然數中不相同數的個數),按照自然數從小到大的順序輸出。每行輸出兩個整數,分別是自然數和該數出現的次數,其間用一個空格隔開。
Sample Input
8
2
4
2
4
5
100
2
100
Sample Output
2 3
4 2
5 1
100 2
解題思路
這只是哈希的練習題,不代表哈希是最優解,反正也能過對吧(⊙v⊙)。用哈希統計
代碼
#include<cstdio> #include<algorithm> using namespace std; const int maxn=299993; struct hashs{int c,num; }; hashs hash[maxn]; int n,x; int hashmath(int x)//哈希函數 {return x%maxn; } int locate(int x)//尋找位置 {int i=0,w=hashmath(x);while (i<maxn && hash[(w+i)%maxn].c!=0 && hash[(w+i)%maxn].c!=x)i++;return (w+i)%maxn; } void ins(int x)//插入元素 {int w=locate(x);hash[w].c=x;hash[w].num++;//統計次數 } bool find(int x)//查找 {int w=locate(x);if (hash[w].c==x) return true;else return false; } bool cmp(hashs x,hashs y)//排序 {if (x.num==0 || y.num==0) return x.num>y.num;return x.c<y.c; } int main() {scanf("%d",&n);for (int i=1;i<=n;i++){scanf("%d",&x);ins(x);//加入}sort(hash,hash+maxn-1,cmp);//排序int i=0;while (hash[i].num!=0){printf("%d %d\n",hash[i].c,hash[i].num);i++;//輸出} }總結
以上是生活随笔為你收集整理的ssl1063-统计数字【哈希表】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果发布会即将开始,在线商店已下线维护
- 下一篇: ZOJ1101-赌徒【二分查找】