集合的位向量表示
/*集合的位向量表示,1表示有,0表示无,这种表示可以很大的节省空间*/ #include<iostream> #include<cstdio> #include<cstring> #include <string> #include <algorithm> #define MAX 1000000000 using namespace std; struct node { int Size; char *s; }; node * Creatnull(int n)//创建一个空的集合 { node * p=new node; p->Size=(n+7)/8; p->s=new char [p->Size]; for (int number=0;number<p->Size;number++) { p->s[number]='\0'; } return p; } bool Insert(node * p,int index)//往集合中插入元素 { if (index>=0&&(index>>3<p->Size))//用>>比用除号节省计算时间 { (p->s[index>>3])|=(1<<(index&7)); return true; } return false; } bool Union(node * s0,node * s1,node * s2)//两集合求并集 { if(s0->Size!=s1->Size||s1->Size!=s2->Size) { return false; } for (int i=0;i<s0->Size;i++) { s0->s[i]=s1->s[i]|s2->s[i]; } return true; } bool jiao(node * s0,node * s1,node * s2)//两集合求交集 { if(s0->Size!=s1->Size||s1->Size!=s2->Size) { return false; } for (int i=0;i<s0->Size;i++) { s0->s[i]=(s1->s[i]&s2->s[i]); } return true; } bool cha(node * s0,node * s1,node *s2)//两集合求差集 { if(s0->Size!=s1->Size||s1->Size!=s2->Size) { return false; } for (int i=0;i<s0->Size;i++) { s0->s[i]=s1->s[i]&~s2->s[i]; } return true; } void show(node * p)//显示集合中的元素 { for (int number=0;number<10;number++) { if ((p->s[number>>3])&(1<<(number&7))) { cout<<number<<endl; } } } bool If(node * p,int index)//判断某个数是否在集合当中 { if (index>=0&&index<<3<p->Size&& p->s[index>>3]&(1<<(index&7))) { return true; } return false; } bool Delete (node * p,int index)//去掉集合中的某个元素 { if (index>=0&&index>>3<p->Size) { p->s[index>>3]&=~(1<<(index&7)); return true; } return false; } int main() { node * p=Creatnull(10); node * head=Creatnull(10); node * q=Creatnull(10); Insert(p,5); Insert(p,9); Insert(q,8); Insert(q,9); Insert(q,7); jiao(head,p,q); cout<<"两集合的交集"<<endl; show(head); cout<<"p集合与q集合的差集"<<endl; cha(head,p,q); show(head); cout<<"p与q的并集"<<endl; Union(head,p,q); show(head); }
集合的链表表示法,里面存储的是集合当中的真实元素,元素先按顺序排好然后再存入。现在还没完善好,只写了一个交集的
#include<iostream> #include<cstdio> #include<cstring> #include <string> #include <algorithm> #define MAX 1000000000 using namespace std; struct node { int value; node * next; }; void Insert(node * & p,int num) { node * it=new node; it->value=num; it->next=nullptr; if (p==nullptr) { p=it; } else { node* t=p; while(t->next!=nullptr) { t=t->next; } t->next=it; } } void jiaoji(node * & head,node * it,node * is) { head=nullptr; node *k; while(it!=nullptr&&is!=nullptr) { if (it->value>is->value)is=is->next; else if (it->value<is->value)it=it->next; else if (it->value==is->value) { node * x=new node; x->next=nullptr; x->value=it->value; if (head==nullptr) { head=x; k=head->next; } else { k=x; k=k->next; } it=it->next; is=is->next; } } } void show(node * p) { while(p!=nullptr) { cout<<p->value<<" "; p=p->next; } } int main() { node * head=nullptr; node *s1=nullptr; node *s2=nullptr; Insert(s1,2); Insert(s1,3); Insert(s2,3); Insert(s2,5); jiaoji(head,s1,s2); show(head); }