王道机试指南5.1~5.3向量,队列,栈
例题5.1完数和盈数(清华大学复试上机)
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int sum(int n){
int sum0 = 0;
for(int i = 1; i < n; i++){
if(n % i == 0) sum0 += i;
}
return sum0;
}
int main(){
vector<int> a, b;
for(int i = 2; i < 61; i++){
if(sum(i) == i) a.push_back(i);
if(sum(i) > i) b.push_back(i);
}
cout << "E :";
for(int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << "G :";
for(int i = 0; i < b.size(); i++)
cout << b[i] << " ";
}
例题5.4 Zero-complexity Transposition(上海交通大学上机)
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
int main(){
int n;
cin >> n;
stack<long long> s;
for(int i = 0; i < n; i++){
int temp;
cin >> temp;
s.push(temp);
}
for(int i = 0; i < n; i++){
cout << s.top() << " ";
s.pop();
}
return 0;
}
例题5.6简单计算器(浙江大学上机)
#include<iostream>
#include<cstdio>
#include<string>
#include<stack>
#include<cctype>
using namespace std;
int priority(char c){
if(c == '#') {
return 0;
}else if(c == '$'){
return 1;
} else if(c == '+' || c == '-'){
return 2;
}else{
return 3;
}
}
double getnumber(string s, int& index){
double number = 0;
while(isdigit(s[index])){
number = number * 10 + s[index] - '0';
index ++;
}
return number;
}
double cal(double x, double y, char op){
double result = 0;
if(op == '+') result = x + y;
if(op == '-') result = x - y;
if(op == '*') result = x * y;
if(op == '/') result = x / y;
return result;
}
int main(){
string s;
while(getline(cin, s)){
if(s == "0") break;
int index = 0;
stack<double> data;
stack<char> oper;
s += '$';
oper.push('#');
while(index < s.size() ){
if(s[index] == ' '){
index ++;
}else if(isdigit(s[index])){
data.push(getnumber(s, index));
}else{
if(priority(oper.top()) < priority(s[index])){
oper.push(s[index]);
index ++;
}else{
double y = data.top();
data.pop();
double x = data.top();
data.pop();
data.push(cal(x, y, oper.top()));
oper.pop();
}
}
}
printf("%.2f\n", data.top());
}
return 0;
}
习题5.1堆栈的使用(吉林大学上机)
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
int main(){
int n;
while(cin >> n){
if(n == 0) break;
stack <int> s;
while(n){
char op;
cin >> op;
if(op == 'P'){
int data;
cin >> data;
s.push(data);
}else if(op =='O'){
if(!s.empty()){
s.pop();
}
}else if(op == 'A'){
if(!s.empty()){
cout << s.top() << endl;
}else{
cout << "E" << endl;
}
}
n--;
}
cout << endl;
}
return 0;
}