题目链接: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();
}
}