递推-nyoj-The number of maximum subset

来源:互联网 发布:cdn是什么 知乎 编辑:程序博客网 时间:2024/06/02 07:02

The number of maximum subset

描述
You are given a set with n distinct numbers of 1 to n, and your task is to calculate the number of maximum subsets with the following properties:
no two elements in the subset should be adjacent
it shouldn't be possible to add numbers to the subset without violating the first condition
For example, if n = 5, the number of maximum subsets which fulfill the above conditions is 4. The subsets are {1,3,5},{2,4},{2,5},{1,4}. 
输入
The input will consist of a sequence of numbers n,1 ≤ n ≤ 76. Each number will be on a separate line. The input will be terminated by EOF.
输出
Output the number of maximum subsets as described above on a single line. The number of all subsets will be less than 2^31.
样例输入
1234530
样例输出
122344410

题意:给你n个不同的数(从1~n),求满足下列条件的子集有多少个。

1)没有两个数在集合中是相邻的

2)在没有违反第一个条件的情况下,不能把数字加到集合里

貌似不太好理解。。。。

当n=5时,符合条件的集合是{1,3,5},{2,4},{2,5},{1,4}.为什么{1,3}不符合呢?因为当集合为{1,3}时,加进去5是不违反第一个条件的,所以就不能把1,3放到集合中。

当元素有n个时,1、把n加进集合中

  2、把n-1加进集合中

1、把n加进集合中,则n-1不能加,n-2能加,所以把n加进集合中的集合个数等于把n-2加进集合中时集合素个数,用s[i]记录把n=i时的最大集合个数,则有s[n]=s[n-2];

2、把n-1加进集合中,则n-2不能加,n-3能加,同理可得s[n-1]=s[n-3]

综上可得一个递推公式:当元素有n个时,s[n]=s[n-2]+s[n-3];

 #include<stdio.h>#include<stack>#include<math.h>#include<queue>#include<string.h>#include<iostream>#include<algorithm>using namespace std;int main(){    int n;    int s[100];    s[1]=1;s[2]=2;s[3]=2;    for(int i=4;i<=76;i++)    {        s[i]=s[i-2]+s[i-3];    }    while(scanf("%d",&n)!=EOF)    {        printf("%d\n",s[n]);    }    return 0;}        


0 0
原创粉丝点击