2017年12月11日 星期一

[C_ST82-易] 交集(C++)

[C_ST82-易] 交集

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

輸入範例輸出範例
1,3,5,7,9,11
2,3,4,5,6,8,10
3 5
1,3,5,7,9
2,4,6,8,10
null
33,26,11,45,86,57
11,22,33,45,77,98
11 33 45

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

沒有留言:

張貼留言