Discrete Problem 4(离散数学4)

Think:
因为不知道输出的字符串是多长的,所以用getline(cin, str);读取至换行。然后进行分割字符串,直接用stringstream来进行分割字符串,利用用set自动去重复的特性来进行存储。随后在第二组输入的时候 判断 之前是否出现过 即s.count()是否为0, 不为0 就进行存储。然后直接sort排序,输出。

Problem Description

Given two sets of numbers (set1 and set2), write a function to get their intersection.

The maximum size of set1 and set2 is 3000, and each element of A never exceed 2^32-1.
Input

Input consists of multiple problem instances.Each instance contains two lines. The first line is elements of set1,and the second line is elements of set2.
Output

For each input instance, output one line which contains a row of elements of set1 and set2’s intersection (sorted by ascending order). If set1 and set2’s intersection is empty,output a string ‘NULL’ occupying one line.
Example Input

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

Example Output

1 3 5
NULL

PS:中文翻译

Problem Description

题目给出两个非空整数集,请写出程序求两个集合的交集。
Input

多组输入,每组输入包括两行,第一行为集合A的元素,第二行为集合B的元素。具体参考示例输入。 每个集合元素个数不大于3000,每个元素的绝对值不大于2^32 - 1。
Output

每组输入对应一行输出,为A、B的交集,如果交集为空输出”NULL”,否则交集的元素按递增顺序输出,每个元素之间用空格分割。
Example Input

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

Example Output

1 3 5
NULL

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long int ll;
int main()
{
    string a, b;
    int display[6000];
    ll cnt;
    while(getline(cin, a))
    {
        getline(cin, b);
        memset(display, 0, sizeof(display));
        cnt = 0;
        bool flag = false;
        stringstream ss;
        sets;
        ss.clear();
        ss.str(a);
        while(1)
        {
            ll key;
            ss >> key;
            if (ss.fail())
                break;
            else
                s.insert(key);
        }
        ss.clear();
        ss.str(b);
        while(1)
        {
            ll key;
            ss >> key;
            if (ss.fail())
                break;
            else
            {
                if (s.count(key) != 0)
                {
                    flag = true;
                    display[cnt ++] = key;
                }
            }
        }
        sort(display, display + cnt);
        set::iterator it;
        if (flag == false)
            printf("NULL\n");
        else
        {
            for (int i = 0; i <= cnt - 1; i ++)
            {
                if (i == cnt - 1)
                    printf("%d\n",display[i]);
                else
                    printf("%d ", display[i]);
            }
        }


    }
    return 0;
}

你可能感兴趣的:(STL,离散数学)