题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2035
你可以直接用C语言去模拟一个集合,然后每读入一个数字,做一次遍历,如果找到就删除。最后才排一次序输出。
虽然效率很低,时间复杂度有O(m*n),但对付这一题已经绰绰有余了。也可以0MS 0K AC掉。
Code:
#include <stdio.h>
#include <stdlib.h>
int cmp(const int *a, const int *b)
{
return *a - *b;
}
int main(void)
{
int n, m, i, j;
int s[101];
while (scanf("%d%d", &n, &m), m+n)
{
for (i = 0; i < n; i++)
scanf("%d", s + i);
for (i = 0; i < m; i++)
{
scanf("%d", s + n);
for (j = 0; s[j] != s[n]; j++);
if (j != n) s[j] = s[--n];
}
qsort(s, n, sizeof(int), cmp);
for (i = 0; i < n; i++)
printf("%d ", s[i]);
printf(n ? "\n" : "NULL\n");
}
return 0;
}
如果你讨厌用线性的查找方式,也可以修改一下。配合使用库函数的二分找和快速排序,来实现。
但对付这题来说,有点杀鸡用牛刀的感觉,呵呵。
Code:
#include <stdio.h>
#include <stdlib.h>
int cmp(const int *a, const int *b)
{
return *a - *b;
}
int main(void)
{
int a;
int b;
int i;
int n;
int *p;
int s[128];
while (scanf("%d%d", &a, &b), a || b)
{
for (i = 0 ; i < a ; i++)
scanf("%d", s + i);
qsort(s, a, sizeof(int), cmp);
for (i = 0 ; i < b ; i++)
{
scanf("%d", &n);
p = bsearch(&n, s, a, sizeof(int), cmp);
if (p)
{
a--;
*p = s[a];
qsort(s, a, sizeof(int), cmp);
}
}
if (a)
{
for (i = 0 ; i < a ; i++)
printf("%d ", s[i]);
putchar('\n');
}
else
puts("NULL");
}
return 0;
}
其实我们可以用归并排序的思想来做。效率从O(m*n) -> O((m+n)log2(m+n))
#include <stdio.h>
#include <stdlib.h>
int cmp(const int *a, const int *b)
{
return *a - *b;
}
int main(void)
{
int n, m, i, j, c;
int s[128];
int t[128];
while (scanf("%d%d", &n, &m), m+n)
{
for (i = 0; i < n; i++)
scanf("%d", s + i);
for (i = 0; i < m; i++)
scanf("%d", t + i);
qsort(s, n, sizeof(int), cmp);
qsort(t, m, sizeof(int), cmp);
for (c = i = j = 0; i < n && j < m;)
{
if (s[i] < t[j])
printf("%d ", s[i++], c++);
else if (s[i] > t[j])
j++;
else
{
i++;
j++;
}
}
for (; i < n;) printf("%d ", s[i++], c++);
printf(c ? "\n" : "NULL\n");
}
return 0;
}
其实这些集合的操作都包含在C++的set类库里了。
这时候用C++编码真是提速不少。详请参见参考代码。