例题6-2 铁轨(Rails, ACM/ICPC CERC 1997, UVa 514)

本文探讨了如何使用队列和栈解决特定问题,通过两种不同的实现方式展示算法设计思路。一种是利用队列和辅助栈进行判断,另一种是采用栈进行数据处理。这两种方法都有效地解决了数据结构中的常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>
#include <sstream>
#include <utility>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
const int maxn = 1000005;
using LL = long long;
using UI = unsigned int;
const int mod = 1e6 + 7;
using namespace std;
//------------------------------------------------------------------------------------------//
int q[1005] = { 0 }, rear = 0, front = 0;
int s[1005] = { 0 }, sfront = 0;

bool judge(int x) {
	if (x >= q[rear] && front != rear) {//若出栈的数大于等于队首的数,则应当把数入栈,当然队列空了也要考虑
		while (q[rear] != x) s[sfront++] = q[rear++];//把到x为止的所有数入栈,出队
		rear++;//x出队,入栈出栈
	}
	else {
		if (s[--sfront] != x) return false;//比较栈顶元素与出栈元素
	}
	return true;
}

int main() {
#ifdef _DEBUG
	IN(); OUT();
#endif
	int N;
	while (cin >> N && N) {
		int x;
		while (cin >> x && x) {
			bool flag = true;
			CLEAR(q, 0), rear = 0, front = 0;
			CLEAR(s, 0), sfront = 0;
			for (int i = 1; i <= N; i++) q[front++] = i;//入队
			if (!judge(x)) flag = false;
			for (int i = 0; i < N - 1; ++i) {
				scanf("%d", &x);
				if (!judge(x)) flag = false;
			}
			if (flag) cout << "Yes\n";
			else cout << "No\n";
		}
		cout << endl;
	}
	return 0;
}



//参考了lls的代码

int a[1005];

int main() {
#ifdef _DEBUG
	IN(); OUT();
#endif
	int n;
	while (cin >> n && n) {
		while (cin >> a[1] && a[1]) {
			stack<int> s;
			bool flag = true;
			for (int i = 2; i <= n; ++i) cin >> a[i];
			int A = 1, B = 1;//定义A,B两个类似指针的变量来比较,值得学习。
			while (B != n) {//这个循环把情况全考虑了,,,好厉害啊。。
				if (A == a[B]) A++, B++;
				else if (!s.empty() && s.top() == a[B]) s.pop(), B++;
				else if (A < a[B]) s.push(A++);
				else { flag = false; break; }
			}
			if (flag) cout << "Yes" << endl;
			else cout << "No" << endl;
		}
		cout << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值