PAT常用自定义函数总结
1. 素数判断
bool isprime(int a)
{
if(a<=1) return false;
int sqr=(int)sqrt(a*1.0);
for(int i=2;i<=sqr;i++) if(a%i==0) return false;
return true;
}
2. 求最大公约数(greatest common divisor)
int gcd(int a,int b)
{
if(b==0) return a;
return gcd(b,a%b);
}
3. 判断回文数
//这个现想的,也不知道对不对,一直用的vector传入
bool ispal(int a)
{
string str1=to_string(a);
string str2=str1;
reverse(str1.begin(),str2.end());
if(str1==str2) return true;
return false;
}
4.静态链表排序函数
struct Node{
int data,flag;//还可以添加成员如group/num等参与排序
int add,next;
}node[maxn];
bool cmp(Node a,Node b)
{
if(a.flag!=b.flag) return a.flag>b.flag;
else return a.data<b.data;
//排序需要根据题意进行,基本就是根据data/group/num等排序
}
5. 结构体小于号重载
//其实这个不算是自定义函数的范畴,但是没地方放就一起总结在这吧
//基本思路与排序函数相同
struct node{
int x,y;
bool operator<(const node &a)const
{
if(x!=a.x) return x>a.x;
else return y<a.y;
}
};
6. 二叉树前序、中序、后序、层序遍历
struct node{
int data;
node *lc,*rc;
};
//前序遍历
void pretrave(node *root)
{
if(root==NULL) return;
(根据需要添加操作)
preorder(root->lc);
preorder(roor->rc);
}
//中序遍历
void intrave(node *root)
{
if(root==NULL) return;
inorder(root->lc);
(根据需要添加操作)
inorder(root->rc);
}
//后序遍历
void posttrave(node *root)
{
if(root==NULL) return;
posttrave(root->lc);
poattrave(root->rc);
(根据需要添加操作)
}
//层序遍历
void leveltrave(node *root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node *temp=q.front();
q.pop();
(根据需要添加操作)
if(temp->lc!=NULL) q.push(temp->lc);
if(temp->rc!=NULL) q.push(temp->rc);
}
}
7. 树的层序遍历和深度遍历
struct Node{
int data;
vector<int> child;
}node[maxn];
void BFS(int root)
{
queue<int> q;
q.push(root);
while(!q.empty())
{
int now=q.front();
q.pop();
(根据需要添加操作)
for(int i=0;i<node[now].child.size();i++) q.push(node[now].child.[i]);
}
}
void DFS(int root)
{
if(node[root].child.size()==0)
{
(根据需要添加操作)
}
for(int i=0;i<node[now].child.size();i++) DFS(node[now].child[i]);
}
8. 并查集
int father[maxn];
void init(int n)
{
for(int i=1;i<=n;i++) fathe[i]=i;
}
int findfather(int root)
{
int temp=root;
while(root!=father[root]) root=father[root];
//压缩路径
while(temp!=father[temp])
{
int z=temp;
temp=father[temp];
father[z]=root;
}
return root;
}
void merge(int a,int b)
{
int fa=findfather(a);
int fb=findfather(b);
if(fa!=fb) father[fa]=fb;
}