k元环问题,即邻接矩阵的k次幂
用矩阵快速幂加速
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 110
#define inf -1000000000
using namespace std;
int n,m;
struct Matrix{
int d[N][N];
};
Matrix multiply(Matrix a,Matrix b){
Matrix res;
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++){
res.d[i][j]=inf;
for(k=1;k<=n;k++){
if(a.d[i][k] != inf && b.d[k][j] != inf)
res.d[i][j]=max(res.d[i][j],a.d[i][k]+b.d[k][j]);
}
}
return res;
}
Matrix solve(Matrix mp,int k){
int i,j;
Matrix res;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j) res.d[i][j]=0;
else res.d[i][j]=inf;
while(k){
if(k%2){
res=multiply(res,mp);
}
mp=multiply(mp,mp);
k>>=1;
}
return res;
}
int main(){
int i,j,k,t,T;
int u,v,w;
Matrix mp;
scanf("%d",&T);
for(t=1;t<=T;t++){
scanf("%d %d %d",&n,&m,&k);
for(i=1;i<=n;i++) //之前一直WA是这个初始化写在scanf之前了....
for(j=1;j<=n;j++)
mp.d[i][j]=inf;
for(i=1;i<=m;i++){
scanf("%d %d %d",&u,&v,&w);
mp.d[u][v]=max(mp.d[u][v],w);
}
mp=solve(mp,k);
int ans=inf;
for(i=1;i<=n;i++) ans=max(ans,mp.d[i][i]);
if(ans==inf) printf("No solution\n");
else printf("%d\n",ans);
}
return 0;
}