본문 바로가기
Develop/백준 (Cpp)

[백준] 1822번 : 차집합 (C++)

by Tarra 2023. 2. 20.

10984번: 내 학점을 구해줘


문제 )

몇 개의 자연수로 이루어진 두 집합 A와 B가 있다. 집합 A에는 속하면서 집합 B에는 속하지 않는 모든 원소를 구하는 프로그램을 작성하시오.

 

 

입력 :

첫째 줄에는 집합 A의 원소의 개수 n(A)와 집합 B의 원소의 개수 n(B)가 빈 칸을 사이에 두고 주어진다. (1 ≤ n(A), n(B) ≤ 500,000)이 주어진다. 둘째 줄에는 집합 A의 원소가, 셋째 줄에는 집합 B의 원소가 빈 칸을 사이에 두고 주어진다. 하나의 집합의 원소는 2,147,483,647 이하의 자연수이며, 하나의 집합에 속하는 모든 원소의 값은 다르다.

 

 

 

출력 :

첫째 줄에 집합 A에는 속하면서 집합 B에는 속하지 않는 원소의 개수를 출력한다. 다음 줄에는 구체적인 원소를 빈 칸을 사이에 두고 증가하는 순서로 출력한다. 집합 A에는 속하면서 집합 B에는 속하지 않는 원소가 없다면 첫째 줄에 0만을 출력하면 된다.

 

 

 

 

 

 

풀이)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <set>
 
using namespace std;
 
int main()
{
    int n, m;
    cin >> n >> m;
    set<int> a;
    set<int> b;
 
    int num;
    for (int i = 0; i < n; i++)
    {
        cin >> num;
        a.insert(num);
    }
 
    for (int i = 0; i < m; i++)
    {
        cin >> num;
        b.insert(num);
    }
 
    for (auto& ele : b)
    {
        a.erase(ele);
    }
 
    if (a.size() == 0)
    {
        cout << 0;
    }
    else {
        cout << a.size() << "\n";
        for (auto& ele : a)
        {
            cout << ele << " ";
        }
    }
 
    return 0;
}
 
cs

 

좀 더 빠른 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int n, m;
int a[500010];
int b[500010];
 
int main()
{
    cin.tie(NULL);
    std::ios::sync_with_stdio(false);
 
    cin >> n >> m;
 
    int num;
    for (int i = 0; i < n; i++)
    {
        cin >> num;
        a[i] = num;
    }
 
    for (int i = 0; i < m; i++)
    {
        cin >> num;
        b[i] = num;
    }
 
    sort(begin(a), end(a));
    sort(begin(b), end(b));
 
    vector<int> vec;
    for (auto &ele : a)
    {
        if (!binary_search(begin(b), end(b), ele))
        {
            vec.push_back(ele);
        }
    }
 
    if (vec.size() == 0)
    {
        cout << "0";
    } 
    else 
    {
        cout << vec.size() << "\n";
        for (auto& ele : vec)
        {
            cout << ele << " ";
        }
    }
 
}
 
cs

출처 : https://www.acmicpc.net/problem/1822 

 

1822번: 차집합

첫째 줄에는 집합 A의 원소의 개수 n(A)와 집합 B의 원소의 개수 n(B)가 빈 칸을 사이에 두고 주어진다. (1 ≤ n(A), n(B) ≤ 500,000)이 주어진다. 둘째 줄에는 집합 A의 원소가, 셋째 줄에는 집합 B의 원소

www.acmicpc.net