Intersect交集

Description

 设计一个求集合交的算法:输入集合A与集合B,求集合A与B之交。集合中的元素为整数(可以用c语言中的int表示),且互不相同。

Input

 输入第一行为一个整数t(0<t<10),表示测试用例个数。
每个测试样例由3行构成。第1行是2个正整数a(1≤a≤1000000),b(1≤a≤1000000),分别表示集合A和B的元素个数;第2行为a个以空格分隔的整数,为集合A中元素;第3行为b个以空格分隔的整数,为集合B中元素。

Output

 每个样例单独一行输出交集中元素的个数。

Sample Input
 Copy sample input to clipboard
2
7 5
0 1 2 4 7 8 9
1 2 5 6 7
7 8
1 2 3 4 5 6 8
1 2 4 5 6 7 8 9
Sample Output
3
6

#include<iostream>
using namespace std;

struct Node
{
	Node* next;
	int data;
};

Node* Create(int n)
{
	Node* head = new Node;
	Node*p, *pre;
	head->next = NULL;
	pre = head;
	int k;
	for (int i = 1; i <= n; i++)
	{
		p = new Node;
		cin >> k;
		p->data = k;
		p->next = NULL;
		pre->next = p;
		pre = p;
	}
	return head;
}

void jiao(Node*A, Node*B)
{
	Node*p1, *p2;
	p1 = A->next;
	int count = 0;
	while (p1)
	{
		p2 = B->next;
		while (p2)
		{
			if (p2->data == p1->data)
			{
				count++;
				break;
			}
			p2 = p2->next;
		}
		p1 = p1->next;
	}
	cout << count << endl;
}

int main()
{
	int m;
	cin >> m;
	while (m-->0)
	{
		int n1, n2;
		cin >> n1 >> n2;
		Node*A = Create(n1);
		Node*B = Create(n2);
		jiao(A, B);
		delete A, B;
	}

	return 0;
}

  

转载于:https://www.cnblogs.com/KennyRom/p/5910516.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值