1、系统中有最近打开文件的记录,现用整数表示打开的文件名,且只
显示最近3个打开的文件,输出文件序列.
示例:
输入:1输出:1
输入:2输出:2, 1
输入:3
输出:3, 2, 1
输入:4
输出:4,3,2
输入:1
输出:1,4,3
输入:4
输出:1,4, 3
输入:3
输出:1,4,3
代码:
#include <bits/stdc++.h>using namespace std;
vector<int> ans;
int main()
{cout << "请输入:";int a;while (cin >> a) {int flag = false; // 当前输入不在最近访问列表for (int i = ans.size()-1, cnt = 0; i >= 0 && cnt < 3; i--, cnt++) {if (ans[i] == a) {flag = true;break;}}if (!flag) ans.push_back(a);for (int i = ans.size()-1, cnt = 0; i >= 0 && cnt < 3; i--, cnt++) {cout << ans[i];if (i != 0) cout << ',';}cout << endl;cout << "请输入:";}return 0;
}
2、在第1题基础上,稍作改动,显示最新打开的文件.
示例:
输入:1
输出:1
输入:2
输出:2,1
输入:3
输出:3,2,1
输入:4
输出:4,3,2
输入:1输出:1,4,3
输入:4
输出:4,1,3
输入:3
输出:3,4,1
代码:
#include <bits/stdc++.h>using namespace std;
vector<int> ans;
int main()
{cout << "请输入:";int a;while (cin >> a) {int flag = false; // 当前输入不在最近访问列表for (int i = ans.size()-1, cnt = 0; i >= 0 && cnt < 3; i--, cnt++) {if (ans[i] == a) {flag = true;break;}}if (!flag) ans.push_back(a);else if (flag) { // 访问的数据a如果已在最近列表中,则.。。int idx = -1;for (int i = ans.size()-1, cnt = 0; i >= 0 && cnt < 3; i--, cnt++) {if (ans[i] == a){idx = i;break;} } while (idx < ans.size()-1) { // 这里就是将数据a交换到列表末尾int temp = ans[idx];ans[idx] = ans[idx+1];ans[idx+1] = temp;idx++;}}for (int i = ans.size()-1, cnt = 0; i >= 0 && cnt < 3; i--, cnt++) {cout << ans[i];if (i != 0) cout << ',';}cout << endl;cout << "请输入:";}return 0;
}
3、求广义表的深度(实际就是括号匹配),示例:输入(c,((d,e),f),h)
输出:3
提示:答案就是匹配过程中栈的最大深度
代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{string s;cin >> s;stack<char> st;int m = 0;for (int i = 0; i < s.size(); i++) {if (s[i] == '(') {st.push(s[i]); // 左括号进栈m = max(m, (int)st.size()); // 因为st.size()返回的是一个无符号整数,而max要求比较的两个数据类型一样,所以要将st.size()从无符号整数强转成有符号整数 更新栈的最大 大小}else if (s[i] == ')') st.pop(); // 遇到右括号 栈顶一定是左括号 括号一定是匹配的}cout << m << endl;}