【牛客 - 1080B】tokitsukaze and Hash Table(STLset,并查集,Hash)
題干:
鏈接:https://ac.nowcoder.com/acm/contest/1080/B
來(lái)源:牛客網(wǎng)
?
tokitsukaze有n個(gè)數(shù),需要按順序把他們插入哈希表中,哈希表的位置為0到n-1。
插入的規(guī)則是:
剛開始哈希表是空的。
對(duì)于一個(gè)數(shù)x,在哈希表中,如果(x mod n)的位置是空的,就把x放在(x mod n)的位置上。如果不是空的,就從(x mod n)往右開始找到第一個(gè)空的位置插入。若一直到n-1都不是空的,就從位置0開始繼續(xù)往右找第一個(gè)空的位置插入。
因?yàn)楣1砜偣灿衝個(gè)空位,需要插入n個(gè)數(shù),所以每個(gè)數(shù)都能被插入。
現(xiàn)在tokitsukaze想知道把這n個(gè)數(shù)按順序插入哈希表后,哈希表中的每個(gè)位置分別對(duì)應(yīng)的是哪個(gè)數(shù)。
輸入描述:
第一行包含一個(gè)正整數(shù)n(1≤n≤10^6)。 第二行包含n個(gè)非負(fù)整數(shù)x(0≤x≤10^9),這些數(shù)按從左到右的順序依次插入哈希表。輸出描述:
輸出一行,n個(gè)數(shù),第i個(gè)數(shù)表示哈希表中位置為i所對(duì)應(yīng)的數(shù)。(0≤i≤n-1)示例1
輸入
復(fù)制
4 1 2 6 5輸出
復(fù)制
5 1 2 6說明
插入1時(shí),1 mod 4=1,是空的,在位置1插入。 插入2時(shí),2 mod 4=2,是空的,在位置2插入。 插入6時(shí),6 mod 4=2,不是空的,找到下一個(gè)空的位置為3,所以在位置3插入。 插入5時(shí),5 mod 4=1,不是空的,找到下一個(gè)空的位置為0,所以在位置0插入。示例2
輸入
復(fù)制
4 3 0 7 11輸出
復(fù)制
0 7 11 3說明
插入3時(shí),3 mod 4=3,是空的,在位置3插入。 插入0時(shí),0 mod 4=0,是空的,在位置0插入。 插入7時(shí),7 mod 4=3,不是空的,找到下一個(gè)空的位置為1,所以在位置1插入。 插入11時(shí),11 mod 4=3,不是空的,找到下一個(gè)空的位置為2,所以在位置2插入。解題報(bào)告:
? ?這題做法不少,可以直接set維護(hù)第一個(gè)空位,二分查找即可。
? ?還可以用并查集維護(hù)空位,每次在x位置插入數(shù)后,合并x和(x+1)%n,也不難寫。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e6 + 5; set<int> ss; int ans[MAX]; int main() {int n;cin>>n;for(int i = 0; i<n; i++) ss.insert(i);for(int x,i = 1; i<=n; i++) {scanf("%d",&x);auto it = ss.lower_bound(x%n );if(it == ss.end()) ans[*ss.begin()] = x,ss.erase(ss.begin());else ans[*it] = x,ss.erase(it);}for(int i = 0; i<n; i++) printf("%d%c",ans[i],i == n-1 ? '\n' :' ');return 0 ; }附一個(gè)并查集代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e6 + 5; int f[MAX]; int getf(int v) {return f[v] == v ? v : f[v] = getf(f[v]); } void merge(int u,int v) {int t1 = getf(u),t2 = getf(v);f[t1] = t2; } int ans[MAX]; int main() {int n;cin>>n;for(int i = 0; i<=n; i++) f[i] = i;for(int x,i = 1; i<=n; i++) {scanf("%d",&x);int pos = x%n;int fa = getf(pos);ans[fa] = x;merge(fa,(fa+1)%n);}for(int i = 0; i<n; i++) printf("%d%c",ans[i],i == n-1 ? '\n' : ' ');return 0 ; }?
總結(jié)
以上是生活随笔為你收集整理的【牛客 - 1080B】tokitsukaze and Hash Table(STLset,并查集,Hash)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深海与章鱼老师
- 下一篇: 【HRBUST - 1621】迷宫问题I