poj3532 Resistance(高斯消元+基尔霍夫定理)

Resistance
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 1325 Accepted: 430

Description

H.L. is preparing a circuit for the next coming physical experiment. His circuit consists of N nodes, numbered 1 to N, which are connected by wires with certain resistance. H.L is curious about the equivalent resistance between Node 1 and Node N.

Input

The first line contains two positive integers N and M, the number of nodes and wires in the circuit.( N, M ≤ 100)
The next M lines, each describe a wire connection by three integers XYR which indicates that between Node X and Node Y, there is a wire with resistance of R ohm.

Output

The equivalent resistance rounded after the second decimal place.

Sample Input

2 2
1 2 1
1 2 1

Sample Output

0.50

思路:每个点发出的电流和接收的电流相等,根据这个我们可以列n个方程,运用高斯消元法来解。

代码:

#include<iostream>
#include <stdio.h>
#include <string.h>
#include <cmath>
using namespace std;
#define ll long long
const int mod=1000;
const double erp=1e-9;
double a[1010][1010];
double x[1010];
int n,m;
int gauss()
{
    int i,j;
    int maxn;
     for(i=0,j=0;i<n&&j<n;i++,j++)
     {
         maxn=i;
         for(int k=i+1;k<n;k++)
         {
             if(fabs(a[k][j])>fabs(a[maxn][j]))
             {
                 maxn=k;
             }
         }
         if(fabs(a[maxn][j])<erp)return 0;
         if(i!=maxn)
         {
             for(int z=j;z<n;z++)
             {
                 swap(a[i][z],a[maxn][z]);
             }
             swap(x[i],x[maxn]);
         }
         x[i]/=a[i][j];
         for(int z=j+1;z<n;z++)a[i][z]/=a[i][j];
         a[i][j]=1;
         for(int k=0;k<n;k++)
         {
             if(i!=k)
             {
                 x[k]-=x[i]*a[k][i];
                 for(int z=j+1;z<n;z++)
                 {
                     a[k][z]-=a[i][z]*a[k][j];
                 }
                 a[k][j]=0;
             }
         }
     }    
     return 1;
}
int main()
{
    
    while(~scanf("%d%d",&n,&m))
    {
        memset(a,0,sizeof(a));
        for(int i=0;i<m;i++)
        {
            int u,v;
            float r;
            scanf("%d%d%f",&u,&v,&r);
            u--,v--;
            double r1=1.0/r;
            a[u][u]+=r1;
            a[v][v]+=r1;
            a[u][v]-=r1;
            a[v][u]-=r1;
        }
        for(int i=0;i<=n-1;i++)
             x[i]=0;
        x[0]=1;
        for(int i=0;i<n;i++)
             a[n-1][i]=0;
        a[n-1][0]=1;gauss();
        printf("%.2f\n",fabs(x[n-1]));
             
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值