树重构问题

来源:百度知道 编辑:UC知道 时间:2024/05/09 15:23:06
题目如下;请大家用C语言帮解一下,顺便附加点必要解释
算法实验题5.18 树重构问题
.问题描述:
给定一棵有n 个叶结点的树, 叶结点的编号为1,2,…,n。树中每条边的边长均为非
负整数。已知各叶结点对之间的最短路长度m[i][j],1≤i,j≤n。试设计一个算法,根据
m[i][j]给出的信息, 计算树的边长总和。
.实验任务:
对于给定的叶结点对之间的最短路长度,计算树的边长总和。
.数据输入:
由文件input.txt 给出输入数据。文件中有若干组数据。每组数据的第一行有1 个正整数
n,表示给定的树有n 个叶结点,叶结点的编号为1,2,…,n。接下来的n-1 行,给出最
短路长度矩阵m[i][j] 的上三角( 不含对角线)。文件的最后以n=0 结束。
.结果输出:
将计算出的树的边长总和输出到文件output.txt 。
输入文件示例输出文件示例
input.txt output.txt
5 15
5 9 12 8
8 11 7
5 1
4
0
input.txt output.txt
5 15
5 9 12 8
8 11 7
5 1
4
0

有个最小生成树的code:你可以改一下,

#include <cstdio>
#include <cstdlib>

#define MAX 65535

typedef struct
{
bool same;
int m_iPoint;
}Same;

typedef struct Edge //边的数据结构;
{
int m_iPoint1; //边的端点
int m_iPoint2; //边的端点
int key; //边的权值
bool bFind; //标记是否被选中;
} Edge;

//////////////////////////////////////////////////////////////////////////
//数组s用来保存顶点的数值;s【0】中记录数组个数;顶点数组;
//iCount有何作用:记录顶点的数目;
//////////////////////////////////////////////////////////////////////////
void InputData( Edge* lLine, int n, int &iCount ) //初始化数据
{
int Vertex[31];
Vertex[0] = 0;
bool IsSame[2];

for ( int i = 0; i < n ; i++) //利用循环读入数据
{
printf("--------