题目描述
树可以用来表示物种之间的进化关系。一棵“进化树”是一个带边权的树,其叶节点表示一个物种,两个叶节点之间的距离表示两个物种的差异。现在,一个重要的问题是,根据物种之间的距离,重构相应的“进化树”。
令N={1..n},用一个N上的矩阵M来定义树T。其中,矩阵M满足:对于任意的i,j,k,有M[i,j] + M[j,k] >= M[i,k]。树T满足:
1.叶节点属于集合N;
2.边权均为非负整数;
3.dT(i,j)=M[i,j],其中dT(i,j)表示树上i到j的最短路径长度。
如下图,矩阵M描述了一棵树。
树的重量是指树上所有边权之和。对于任意给出的合法矩阵M,它所能表示树的重量是惟一确定的,不可能找到两棵不同重量的树,它们都符合矩阵M。你的任务就是,根据给出的矩阵M,计算M所表示树的重量。下图是上面给出的矩阵M所能表示的一棵树,这棵树的总重量为15。
输入格式:
输入数据包含若干组数据。每组数据的第一行是一个整数n(2
输出格式:
对于每组输入,输出一行,一个整数,表示树的重量。
题解
对于这种题目我是毫无想法
看题解然后自己想了下,大概意思是对于每个点i都能从1~j的分支中延伸出来,用类似lca求路径的方法能搞出新增距离,找最小值
(d[1][i]+d[i][j]−d[1][j])/2
还不是很懂:-D
Code
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <numeric>
#include <iomanip>
#include <bitset>
#include <sstream>
#include <fstream>
#define debug puts("-----")
#define rep(i, st, ed) for (int i = st; i <= ed; i += 1)
#define drp(i, st, ed) for (int i = st; i >= ed; i -= 1)
#define fill(x, t) memset(x, t, sizeof(x))
#define min(x, y) x<y?x:y
#define max(x, y) x>y?x:y
#define PI (acos(-1.0))
#define EPS (1e-8)
#define INF (1<<30)
#define ll long long
#define db double
#define ld long double
#define N 61
#define E N * 8 + 1
#define MOD 100000007
#define L 255
using namespace std;
int matrix[N][N];
inline int read(){
int x = 0, v = 1;
char ch = getchar();
while (ch < '0' || ch > '9'){
if (ch == '-'){
v = -1;
}
ch = getchar();
}
while (ch <= '9' && ch >= '0'){
x = (x << 1) + (x << 3) + ch - '0';
ch = getchar();
}
return x * v;
}
int main(void){
while (int n = read()){
rep(i, 1, n){
rep(j, i + 1, n){
matrix[i][j] = matrix[j][i] = read();
}
}
int ans = matrix[1][2];
rep(i, 3, n){
int now = INF;
rep(j, 2, i - 1){
now = min(now, (matrix[1][i] + matrix[i][j] - matrix[1][j]) / 2);
}
ans += now;
}
printf("%d\n", ans);
}
return 0;
}