题目信息
Problem Description
A-B求的是两个集合的差,就是做集合的减法运算。
Input
每组输入数据占1行,每行数据的开始是2个整数n(0<=n<=100)和m(0<=m<=100),分别表示集合A和集合B的元素个数,然后紧跟着n+m个元素,前面n个元素属于集合A,其余的属于集合B. 每个元素为不超出int范围的整数,元素之间有一个空格隔开.
如果n=0并且m=0表示输入的结束,不做处理。
Output
针对每组数据输出一行数据,表示A-B的结果,如果结果为空集合,则输出“NULL”,否则从小到大输出结果,为了简化问题,每个元素后面跟一个空格.
Sample Input
3 3 1 2 3 1 4 7
3 7 2 5 8 2 3 4 5 6 7 8
0 0
Sample Output
2 3
NULL
解法思路
int数组
我的第一种思路是定义三个长度为100的int类型数组。
首先读入两个数组的长度 a , b ,然后读入两个集合的所有元素到 n[] 和 m[] ,其次全部遍历寻找 {A} - {B} 的数据,将数据放在另一个数组 k[] 中,然后快速排序输出。
需要注意的是a或b只有一个为零的情况,以及输出格式的问题。
#include<iostream>
using namespace std;
int comp(const void *a,const void *b)'''快速排序所需的比较函数'''
{
return *(int*)a-*(int*)b;
}
int main()
{
unsigned int a,i,t,count,b;
int n[100],m[100],k[100];
bool test,judge;
while(cin>>a>>b&&(a||b))
{
memset(n,0,sizeof(int)*100);'''初始化数组'''
memset(m,0,sizeof(int)*100);
memset(k,0,sizeof(int)*100);
count=0;
for(i=0;i<a;i++)'''读入两组数据'''
cin>>n[i];
for(i=0;i<b;i++)
cin>>m[i];
for(i=0;i<a;i++)'''遍历n组'''
{
test=true;
for(t=0;t<b;t++)'''遍历m组找相同值'''
if(n[i]==m[t])
{
test=false;'''相同则test为F,下一个~'''
break;
}
if(test==true)'''全都不同则写入k组'''
k[count++]=n[i];
}
qsort(k,count,sizeof(int),comp);
for(i=0;i<count;i++)'''输出部分格式'''
cout<<k[i]<<" ";
if(count==0)
cout<<"NULL";
cout<<endl;
}
return 0;
}
bool数组
这个解法是在Discuss里面看到的,但是感觉问题好大。首先布尔数组只定义了0-10000,而int类型包括了-2147483648~2147483647,超出0-10000的部分,这个解法无法处理,但是很诡异的可以AC……..不知道是OJ的BUG还是有我没理解的思路。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int a,b,i,j,count;
bool test[10001];
while(cin>>a>>b&&(a||b))'''读入a和b两个集合长度'''
{
memset(test,false,sizeof(bool)*2147483648) ;'''首先初始化,设定所有数据都不存在与{A}中'''
count=0;
for(i=0;i<a;i++)
{
cin>>j;
test[j]=true;'''存在于{A}中的元素,设定为T'''
}
for(i=0;i<b;i++)
{
cin>>j;
test[j]=false;'''存在于{B}中的元素,值修改为F'''
}
for(i=0;i<100;i++)
{
if(test[i]==true)'''将所有值仍为T的的数据的代号输出(代号即为)'''
{
cout<<i<<" ";
count++;
}
}
if(0==count)
cout<<"NULL";
cout<<endl;
}
return 0;
}