http://acm.hdu.edu.cn/showproblem.php?pid=3976
题意:给定有N个结点的电路图,编号为1-N,求1号和N号结点之间的等效电阻。
思路:由基尔霍夫定理对每个结点列电流定理(用每个结点的电压),得到N个方程组和N个变量,求解方程组即可,因此就是高斯消元。
代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
const double eps = 1e-8 ;
using namespace std;
int T ,cas ,N,M;
double mat[55][55] ;
double ans[55] ;
void gauss(){
int row, col ;
row = col = 0 ;
for( ;row<N && col<N;row++,col++){
int max_r = row ;
for(int i=row+1;i<N;i++){
if(fabs(mat[max_r][col]) < fabs(mat[i][col]) ) max_r = i ;
}
if(max_r != row){
for(int j=col;j<=N;j++){
swap(mat[row][j] ,mat[max_r][j] );
}
}
for(int i=row+1;i<N;i++){
if(fabs(mat[i][col]) < eps) continue ;
double a = - mat[i][col] / mat[row][col] ;
for(int j=col;j<=N;j++){
mat[i][j] += mat[row][j]*a ;
}
}
}
memset(ans , 0 ,sizeof(ans)) ;
for(int i=row-2;i>=0;i--){
double res = mat[i][N] ;
for(int j=i+1;j<N;j++){
res -= mat[i][j]*ans[j];
}
ans[i] = res / mat[i][i] ;
}
printf("%.2f\n",ans[0]-ans[N-1]);
}
int main(){
scanf("%d",&T);
cas = 0 ;
while(T--){
++cas ;
scanf("%d %d",&N,&M);
memset(mat , 0 ,sizeof(mat));
for(int i=0;i<M;i++){
int a,b, c;
scanf("%d %d %d",&a,&b,&c);
a -- ; b-- ;
mat[a][a] -= 1.0/(c*1.0) ;
mat[b][b] -= 1.0/(c*1.0) ;
mat[a][b] += 1.0/(c*1.0) ;
mat[b][a] += 1.0/(c*1.0) ;
}
mat[0][N] = -1 ;
mat[N-1][N] = 1 ;
printf("Case #%d: ",cas);
gauss() ;
}
return 0;
}