UVa 12096 - The SetStack Computer

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

將集合做交集、聯集、插入的操作,輸出每次操作的集合大小。

Sample Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
9
PUSH
DUP
ADD
PUSH
ADD
DUP
ADD
DUP
UNION
5
PUSH
PUSH
ADD
PUSH
INTERSECT

Sample Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
0
0
1
0
1
1
2
2
2
***
0
0
1
0
0
***

Solution

STL 高招解決,都有提供集合交集和聯集,但是為了方便查找,使用重新命名每一個集合為一個整數表示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <string.h>
#include <assert.h>
#include <map>
using namespace std;
map< set<int>, int > R;
map<int, set<int> > mR;
int rename(set<int> s) {
int &ret = R[s];
if (ret == 0)
ret = (int)R.size(), mR[ret] = s;
return ret;
}
int main() {
int testcase, n;
int a, b;
char cmd[1024];
scanf("%d", &testcase);
while (testcase--) {
scanf("%d", &n);
stack<int> stk;
for (int i = 0; i < n; i++) {
scanf("%s", cmd);
if (!strcmp(cmd, "PUSH")) {
stk.push(rename(set<int>()));
} else if(!strcmp(cmd, "DUP")) {
stk.push(stk.top());
} else if(!strcmp(cmd, "UNION")) {
a = stk.top(), stk.pop();
b = stk.top(), stk.pop();
set<int> &A = mR[a], &B = mR[b], C;
set_union(A.begin(), A.end(), B.begin(), B.end(), inserter(C, C.begin()));
stk.push(rename(C));
} else if(!strcmp(cmd, "INTERSECT")) {
a = stk.top(), stk.pop();
b = stk.top(), stk.pop();
set<int> &A = mR[a], &B = mR[b], C;
set_intersection(A.begin(), A.end(), B.begin(), B.end(), inserter(C, C.begin()));
stk.push(rename(C));
} else if(!strcmp(cmd, "ADD")) {
a = stk.top(), stk.pop();
b = stk.top(), stk.pop();
set<int> B = mR[b];
B.insert(a);
stk.push(rename(B));
}
printf("%d\n", (int)mR[stk.top()].size());
}
puts("***");
}
return 0;
}