The SetStack Computer UVA-12096 (set 操作)

vjudge链接

原题链接

  • 题目大意

模拟集合栈计算机。PUSH、DUP、UNION、INTERSECT、ADD五个操作。

  • 分析

呵呵刚学 STL,不知道 set 的操作,也没看书上的题解直接上了,手动模拟了五个操作,简单的操作可以秒出,但是当操作达到几十个时,不仅铁定 TLE,8G的内存也秒占用光。

显然 UNION 和 INTERSECT 可用现成的库函数解决。

  • 几个库函数

定义于头文件 <algorithm>

set_union(first1, last1, first2, last2, output); 将 [first1, last1) 和 [first2, last2) 两个范围的元素取并集,存放在 output 指定的容器中。output 可以是下面讲到的三个输出迭代器之一。两个输入序列须保证已排好序。

set_intersect(first1, last1, first2, last2, output); 将 [first1, last1) 和 [first2, last2) 两个范围的元素取交集,存放在 output 指定的容器中。output 可以是下面讲到的三个输出迭代器之一。两个输入序列须保证已排好序。

set_difference(first1, last1, first2, last2, output); 将 [first1, last1) 和 [first2, last2) 两个范围的元素取差集,存放在 output 指定的容器中。output 可以是下面讲到的三个输出迭代器之一。两个输入序列须保证已排好序。

merge(first1, last1, first2, last2, output); 将 [first1, last1) 和 [first2, last2) 两个范围的元素归并,存放在 output 指定的容器中。output 可以是下面讲到的三个输出迭代器之一。两个输入序列须保证已排好序。

一些输出迭代器,定义于头文件 <iterator>

inserter(c, i); 为容器 c 与其迭代器 i 构造 std::insert_iterator 的便利函数模板,拥有从参数类型推导的类型。向支持 insert 操作的容器 c 中用 insert 操作插入元素。迭代器 i 指示插入位置。

back_inserter(c, i); 为容器 c 构造 std::back_insert_iterator 的便利函数模板,拥有从参数类型推导的类型。向支持 push_back 操作的容器 c 中用 push_back 操作插入元素。迭代器 i 指示插入位置。

front_inserter(c, i); 为类型从参数类型推导的容器 c 构造 std::front_insert_iterator 的便利函数模板。向支持 push_front 操作的容器 c 中用 push_front 操作插入元素。迭代器 i 指示插入位置。

/*
 *这里补全了紫书上的代码
 *并手动将宏定义展开
 */

#include <iostream>
#include <algorithm>
#include <iterator>
#include <stack>
#include <set>
#include <vector>
#include <map>

using namespace std;

map <set<int>, int> IDcache;
vector <set<int>> Setcache;
stack<int> s;

int ID (set<int> x) {
	if (IDcache.count(x)) return IDcache[x];
	Setcache.push_back(x);
	return IDcache[x] = Setcache.size() - 1;
}

int main()
{
	int n;
	cin >> n;

	for (int i = 0; i < n; i++) {
		IDcache.clear();
		Setcache.clear();
		while (!s.empty()) s.pop();

		int m;
		cin >> m;
		for (int i = 0; i < m; i++) {
			string op;
			cin >> op;
			if (op[0] == 'P') s.push(ID(set<int>()));
			else if (op[0] == 'D') s.push(s.top());
			else {
				set<int> x1 = Setcache[s.top()]; s.pop();
				set<int> x2 = Setcache[s.top()]; s.pop();
				set<int> x;
				if (op[0] == 'U') set_union (x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));
				if (op[0] == 'I') set_intersection (x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));
				if (op[0] == 'A') { x = x2; x.insert(ID(x1));}
				s.push(ID(x));
			}
			cout <<  Setcache[s.top()].size() << endl;
		}
		cout << "***" << endl;
	}

	return 0;
}

by SDUST weilinfox
原文链接:https://www.cnblogs.com/weilinfox/p/12269450.html

posted @ 2020-02-06 17:21  桜風の狐  阅读(163)  评论(0编辑  收藏  举报