您的位置:首页 > 其它

离散题目4

2017-05-26 17:56 197 查看


离散题目4

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic


Problem Description

题目给出两个非空整数集,请写出程序求两个集合的交集。


Input

多组输入,每组输入包括两行,第一行为集合A的元素,第二行为集合B的元素。具体参考示例输入。 每个集合元素个数不大于3000,每个元素的绝对值不大于2^32 - 1。


Output

每组输入对应一行输出,为A、B的交集,如果交集为空输出"NULL",否则交集的元素按递增顺序输出,每个元素之间用空格分割。


Example Input

1 2 3 4 5
1 5 3 6 7
1 2 4 5 3
6 7 8 9 10



Example Output

1 3 5
NULL

代码:

#include <bits/stdc++.h>

using namespace std;
int main()
{
string ac, bc, buf;
vector<int> a, b;
vector<int>::iterator it;
int i, t;
while(getline(cin, ac)) //因为数组的长度不知道,所以用字符串读入对应的集合。
{
getline(cin, bc);
stringstream ss(ac);  //分割字符串,将数字分离出来存到vector中
while(ss >> buf)
{
sscanf(buf.c_str(), "%d", &t);
a.push_back(t);
}
stringstream cc(bc);
while(cc >> buf)
{
sscanf(buf.c_str(), "%d", &t);
b.push_back(t);
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int count = 0;
for(i = 0; i < a.size(); i++)  //求交集
{
it = find(b.begin(), b.end(), a[i]);
if(it != b.end())
{
                 if(count == 0)
                 	cout<<*it;
                 else
                 	cout<<" "<<*it;
                 b.erase(it);
                 count++;
}
}
if(count == 0)  判断是否有交集
cout<<"NULL";
cout<<endl;
a.clear();
b.clear();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  离散数学 集合