Description:
在一个N个节点的无向图(没有自环、重边)上,每个点都有一个符号,可能是数字,也可能是加号、减号、乘号、除号、小括号。你要在这个图上数一数,有多少种走恰好K个节点的方法,使得路过的符号串起来能够得到一个算数表达式 算数表达式。路径的起点和终点可以任意选择。
所谓算数表达式 算数表达式,就是由运算符连接起来的一系列数字。括号可以插入在表达式中以表明运算顺序。
注意,你要处理各种情况,比如数字不能有多余的前导0,减号只有前面没有运算符或数字的时候才可以当成负号,括号可以任意添加(但不能有空括号),0可以做除数(我们只考虑文法而不考虑语意),加号不能当正号。
例如,下面的是合法的表达式:
-0/ 0
((0)+(((2*3+4)+(-5)+7))+(-(2*3)*6))
而下面的不是合法的表达式:
001+0
1+2(2)
3+-3
–1
+1
()
Input:
第一行三个整数N,M,K,表示点的数量,边的数量和走的节点数。
第二行一个字符串,表示每个点的符号。
接下来M行,每行两个数,表示一条边连的两个点的编号。
Output:
输出一行一个整数,表示走的方法数。这个数可能比较大,你只需要输出它模1000000007的余数即可。
Sample Input:
6 10 3
)(1*+0
1 2
1 3
1 4
2 3
3 4
2 5
3 5
3 6
4 6
5 6
Sample Output:
10
Data Constraint:
对于40%的数据,N,M,K≤10
对于100%的数据,1≤N≤20,0≤M≤N×(N-1)/ 2,0≤K≤30
Hint:
【样例解释】
一共有10条路径,构成的表达式依次是101, (1), 1+1, 1+0, 1*1, 1*0, 0+0, 0+1, 0*0, 0*1
题目大意:
给出n个点,每个点上有一个字符,现在求经过k个点的路径,并且点组成的字符串是一个合法的表达式,有多少条。
题解:
可以dp,一步一步走。
我们发现除了括号和前导0,其它的不合法情况都可以用两个相邻的字符来判断。
于是设一个四维状态dp即可。
我设的是
fi,j,k,l
分别表示走了几步,到哪个点,左括号有几个,当前如果是数字,是否是第一个。
方程很好推,不要漏了情况。
#include<cstdio>
#define fo(i, x, y) for(int i = x; i <= y; i ++)
using namespace std;
const int mo = 1e9 + 7;
int f[31][31][31][2];
char c[31];
int n, m, length, x, y, bz[31][31];
int fu(char c) {return c == '+' || c == '-' || c == '*' || c == '/';}
int num(char c) {return c >= '0' && c <= '9';}
int main() {
scanf("%d %d %d\n", &n, &m, &length);
fo(i, 1, n) c[i] = getchar();
fo(i, 1, m) {
scanf("%d %d", &x, &y);
bz[x][y] = bz[y][x] = 1;
}
fo(i, 1, n) {
if(c[i] == '-') f[1][i][0][0] = 1;
if(fu(c[i])) continue;
if(c[i] == ')') continue;
if(c[i] == '(') f[1][i][1][0] = 1; else f[1][i][0][1] = 1;
}
fo(o, 2, length) {
fo(i, 1, n)
fo(j, 1, n) if(bz[i][j]) {
if(num(c[i])) {
if(c[j] == ')') continue;
int bz = !num(c[j]);
fo(k, 0, length) fo(p, 0, 1)
if(!(c[j] == '0' && p == 1))
f[o][i][k][bz] += f[o - 1][j][k][p], f[o][i][k][bz] %= mo;
} else
if(c[i] == '(') {
if(c[j] == ')') continue;
if(num(c[j])) continue;
fo(k, 0, length - 1)
f[o][i][k + 1][0] += f[o - 1][j][k][0], f[o][i][k + 1][0] %= mo;
} else
if(c[i] == ')') {
if(c[j] == '(') continue;
if(fu(c[j])) continue;
fo(k, 1, length) fo(p, 0, 1)
f[o][i][k - 1][0] += f[o - 1][j][k][p], f[o][i][k - 1][0] %= mo;
} else {
if(c[i] != '-' && c[j] == '(') continue;
if(fu(c[j])) continue;
fo(k, 0, length) fo(p, 0, 1)
f[o][i][k][0] += f[o - 1][j][k][p], f[o][i][k][0] %= mo;
}
}
}
int ans = 0;
fo(i, 1, n) {
if(c[i] == '(') continue;
if(fu(c[i])) continue;
fo(p, 0, 1) ans += f[length][i][0][p], ans %= mo;
}
printf("%d", ans);
}