关闭

[线代小记] 树形图求和

218人阅读 评论(0) 收藏 举报
分类:

未经允许搬了过来

这里写图片描述

代码略丑

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;

inline char nc(){
  static char buf[100000],*p1=buf,*p2=buf;
  return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline void read(int &x){
  char c=nc(),b=1;
  for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
  for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=305;
const int M=100005;
const int P=1e9+7;

inline ll Pow(ll a,int b){
  ll ret=1;
  for (;b;b>>=1,a=a*a%P)
    if (b&1)
      ret=ret*a%P;
  return ret;
}
inline ll Inv(ll a){
  return Pow(a,P-2);
}

int n,m,u[M],v[M],w[M];
ll a[N][N<<1],b[N][N],cof[N][N],c[N][N];

inline void add(int u,int v){
  (b[v][u]+=P-1)%=P; (b[u][u]+=1)%=P;
}

inline ll Gauss(int n){
  for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) a[i][j]=b[i][j];
  for (int i=1;i<=n;i++) a[i][n+i]=1;
  int f=0;
  for (int i=1;i<=n;i++){
    int k=0;
    for (int j=i;j<=n;j++) if (a[j][i]) { k=j; break; }
    if (k==0) return 0;
    if (k^i) { for (int j=1;j<=n+n;j++) swap(a[i][j],a[k][j]); f^=1; }
    ll inv=Inv(a[i][i]);
    for (int j=1;j<=n;j++){
      if (j==i) continue;
      ll t=(ll)a[j][i]*inv%P;
      for (int k=i;k<=n+n;k++)
    (a[j][k]+=P-t*a[i][k]%P)%=P;
    }
    for (int j=1;j<=n+n;j++) a[i][j]=a[i][j]*inv%P;
  }
  return 1;
}

inline ll det(int n){
  for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) c[i][j]=b[i][j];
  int f=0;
  for (int i=1;i<=n;i++){
    int k=0;
    for (int j=i;j<=n;j++) if (c[j][i]) { k=j; break; }
    if (k==0) return 0;
    if (k^i) { for (int j=1;j<=n;j++) swap(c[i][j],c[k][j]); f^=1; }
    for (int j=i+1;j<=n;j++){
      ll t=(ll)c[j][i]*Inv(c[i][i])%P;
      for (int k=i;k<=n;k++)
    (c[j][k]+=P-t*c[i][k]%P)%=P;
    }
  }
  ll ret=1;
  for (int i=1;i<=n;i++) ret=ret*c[i][i]%P;
  return f?(P-ret)%P:ret;
}

int main(){
  freopen("calc.in","r",stdin);
  freopen("calc.out","w",stdout);
  read(n); read(m);
  for (int i=1;i<=m;i++)
    read(u[i]),read(v[i]),read(w[i]),add(u[i],v[i]);
  ll tot=det(n-1);
  if (!tot) return printf("0\n"),0;
  Gauss(n-1); ll ans=0;
  for (int i=1;i<n;i++) for (int j=1;j<n;j++) cof[j][i]=tot*a[i][n-1+j]%P;
  for (int i=1;i<=m;i++){
    if (u[i]==n) continue;
    ll t=tot;
    (t+=P-b[v[i]][u[i]]*cof[v[i]][u[i]])%=P;
    (t+=P-b[u[i]][u[i]]*cof[u[i]][u[i]])%=P;
    (b[v[i]][u[i]]+=1)%=P; (b[u[i]][u[i]]+=P-1)%=P;
    (t+=b[v[i]][u[i]]*cof[v[i]][u[i]])%=P;
    (t+=b[u[i]][u[i]]*cof[u[i]][u[i]])%=P;
    ans+=(tot+P-t)*w[i]%P;
    add(u[i],v[i]);
  }
  printf("%lld\n",ans%P);
  return 0;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:308754次
    • 积分:12395
    • 等级:
    • 排名:第1311名
    • 原创:969篇
    • 转载:3篇
    • 译文:0篇
    • 评论:54条
    最新评论