hdu 3976 Electric resistance 高斯消元

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; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值