普及练习场 树形数据结构 FBI树

题目链接

题意理解

这条题目是这样的:

全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串。

如果一个节点的字符串满足这样的性质,那么它的值就是FBI中的一个。然后需要将这个节点的字符串对半分去构建子树。

代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Node {
    String value;
    char type;
    public char getType() {
        int zero = 0;
        int one = 0;
        for(int i = 0; i < value.length(); i++) {
            if(value.charAt(i) == '0') {
                zero++;
            } else {
                one++;
            }
        }
        if(zero > 0 && 0 == one) {
            return 'B';
        } else if(0 == zero && one > 0){
            return 'I';
        } else {
            return 'F';
        }
    }
    Node left;
    Node right;
    public Node(String value) {
        this.value = value;
        this.type = getType();
        int len = value.length();
        if(len > 1) {
            String leftValue = value.substring(0, len / 2);
            String rightValue = value.substring(len / 2);
            Node lc = new Node(leftValue);
            Node rc = new Node(rightValue);
            this.left = lc;
            this.right = rc;
        }
    }

    public void print() {
        if(left != null) {
            left.print();
            right.print();
        }
        System.out.print(this.type);
    }
}
public class Main {
    public static class FastScanner {
        private BufferedReader br;
        private StringTokenizer st;

        public FastScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public String nextToken() {
            while(null == st || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.valueOf(nextToken());
        }
    }
    static int N;
    static String input;
    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        N = fs.nextInt();
        input = fs.nextToken();
        Node node = new Node(input);
        node.print();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值