Number theory:
1. Prime number
①定义法:O(n)
n>=2 && i<=n-1
②Property method: O(sqrt(n))
appears in pairs.
If d can divide n, then n/d can also divide n.
d and n/d are a pair,
then we only need to enumerate to the smaller one.
Answer: d <=n/d,
d d<=n PS: This writing method is not recommended. If n is close to the maximum value of int, then d d may have overflow risk
d<=sqrt(n) PS: This writing method is not recommended because the function must be called every time, which is inefficient.
2.
Divisors are opposite
to prime numbers, the same as prime numbers
Consolidated collection : 836. Consolidated collection
title link
It's the same as the kruscal I learned before
#include<iostream>
using namespace std;
const int N=100000+10;
int n,m;
int father[N];
int find(int x){
return father[x]==x?x:father[x]=find(father[x]);
}
void my_union(int a, int b){
int xx=find(a);
int yy=find(b);
if(xx!=yy){
if(yy>xx){
father[yy]=xx;
}else{
father[xx]=yy;
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
father[i]=i;
}
while(m--){
char s[2];
int a,b;
cin>>s>>a>>b;
if(s[0]=='M'){
my_union(a,b);
}else{
if(find(a)==find(b)){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}
}
return 0;
}
The extended application of the union search set:
837. Links to the number of points in connected blocks
Transform on the basis of merged and collected the original code.
#include<iostream>
using namespace std;
const int N=100000+10;
int n,m;
int father[N];
int se[N];
int find(int x){
return father[x]==x?x:father[x]=find(father[x]);
}
void my_union(int a, int b){
int xx=find(a);
int yy=find(b);
if(xx!=yy){
if(yy>xx){
se[xx]+=se[yy];
father[yy]=xx;
}else{
se[yy]+=se[xx];
father[xx]=yy;
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
father[i]=i;
se[i]=1;
}
while(m--){
char s[5];
int a,b;
cin>>s;
if(s[0]=='C'){
cin>>a>>b;
my_union(a,b);
}else if(s[1]=='1'){
cin>>a>>b;
if(find(a)==find(b)){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}else{
cin>>a;
int f=find(a);
cout<<se[f]<<endl;
}
}
return 0;
}
240. Food Chain and Collecting Practice Questions
ps: The recursive form of dp-memoized search (the interval dp is better to understand when written as recursion)