Rosalind Java|Completing a Tree

“As buds give rise by growth to fresh buds, and these, if vigorous, branch out and overtop on all sides many a feebler branch, so by generation I believe it has been with the great Tree of Life, which fills with its dead and broken branches the crust of the earth, and covers the surface with its ever-branching and beautiful ramifications.” 枝蔓所到之处,万物生生不息。生命之树因而美丽。
——Charles Darwin

Rosalind编程问题之算树。

Completing a Tree

Problem:
An undirected graph is connected if there is a path connecting any two nodes. A tree is a connected (undirected) graph containing no cycles; this definition forces the tree to have a branching structure organized around a central core of nodes, just like its living counterpart. See Figure 2.

We have already grown familiar with trees in “Mendel’s First Law”, where we introduced the probability tree diagram to visualize the outcomes of a random variable.

In the creation of a phylogeny, taxa are encoded by the tree’s leaves, or nodes having degree 1. A node of a tree having degree larger than 1 is called an internal node.
Given: A positive integer n (n≤1000) and an adjacency list corresponding to a graph on n nodes that contains no cycles.
Sample input

10
1 2
2 8
4 10
5 9
6 10
7 9

Return: The minimum number of edges that can be added to the graph to produce a tree.
Sample output

3


在这里插入图片描述
系统发育树是每个生物人挥之不去的梦魇,今天我们就来认识树。树是由节点(nodes)和分枝(edges)组成。节点具有层数(degrees),如果节点只有一个层就叫叶节点(leaves),有多个层就叫做内部节点(internal node)


题目将会给出两个数据:节点数n(数据第一行),和已有的节点连成的分枝。节点之间不考虑循环闭合,即不会出现下图情况(节点4,5,2,3就形成了闭合的环):
在这里插入图片描述

解决这个问题关键在于意识到n个节点生成的树,将会有n-1个分枝。 题目中给出了几个节点的分支,我们只需要统计有几个已有的节点分枝,再用总分枝数n-1减去已有节点数即可。

下面是实现代码:

public class Completing_a_Tree {
    public static void main(String[] args) {
        tree("C:/Users/Administrator/Desktop/rosalind_tree.txt");
    }

    public static void tree(String path) {//返回值类型是新建集合大类,此处是Set而非哈希。
        BufferedReader reader;
        String n = null;
        int count = 0;//创建计数器
        try {
            reader = new BufferedReader(new FileReader(path));
            n = reader.readLine();//读取第一行并保存为节点数
            String line = reader.readLine();//往下读取第二行
            while (line != null) {//行非空则计数器累加
                count = count + 1;//向计数器累加数值
                line = reader.readLine();
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int point = Integer.parseInt(n);//Integer.parseInt转化string类型为int
        System.out.println(point-1-count);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值