1. 程式人生 > >杭電 HDU 2034 人見人愛A-B

杭電 HDU 2034 人見人愛A-B

人見人愛A-B

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 51654    Accepted Submission(s): 14567


Problem Description 參加過上個月月賽的同學一定還記得其中的一個最簡單的題目,就是{A}+{B},那個題目求的是兩個集合的並集,今天我們這個A-B求的是兩個集合的差,就是做集合的減法運算。(當然,大家都知道集合的定義,就是同一個集合中不會有兩個相同的元素,這裡還是提醒大家一下)

呵呵,很簡單吧?
Input 每組輸入資料佔1行,每行資料的開始是2個整數n(0<=n<=100)和m(0<=m<=100),分別表示集合A和集合B的元素個數,然後緊跟著n+m個元素,前面n個元素屬於集合A,其餘的屬於集合B. 每個元素為不超出int範圍的整數,元素之間有一個空格隔開.
如果n=0並且m=0表示輸入的結束,不做處理。
Output 針對每組資料輸出一行資料,表示A-B的結果,如果結果為空集合,則輸出“NULL”,否則從小到大輸出結果,為了簡化問題,每個元素後面跟一個空格.

Sample Input 3 3 1 2 3 1 4 7 3 7 2 5 8 2 3 4 5 6 7 8 0 0
Sample Output 2 3 NULL
Author lcy 本孩子 最近 剛開始接觸 STL 今天晚自習的時候 被他強大的功能 可感染了!別當時看見string和動態分配陣列還他媽激動。
下面是在網上找的 用到的知識點 我也算學習了。

一.count函式

algorithm標頭檔案定義了一個count的函式,其功能類似於find。這個函式使用一對迭代器和一個值做引數,返回這個值出現次數的統計結果。

編寫程式讀取一系列int型資料,並將它們儲存到vector物件中,然後統計某個指定的值出現了多少次。應用範例:

//讀取一系列int資料,並將它們儲存到vector物件中,
//然後使用algorithm標頭檔案中定義的名為count的函式,
//統計某個指定的值出現了多少次
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
int main()
{
    int ival , searchValue;
    vector<int> ivec;
 
    //讀入int型資料並存儲到vector物件中,直至遇到檔案結束符
    cout<<"Enter some integers(Ctrl+Z to end): "<<endl;
    while(cin >> ival)
        ivec.push_back(ival);
 
    cin.clear(); // 使輸入流重新有效
 
    //讀入欲統計其出現次數的int值
    cout<<"Enter an integer you want to search: "<<endl;
    cin>>searchValue;
 
    //使用count函式統計該值出現的次數並輸出結果
    cout<<count(ivec.begin() , ivec.end() , searchValue)
        <<"  elements in the vector have value "
        <<searchValue<<endl;
 
    return 0;
}

普通解法:

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main()
{
    int n,t,m,ls[101],gq[101],cnt[101];
    while(cin>>n>>m,n||m)
    { 
        int q=0;
        memset(ls,0,sizeof(ls));
        memset(gq,0,sizeof(gq));
        memset(cnt,0,sizeof(cnt));
        for(int i=0;i<n;i++)
            cin>>ls[i];
        for(int j=0;j<m;j++)
            cin>>gq[j];
        for(int k=0;k<n;k++)
        {
            for( t=0;t<m;t++)
            if(ls[k]==gq[t])
            break;
            
                    if(t==m)
                    cnt[q++]=ls[k];
        }
        
        if(q==0)
            cout<<"NULL"<<endl;
        else
        {

        sort(cnt,cnt+q);
        for(int p=0;p<q;p++)
            cout<<cnt[p]<<" ";
        cout<<endl;
        }
        
    }
    return 0;
}


set解法:

#include<set>
#include<iostream>
using namespace std;

int main()
{
	int n,m,t;
	set<int>s;
	set<int>::iterator  it;

	while(cin>>n>>m,n+m)
	{
		while(n--)
		{
			cin>>t;
			s.insert(t);
		}
		while(m--)
		{
			cin>>t;
			if(s.count(t))
				s.erase(t);
		}
		for(it=s.begin();it!=s.end();it++)
			cout<<*it<<" ";
		printf(s.size()?"\n":"NULL\n");
		s.clear();
	}
	return 0;
}


STL相信我把你幹掉!