Blue Bridge Cup Algorithm Training Set Operation-(Detailed Explanation)

Topic 1606: [Blue Bridge Cup] [Algorithm Training VIP] Set Operations

Time limit: 1Sec Memory limit: 128MB Submit: 516 Resolution: 228

                题目描述
                给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集。 

Input The
first line is an integer n, which represents the number of elements in the set A.

The second line has n different integers separated by spaces, representing the elements in set A.

The third line is an integer m, which represents the number of elements in the set B.

The fourth line has m different integers separated by spaces, representing the elements in the set B.

All elements in the set are integers in the range of int, n, m<=1000.

                输出
                第一行按从小到大的顺序输出A、B交集中的所有元素。 

The second line outputs all the elements in the union of A and B in ascending order.

The third line outputs all the elements of B in the remainder of A in ascending order.

                样例输入

5
1 2 3 4 5
5
2 4 6 8 10

                样例输出

2 4
1 2 3 4 5 6 8 10
1 3 5
This question has a large amount of code

#include<iostream>
#include<algorithm>
#define MAX 10000
using namespace std;

int dfs(int *str,int len,int a)//判断某给元素是否在当前集合 
{
    
    
	for(int i=0;i<len;i++)
	{
    
    
		if(str[i]==a)
		{
    
    
			return 1;
		}
	}
   return 0;	
}


int main()
{
    
    
	int sta[MAX];//集合a 
	int stb[MAX];//集合b 
	int n,m,i,j;
	cin>>n;
	for(i=0;i<n;i++)
	{
    
    
		scanf("%d",&sta[i]);
	}
	cin>>m;
	for(j=0;j<m;j++)
    {
    
    
    	scanf("%d",&stb[j]);
	 }
	 
	 int jiao[MAX];//交集 
	 int bing[MAX];//并集 
	 int yu[MAX];//b在a的余 
	 int cj=0,cb=0,cy=0;//他们的个数 
	  
	 for(i=0;i<m;i++)
	 {
    
    
	 	bing[cb++]=stb[i];//先将b的所有元素放到并集数组里面	 	
	 }
	 
	 for(i=0;i<n;i++)
	 {
    
    
	 	int xb=0;
	 	xb=dfs(stb,m,sta[i]);//查询当前元素在b集合里是否有 
	     if(xb==1)
		 {
    
    
		 	jiao[cj++]=sta[i];//有的话就是交际 
			 }
		  else{
    
    //这里主要偷懒少写一给if语句 
		  	bing[cb++]=sta[i];//刚好没有的可以反正并集里  
		  }	
	 }
	 
	 for(i=0;i<n;i++)
	 {
    
    
	 	int xb=0;
	 	xb=dfs(jiao,cj,sta[i]);//查询交集在a的余 
	 	if(xb==0)
	 	{
    
    
	 		yu[cy++]=sta[i];//存入数组 
		 }
	 }
   //使用sort快排  
   sort(jiao,jiao+cj,less<int>());//升序排序 
   sort(bing,bing+cb,less<int>());
   sort(yu,yu+cy,less<int>());
   
   for(i=0;i<cj;i++)
   {
    
    
   	   cout<<jiao[i]<<' ';//依次输出 
   }
   cout<<endl;
   
   for(i=0;i<cb;i++)
   {
    
    
   	  cout<<bing[i]<<' ';
   }
   cout<<endl;
   
   for(i=0;i<cy;i++)
   {
    
    
   	   cout<<yu[i]<<' ';
   }
   cout<<endl;
   
   return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_46232829/article/details/107882528