Bessie is leading the cows in an attempt to escape! To do this, the cows are sending secret binary messages to each other.html
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.c++
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.this
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.spa
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.code
Memory Limit: 32MBhtm
POINTS: 270blog
貝茜正在領導奶牛們逃跑.爲了聯絡,奶牛們互相發送祕密信息.get
信息是二進制的,共有M(1≤M≤50000)條.反間諜能力很強的約翰已經部分攔截了這些信息,知道了第i條二進制信息的前bi(l《bi≤10000)位.他同時知道,奶牛使用N(1≤N≤50000)條密碼.可是,他僅僅瞭解第J條密碼的前cj(1≤cj≤10000)位.input
對於每條密碼J,他想知道有多少截得的信息可以和它匹配.也就是說,有多少信息和這條密碼有着相同的前綴.固然,這個前綴長度必須等於密碼和那條信息長度的較小者.it
在輸入文件中,位的總數(即∑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
輸出格式:
輸入樣例#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
Four messages; five codewords.
The intercepted messages start with 010, 1, 100, and 110.
The possible codewords start with 0, 1, 01, 01001, and 11.
0 matches only 010: 1 match
1 matches 1, 100, and 110: 3 matches
01 matches only 010: 1 match
01001 matches 010: 1 match
11 matches 1 and 110: 2 matches
首先,咱們要知道,若是是在後面m個詢問中尋找前n個數字組有多少個是第\(M_i\)個數字組的前綴,那這道題就是一道模板題,詳情見前綴統計
可是這道題,除此以外,因外根據題目描述,在後m個詢問中,若是\(m_i\)的前綴與\(n_i\)的前綴匹配,也能夠算一種方案,因此咱們還要在插入時咱們除了要記錄該節點是多少個數字組的末尾節點cnt[],還要記錄它的兒子個數size[]
更新方式:在遍歷的過程當中,若是不是末尾節點,就加上cnt[],不然加上size[],由於這時咱們的密碼已經遍歷完了,可是此時這個節點在前面的n個數字組中並無統計完,這依然能夠算一種方案(或多種),因此還要加上當前節點的兒子個數size[],表明還能夠匹配size[]個數字組
#include<bits/stdc++.h> #define in(i) (i=read()) using namespace std; int read() { int ans=0,f=1; char i=getchar(); while(i<'0' || i>'9') {if(i=='-') f=-1; i=getchar();} while(i>='0' && i<='9') {ans=(ans<<1)+(ans<<3)+i-'0'; i=getchar();} return ans*f; } int n,m,tot; int trie[500010][2],a[5000010],cnt[500010],size[500010]; void insert(int k) { int p=0; for(int i=1;i<=k;i++) { if(!trie[p][a[i]]) trie[p][a[i]]=++tot; p=trie[p][a[i]]; size[p]++; } cnt[p]++; } int find(int k) { int ans=0,p=0; for(int i=1;i<=k;i++) { p=trie[p][a[i]]; if(!p) return ans; if(i!=k) ans+=cnt[p]; else ans+=size[p]; } return ans; } int main() { int k; in(n); in(m); for(int i=1;i<=n;i++) { in(k); for(int j=1;j<=k;j++) in(a[j]); insert(k); } memset(a,0,sizeof(a)); for(int i=1;i<=m;i++) { in(k); for(int j=1;j<=k;j++) in(a[j]); printf("%d\n",find(k)); } }