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<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<functional>
#include<stdlib.h>
#include<string.h>
#include<set>
#include<sstream>
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;
        set<ll>s;
        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<ll>::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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值