王道机试指南读后总结-3

来源:互联网 发布:mlily床垫怎么样知乎 编辑:程序博客网 时间:2024/06/17 18:29

1.树中一个很容易出先现的问题:
已知树的先序和中序遍历构建树。

#include <stdio.h>#include <string.h>struct Node{    Node *lchild;    Node *rchild;    char c;}Tree[50];int loc;Node *Create(){           //创建新节点    Tree[loc]->lchild=Tree[loc]->rchild=NULL;    return &Tree[loc++];}char str[30],str2[30];void postOrder(Node *T){    if(T!=NULL){        postOrder(T->lchild);        postOrder(T->rchild);        printf("%c",T->c);    }}Node *build(int l1,int r1,int l2,int r2){  //由两个字符串建立二叉树    Node* ret=Create();    rec->c=str1[l1];  //前序遍历第一个字符    int rootidx;    for(i=l2;i<r2;i++){        if(str2[i]==str1[l1]){            rootidx=i;            break;        }    }    if(rootidx!=l2)  //左子树不为空        ret->lchild=build(l1+1,l1+rootidx-l2,l2,rootidx-1);    if(rootidx!=r2)  //右子树不为空        ret->rchild=build(l1+rootidx-l2+1,r1,rootidx+1,r2);    return ret;}int main(){    whiel(scanf("%s",str1)!=EOF){        scanf("%s",str2);        loc=0;        int L1=strlen(str1);        int L2=strlen(str2);        Node *T=build(0,L1-1,0,L2-1);        postOrder(T);        printf("\n");    }    return 0;}

2.数学问题例题:求a的b次方的后三位
如果输入规模大,直接求然后取后三位肯定是不行了,所以在计算的时候我们的中间值也保留到后三位即可。并且用到二分求幂的技巧。

#include <stdio.h>int main(){    int a,b;    while(scanf("%d%d",&a,&b)!=EOF){        if(a==0&&b==0) break;  半年内女女女女女女女女女        int ans=1;        while(b!=0){            if(b%2==1){                ans*=a;                ans%=1000;            }            b/=2;            a*=a;       //a的权值变大            ans%=1000;  //中间值只保留后三位        }        printf("%d\n",ans);    }    return 0;}

3.在图论问题邻接表的模拟时,可以使用std::vector来实现链表
vector在这里的简单使用方法:
vector edge[N]; 数组中的元素即vector对象
开头

#include <vector>using namespace std;for(i=0;i<N;i++){    edge[i].clear();  //清空单链表}edge[0].push_back(1);  //将1插入结点0的单链表中edge[0].erase(edge[0].begin()+i,edge[0].begin()+i+1); //这里是删除i,即erase里面是第一个要删除的元素编号和最后一个要删除的元素编号+1 

4.并查集可用来求图上联通分量个数,也可求得并查集中元素个数最多是多少。同理,这启发我们可以在并查集的根节点保存其他额外信息,并且在集合合并的过程中
维护该值,以便用来求解某些集合问题,

0 0