NC52847. Determinant
描述
输入描述
The input contains zero or more test cases and is terminated by end-of-file. For each test case:
The first line contains an integer n.
The i-th of following n lines contains n integers.
*
*
* The sum of n does not exceed 5000.
输出描述
For each case, output n rows where the i-th row contains n integersmodulo
.
示例1
输入:
2 0 1 0 1000000006
输出:
1000000006 0 1 0
C++14(g++5.4) 解法, 执行用时: 1209ms, 内存消耗: 8804K, 提交时间: 2019-10-05 17:20:34
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 5e2 + 5; const int mod = 1e9 + 7; const long double pi = acos(-1.0); ll qpow(ll n,ll m) { ll res=1; while(m) { if(m&1) res=res*n%mod; n=n*n%mod; m>>=1; } return res; } ll a[N][N],b[N][N]; ll gauss(int n) { for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { b[i][j]=(i==j); } } int max_r; ll temp=1; for(int k=0; k<n; k++) { max_r=k; for(int i=k; i<n; i++) { if(a[i][k]) max_r=i; } if(k!=max_r) { temp*=-1; for(int j=0; j<n; j++) { swap(a[k][j],a[max_r][j]); swap(b[k][j],b[max_r][j]); } } temp=temp*a[k][k]%mod; // cout<<temp<<endl; ll inv=qpow(a[k][k],mod-2); for(int j=0; j<n; j++) { a[k][j]=a[k][j]*inv%mod; b[k][j]=b[k][j]*inv%mod; } for(int i=0; i<n; i++) { if(i!=k) { ll tep=a[i][k]; for(int j=0; j<n; j++) { a[i][j]=(a[i][j]-a[k][j]*tep%mod+mod)%mod; b[i][j]=(b[i][j]-b[k][j]*tep%mod+mod)%mod; } } } } return (temp+mod)%mod; } int main() { srand(time(0)); int n; while(~scanf("%d",&n)) { for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { scanf("%lld",&a[i][j]); } } for(int i=0; i<n; i++) a[0][i]=1; ll temp=gauss(n); // cout<<temp<<endl; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if((i+j)%2==0) { printf("%lld",b[j][0]*temp%mod); } else { printf("%lld",(mod-b[j][0]*temp%mod)%mod); } if(j!=n-1) printf(" "); else printf("\n"); } } } return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 1340ms, 内存消耗: 13460K, 提交时间: 2019-10-09 16:22:15
#include<bits/stdc++.h> #define debug printf("!"); using namespace std; typedef long long ll; const int mod=1e9+7; const int N=505; ll inv(ll x){return x==1?x:(mod-mod/x)*inv(mod%x)%mod;} ll a[N][N],b[N][N]; int n; ll Gauss(ll a[N][N],ll b[N][N]) { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) b[i][j]=i==j; ll det=1; for(int i=1;i<=n;i++) { int p=i; while(p<n&&!a[p][i]) p++; swap(a[i],a[p]);swap(b[i],b[p]); if(i!=p) det*=-1; det=det*a[i][i]%mod; ll t=inv(a[i][i]); for(int j=1;j<=n;j++) a[i][j]=a[i][j]*t%mod,b[i][j]=b[i][j]*t%mod; for(int j=1;j<=n;j++) { if(i==j) continue; t=a[j][i]; for(int k=1;k<=n;k++) { a[j][k]=(a[j][k]-a[i][k]*t%mod+mod)%mod; b[j][k]=(b[j][k]-b[i][k]*t%mod+mod)%mod; } } } return (det+mod)%mod; } int main() { while(~scanf("%d",&n)) { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&a[i][j]); for(int i=1;i<=n;i++) a[1][i]=rand()%mod; ll det=Gauss(a,b); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) printf(j==n?"%lld\n":"%lld ",(i+j+1)&1?b[j][1]*det%mod:(mod-b[j][1])*det%mod); } }