2021牛客多校10 - Browser Games(哈希)
生活随笔
收集整理的這篇文章主要介紹了
2021牛客多校10 - Browser Games(哈希)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出 nnn 個字符串,對于每個 iii ,輸出最少需要用多少個前綴,可以表示第 1~i1\sim i1~i 個字符串而不能表示第 i+1~ni+1\sim ni+1~n 個字符串
題目分析:銀川原題的數據加強版,正著模擬的思路被推翻,看了蔣佬隊伍的代碼用哈希倒著模擬的,太妙了。
簡單翻譯一下題面就是,對于每個 iii 來說,需要在第 1~i1\sim i1~i 個字符串中分別找到一個前綴,滿足:
如果是用字典樹正著考慮的話,不難看出每個前綴的長度是逐漸變短的,所以利用這個性質去模擬。
首先考慮 i=ni=ni=n 時的答案,不難想到將 nnn 個字符串的第一個字母去重后就是 ans[n]ans[n]ans[n] 了。這里的 nnn 個首字母代表的本質上是 nnn 個長度為 111 的前綴。
然后考慮刪除掉第 nnn 個字符串會造成的影響,對于第 nnn 個字符串的所有前綴 preprepre 來說,如果在字符串 1~n?11\sim n-11~n?1 中,存在著一個前綴 sss 和 preprepre 相等,那么需要將 sss 加長,這樣 sss 才不會作為前綴出現在第 nnn 個字符串中。
用哈希優化一下空間,上述做法的空間復雜度和時間復雜度就都是 O(∑∣S∣)O(\sum|S|)O(∑∣S∣) 的了
代碼:
// Problem: Browser Games // Contest: NowCoder // URL: https://ac.nowcoder.com/acm/contest/11261/A // Memory Limit: 65536 MB // Time Limit: 4000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) (x&-x) using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; struct Hash {static const int mod1=1e9+7,mod2=1e9+9;int x,y;Hash(int x=0,int y=0):x(x),y(y){}Hash operator+(const Hash& t)const {return Hash((x+t.x)%mod1,(y+t.y)%mod2);}Hash operator*(const Hash& t)const {return Hash(1LL*x*t.x%mod1,1LL*y*t.y%mod2);}LL val() {return 1LL*x*mod2+y;} }base(2333,23333),h[N]; unordered_map<LL,vector<int>>mp; char s[N][110]; int pos[N],ans[N]; int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int n;read(n);for(int i=1;i<=n;i++) {scanf("%s",s[i]);h[i]=Hash(s[i][0],s[i][0]);mp[h[i].val()].push_back(i);pos[i]=0;}for(int i=n;i>=1;i--) {ans[i]=mp.size();int len=strlen(s[i]);Hash tmp;for(int j=0;j<len;j++) {tmp=tmp*base+Hash(s[i][j],s[i][j]);auto it=mp.find(tmp.val());if(it!=mp.end()) {for(auto k:it->second) {if(k!=i) {pos[k]++;h[k]=h[k]*base+Hash(s[k][pos[k]],s[k][pos[k]]);mp[h[k].val()].push_back(k);}}mp.erase(it);}}}for(int i=1;i<=n;i++) {printf("%d\n",ans[i]);}return 0; }總結
以上是生活随笔為你收集整理的2021牛客多校10 - Browser Games(哈希)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021HDU多校8 - 7057 Bu
- 下一篇: 2021牛客多校10 - Train W