# 集合的交和并算法

-1e9<=ai,bi<=1e9

### 输入样例1:

``````1 3
1
1 3 4
``````

### 输出样例1:

``````1 1
3 1 3 4
``````

### 输入样例2:

``````1 3
1
2 3 4
``````

### 输出样例2:

``````0
4 1 2 3 4``````

### 题解

``````/*1.将数据读入vector v1 v2中
2.将v1,v2排序
3.双指针的方法记录交集值
4.用双指针,每一次将较小的放进并集
5.输出
*/
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
int n, m, a = 0, b = 0;
cin >> n >> m;
vector<int> v1(n), v2(m), J, B;//J是交集，B是并集
for (int i = 0; i < n; i++) cin >> v1[i];
for (int i = 0; i < m; i++) cin >> v2[i];
sort(begin(v1), end(v1));
sort(begin(v2), end(v2));
while (a < n && b < m) {
if (v1[a] < v2[b]) {
B.push_back(v1[a]);
a++;
} else if (v1[a] > v2[b]) {
B.push_back(v2[b]);
b++;
} else {
J.push_back(v1[a]);
b++;
}
}
if (a==n) {
for (int b_temp=b; b_temp < m; b_temp++) B.push_back(v2[b_temp]);
} else {
for (int a_temp=a; a_temp < n; a_temp++) B.push_back(v1[a_temp]);
}
if (J.size()) {
cout << J.size();
for (auto temp : J) {
cout <<" "<< temp;
}
cout << endl;
} else {
cout << "0" << endl;
}
cout << B.size() ;
for (auto temp : B) {
cout <<" "<< temp ;
}
system("pause");
}``````

``  for(i=1;i<=5;i++)   printf("hello\n"); ``

• 1.最后一项单独判断
``````  for(i=1;i<=5;i++)
{
if(i==5) printf("hello");
else printf("hello\n");
}``````
• 2.最后一项不好确定，引入flag
``````int flag=1;
for(i=1;i<=5;i++)
{
if(flag)  {printf("hello");flag=0;}
else printf("\nhello");
}``````