uva514 Rails

题目:详见uva514.

此题就是输入1~n的任意一种顺序组合,问能否通过1,2,3,……n转换为此组合。
此题的C铁轨其实就是栈,特点是后进先出,通过栈能够改变数字的顺序。

参考代码:

#include 
#include 
#include 
using namespace std;
int rail[1005];
void yesandno(int rail[],int n) {
    stack s;
    int flag = 1;
    int a = 1,b = 1;
    while (b <= n) {
        if (a == rail[b]) {
            a++;
            b++;
        }
        else if (!s.empty() && s.top() == rail[b]) {
            s.pop();
            b++;
        }
        else if (a <= n) {
            s.push(a++);
        }       
        else {
            flag = 0;
            break;
        }
    }
    if (flag == 1) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
}
int main() {
    int n;
    while (cin >> n && n) {
        for (int i = 1;i <= n;++i) {
            cin >> rail[i];
            if (rail[i] == 0) {
                cout << endl;
                break;
            }
            if (i == n) {
                yesandno(rail,n);
                i = 0;
                memset(rail,0,sizeof(rail));
            }
        }
    }
    return 0;
}

你可能感兴趣的:(uva514 Rails)