c++求集合幂集 源代码及算法优化
2010-10-23 20:47
183 查看
//求集合幂集的算法:这是目前最高效的算法By迷若烟雨
#include<iostream.h>
#include<windows.h>
#include<fstream.h>
int qiumiji(char *a,int len)//找所有子集的函数,集合放在数组a中,长度为len,直接移位操作,这是目前最高效的算法
{
int i=0,j=0;
bool flag=false;
cout<<"{NULL}"<<endl;
for(i=1;!flag;i++)
{
cout<<"{";
flag=true;
for(j=0;j<len;j++)
{
if((i>>j)&1)
cout<<a[j]<<" ";
else
flag=false;
}
cout<<"/b}"<<endl;
}
return i;
}
int main()
{
int num;//num代表集合长度
int count=0;
cout<<"Please input the number of aggerate:"<<endl;
cin>>num;
char *item=new char[num];
for(int i=0;i<num;i++)
{
cout<<"Please input the "<<i+1<<"th element:";
cin>>item[i];
}
int t0=GetTickCount();
count=qiumiji(item,num);
int t1=GetTickCount();
cout<<"总数:"<<count<<endl;
cout<<"求长度为"<<num<<"的集合的幂集所花费的时间为:"<<t1- t0<<"ms."<<endl;
delete [] item;
return 0;
}
时间复杂度为O(2^n*n),求10个元素的时间在265ms左右,比上一个算法效率提高了不少。
#include<iostream.h>
#include<windows.h>
#include<fstream.h>
int qiumiji(char *a,int len)//找所有子集的函数,集合放在数组a中,长度为len,直接移位操作,这是目前最高效的算法
{
int i=0,j=0;
bool flag=false;
cout<<"{NULL}"<<endl;
for(i=1;!flag;i++)
{
cout<<"{";
flag=true;
for(j=0;j<len;j++)
{
if((i>>j)&1)
cout<<a[j]<<" ";
else
flag=false;
}
cout<<"/b}"<<endl;
}
return i;
}
int main()
{
int num;//num代表集合长度
int count=0;
cout<<"Please input the number of aggerate:"<<endl;
cin>>num;
char *item=new char[num];
for(int i=0;i<num;i++)
{
cout<<"Please input the "<<i+1<<"th element:";
cin>>item[i];
}
int t0=GetTickCount();
count=qiumiji(item,num);
int t1=GetTickCount();
cout<<"总数:"<<count<<endl;
cout<<"求长度为"<<num<<"的集合的幂集所花费的时间为:"<<t1- t0<<"ms."<<endl;
delete [] item;
return 0;
}
时间复杂度为O(2^n*n),求10个元素的时间在265ms左右,比上一个算法效率提高了不少。
相关文章推荐
- C++提高5 STL算法 :查找,统计,排序,拷贝,替换,算术,集合 |STL 案例:学校演讲比赛介绍
- C++ STL源代码学习之算法篇
- Harris角点检测算法优化(有matlab源代码)
- 海量数据库的查询优化及分页算法方案集合1/2第1/2页
- C++ 递归艺术----求任意集合的幂集组合和子集合的总个数
- [C++] 测试硬件popcnt(位1计数)指令与各种软件算法,利用模板实现静态多态优化性能
- 最速下降优化算法的C++实现
- 贪心算法之埃及分数问题(附c++源代码)
- 八皇后算法-算法设计-C++源代码 -good code
- 基于集合关系对求解闰年数的算法优化
- 【算法】分而治之(DivideAndConquer) -- C++源代码(VS2015)
- 将任意集合, 平分成若干份算法, 有待优化
- 内部元素一一对应的集合的算法优化,从list到hashmap
- Bellman算法优化使用邻接表C++实现
- 如何用O(n)时间复杂度查找第k大数的优化算法 C++程序
- 普林斯顿大学公开课 算法1-10:并检查集合-高速整合方法优化
- C++:罗列出1~100000000的所有雷劈数(算法优化版本)
- 【算法竞赛入门经典】集合的动态规划;时间优化 例题9-16 UVa1252
- 【源代码】C++实现严蔚敏数据结构所有算法(一)线性表-顺序表