2014年北理复试上机

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<iostream>
using namespace std;

int a[4];
int l = 0;

bool find(int x)
{
    for (int i = 0; i < l; i++)
    {
        if (a[i] == x)return true;
    }
    return false;
}

void print()
{
    cout << a[l - 1];
    if (l > 1)
    {
        for (int i = l - 2; i >= 0; i--)cout << "," << a[i];
    }
    cout << endl;
}

int main()
{
    int x;
    while (cin >> x)
    {
        if (l == 0){a[l++] = x;print();}
        else
        {
            if (find(x))print();
            else
            {
                if (l < 3)
                {
                    a[l++] = x;
                    print();
                }
                else
                {
                    a[0] = a[1];
                    a[1] = a[2];
                    a[2] = x;
                    print();
                }
            }
        }
    }
    return 0;
}

2、在第一题基础上稍作改动,显示最新打开的文件(显示的三个文件名不同)。

输入: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<iostream>
#include<vector>
using namespace std;

vector<int> v;
vector<int>::iterator i;
vector<int>::reverse_iterator ri;

void insert(int x)
{
    i = v.begin();
    while (i != v.end() && (*i) != x)i++;
    if (i == v.end())//没有该元素
    {
        if (v.size() < 3)v.push_back(x);
        else
        {
            v.erase(v.begin());
            v.push_back(x);
        }
    }
    else//有该元素,则删去之前的记录
    {
        v.erase(i);
        v.push_back(x);
    }
}

void print()
{
    cout << (*(v.rbegin()));
    if (v.size() > 1)
    {
        for (ri = v.rbegin() + 1; ri != v.rend(); ri++)cout << "," << (*ri);
    }
    cout << endl;
}

int main()
{
    int x;
    while (cin >> x)
    {
        if (v.size() == 0) {v.push_back(x); print();}
        else{ insert(x);print(); }
    }
    return 0;
}

3、求广义表的深度(实际就是括号匹配),示例:输入(c,((d,e),f),h)  输出:3

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string a;
    int ans = 0;
    int num = 0;
    cin >> a;
    for (int i = 0; i < a.size(); i++)
    {
        if (a[i] == '(') 
        {
            num++;
            if (num > ans)ans = num;
        }
        else if (a[i] == ')') num--;
    }
    if (num != 0)cout << "输入格式不正确!" << endl;
    else cout << ans << endl;
    return 0;
}

 

posted @ 2019-08-19 17:40  郭怡柔  阅读(208)  评论(0)    收藏  举报