计算机复试上机C/C++算法积累

 

C/C++字符串处理

strncpy(a,b,5);

a[5]='\0';

 

char a[10];

memset(a,'#',sizeof(a));

a[10]='\0';

 

C

char st[100];

1. 字符串长度

   strlen(st);

2. 字符串比较

   strcmp(st1,st2);

   strncmp(st1,st2,n);   st1,st2的前n个进行比较。

3. 附加

   strcat(st1,st2);

   strncat(st1,st2,n);   n表示连接上st2的前n个给st1,在最后不要加'\0'

4. 替换

   strcpy(st1,st2);

   strncpy(st1,st2,n); n表示复制st2的前n个给st1,在最后要加'\0'

5. 查找

   where = strchr(st,ch)   ch为要找的字符。

   where = strspn(st1,st2); 查找字符串。

   where = strstr(st1,st2);

 

C++

#include <string>

string str;

1. 字符串长度

   len = str.length();

   len = str.size();

2. 字符串比较

   可以直接比较

   也可以:

   str1.compare(str2);

   str1.compare(pos1,len1,str2,pos2,len2); 值为负,0 ,正。

   nops 长度到完。

3. 附加

   str1 += str2; 

   str1.append(str2);

   str1.append(str2.pos2,len2);

4. 字符串提取

   str2 = str1.substr();

   str2 = str1.substr(pos1);

   str2 = str1.substr(pos1,len1);

   string a=s.substr(0,4);       //获得字符串s中从第0位开始的长度为4的字符串

5. 字符串搜索

   where = str1.find(str2);

   where = str1.find(str2,pos1); pos1是从str1的第几位开始。

   where = str1.rfind(str2); 从后往前搜。

6. 插入字符串

   不是赋值语句。

   str1.insert(pos1,str2);

   str1.insert(pos1,str2,pos2,len2);

   str1.insert(pos1,numchar,char);    numchar是插入次数,char是要插入的字符。

7. 替换字符串

   str1.replace(pos1,str2);

   str1.replace(pos1,str2,pos2,len2);

8. 删除字符串

   str.erase(pos,len)

   str.clear();

9. 交换字符串

   swap(str1,str2);

10. C --> C++

   char *cstr = "Hello";

   string str1;

   cstr = cstr;

   string str2(cstr);

 

关于sprintf应用:将数打印到字符串中

char s[ ];

int a;

double b;

sprintf(s,"%d",a);

sprintf(s,”%.2lf”,b); //b精确到小数点后两位,并打印到s

 

字符串左循环移位

string a, c;

lena=a.length();

for(i=0;i<lena;i++)

{

       c=a.substr(i);    //从位置i开始复制字符串到末尾,向左循环

       c.append(a,0,i);  //把字符串a,从位置0开始复制i个到字符串c

    cout<<c<<endl;

}

 

 

小数点后几位输出

C:

double ans;

print("%.2lf\n",ans);

 

%lf double   %f float  %d int  %ld long  %c char

 

C++:

#include <iomanip>

double ans

cout<<fixed<<showpoint<<setprecision(2)<<ans<<endl;

 

格式对齐,C++默认是右对齐

cout.width(20);

cout<<s<<endl;  //结果是右对齐

 

cout.width(20);

cout.setf(ios_base::left);

cout<<s<<endl;  //结果是左对齐

 

C输入输出

int a , b;

scanf(“%d%d”,&a,&b);

printf(“%d%d”,&a,&b);

 

math函数库

#include <math.h>

求平方根   double c=sqrt(a);

x的y次得用函数  pow(x,y),x为double,y为int

开方 开x的y次方  pow(x,1/y)

 

关于map容器

#pragma warning(disable:4786)

#include <map>

 

map<string,int> m;

string a="hello";

如果m[a]没赋值,那么m[a]=0;

 

map<string,string> m;

如果m[a]没赋值,那么m[a]="";

 

判断素数

1.从2一直到sqrt(x)判断法

bool jude(int x)

{

    if(x==1 || x==0) return false;

    double m=sqrt((double)x);

    for(int i=2;i<=m;i++)

        if(x%i==0) return false;

    return true;

}


 

 

2.筛法判断素数

bool isprime[1000000+5]

memset(isprime,true,sizeof(isprime));

isprime[0]=isprime[1]=false;

for(i=2;i<1000000+5;i++)

{

    if(isprime[i]==true)

    {

        temp=2*i;

        while(temp<1000000+5)

        {

            isprime[temp]=false;

            temp+=i;

        }

    }

}


 

 

sort( )函数用法

#include <algorithm>

 

bool cmp(int a,int b)

{

     return a>b;

}

int a[10];

sort(a,a+10,cmp);

 

stable_sort(a,a+10,cmp);

//稳定排序方法 对于数组中出现的任意a[i],a[j](i<j),其中a[i]==a[j],在进行排序以后a[i]一定出现在a[j]之前,则认为该排序是稳定的。


 

 

stack和queue

1.About stack

#include <stack>

stack<int> s;

s.push(a);

while(!s.empty)

{

    cout<<s.top();

    s.pop();

}

 

int size=s.size();


 

 

2.About queue

#include <queue>

queue<string> Q;

 

Q.push(s);

while(!Q.empty())

{

    cout<<Q.front();

    Q.pop();

}

 

cout << "The first element is " << Q.front()

     << " and the last element is " << Q.back() << endl;

 

int size=Q.size();


 

 

priority_queue

#include <queue>

empty() true if the priority queue has no elements

pop() removes the top element of a priority queue

push() adds an element to the end of the priority queue

