率辉考研oj——1323: 算法2-1:集合union

干货1:首先介绍一个考研oj网站 http://arena.acmclub.com/cate_index.php 这是配套考研高分笔记书籍的(无偿免费广告,不喜勿喷)

干货2:oj小技巧RA有可能是主函数结尾有system(“pause”);

干货3:上题目和代码

       题目描述:假设利用两个线性表LA和LB分别表示两个集合A和B(即:线性表中的数据元素即为集合中的成员),现要求一个新的集合A=A∪B。这就要求对线性表做如下操作:扩大线性表LA,将存在于线性表LB中而不存在于线性表LA中的数据元素插入到线性表LA中去。只要从线性表LB中依次取得每个元素,并依值在线性表LA中进行查访,若不存在,则插入之。

      输入:有多组测试数据,每组测试数据占两行。第一行是集合A,第一个整数m0<m<=100)代表集合A起始有m个元素,后面有m个整数,代表A中的元素。第二行是集合B,第一个整数n(0<n<=100)代表集合B起始有n个元素,后面有n个整数,代表B中的元素。每行中整数之间用一个空格隔开。

      输出:每组测试数据输出n+2行:前两行分别输出集合A、集合B中的数据,后面n行是每次从B中取出元素插入到A尾部后的集合A。每行整数之间用一个空格隔开,每组测试数据之间用一行空行隔开。

      样例输入:

      5 1 5 2 6 3

3 1 7 9

1 3

2 2 7

4 2 5 1 4

4 1 2 4 5

样例输出:

1 5 2 6 3

1 7 9

1 5 2 6 3

1 5 2 6 3 7

1 5 2 6 3 7 9

3

2 7

3 2

3 2 7

2 5 1 4

1 2 4 5

2 5 1 4

2 5 1 4

2 5 1 4

2 5 1 4

解题思路:根据书上章节,开两个数组,第一个为主数组,第二个为辅助数组,逐个扫描辅助数组元素,检查其是否出现在主数组中,如果在,则

  直接输出主数组一边,如果不在,则将该元素插入主数组并输出主数组一边

/*readme:
there are two arrays A and B; we want to output the process
of computing the results of AUB step by step; if current element
tested in B is not in A, it will be push back to A and then print A;
if it is in, A will be printed only*/
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
//checkin()
//print()
class Union{
private:
	int mlen, auxlen,comlen;
	int*marr, *auxarr;
public:
	Union(string ms, string as){
		stringstream min(ms);
		stringstream ain(as);
		min >> mlen;
		ain >> auxlen;
		marr = new int[mlen+auxlen];
		int i = 0;
		while (i != mlen)min >> marr[i++];
		i = 0;
		auxarr = new int[auxlen];
		while (i != auxlen)ain >> auxarr[i++];
		comlen = mlen;
		printf("%d",marr[0]);
		for (i = 1; i != comlen; i++)
			printf(" %d",marr[i]);
		printf("\n");
		printf("%d", auxarr[0]);
		for (int i = 1; i != auxlen; i++)
			printf(" %d", auxarr[i]);
		printf("\n");
	};
	~Union(){ delete[]marr;
	delete[]auxarr;
	}
	int checkin(int index);
	void print(int len);
	void operation();
};
int Union::checkin(int val){//false indicate not in;
	for (int i = 0; i != mlen;i++)
	if (val == marr[i]) return comlen;
	marr[comlen++] = val;//comlen is the length of comb
	return comlen;
}
void Union::print(int len){
	printf("%d", marr[0]);
	for (int i = 1; i != len; i++)
		printf(" %d", marr[i]);
	printf("\n");
}
void Union::operation(){
	for (int i = 0; i != auxlen; i++){
		print(checkin(auxarr[i]));
	}
	printf("\n");
}
int main(){
	string s1, s2;
	while (getline(cin,s1)){
		getline(cin, s2);
		Union u(s1, s2);
		u.operation();
	}
	//system("pause");//oj should not allow the existence of this phrase
	return 0;
}
贴图:




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值