CF909C Python Indentation (dp)

CF909C Python Indentation

洛谷链接

思路借鉴自链接

题目描述
In Python, code blocks don’t have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.

We will consider an extremely simplified subset of Python with only two types of statements.

Simple statements are written in a single line, one per line. An example of a simple statement is assignment.

For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with “for” prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can’t be empty.

You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.

输入格式
The first line contains a single integer N ( 1<=N<=5000 ) — the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either “f” (denoting “for statement”) or “s” (“simple statement”). It is guaranteed that the last line is a simple statement.

输出格式
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 10^9+7 .

输入输出样例
输入 #1
4
s
f
f
s
输出 #1
1
输入 #2
4
f
s
f
s
输出 #2
2

说明/提示
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
the second test case, there are two ways to indent the program: the second for statement can either be part of the first one’s body or a separate statement following the first one.

Solution

统计方案数的dp

决策时要考虑当前的语句嵌套在哪个语句里,所以需要考虑缩进几格。
令dp[i][j]为第i行缩进j格的方案数。
答案为 Σdp[n][i]

状态转移

若上一行为f,那么当前行无论是什么都要缩进
即dp[i][j] = dp[i - 1][j - 1];

若上一行为s,无论当前行为什么,缩进的格子一定不能超过上一行的缩进格子数。
dp[i][j] = dp[i - 1][j~n];

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int SZ = 5000 + 20;
const int MOD =  1e9 + 7;
ll dp[SZ][SZ],n,sum;
char s[SZ];
int main()
{
	scanf("%lld",&n);
	for(int i = 1;i <= n;i ++ )
	{
		getchar();
		scanf("%c",&s[i]);
	}
	dp[1][0] = 1;
	for(int i = 2;i <= n;i ++ )
	{
		if(s[i - 1] == 'f') 
		{
			for(int j = 1;j <= n;j ++ )
			dp[i][j] = dp[i - 1][j - 1] % MOD; 
		}
		else if(s[i - 1] == 's')
		{
			sum = 0;
			for(int j = n - 1;j >= 0;j -- )
			{
				sum += dp[i - 1][j];
				sum %= MOD;
				dp[i][j] = sum;
			}
		}
	}
	sum = 0;
	for(int i = 0;i < n;i ++)
	{
		sum += dp[n][i];
		sum %= MOD; 
	}
	printf("%lld",sum);
	return 0;
} 

2020.4.3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章