Title Description
Input Format
Output Format
Sample
solution:
Linear Algebra first question
If someone told me to one conclusion: For an adjacency matrix A (only 0,1 elements, there is no representation that path, not with weights),
A n elements A [i] [j] n is to take the steps from i to j number of path
Well, then what power matrix fast
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #define MAXN 1000005 5 #define MAXM 205 6 using namespace std; 7 int n,t,s,e,id[MAXN],tot_num=0; 8 struct matrix{ 9 int dis[MAXM][MAXM]; 10 void clear(){memset(dis,0x3f,sizeof(dis));} 11 void clean(){ 12 memset(dis,0x3f,sizeof(dis)); 13 for(int i=1;i<=tot_num;i++) 14 dis[i][i]=0; 15 } 16 friend matrix operator * (matrix a,matrix b){ 17 matrix c; 18 c.clear(); 19 for(int i=1;i<=tot_num;i++) 20 for(int j=1;j<=tot_num;j++) 21 for(int k=1;k<=tot_num;k++) 22 c.dis[i][j]=min(c.dis[i][j],a.dis[i][k]+b.dis[k][j]); 23 return c; 24 } 25 friend matrix operator ^ (matrix a,int b){ 26 matrix c; 27 c.clean(); 28 while(b){ 29 if(b&1) c=c*a; 30 a=a*a; 31 b>>=1; 32 } 33 return c; 34 } 35 }ans,a; 36 int main(){ 37 scanf("%d%d%d%d",&n,&t,&s,&e); 38 a.clear();ans.clean(); 39 for(int i=1,l,u,v;i<=t;i++){ 40 scanf("%d%d%d",&l,&u,&v); 41 if(!id[u]) id[u]=++tot_num; 42 if(!id[v]) id[v]=++tot_num; 43 u=id[u],v=id[v]; 44 a.dis[u][v]=a.dis[v][u]=min(a.dis[u][v],l); 45 } 46 ans=a^n; 47 printf("%d\n",ans.dis[id[s]][id[e]]); 48 return 0; 49 }