前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >挑战程序竞赛系列(58):4.6树上的分治法(1)

挑战程序竞赛系列(58):4.6树上的分治法(1)

作者头像
用户1147447
发布2019-05-26 09:20:32
3610
发布2019-05-26 09:20:32
举报
文章被收录于专栏:机器学习入门机器学习入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1434608

挑战程序竞赛系列(58):4.6树上的分治法(1)

传送门:POJ 1655: Balancing Act

思路:

选择使得删除该顶点后得到的最大子树的顶点数最少的顶点作为分割顶点。为什么就是最大顶点数的最小呢?

可以这么考虑,如果存在一种极度不平衡的状态,那么我们可以通过移动树的顶点,让它进入下一状态减少不平衡态,这种情况总能在不平衡态时发生。那么最大子树顶点数最小,意味着剩余顶点数最大但比这最大子树小那么一点,嗯哼,当然是最平衡的。

可以证明树的重心每个子孩子的顶点数不会超过 n / 2,比如一个重心带两条边的情况,我们可以认为较大顶点 ≈ 较小顶点数,而总和为n-1,除一除更不会超过 n / 2了。

参考《挑战》P361:

思路就那么一条,提供两种做法。

方法1:

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class Main{

    String INPUT = "./data/judge/201709/P1655.txt";

    public static void main(String[] args) throws IOException {
        new Main().run();
    }

    static final int MAX_N = 20000 + 16;
    static final int INF   = 0x3f3f3f3f;

    class Edge{
        int from;
        int to;

        public Edge(int from, int to) {
            this.from = from; 
            this.to   = to;
        }

        @Override
        public String toString() {
            return from + " " + to;
        }
    }

    List<Edge>[] tree = new ArrayList[MAX_N];
    int N;
    int minv;
    int balance;
    int son[];
    boolean[] visited;


    public void init() {
        visited = new boolean[MAX_N];
        son = new int[MAX_N];
        balance = INF;
        for (int i = 0; i < N; ++i) tree[i] = new ArrayList<Edge>();
    }

    public void dfs(int s) {
        son[s] = 0;
        visited[s] = true;
        int tmp = 0;
        for (Edge e : tree[s]) {
            int v = e.to;
            if (!visited[v]) {
                dfs(v);
                son[s] += son[v] + 1;
                tmp = Math.max(tmp, son[v] + 1);
            }
        }

        tmp = Math.max(tmp, N - 1 - son[s]);
        if (tmp < balance || tmp == balance && s < minv) {
            balance = tmp;
            minv = s;
        }
    }


    public void addEdge(int from, int to) {
        tree[from].add(new Edge(from, to));
        tree[to].add(new Edge(to, from));
    }



    void solve() {
        int T = ni();
        while (T --> 0) {
            N = ni();
            init();
            for (int i = 1; i < N; ++i) {
                int from = ni();
                int to   = ni();
                from --;
                to --;
                addEdge(from, to);
            }

            dfs(0);
            out.println((minv + 1) + " " + balance);
        }
    }

    void solve_problem() {

    }

    FastScanner in;
    PrintWriter out;

    void run() throws IOException {
        boolean oj;
        try {
            oj = ! System.getProperty("user.dir").equals("F:\\java_workspace\\leetcode");
        } catch (Exception e) {
            oj = System.getProperty("ONLINE_JUDGE") != null;
        }

        InputStream is = oj ? System.in : new FileInputStream(new File(INPUT));
        in = new FastScanner(is);
        out = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        out.flush();
        if (!oj){
            System.out.println("[" + (System.currentTimeMillis() - s) + "ms]");
        }
    }

    public boolean more(){
        return in.hasNext();
    }

    public int ni(){
        return in.nextInt();
    }

    public long nl(){
        return in.nextLong();
    }

    public double nd(){
        return in.nextDouble();
    }

    public String ns(){
        return in.nextString();
    }

    public char nc(){
        return in.nextChar();
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        boolean hasNext;

        public FastScanner(InputStream is) throws IOException {
            br = new BufferedReader(new InputStreamReader(is));
            hasNext = true;
        }

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

        String next = null;
        public boolean hasNext(){
            next = nextToken();
            return hasNext;
        }

        public int nextInt() {
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return Integer.parseInt(more);
        }

        public long nextLong() {
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return Long.parseLong(more);
        }

        public double nextDouble() {
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return Double.parseDouble(more);
        }

        public String nextString(){
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return more;
        }

        public char nextChar(){
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return more.charAt(0);
        }
    }

    static class ArrayUtils {

        public static void fill(int[][] f, int value) {
            for (int i = 0; i < f.length; ++i) {
                Arrays.fill(f[i], value);
            }
        }

        public static void fill(int[][][] f, int value) {
            for (int i = 0; i < f.length; ++i) {
                fill(f[i], value);
            }
        }

        public static void fill(int[][][][] f, int value) {
            for (int i = 0; i < f.length; ++i) {
                fill(f[i], value);
            }
        }
    }
}

