Chinaunix首页 | 论坛 | 博客
  • 博客访问: 986554
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C/C++

2012-10-17 19:17:40

有n个集合(1<=n<=100),n个集合中有k个数字,每个数字的值v(1<=v<=m),并且1<=m<=14。
重组这n个集合,他们能构成多少种不同的集合?

input:
4 4
1 1
1 2
1 3
1 4

2 4
3 1 2 3
4 1 2 3 4

数字的第一行是两个数字,第一个数字是n,第二个数字是m。接下来的n行描述了n个集合。
其中每行的第一个数字代表这个集合中的数字个数k,接下来的k个数字是这个集合中的每个元素。
例如第二个输入。
有2个集合,集合的最大值是4.
集合1有3个元素,分别为1 2 3
集合2有4个元素,分别为1 2 3 4

题解:
1.用bit表表示集合。这个方法在《编程珠玑》头开始就介绍了。
对于集合 比如1,2,3 使用0111表示, 1,2,3,4则是1111.
数字是几,哪一位就设置成1.
这样两个集合的并集,就是 0111 & 1111 = 1111

2.完成格式化输入后,就是一个简单的动态规划问题。属于01背包问题。


点击(此处)折叠或打开

  1. /*
  2.  * =====================================================================================
  3.  *
  4.  * Filename: numset.c
  5.  *
  6.  * Description:
  7.  *
  8.  * Version: 1.0
  9.  * Created: 10/17/2012 06:27:06 PM
  10.  * Revision: none
  11.  * Compiler: gcc
  12.  *
  13.  * Author: royn.wang.renyuan@gmail.com (),
  14.  * Organization:
  15.  *
  16.  * =====================================================================================
  17.  */
  18. #include <stdlib.h>

  19. #include <stdio.h>

  20. #define    MAX (1<<14)-1            /* */

  21. #define    M 14            /* */
  22. #define N 100
  23. char result[MAX] = {0};
  24. void test(int sets[], int count){
  25.     result[0] = 1;
  26.     int i = 0;
  27.     for(;i<count;i++){
  28.         int j = 0;
  29.         for(;j<MAX;j++){
  30.             if(result[j] == 1){
  31.                 result[j|sets[i]] = 1;
  32.             }
  33.         }
  34.     }
  35. }
  36. int* formatinput(int ain[][10], int size){
  37.     int *res = (int*)malloc(sizeof(int)*size);
  38.     int i = 0;
  39.     for(;i<size;i++){
  40.         int t = 1;
  41.         int v = 0;
  42.         for(;t<=ain[i][0];t++){
  43.             v|=(1<<(ain[i][t]-1));
  44.         }
  45.         res[i] = v;
  46.     }
  47.     return res;
  48. }
  49. /*
  50.  * === FUNCTION ======================================================================
  51.  * Name: main
  52.  * Description:
  53.  * =====================================================================================
  54.  */
  55.     int
  56. main ( int argc, char *argv[] )
  57. {
  58.     int ain[][10] = {{3,1,2,3},{4,1,2,3,4}};
  59.     int size = sizeof(ain)/sizeof(int)/10;
  60.     int * input = formatinput(ain, size);
  61.     test(input, size);
  62.     int i = 1;
  63.     int count = 0;
  64.     for(;i<MAX;i++){
  65.         if(result[i] == 1) count++;
  66.     }
  67.     printf ( "%d\n", count );
  68.     return EXIT_SUCCESS;
  69. }                /* ---------- end of function main ---------- */



点击(此处)折叠或打开

您没有插入代码!

阅读(1077) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~