藍橋杯算法題解 算法訓練 集合運算

題目描述

問題描述
  給出兩個整數集合A、B,求出他們的交集、並集以及B在A中的餘集。
輸入格式
  第一行爲一個整數n,表示集合A中的元素個數。
  第二行有n個互不相同的用空格隔開的整數,表示集合A中的元素。
  第三行爲一個整數m,表示集合B中的元素個數。
  第四行有m個互不相同的用空格隔開的整數,表示集合B中的元素。
  集合中的所有元素均爲int範圍內的整數,n、m<=1000。
輸出格式
  第一行按從小到大的順序輸出A、B交集中的所有元素。
  第二行按從小到大的順序輸出A、B並集中的所有元素。
  第三行按從小到大的順序輸出B在A中的餘集中的所有元素。
樣例輸入
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
樣例輸入
4
1 2 3 4
3
5 6 7
樣例輸出
1 2 3 4 5 6 7
1 2 3 4

題解:

思路:用map記錄兩個集合的數的出現次數
**求並集:**只要出現了的數就可以加進來
**求交集:**出現了兩次的數加進來
求B對A的餘集: A有B沒有的(實際上就是A的減去AB的交集),我這裏還是用的map,A集合出現的數+1,B集合也出現了的數-1,最後把次數爲1的數加進來。

代碼:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;

int n,m;
vector <int> A,B;
vector <int> r1,r2,r3;// 交集r1、並集r2、B對A的餘集(A有B沒有的)r3
map <int,int> mp;

int main()
{
    cin >> n;
    int x;
    for(int i = 0; i < n; i++)
    {
        cin >> x;
        A.push_back(x);
        mp[x]++;
    }
    cin >> m;
    for(int i = 0; i < m; i++)
    {
        cin >> x;
        B.push_back(x);
        mp[x]++;
    }
    for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
    {
        r2.push_back(it->first);// 求並集
        if(it->second == 2)
        {
            r1.push_back(it->first);// 求交集
        }
    }
    mp.clear();
    for(int i = 0; i < n; i++)
    {
        mp[A[i]]++;
    }
    for(int i = 0; i < m; i++)
    {
        mp[B[i]]--;
    }
    for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
    {
        if(it->second == 1)
        {
            r3.push_back(it->first);
        }
    }
    if((int)r1.size() != 0)
    {
        for(int i = 0; i < (int)r1.size(); i++)
        {
            cout << r1[i] << " ";
        }
        cout << endl;
    }
    if((int)r2.size() != 0)
    {
        for(int i = 0; i < (int)r2.size(); i++)
        {
            cout << r2[i] << " ";
        }
        cout << endl;
    }
    if((int)r3.size() != 0)
    {
        for(int i = 0; i < (int)r3.size(); i++)
        {
            cout << r3[i] << " ";
        }
        cout << endl;
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章