• 集合的检索:位图法


                                位图法

    位图(bit-map)法是一种逻辑上非常巧妙的描写叙述集合的方法。

    如集合S={2,4,1,5,12},它用位图描写叙述就是 0110 1100 0000 1000,两个字节就可以描写叙述S,左边是低阶位。用bitset<16>存储的话就是{[15]、[14]、...[1]、[0]}={0001000000110110}。

    用位图对集合进行描写叙述后,就非常方便进行集合的运算,如交、并和差。

    以下来演示详细操作

    集合S={1,2,4,5}。集合T={2,5,8,10}

    集合S的位图是 0110110000000000

    集合T的位图是 0010010010100000

    求S与T的交集即是 S&T=0010010000000000={2,5}

    求S与T的并集即是 S|T=0110110010100000={1,2,4,5,8,10}

    求S与T的差集即是 S&~T=(0110110000000000)&(1101101101011111)=0100100000000000={1,4}

    以上样例的完整代码例如以下

    #include<iostream>
    #include<bitset>
    using namespace std;
    int main()
    {
    	cout << "------位图法---by David---" << endl;
    	int S[] = { 1, 2, 4, 5 };
    	int T[] = { 2, 5, 8, 10 };
    
    	bitset<16> s, t;
    	s.reset();
    	t.reset();
    	int size_s, size_t, i;
    	size_s = sizeof(S) / sizeof(int);
    	size_t = sizeof(T) / sizeof(int);
    	cout << "集合S" << endl;
    	for (i = 0; i < size_s; i++)
    	{
    		cout << S[i] << " ";
    		s.set(S[i]);
    	}
    	cout << endl;
    	cout << "集合T" << endl;
    	for (i = 0; i < size_t; i++)
    	{
    		cout << T[i] << " " ;
    		t.set(T[i]);
    	}
    	cout << endl << endl;
    
    	//求交集
    	bitset<16> r1(s.to_ulong() & t.to_ulong());
    	//求并集
    	bitset<16> r2(s.to_ulong() | t.to_ulong());
    	//求差集
    	bitset<16> r3(s.to_ulong() & (~t.to_ulong()));
    
    	cout << "交集" << endl;
    	for (i = 0; i < 16; i++)
    	if (r1[i])
    		cout << i << " ";
    	cout << endl;
    	cout << "并集" << endl;
    	for (i = 0; i < 16; i++)
    	if (r2[i])
    		cout << i << " ";
    	cout << endl;
    	cout << "差集" << endl;
    	for (i = 0; i < 16; i++)
    	if (r3[i])
    		cout << i << " ";
    	cout << endl;
    	system("pause");
    	return 0;
    }
    执行




    专栏文件夹



  • 相关阅读:
    Qt编写物联网管理平台35实时曲线
    Qt开发经验小技巧221225
    Qt编写物联网管理平台36通信协议
    Qt编写物联网管理平台34地图按钮
    【Python】抛砖引玉连续有序数组的排序问题
    java经验总结
    0618
    面试_子数组类问题
    【segmentation fault】vsnprintf错误用法
    Sword jemalloc使用小结
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5216625.html
Copyright © 2020-2023  润新知