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

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