kmp自身匹配和两者匹配,都是i和j+1匹配(让两个字符串从1开始)
自身匹配找ne【】数组的值,i从2开始,j从0开始
两者匹配,i从1开始,j从0开始
#include<iostream>
using namespace std ;
const int M = 1e5 + 10 , N = 1e6 + 10 ;
int a , b ;
char s[N] , p[M] ;
int ne[M] ;
int main()
{
cin >> a >> p + 1 >> b >> s + 1 ;
for(int i = 2 , j = 0 ; i <= a ; i++)
{
while(j&&p[i] != p[j+1]) j = ne[j] ;
if(p[i] == p[j+1]) j++ ;
ne[i] = j ;
}
for(int i = 1 , j = 0 ; i <= b ; i++)
{
while(j&&s[i] != p[j+1]) j = ne[j] ;
if(s[i] == p[j+1]) j++ ;
if(j == a)
{
printf("%d ", i - a);
j = ne[j] ;
}
}
return 0 ;
}
trie字符串看原来的博客
能用char , string不对
#include<iostream>
using namespace std ;
const int N = 1e5 + 10 ;
int son[N][26] ;
int cnt[N] , idx ;
char str[N] ;
void insert(char str[])
{
int p = 0 ;
for(int i = 0 ; str[i] ; i++)
{
int u = str[i] - 'a' ;
if(!son[p][u]) son[p][u] = ++ idx ;
p = son[p][u] ;
}
cnt[p] ++ ;
}
int query(char str[])
{
int p = 0 ;
for(int i = 0 ; str[i] ; i++)
{
int u = str[i] - 'a' ;
if(!son[p][u]) return 0 ;
p = son[p][u] ;
}
return cnt[p] ;
}
int main()
{
int n ;
cin >> n ;
while(n--)
{
char op[2];
scanf("%s%s",op,str);
if (op[0] == 'I') insert(str);
else printf("%d\n",query(str));
}
return 0 ;
}
异或
^ 相同为0,不同为1
根据每一位的0和1来建立trie数组
query 的返回值是res ^ x 如果是单单返回res的话,让max里面是res ^ query(a[i]) 会有结果错误的情况出现。
#include<iostream>
#include<algorithm>
using namespace std ;
int n ;
const int N = 100010 ;
int son[N*31][2] ;
int a[N] ;
int idx ;
void insert(int x)
{
int p = 0 ;
for(int i = 31 ; i >= 0 ; i--)
{
int u = x >> i & 1 ;
if (!son[p][u])
{
son[p][u] = ++idx ;
}
p = son[p][u] ;
}
}
int query(int x)
{
int p = 0 ;
int res = 0 ;
for(int i = 31 ; i >= 0 ; i--)
{
int u = x >> i & 1 ;
if(son[p][!u])
{
p = son[p][!u];
res = res * 2 + !u ;
}
else
{
p = son[p][u] ;
res = res * 2 + u ;
}
}
res = res ^ x ;
return res ;
}
int main()
{
cin >> n ;
int res = 0;
for(int i = 0 ; i < n ; i++)
{
cin >> a[i] ;
insert(a[i]) ;
}
for(int i = 0 ; i < n ; i++)
{
res = max(res, query(a[i]) );
}
cout << res ;
return 0 ;
}
并查集
优化:路径压缩
#include<iostream>
using namespace std ;
const int N = 1e5 + 10 ;
int n , m;
int p[N] ;
int find(int x)
{
if(p[x] != x) return find(p[x]) ;
return p[x] ;
}
int main()
{
cin >> n >> m;
for(int i = 0 ; i < n ; i++)
{
p[i] = i ;
}
while(m--)
{
char op[2] ;
cin >> op ;
int a , b ;
cin >> a >> b ;
if(op[0] == 'M')
{
p[find(a)] = find(b) ;
}
else
{
if(find(a) == find(b))
{
cout << "Yes" << endl ;
}
else
{
cout << "No" << endl ;
}
}
}
return 0 ;
}