EI judge 002 Set Intersection 算法题解

Set Intersection

Time limit = 5 second(s)

Memory limit = 33000 Kb

Your task is to find the intersection of two sets of positive integers.

InputThe input consists of two sets of positive integersA={a1,a2, ...,an} andB={b1,b2, ...,bk} represented as two whitespace-separated lists of numbers. Each list ends with -1, that serves as an end-of-set marker. Repetitions of elements are possible in the input, but not in the output. You may assume that 0 <ai,bi<106and that the setsAandBare of size less than 1000.

Outputis list of numbers or word "empty" if intersection is empty.

Input#1
6 7 8 1 2 3 -1
4 3 2 1 1 -1
Output#1
1 2 3
Input#2
1 2 3 -1
4 4 5 5 6 6 -1
Output#2
empty


注意地方:

1 防止重复 -- 这里使用set,第二次遍历数组的时候,记得把set重的数据erase掉

2 输出格式这个oj也很严格的,不能多一个空格


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

int A[1000] = {0};

void SetIntersection()
{
	set<int> si;
	int a = 0;
	while (cin>>a && -1 != a)
	{
		si.insert(a);
	}

	int j = 0;
	while (cin>>a && -1 != a)
	{
		if (si.count(a))
		{
			A[j++] = a;
			si.erase(a);
		}
	}
	if (!j) cout<<"empty";
	else
	{
		j--;
		for (int i = 0; i < j; i++)
		{
			cout<<A[i]<<' ';
		}
		cout<<A[j];//原来要防止多输出一个' '
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值