2017年12月11日 星期一

[C_ST84-易] 差集(C++)

[C_ST84-易] 差集

問題描述 :
差集:設 A 、 B 表兩集合, A 差集 B 以 A-B 表示之,其意思表示某些元素在 A 集合且不在 B 集合的元素集合。
範例 :
A 、 B 分別為兩個集合,集合裏有不同的元素,如下列所示,求出其 A 差集 B 之集合內容 :
A = 1,2,3,4,5,7,9
B = 2,4,6,8,10
A 差集 B : 1,3,5,7,9
求輸入任 2 個集分別為合 A 集合及 B 集合,求 A 差集 B 之集合 ?
輸入說明 :
輸入兩列的數字代表 A 及 B 兩集合,第一列為 A 集合,第一列為 B 集合,每一列集合中的元素以逗號分隔開來。
例如:
輸入 2 列字串 ( 第一列為 A 集合,第一列為 B 集合 ) :
1,2,3,4,5,7,9
2,4,6,8,10
輸出說明 :
輸出 A 及 B 兩集合之 A 差集 B 之集合 , 輸出元素以空白分隔開來, 須按照小到大排列 . 若空集合則輸出 null
例如, 按照小到大排列 輸出為:
1,3,5,7,9
範例 :

輸入範例輸出範例
1,3,5,7,9
2,4,6,8,10
1 3 5 7 9
4,5,6,7,8,9,10,13
2,3,4,6,7,8,10,15,19
5 9 13
29,23,15,17,31,11
12,10,9,11,23,6 17
15 29 31


  1. #include <iostream>    
  2. #include <string>    
  3. #include <sstream>    
  4. #include <algorithm>    
  5.     
  6. using namespace std;    
  7.     
  8. int main() {    
  9.     // [C_ST84-易] 差集    
  10.     // 差集 = 在 A 集合且不在 B 集合的元素集合    
  11.     // g++(c++11)  
  12.     string A, B;    
  13.     cin >> A >> B;    
  14.     int i_A[1000000];    
  15.     int i_B[1000000];    
  16.     //切割字串A    
  17.     stringstream ssa(A);    
  18.     string token;    
  19.     int countA = 0;    
  20.     while (getline(ssa, token, ','))    
  21.     {    
  22.         i_A[countA] = stoi(token);    
  23.         countA++;    
  24.     }    
  25.   
  26.     //切割字串B    
  27.     stringstream ssb(B);    
  28.     int countB = 0;    
  29.     while (getline(ssb, token, ','))    
  30.     {    
  31.         i_B[countB] = stoi(token);    
  32.         countB++;    
  33.     }    
  34.         
  35.     int fin[countA];    
  36.     fill(fin, fin+countA,0);    
  37.     bool exist = true;    
  38.     int fpos = 0;    
  39.     for(int i = 0;i < countA;i++)    
  40.     {    
  41.         for(int j = 0;j < countB;j++)    
  42.         {    
  43.             if(i_A[i] == i_B[j])    
  44.             {    
  45.                 exist = false;    
  46.             }    
  47.         }    
  48.         if(exist == true)//不重複就放入fin    
  49.         {    
  50.             fin[fpos] = i_A[i];    
  51.             fpos++;    
  52.         }    
  53.         exist = true;    
  54.     }    
  55.     sort(fin, fin+fpos);    
  56.     for(int i = 0;i < fpos;i++)    
  57.     {    
  58.         if(i != fpos-1)    
  59.         {    
  60.             cout << fin[i] << " ";    
  61.         }    
  62.         else    
  63.         {    
  64.             cout << fin[i] << endl;    
  65.         }    
  66.     }    
  67.     return 0;    
  68. }  

沒有留言:

張貼留言