版权声明:xgc原创文章,未经允许不得转载。 https://blog.csdn.net/xgc_woker/article/details/82916743
Description
给你n个点,给一张邻接矩阵表示点与点的关系,若a[i][j]=1,则表示i和j有边相连,要求不允许存在两条边(i,j),(x,y)满足i < x < j < y,问有多少种方案。
Sample Input
3
0 0 1
0 0 1
1 1 0
Sample Output
1
计数题啊。。。
首先考虑区间DP。
设f[i][j]为i到j有边相连,i和j之间的边都连好了的方案数。
设g[i][j]为i到j没有边相连,i和j之间的边都连好了的方案数。
对于每一个l,r枚举断点,对于f的转移:
对于g的转移:
然后统计f[1][n]和g[1][n]即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const LL mod = 1e9 + 7;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
int s = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * f;
}
int a[510][510];
LL f[510][510], g[510][510];
int main() {
int n = read();
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) a[i][j] = read();
for(int i = 1; i <= n; i++) f[i][i] = 1;
for(int len = 2; len <= n; len++) {
for(int l = 1; l <= n - len + 1; l++) {
int r = l + len - 1;
if(a[l][r]) {
for(int k = l; k < r; k++) (f[l][r] += (f[l][k] + g[l][k]) * (g[k + 1][r] + f[k + 1][r]) % mod) %= mod;
} for(int k = l + 1; k < r; k++) if(a[l][k]){
(g[l][r] += f[l][k] * (f[k][r] + g[k][r])) %= mod;
}
}
} LL ans = f[1][n];
(ans += g[1][n]) %= mod;
printf("%lld\n", ans);
return 0;
}