2018南京大学计算机夏令营机试

题目1
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 .

  Input:  2 
  Output: 3 // The 3 strings are 00, 01, 10 
  ​
  Input: 3 
  Output: 5 // The 5 strings are 000, 001, 010, 100, 101

先上dfs,时间复杂度太高

#include<iostream>
using namespace std;

int n;
const int MAXN=100;

long long ans;

void dfs(int now,int con)
{
	if(con>1)   //减枝 
		return ;
	if(now==n ) 
	{
		ans++;
		return ;
	}
	
	dfs(now+1,0);
	dfs(now+1,con+1);
	
}
int main()
{
	cin>>n;
	dfs(0,0);  //从下标0开始,末尾连续1的个数 
	cout<<ans;		
	return 0;
 } 

比较容易想的dp

#include<iostream>
using namespace std;

int n;
const int MAXN=105;

long long dp[105][2];



int main()
{
	cin>>n;
	dp[1][0]=1;
	dp[1][1]=1;
	
	for(int i=2;i<=n;i++)
	{
		dp[i][1]=dp[i-1][0];
		dp[i][0]=dp[i-1][0]+dp[i-1][1];
	}		
	
	cout<<dp[n][1]+dp[n][0];
	
	return 0;
}
第二种dp   dp[i]=dp[i-1]+dp[i-2]  //dp[i]表示前i位没有连续的1 
//当第i位为1,dp[i]=dp[i-2]  当第i位为0,dp[i]=dp[i-1]
题目二:
2. Missing number

Given a positive integer n(n≤40), pick n-1 numbers randomly from 1 to n and concatenate them in random order as a string s, which means there is a missing number between 1 and n. Can you find the missing number?(Notice that in some cases the answer will not be unique, and in these cases you only need to find one valid answer.)

Input: 20
         81971112205101569183132414117
Output: 16


dfs就完事了
#include<iostream>
using namespace std;

const int MAXN=45;

string str;
int n;
int full[MAXN];
int ok;

void dfs(int now,int last)
{
	if(ok)
		return ;
		
	if((last>n)||(now && last==0))  //注意第二个条件,因为now==1时 last为0 
		return ; 
	
	if(now==str.size())
	{
		full[last]++;
		
		int no=0;
		int i;
		int a;
		for(i=1;i<=n;i++)
		{
			if(!full[i])
			{
				a=i;
				no++;
			}
		}
		if(no==1)
		{
			ok=1;
			cout<<a;
		}
		return;
	} 
	dfs(now+1,last*10+(str[now]-'0')); //和last组合成备选数 
 	full[last]++;    //last自成一家  
	dfs(now+1,str[now]-'0');
	full[last]--;               //回溯 
}

int main()
{
	cin>>n>>str;
	
	dfs(0,0);
		
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值