标签:cout pre bsp cin strong 思路 遍历 mes tor
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 6 bool cmp(int a, int b) 7 { 8 return a < b; 9 } 10 11 int main() 12 { 13 int arr1Num,arr2Num; 14 int flag = 0; 15 16 cin >> arr1Num; 17 vector<int> arr1(arr1Num); 18 for (int i = 0; i < arr1Num; i++) 19 { 20 cin >> arr1[i]; 21 } 22 23 cin >> arr2Num; 24 vector<int> arr2(arr2Num); 25 for (int i = 0; i < arr2Num; i++) 26 { 27 cin >> arr2[i]; 28 } 29 30 //交集 31 int b[2000] = { 0 }; 32 int l = -1; 33 for (int i = 0; i < arr1Num; i++) 34 { 35 for (int j = 0; j < arr2Num; j++) 36 { 37 if (arr1[i] == arr2[j]) 38 { 39 flag = 1; //有交集 40 b[++l] = arr1[i]; 41 } 42 } 43 } 44 if (flag == 1) //有交集才输出换行 45 { 46 sort(b, b + l + 1, cmp); 47 for (int i = 0; i < l + 1; i++) 48 { 49 cout << b[i] << " "; 50 } 51 cout << endl; 52 } 53 54 //并集 55 vector<int> arr3(arr1Num+arr2Num); 56 for (int i = 0; i < arr1Num; i++) //把两个数组的数字全导入arr3中 57 { 58 arr3[i] = arr1[i]; 59 } 60 for (int j = arr1Num; j < arr1Num + arr2Num; j++) 61 { 62 arr3[j] = arr2[j - arr1Num]; 63 } 64 sort(arr3.begin(), arr3.end(), cmp); //从小到大排序 65 cout << arr3[0] << " "; 66 for (int i = 1; i < arr1Num + arr2Num; i++) 67 { 68 if (arr3[i] != arr3[i - 1]) 69 { 70 cout << arr3[i] << " "; 71 } 72 } 73 cout << endl; 74 75 //余集 76 int i, j,k = -1; 77 int a[2000] = { 0 }; //先记录下来 78 int cnt = 0; 79 for (i = 0; i < arr1Num; i++) 80 { 81 for (j = 0; j < arr2Num; j++) 82 { 83 if (arr1[i] == arr2[j]) 84 { 85 break; 86 } 87 } 88 if (j == arr2Num) 89 { 90 a[++k] = arr1[i]; 91 cnt++; 92 } 93 } 94 sort(a, a + k + 1, cmp); //从小到大输出 95 for (i = 0; i < cnt; i++) 96 { 97 cout << a[i] << " "; 98 } 99 return 0; 100 }
标签:cout pre bsp cin strong 思路 遍历 mes tor
原文地址:https://www.cnblogs.com/ZhengLijie/p/12715015.html