[Trie] Luogu P2992 [USACO08DEC]秘密消息Secret Message
題目描述
Bessie is leading the cows in an attempt to escape! To do this, the cows are sending secret binary messages to each other.
Ever the clever counterspy, Farmer John has intercepted the first b_i (1 <= b_i <= 10,000) bits of each of M (1 <= M <= 50,000) of these secret binary messages.
He has compiled a list of N (1 <= N <= 50,000) partial codewords that he thinks the cows are using. Sadly, he only knows the first c_j (1 <= c_j <= 10,000) bits of codeword j.
For each codeword j, he wants to know how many of the intercepted messages match that codeword (i.e., for codeword j, how many times does a message and the codeword have the same initial bits). Your job is to compute this number.
The total number of bits in the input (i.e., the sum of the b_i and the c_j) will not exceed 500,000.
Memory Limit: 32MB
POINTS: 270
貝茜正在領導奶牛們逃跑.為了聯絡,奶牛們互相發送秘密信息.
信息是二進制的,共有M(1≤M≤50000)條.反間諜能力很強的約翰已經部分攔截了這些信息,知道了第i條二進制信息的前bi(l《bi≤10000)位.他同時知道,奶牛使用N(1≤N≤50000)條密碼.但是,他僅僅了解第J條密碼的前cj(1≤cj≤10000)位.
對于每條密碼J,他想知道有多少截得的信息能夠和它匹配.也就是說,有多少信息和這條密碼有著相同的前綴.當然,這個前綴長度必須等于密碼和那條信息長度的較小者.
在輸入文件中,位的總數(即∑Bi+∑Ci)不會超過500000.
輸入輸出格式
輸入格式:
* Line 1: Two integers: M and N
* Lines 2..M+1: Line i+1 describes intercepted code i with an integer b_i followed by b_i space-separated 0's and 1's
* Lines M+2..M+N+1: Line M+j+1 describes codeword j with an integer c_j followed by c_j space-separated 0's and 1's
輸出格式:
* Lines 1..M: Line j: The number of messages that the jth codeword could match.
輸入輸出樣例
輸入樣例#1:4 5 3 0 1 0 1 1 3 1 0 0 3 1 1 0 1 0 1 1 2 0 1 5 0 1 0 0 1 2 1 1 輸出樣例#1:
1 3 1 1 2
?
題解
- 顯然是一道字符統計圖
- 依然常規trie
- 在插入字串時,統計經過該點的個數(cnt)和一樣的字串個數(sum)
- 那么在查找字串,題目其實就是要求"一個包含另一個"
- 搜索中,如果覆蓋了字串(q[p]==true),那么就將sum[p]相加
- 那么搜完了,就找比他長的字串,就是經過該點的個數cnt
- 然后我們發現一個問題,就是與被搜索相同的字串在cnt和sum里都統計過了
- 那么不就多出來一個sum了嗎?
- 減去就好了
代碼
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 using namespace std; 5 int n,m,trie[500010][2],sum[500010],num[500010],cnt[500010],tot,k; 6 bool q[500010]; 7 void insert(int k) 8 { 9 int p=0; 10 for (int i=1;i<=k;i++) 11 { 12 if (trie[p][num[i]]==0) trie[p][num[i]]=++tot; 13 p=trie[p][num[i]]; 14 cnt[p]++; 15 } 16 q[p]=1; sum[p]++; 17 } 18 int search(int k) 19 { 20 int p=0,ans=0; 21 for (int i=1;i<=k;i++) 22 { 23 if (!trie[p][num[i]]) return ans; 24 p=trie[p][num[i]]; 25 if (q[p]) ans+=sum[p]; 26 } 27 ans+=cnt[p]; 28 if (q[p]) ans-=sum[p]; 29 return ans; 30 } 31 int main() 32 { 33 scanf("%d%d",&m,&n); 34 for (int i=1;i<=m;i++) 35 { 36 scanf("%d",&k); 37 for (int j=1;j<=k;j++) scanf("%d",&num[j]); 38 insert(k); 39 } 40 for (int i=1;i<=n;i++) 41 { 42 scanf("%d",&k); 43 for (int j=1;j<=k;j++) scanf("%d",&num[j]); 44 printf("%d\n",search(k)); 45 } 46 return 0; 47 }?
轉載于:https://www.cnblogs.com/Comfortable/p/8796693.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的[Trie] Luogu P2992 [USACO08DEC]秘密消息Secret Message的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: adb(4)-应用管理
- 下一篇: Ajax+Node.js前后端交互最佳入