2018年南京大学夏令营机试-1
题目描述
Count number of binary strings without consecutive 1’s
输入
Given a positive integer n(3≤n≤90), count all possible distinct binary strings of length n such that there are no consecutive 1’s .
Examples:
Input: 2
Output: 3 // The 3 strings are 00, 01, 10
Input: 3
Output: 5 // The 5 strings are 000, 001, 010, 100, 101
中文题意:
给定一个正整数n(3≤n≤90),数出长度为n的所有可能的不同二进制串的个数,使得串中没有连续的1出现。
解题思路:
设a[i]为长度为i的二进制串且不含有连续的1;
则a[1]=2 //0,1
a[2]=3 //00,01,10
若a[i]的第i位为0,那么第i-1位可以是0也可以是1,此种情况的二进制串有a[i-1]个;
若a[i]的第i位为1,那么第i-1位必为0,第i-2位可以是0或1,此种情况的二进制串有a[i-2]个。
所以当n>=3时,a[i]=a[i-1]+a[i-2];
AC代码
/*给定一个正整数n(3≤n≤90),数出长度为n的所有可能的不同二进制串的个数,使得串中没有连续的1出现。*/
#include<iostream>
using namespace std;
long long a[91];//注意数据类型
int main(){
int n;
cin >> n;
a[1] = 2;
a[2] = 3;
if (n >= 3){
for (int i = 3; i <= n; i++){
a[i] = a[i - 1] + a[i - 2];
}
cout << a[n] << endl;
}
return 0;
}