stack应用 POJ 2929&3704 括号匹配

数据结构学了堆栈,找了些题做做,都是水题,对栈的应用

3704

#include <iostream>

#include <stack>

#include <memory.h>

using namespace std;



int main()

{

	int count = 0;

	char c[101];

	int totalnum;

	int hold[100];

	stack<char> ST1;

	stack<int> ST2;



	//freopen("C:\\Users\\Haojian\\Desktop\\test.txt", "r", stdin);



	while (cin.getline(c, 101))

	{

		memset(hold, 0, 100*sizeof(int));

		while (!ST1.empty()) ST1.pop();

		while (!ST2.empty()) ST2.pop();



		for (int i = 0; c[i] != '\0'; i++)

		{

			if (c[i] == '(')

			{

				ST1.push(c[i]);

				ST2.push(i+1);

			}

			else

			{

				if (c[i] == ')' && !ST1.empty())

				{

					ST1.pop();

					hold[ST2.top()] = 1;

					hold[i+1] = 1;

					ST2.pop();

				}



			}

		}



		cout << c << endl;

		for (int i = 0; c[i] != '\0'; i++)

		{

			if (c[i] == '(' && !hold[i+1])

				cout << "$";

			else if (c[i] == ')' && !hold[i+1])

				cout << "?";

			else 

				cout << " ";

		}

		cout << endl;

	}





	return 0;

}
 
2929
#include <iostream>

#include <stack>

#include <memory.h>

using namespace std;



int main()

{

	int count = 0;

	char n;

	int totalnum;

	int hold[100];

	stack<char> ST1;

	stack<int> ST2;



	//freopen("C:\\Users\\Haojian\\Desktop\\test.txt", "r", stdin);

	while (cin >> totalnum)

	{

		memset(hold, 0, 100*sizeof(int));

		count  = 0;

		for (int i = 1; i <= totalnum; i++)

		{

			cin >> n;

			if (n == '1')

			{

				ST1.push(n);

				ST2.push(i);

			}

			else

			{

				ST1.pop();

				hold[count++] = ST2.top();

				ST2.pop();

			}

		}



		for (int i = 0; i < count - 1; i++)

			cout << hold[i] << " ";



		cout << hold[count-1] << endl;

	}

	return 0;

}

你可能感兴趣的:(stack)