率輝考研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;
}
貼圖:




發佈了39 篇原創文章 · 獲贊 18 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章