离散题目4

来源:互联网 发布:罗马安全 知乎 编辑:程序博客网 时间:2024/06/05 14:13

离散题目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 51 5 3 6 71 2 4 5 36 7 8 9 10

Example Output

1 3 5NULL
代码:#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;}
原创粉丝点击