算法竞赛入门经典 第六章 数据结构基础

来源:互联网 发布:java分布式开发 编辑:程序博客网 时间:2024/05/17 07:36

这章基本学过,练习几道题就过了。


卡片游戏

桌上有一叠牌,从第一张牌(即位于顶面的牌)开始从上往下依次编号为1~n。当至少还剩两张牌时进行以下操作:把第一张牌扔掉,然后把新的第一张放到整叠牌的最后。输入n,输出每次扔掉的牌,以及最后剩下的牌。
样例输入:7
样例输出:1 3 5 7 4 2 6

#include <iostream>#include <queue>using namespace std;int main(){queue<int> q;int n;cin>>n;for(int i=0;i<n;i++)q.push(i+1);while(!q.empty()){cout<<q.front()<<" ";q.pop();q.push(q.front());q.pop();}cout<<endl;return 0;}


铁轨中转站

某城市有一个火车站,铁轨铺设如图所示。有n节车厢从A方向驶入车站,按进站顺序编号为1~n.你的任务是让它们按照某种特定的顺序进入B方向的铁轨并驶出车站。为了重组车厢,你可以借助中转站C。这是一个可以停放任意多节车厢的车站,但由于末端封顶,驶入C的车厢必须按照相反的顺序驶出C。对于每个车厢,一旦从A移入C,就不能再回到A了;一旦从C移入B,就不能回到C了。换句话说,在任一时刻,只有两种选择:A->C和C->B。


#include <iostream>#define MAXN 1000+10using namespace std;int n,target[MAXN];int main(){while(cin>>n){int stack[MAXN],top=0;for(int i=1;i<=n;i++){cin>>target[i];}int ok=1;int A=1,B=1;while(B<=n){if(A==target[B]) {A++;B++;}else if(top&&stack[top]==target[top]){top--;B++;}else if(A<=n) stack[++top]=A++;else {ok=1;break;}}if(ok==1)cout<<"Yes"<<endl;else cout<<"No"<<endl;}return 0;}

也可利用STL

#include <iostream>#include <stack>using namespace std;#define MAXN 1000+10int n,target[MAXN];int main(){while(cin>>n){stack<int> s;int A=1,B=1;for(int i=1;i<=n;i++)    cin>>target[i];  int ok=1;  while(B<n){  if(A==target[B]){  A++;    B++;  }  else if(!s.empty()&&s.top()==target[B]){  s.pop();  B++;  }  else if(A<n) s.push(A++);  else{    ok=0;  break;  }  }  if(ok)cout<<"yes"<<endl;  else cout<<"no"<<endl;}return 0;}

随机数

#include <iostream>#include <time.h>using namespace std;int main(){srand(time(NULL));while(getchar())cout<<(double)rand()/RAND_MAX<<endl;return 0;}

time做种子

rand()生成从0~RAND_MAX的数。



二叉树



原创粉丝点击