zoukankan      html  css  js  c++  java
  • HDU1412 {A} + {B}

    问题链接:HDU1412 {A} + {B}。这个是一个整数集合求并的问题,是基础训练题。问题的关键在于解题思路。

    问题简述:参见上述链接。

    问题分析(略)。

    程序说明这里分别给出C和C++程序。

    C++中有容器类set,就是集合,用起来方便。因为是求并集,读入的两个集合数据直接放到一个集合就可以了。输出时,将集合元素输出到一行里,并且用空格隔开,最后一个元素没有空格,所以需要小心处理。程序中,把空格与后一个元素一起输出。

    C语言程序中,用数组来存放集合。需要注意的是,要根据题意定义数组的大小,以免溢出。因为是求并集,读入的两个集合数据直接放到同一个数组中。然后,对数组中的数据进行排序,输出时剔除值相同的元素即可。之所以要排序,是因为排序后相同的值就放在数组中相邻的单元里,容易处理。

    AC的C++语言程序如下:

    /* HDU1412 {A} + {B} */
    
    #include <cstdio>
    #include <iostream>
    #include <set>
    
    using namespace std;
    
    int main()
    {
        int n, m, val;
        set<int> result;
    
        while(cin >> n >> m) {
            result.clear();
    
            for(int i=1; i<=n+m; i++) {
                cin >> val;
                result.insert(val);
            }
    
            bool nofirstflag = false;
            for(set<int>::iterator it = result.begin(); it != result.end(); it++) {
                if(nofirstflag)
                    cout << " ";
                nofirstflag = true;
    
                cout << *it;
            }
            cout << endl;
        }
    
        return 0;
    }

    AC的C语言程序如下:

    /* HDU1412 {A} + {B} */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    int cmp(const void * a, const void * b)
    {
        return *(int *)a - *(int *)b;
    }
    
    int main(void)
    {
        int n, m, set[20000+2], i;
    
        while(scanf("%d%d", &n, &m) != EOF) {
            // 读两个集合数据,放在同一个数组中
            for(i=0; i<n+m; i++)
                scanf("%d", &set[i]);
    
            // 集合数据排序
            qsort(set, n+m, sizeof(int), cmp);
    
            // 归并输出(去掉重复数据)
            for(i=0; i<n+m; i++){
                if(i==0)
                    printf("%d", set[i]);
                else {
                    if(set[i] == set[i-1])
                        continue;
                    else
                        printf(" %d", set[i]);
                }
            }
            printf("
    ");
        }
    
        return 0;
    }

     

  • 相关阅读:
    Codeforces 1265A Beautiful String
    1039 Course List for Student (25)
    1038 Recover the Smallest Number (30)
    1037 Magic Coupon (25)
    1024 Palindromic Number (25)
    1051 Pop Sequence (25)
    1019 General Palindromic Number (20)
    1031 Hello World for U (20)
    1012 The Best Rank (25)
    1011 World Cup Betting (20)
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564713.html
Copyright © 2011-2022 走看看