size() returns the number of items in the priority queue

top() returns the top element of the priority queue

 

priority_queue< Node,vector<Node>,greater<Node> > Q;

 

//greater 从小到大排列

about the overrading of greater,you must write,重载时greater用operator>

bool operator>(Node a)

{

    return a.x > b.x;

}

 

//less从大到小排列

priority_queue<Node> Q;

priority_queue<Node,vector<Node>>Q;

这两种方式都可以

默认的是less函数比较 从大到小 ,重载less时要用 operator<

 

千万不要忘了初始化

尤其对于循环输入数据的题

对于stack queue

都要考虑到 empty()的问题

stack or queue 空了,就不能再用s.top() or q.top() 这样会出错。

每次新循环,都要将stack or queue 腾空

 

并查集找根

1.不改变集合元素值

int findr(int x)

{

    int r=x;

    while(u[r]!=r)

    r=u[r];

    return r;

}


 

 

2.改变并查集元素值,使每个元素都直接指向根,为以后查找提供方便

int findr(int r)

{

    if(u[r]==r) return r;

    u[r]=findr(u[r]);

    return u[r];

}


 

 

深度优先(DFS)搜索

//从x点开始搜索矩阵g[][],并用visit[]标记

void DFS(int x)

{

    visit[x]=1;

    for(int j=1;j<=n;j++)

        if(visit[j]==0 && g[x][j]==1)

            DFS(j);

}


 

Dijkstra寻找单源最短路径

关于dijkstra如果有多个起点,或多个终点,可以再加两个点,一个连接所有起点,另一个链接所有终点,并设两点间值为零。

 

#define max INT_MAX

int g[200+2][200+2];

int dis[200+2],pre[200+2];

bool set[200+2]; 

//模板函数

int dijkstra(int x,int y,int citynum)

{

    int i,j;

    for(i=1;i<=citynum;i++)

    {

        dis[i]=g[x][i];

        set[i]=false;

if(dis[i]==INT_MAX) pre[i]=0;

        else pre[i]=s;

    }

    dis[x]=0;set[x]=true;

    for(i=1;i<citynum;i++)

    {

        int temp=max;

        int u=x;

        for(j=1;j<=citynum;j++)

            if(!set[j] && dis[j]<temp)

            {

                u=j;

                temp=dis[j];

            }

        set[u]=true;

        for(j=1;j<=citynum;j++)

            if(!set[j] && g[u][j]<max)

            {

                int newdis=dis[u]+g[u][j];

                if(newdis<dis[j])

{

dis[j]=newdis;

pre[j]=u;

}

            }

    }

    return dis[y];

}

Practice 1 Date: Monday, March 18th, 2013 We highly encourage being environment friendly and trying all problems on your own. Implement exercise 2.3-7. Implement priority queue. Implement Quicksort and answer the following questions. (1) How many comparisons will Quicksort do on a list of n elements that all have the same value? (2) What are the maximum and minimum number of comparisons will Quicksort do on a list of n elements, give an instance for maximum and minimum case respectively. Give a divide and conquer algorithm for the following problem: you are given two sorted lists of size m and n, and are allowed unit time access to the ith element of each list. Give an O(lg m + lgn) time algorithm for computing the kth largest element in the union of the two lists. (For simplicity, you can assume that the elements of the two lists are distinct). Practice 2 Date: Monday, April 1st, 2013 We highly encourage being environment friendly and trying all problems on your own. Matrix-chain product. The following are some instances. Longest Common Subsequence (LCS). The following are some instances. X: xzyzzyx Y: zxyyzxz X:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCALLAAQANKESSSESFISRLLAIVAD Y:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCTLLAAQANKENSNESFISRLLAIVAG Longest Common Substring. The following are some instances. X: xzyzzyx Y: zxyyzxz X:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCALLAAQANKESSSESFISRLLAIVAD Y:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCTLLAAQANKENSNESFISRLLAIVAG Max Sum. The following is an instance. (-2,11,-4,13,-5,-2) Shortest path in multistage graphs. Find the shortest path from 0 to 15 for the following graph.   A multistage graph is a graph (1) G=(V,E) with V partitioned into K >= 2 disjoint subsets such that if (a,b) is in E, then a is in Vi , and b is in Vi+1 for some subsets in the partition; and (2) | V1 | = | VK | = 1.     Practice 3 Date: Monday, April 15th, 2013 We highly encourage being environment friendly and trying all problems on your own. Knapsack Problem. There are 5 items that have a value and weight list below, the knapsack can contain at most 100 Lbs. Solve the problem both as fractional knapsack and 0/1 knapsack. A simple scheduling problem. We are given jobs j1, j2… jn, all with known running times t1, t2… tn, respectively. We have a single processor. What is the best way to schedule these jobs in order to minimize the average completion time. Assume that it is a nonpreemptive scheduling: once a job is started, it must run to completion. The following is an instance. (j1, j2, j3, j4) : (15,8,3,10) Single-source shortest paths. The following is the adjacency matrix, vertex A is the source.  A B C D E A -1 3 B 3 2 2 C D 1 5 E -3 All-pairs shortest paths. The adjacency matrix is as same as that of problem 3.(Use Floyd or Johnson’s algorithm)     Practice 4 Date: Monday, May 8th, 2013 We highly encourage being environment friendly and trying all problems on your own. 0/1 Knapsack Problem. There are 5 items that have a value and weight list below, the knapsack can contain at most 100 Lbs. Solve the problem using back-tracking algorithm and try to draw the tree generated. Solve the 8-Queen problem using back-tracking algorithm.    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值