天天看点

hdu 1412 {A} + {B} {A} + {B}

{A} + {B}

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 11419    Accepted Submission(s): 4777

Problem Description 给你两个集合,要求{A} + {B}.

注:同一个集合中不会有两个相同的元素.  

Input 每组输入数据分为三行,第一行有两个数字n,m(0<n,m<=10000),分别表示集合A和集合B的元素个数.后两行分别表示集合A和集合B.每个元素为不超出int范围的整数,每个元素之间有一个空格隔开.  

Output 针对每组数据输出一行数据,表示合并后的集合,要求从小到大输出,每个元素之间有一个空格隔开.  

Sample Input

1 2
1
2 3
1 2
1
1 2
        

Sample Output

1 2 3
1 2
        

STL 应用

#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
    int a,b;
    int x;
    while (cin>>a>>b)
    {
        set<int>va;
        set<int>vb;
        for (int i=0; i<a; i++)
        {
            cin>>x;
            va.insert(x);
        }
        for (int i=0; i<b; i++)
        {
            cin>>x;
            vb.insert(x);
        }
        set<int>::iterator it=vb.begin();
        while (it!=vb.end())
        {
            if(vb.find(*it)!=va.end())
            {
                va.insert(*it);
                it++;
            }
        }
        set<int>::iterator te=va.begin();
        int flag=1;
        while (te!=va.end())
        {
            if(flag)
            {
                cout<<*te;
                flag=0;
            }
            else
            {
                cout<<" "<<*te;
            }
            te++;
        }
        cout<<endl;
    }
    return 0;
}
           

(2)

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <list>
#include <iterator>
using namespace std;
int main()
{
    int a,b;
    int x;
    int flag=1;
    while (cin>>a>>b)
    {
        flag=1;
        list<int>La;
        list<int>Lb;
        for (int i=0; i<a; i++)
        {
            cin>>x;
            La.push_back(x);
        }
        for (int i=0; i<b; i++)
        {
            cin>>x;
            Lb.push_back(x);
        }
        La.sort();
        Lb.sort();
        list<int>::iterator last_a=unique(La.begin(), La.end());
        list<int>::iterator last_b=unique(Lb.begin(), Lb.end());
        list<int>LResult;
        set_union(La.begin(), last_a, Lb.begin(), last_b,back_inserter(LResult));
        list<int>::iterator it=LResult.begin();
        while (it!=LResult.end())
        {
            if (flag)
            {
                cout<<*it;
                flag=0;
            }
            else
            {
              cout<<" "<<*it;
            }
            it++;
        }
        cout<<endl;
    }
    return 0;
}