考虑一个未知点连向两个已知点, 边权为 , 点权为 ,
则现在要做的就是使得 最小,
根据二次函数相关知识可得, 当 时, 上式取得最小值,
推广到多个点, 当 时, 答案最小 .
将所有 未知数 提出, 列出方程, 高斯消元 即可 .
#include<bits/stdc++.h>
#define reg register
int read(){
char c;
int s = 0, flag = 1;
while((c=getchar()) && !isdigit(c))
if(c == '-'){ flag = -1, c = getchar(); break ; }
while(isdigit(c)) s = s*10 + c-'0', c = getchar();
return s * flag;
}
const int maxn = 30005;
const double eps = 1e-12;
int N;
int M;
int cnt;
int num0;
int A[maxn];
int B[maxn];
int Mp[maxn];
int head[maxn];
double C[maxn];
double K[305][305];
struct Edge{ int nxt, to, w; } edge[maxn << 1];
struct EDGE{ int u, v, w; } E[maxn];
void Add(int from, int to, int w){ edge[++ num0] = (Edge){ head[from], to, w }; head[from] = num0; }
void Gays(){
for(reg int i = 1; i <= cnt; i ++){
int max_id = i;
for(reg int j = i+1; j <= cnt; j ++)
if(fabs(K[j][i]) > fabs(K[max_id][i])) max_id = j;
std::swap(K[max_id], K[i]);
for(reg int j = cnt+1; j >= i; j --) K[i][j] /= K[i][i]; // !
for(reg int j = i+1; j <= cnt; j ++){
if(fabs(K[j][i]) < eps) continue ;
for(reg int k = cnt+1; k >= i; k --) K[j][k] -= K[j][i] * K[i][k];
}
}
for(reg int i = cnt; i >= 1; i --){
for(reg int j = cnt; j > i; j --) K[i][cnt+1] -= K[i][j] * K[j][cnt+1];
C[B[i]] = K[i][cnt+1];
}
}
int main(){
N = read(), M = read();
for(reg int i = 1; i <= M; i ++){
int u = read(), v = read(), w = read();
E[i].u = u, E[i].v = v, E[i].w = w;
Add(u, v, w), Add(v, u, w);
}
for(reg int i = 1; i <= N; i ++){
C[i] = A[i] = read();
if(A[i] == -1) B[++ cnt] = i, Mp[i] = cnt;
}
for(reg int i = 1; i <= N; i ++){
if(~A[i]) continue ;
double sum = 0;
for(reg int j = head[i]; j; j = edge[j].nxt){
int to = edge[j].to;
if(to == i) continue ;
sum += edge[j].w;
if(A[to] == -1) K[Mp[i]][Mp[to]] -= edge[j].w;
else K[Mp[i]][cnt+1] += 1ll * edge[j].w * A[to];
}
for(reg int j = 1; j <= cnt+1; j ++) K[Mp[i]][j] /= sum;
K[Mp[i]][Mp[i]] = 1;
}
Gays();
double Ans = 0;
for(reg int i = 1; i <= M; i ++) Ans += 1ll*E[i].w * (C[E[i].u] - C[E[i].v]) * (C[E[i].u] - C[E[i].v]);
printf("%.12lf
", Ans);
return 0;
}