题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2034
题解:
定义一个数组p表示存储集合A的元素,每次输入一个集合B的元素时,遍历p中是否有此元素
若有此元素,则将p中的此元素置为初始化时的值
最后输出时,只需判断此值是不是初始化时的值,若是表示此值在集合A-B中
AC代码:
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100 + 5;
const int inf = 0x3f3f3f3f;
int main() {
int n, m, temp;
while (cin >> n >> m && m + n) {
int p[maxn];
memset(p, inf, maxn);//初始化数组
for (int i = 0; i < n; i++) {
cin >> p[i];
}
for (int i = 0; i < m; i++) {
cin >> temp;
for (int j = 0; j < n; j++) {
if (temp == p[j]) {
p[j] = inf;//如果在集合B中找到相同的元素,将集合A的元素置为inf
break;
}
}
}
sort(p, p + n);
bool flag = true;
for (int i = 0; i < n; i++) {
if (p[i] != inf) {//表示此元素属于A且不属于B
flag = false;
cout << p[i] << " ";
}
}
if (flag) cout << "NULL";
cout << endl;
}
return 0;
}