動態規劃(1) 編程題#1:集合加法(Coursera 程序設計與算法 專項課程4 算法基礎 郭煒、劉家瑛;map容器插入元素)

編程題#1:集合加法

來源: POJ (http://bailian.openjudge.cn/practice/2792/)

注意: 總時間限制: 3000ms 內存限制: 65536kB

描述
給出2個正整數集合A = {pi | 1 <= i <= a},B = {qj | 1 <= j <= b}和一個正整數s。問題是:使得pi + qj = s的不同的(i, j)對有多少個。

輸入
第1行是測試數據的組數n,後面跟着n組測試數據。
每組測試數據佔5行,第1行是和s (1 <= s <= 10000),第2行是一個正整數a (1 <= a <= 10000),表示A中元素的數目。第3行是a個正整數,每個正整數不超過10000,表示A中的元素。第4行是一個正整數b (1 <= b <= 10000),表示B中元素的數目。第5行是b個正整數,每個正整數不超過10000,表示B中的元素。
注意:這裏的集合和數學書上定義的集合有一點點區別——集合內可能包含相等的正整數。

輸出
n行,每行輸出對應一個輸入。輸出應是一個非負整數。

樣例輸入

2
99
2
49 49
2
50 50
11
9
1 2 3 4 5 6 7 8 9
10
10 9 8 7 6 5 4 3 2 1

樣例輸出

4
9

程序解答方法一:
本程序主要在於用map容器對集合中的重複元素進行了統計,並按元素由小到大進行了排序。內存:1664kB,時間:1476ms

#include <iostream>
#include <map>
#include <algorithm>
using namespace std;

int main() {
    int n, s, ni, nj;
    int a[10000], b[10000];
    int nCount;
    map<int, int> seti, setj;
    map<int, int>::iterator nii, njj;

    cin >> n;
    while (n--){
        cin >> s;
        cin >> ni;
        for (int i = 0; i < ni; i++)
            cin >> a[i];
        cin >> nj;
        for (int j = 0; j < nj; j++)
            cin >> b[j];
        sort(a, a + ni);  //按元素由小到大進行排序
        sort(b, b + nj);

        int temp = -1;
        for (int i = 0; i < ni; i++){
            if (temp == a[i])   //對集合中的重複元素進行統計
                seti[a[i]]++;
            else
                seti[a[i]] = 1;
            temp = a[i];
        }

        temp = -1;
        for (int j = 0; j < nj; j++){
            if (temp == b[j])
                setj[b[j]]++;
            else
                setj[b[j]] = 1;
            temp = b[j];
        }

        nCount = 0;
        for (nii = seti.begin(); nii != seti.end(); nii++){
            for (njj = setj.begin(); njj != setj.end(); njj++){
                if (nii->first + njj->first == s)
                    nCount += nii->second * njj->second;
            }
        }
        cout << nCount << endl;

        seti.clear();
        setj.clear();
    }

    return 0;
}

程序解答方法二:
直接暴力求解,內存:1024kB,時間:627ms,我就呵呵了。。。。。。

#include<iostream>
using namespace std;
int sum, numA, numB;
int arrayA[10001], arrayB[10001];

int countHelper(int sum, int arrayA[], int numA, int arrayB[], int numB)
{
    int count = 0;
    for (int i = 0; i < numA; ++i) {
        for (int j = 0; j < numB; ++j) {
            if (arrayA[i] + arrayB[j] == sum) {
                count++;
            }
        }
    }
    return count;
}

int main()
{
    int num;
    cin>>num;
    while(num--)
    {
        cin>> sum >> numA;
        for (int i = 0; i < numA; ++i) {
            cin>>arrayA[i];
        }
        cin>>numB;
        for (int j = 0; j < numB; ++j) {
            cin>>arrayB[j];
        }
        int count = countHelper(sum, arrayA, numA, arrayB, numB);
        cout<<count<<endl;
    }

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