方法2:

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main{

    String INPUT = "./data/judge/201709/P1655.txt";

    public static void main(String[] args) throws IOException {
        new Main().run();
    }

    static final int MAX_N = 20000 + 16;
    static final int INF   = 0x3f3f3f3f;

    class Edge{
        int to;
        int nxt;
        Edge(){}
        Edge(int to, int nxt){
            this.to = to;
            this.nxt = nxt;
        }
    }

    Edge[] edge = new Edge[2 * MAX_N];
    int[] son;
    int[] head;
    boolean[] visited;

    int tot;
    int N;
    int minv;
    int balance;

    public void init() {
        son = new int[MAX_N];
        head = new int[MAX_N];
        visited = new boolean[MAX_N];
        Arrays.fill(head, -1);
        tot = 0;
        balance = INF;
    }

    public void addEdge(int from, int to) {
        edge[tot] = new Edge(to, head[from]);
        head[from] = tot++;
    }

    void dfs(int cur) {
        int tmp = 0;
        son[cur] = 0;
        visited[cur] = true;
        for (int i = head[cur]; i != -1; i = edge[i].nxt) {
            int v = edge[i].to;
            if (!visited[v]) {
                dfs(v);
                son[cur] += son[v] + 1;
                tmp = Math.max(tmp, son[v] + 1);
            }
        }

        tmp = Math.max(tmp, N - 1 - son[cur]);
        if (tmp < balance || tmp == balance && cur < minv) {
            minv = cur;
            balance = tmp;
        }
    }

    void read() {
        int T = ni();
        while (T --> 0) {
            N = ni();
            init();
            for (int i = 1; i < N; ++i) {
                int from = ni();
                int to   = ni();
                addEdge(from, to);
                addEdge(to, from);
            }

            dfs(1);
            out.println(minv + " " + balance);
        }
    }

    FastScanner in;
    PrintWriter out;

    void run() throws IOException {
        boolean oj;
        try {
            oj = ! System.getProperty("user.dir").equals("F:\\java_workspace\\leetcode");
        } catch (Exception e) {
            oj = System.getProperty("ONLINE_JUDGE") != null;
        }

        InputStream is = oj ? System.in : new FileInputStream(new File(INPUT));
        in = new FastScanner(is);
        out = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        read();
        out.flush();
        if (!oj){
            System.out.println("[" + (System.currentTimeMillis() - s) + "ms]");
        }
    }

    public boolean more(){
        return in.hasNext();
    }

    public int ni(){
        return in.nextInt();
    }

    public long nl(){
        return in.nextLong();
    }

    public double nd(){
        return in.nextDouble();
    }

    public String ns(){
        return in.nextString();
    }

    public char nc(){
        return in.nextChar();
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        boolean hasNext;

        public FastScanner(InputStream is) throws IOException {
            br = new BufferedReader(new InputStreamReader(is));
            hasNext = true;
        }

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

        String next = null;
        public boolean hasNext(){
            next = nextToken();
            return hasNext;
        }

        public int nextInt() {
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return Integer.parseInt(more);
        }

        public long nextLong() {
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return Long.parseLong(more);
        }

        public double nextDouble() {
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return Double.parseDouble(more);
        }

        public String nextString(){
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return more;
        }

        public char nextChar(){
            if (next == null){
                hasNext();
            }
            String more = next;
            next = null;
            return more.charAt(0);
        }
    }

    static class ArrayUtils {

        public static void fill(int[][] f, int value) {
            for (int i = 0; i < f.length; ++i) {
                Arrays.fill(f[i], value);
            }
        }

        public static void fill(int[][][] f, int value) {
            for (int i = 0; i < f.length; ++i) {
                fill(f[i], value);
            }
        }

        public static void fill(int[][][][] f, int value) {
            for (int i = 0; i < f.length; ++i) {
                fill(f[i], value);
            }
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年09月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 挑战程序竞赛系列(58):4.6树上的分治法(1)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档