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 X, Y, R 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;
}