【BZOJ4894】天赋

【题目链接】

  • 点击打开链接

【思路要点】

  • 矩阵树定理同样可以计算有向图某个点的外向生成树的个数。
  • 具体方法就是认为度数为每个点的入度,删除一号点(树根)所在的行列,然后求行列式。
  • 时间复杂度 O(N3) O ( N 3 )

【代码】


#include

using namespace std;
const int MAXN = 305;
const int P = 1e9 + 7;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); } 
template <typename T> void read(T &x) {
  x = 0; int f = 1;
  char c = getchar();
  for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
  for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
  x *= f;
}
template <typename T> void write(T x) {
  if (x < 0) x = -x, putchar('-');
  if (x > 9) write(x / 10);
  putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
  write(x);
  puts("");
}
int n, a[MAXN][MAXN];
char s[MAXN];
int power(int x, int y) {
  if (y == 0) return 1;
  int tmp = power(x, y / 2);
  if (y % 2 == 0) return 1ll * tmp * tmp % P;
  else return 1ll * tmp * tmp % P * x % P;
}
int solve() {
  int f = 1;
  for (int i = 2; i <= n; i++) {
      for (int j = i; j <= n; j++)
          if (a[j][i]) {
              if (i != j) f = -f;
              swap(a[i], a[j]);
              break;
          }
      if (a[i][i] == 0) return 0;
      int inv = power(a[i][i], P - 2);
      for (int j = i + 1; j <= n; j++) {
          int tmp = 1ll * (P - a[j][i]) * inv % P;
          if (tmp == 0) continue;
          for (int k = i; k <= n; k++)
              a[j][k] = (a[j][k] + 1ll * a[i][k] * tmp) % P;
      }
  }
  int ans = 1;
  for (int i = 2; i <= n; i++)
      ans = 1ll * ans * a[i][i] % P;
  if (f == 1) return ans;
  else return (P - ans) % P;
}
int main() {
  read(n);
  for (int i = 1; i <= n; i++) {
      scanf("\n%s", s + 1);
      for (int j = 1; j <= n; j++) {
          int tmp = s[j] == '1';
          a[j][j] = (a[j][j] + tmp) % P;
          a[i][j] = (a[i][j] + P - tmp) % P;
      }
  }
  printf("%d\n", solve());
  return 0;
}

你可能感兴趣的:(【OJ】BZOJ,【类型】做题记录)