用c++编写程序,求两线性表的交集,并集,差集。
2个回答
2015-11-04 · 知道合伙人教育行家
关注
展开全部
//直接上代码:
#include<iostream>
using namespace std;
int main()
{
int a,b;
int c,d;
cout<<"请输入第一个闭区间的a,b"<<endl;
cin>>a>>b;
cout<<"请输入第二个闭区间的c,d"<<endl;
cin>>c>>d;
if(a>b||c>d) {cout<<"输入的区间不合法"<<endl;}
else
{
if(d<a)
{
cout<<"交集为:空集"<<endl;
cout<<"并集为:"<<"["<<c<<","<<d<<"]"<<","<<"["<<a<<","<<b<<"]"<<endl;
cout<<"差集为:"<<"["<<a<<","<<b<<"]"<<endl;
}
else if(c>b)
{
cout<<"交集为:空集"<<endl;
cout<<"并集为:"<<"["<<a<<","<<b<<"]"<<","<<"["<<c<<","<<d<<"]"<<endl;
cout<<"差集为:"<<"["<<a<<","<<b<<"]"<<endl;
}
else if(c<a)
{
int min,max;
if(d>b) min=b,max=d;else min=d,max=b;
cout<<"交集为:"<<"["<<a<<","<<min<<"]"<<endl;
cout<<"并集为:"<<"["<<c<<","<<max<<"]"<<endl;
if(d>=b) cout<<"差集为:空集"<<endl;
else cout<<"差集为:"<<"["<<d-1<<","<<b<<"]"<<endl;
}
else
{
int min,max;
if(d>b) min=b,max=d;else min=d,max=b;
cout<<"交集为:"<<"["<<c<<","<<min<<"]"<<endl;
cout<<"并集为:"<<"["<<a<<","<<max<<"]"<<endl;
if(c<=a) cout<<"差集为:空集"<<endl;
else
{
cout<<"差集为:"<<"["<<a<<","<<c-1<<"]";
if(d<b)
{
cout<<","<<"["<<d-1<<","<<b<<"]";
}
cout<<endl;
}
}
}
return 0;
}
展开全部
#include<iostream> #include<vector> #include<cstdlib> #include<algorithm> #include<cstring> using namespace std; vector<int> a; vector<int> b; void AND() { bool f[2000]; vector<int>::iterator iter1; vector<int>::iterator iter2; memset(f,false,sizeof(f)); int flag = 0; for(iter1=a.begin();iter1!=a.end();iter1++) { for(iter2=b.begin();iter2!=b.end();iter2++) { if((*iter1)==(*iter2)) { if(f[(*iter1)]==false) { flag = 1; cout << *iter1 << " "; f[(*iter1)] = true; } } } } if(flag==0) cout << "空集" << endl; else cout << endl; } void OR() { bool f[2000]; vector<int>::iterator iter1; vector<int>::iterator iter2; memset(f,false,sizeof(f)); for(iter1=a.begin();iter1!=a.end();iter1++) { f[*iter1] = true; cout << *iter1 << " "; } for(iter2=b.begin();iter2!=b.end();iter2++) { if(f[*iter2]==false) { cout << *iter2 << " "; } } cout << endl; } void CHA() { vector<int>::iterator iter1; vector<int>::iterator iter2; int flag = 0; for(iter1=a.begin();iter1!=a.end();iter1++) { flag = 0; for(iter2=b.begin();iter2!=b.end();iter2++) { if((*iter1)==(*iter2)) { flag = 1; } } if(flag==0) { cout << *iter1 << " "; } } if(flag==1) cout << "空集" << endl; else cout << endl; } int main() { int i,n,temp; printf("请输入集合a个数为:"); scanf("%d",&n); printf("请输入集合a的元素,以空格分开:"); for(i=1;i<=n;i++) { cin >> temp ; a.push_back(temp); } printf("请输入集合b个数为:"); scanf("%d",&n); printf("请输入集合b的元素,以空格分开:"); for(i=1;i<=n;i++) { cin >> temp ; b.push_back(temp); } cout << "两集合的交集为:"; AND(); cout << "两集合的并集为:"; OR(); cout << "两集合的差集为:"; CHA(); system("pause"); return 0; } 自己大概写了个 如果有什么问题 还可以提 希望我的回答可以对您有帮助
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询