OJ:多重集的插入和刪除

Description
給你一個集合,一開始集合是空集,然後進行若干操作,最後你要從小到大輸出集合中的元素,以空格隔開。(集合中可能會有相同元素)
Input
一共有若干輸入數據,開頭一個n(n<=20),n=0代表輸入結束。
然後有n行,每行有2種形式:
“i x”,x是一個整數,代表向集合中插入元素x
“d x”,x是一個整數,代表刪除一個x
Output
每組輸入結束後,從小到大輸出集合中的元素,以空格隔開。
Sample Input
2 i 2 i 2 4 i 1 i 1 i 2 d 1 0
Sample Output
2 2 1 2
#include <iostream>
#include <set>
using namespace std;


int main()
{
    int n,x,y,m;
    char c;
    multiset<int> a;
    multiset<int>::iterator p;
    while(cin>>n)
    {
        m=0;
        if(n==0)
            return 0;
        for(int i=0;i<n;i++)
        {
            cin>>c;
            if(c=='i')
            {
                cin>>x;
                a.insert(x);
            }
            if(c=='d')
            {
                cin>>y;
                m++;
            }



       }
        if(!a.empty())
        {
            if(m!=0)
            {
                while(m--)
                {
                   for(p=a.begin();p!=a.end();++p)
                    {
                        if(*p==y)
                        {a.erase(p);
                            break;}

                    }
                }
            }


        }
        if(!a.empty())
        {
            for(p=a.begin();p!=a.end();++p)
            {
                if(p==a.begin())
                    cout<<*p;
                else
                    cout<<" "<<*p;
            }
            cout<<endl;
        }
     a.clear();
    }
}







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