uva 12096 - The SetStack Computer(STL 的运用)

题目链接:uva 12096 - The SetStack Computer

题目大意:一个栈,有5种操作;

  • PUSH:向栈中放一个空集合。
  • DUP:复制栈顶集合。
  • UNION:取栈顶的两个集合,取并集后放回。
  • INTERSECT:取栈顶的两个集合,取交集后放回。
  • ADD:取栈顶两个集合,将第一个集合作为元素放到第二个集合中,并将第二个集合放回栈。

每次操作后输出栈定集合中元素的个数。

思路:直接模拟即可

package test;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;



public class Test{	
	
	static Stack<HashSet<Set>> stack = new Stack<HashSet<Set>>();
	public static void main(String[] args) {
	
		Scanner sc = new Scanner(System.in);
		String line = null;
		System.out.println("input:");
		while(!"".equals((line=sc.nextLine().toLowerCase()))){
			if("push".equals(line)){
				stack.push(new HashSet<Set>());
			}else if("dup".equals(line)){
				HashSet<Set> temp = stack.pop();
				stack.push(temp);
				stack.push((HashSet<Set>) temp.clone());
			}else if("union".equals(line)){
				HashSet<Set> temp1 = stack.pop();
				HashSet<Set> temp2 = stack.pop();
				temp1.addAll(temp2);
				stack.push(temp1);
			}else if("intersect".equals(line)){
				HashSet<Set> temp1 = stack.pop();
				HashSet<Set> temp2 = stack.pop();
				temp1.retainAll(temp2);
				stack.push(temp1);
			}else if("add".equals(line)){
				HashSet<Set> temp1 = stack.pop();
				HashSet<Set> temp2 = stack.pop();
				temp2.add(temp1);
				stack.push(temp2);
			}
			System.out.println(stack);
		}
	
		sc.close();
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值