Codeforces Round #362 CDE

復習シリーズ

C

Problem - C - Codeforces

二分木上で、以下の2種類のクエリを処理せよ。

  • u-v 間の最短経路の各辺に w の重みを追加する。
  • u-v 間の最短経路のコストを計算せよ。

解法

木の深さは高々 60 くらいにしかならないので、愚直にやって良い。

コード

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.TreeMap;

/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            pass System Test!
*/

public class C {
  private static class Task {
    class Pair implements Comparable<Pair> {
      long from, to;

      Pair(long from, long to) {
        this.from = from;
        this.to = to;
      }

      @Override
      public int compareTo(Pair o) {
        if (this.from == o.from) return Long.signum(this.to - o.to);
        return Long.signum(this.from - o.from);
      }
    }

    void solve(FastScanner in, PrintWriter out) {
      TreeMap<Pair, Long> weights = new TreeMap<>();

      int Q = in.nextInt();
      for (; Q > 0; Q--) {
        int type = in.nextInt();
        if (type == 1) {
          long u = in.nextLong();
          long v = in.nextLong();
          long w = in.nextLong();
          while (u != v) {
            Pair pair;
            if (u > v) {
              long p = u / 2;
              pair = new Pair(p, u);
              u = p;
            } else {
              long p = v / 2;
              pair = new Pair(p, v);
              v = p;
            }

            Long cost = weights.get(pair);
            if (cost == null)
              weights.put(pair, w);
            else
              weights.put(pair, w + cost);
          }
        } else {
          long u = in.nextLong();
          long v = in.nextLong();
          long ans = 0;
          while (u != v) {
            Pair pair;
            if (u > v) {
              long p = u / 2;
              pair = new Pair(p, u);
              u = p;
            } else {
              long p = v / 2;
              pair = new Pair(p, v);
              v = p;
            }

            Long cost = weights.get(pair);
            if (cost != null) ans += cost;
          }
          out.println(ans);
        }
      }
    }
  }

  /**
   * ここから下はテンプレートです。
   */
  public static void main(String[] args) {
    OutputStream outputStream = System.out;
    FastScanner in = new FastScanner();
    PrintWriter out = new PrintWriter(outputStream);
    Task solver = new Task();
    solver.solve(in, out);
    out.close();
  }
  private static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int bufferLength = 0;

    private boolean hasNextByte() {
      if (ptr < bufferLength) {
        return true;
      } else {
        ptr = 0;
        try {
          bufferLength = in.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (bufferLength <= 0) {
          return false;
        }
      }
      return true;
    }

    private int readByte() {
      if (hasNextByte()) return buffer[ptr++];
      else return -1;
    }

    private static boolean isPrintableChar(int c) {
      return 33 <= c && c <= 126;
    }

    private void skipUnprintable() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
    }

    boolean hasNext() {
      skipUnprintable();
      return hasNextByte();
    }

    public String next() {
      if (!hasNext()) throw new NoSuchElementException();
      StringBuilder sb = new StringBuilder();
      int b = readByte();
      while (isPrintableChar(b)) {
        sb.appendCodePoint(b);
        b = readByte();
      }
      return sb.toString();
    }

    long nextLong() {
      if (!hasNext()) throw new NoSuchElementException();
      long n = 0;
      boolean minus = false;
      int b = readByte();
      if (b == '-') {
        minus = true;
        b = readByte();
      }
      if (b < '0' || '9' < b) {
        throw new NumberFormatException();
      }
      while (true) {
        if ('0' <= b && b <= '9') {
          n *= 10;
          n += b - '0';
        } else if (b == -1 || !isPrintableChar(b)) {
          return minus ? -n : n;
        } else {
          throw new NumberFormatException();
        }
        b = readByte();
      }
    }

    double nextDouble() {
      return Double.parseDouble(next());
    }

    double[] nextDoubleArray(int n) {
      double[] array = new double[n];
      for (int i = 0; i < n; i++) {
        array[i] = nextDouble();
      }
      return array;
    }

    double[][] nextDoubleMap(int n, int m) {
      double[][] map = new double[n][];
      for (int i = 0; i < n; i++) {
        map[i] = nextDoubleArray(m);
      }
      return map;
    }

    public int nextInt() {
      return (int) nextLong();
    }

    public int[] nextIntArray(int n) {
      int[] array = new int[n];
      for (int i = 0; i < n; i++) array[i] = nextInt();
      return array;
    }

    public long[] nextLongArray(int n) {
      long[] array = new long[n];
      for (int i = 0; i < n; i++) array[i] = nextLong();
      return array;
    }

    public String[] nextStringArray(int n) {
      String[] array = new String[n];
      for (int i = 0; i < n; i++) array[i] = next();
      return array;
    }

    public char[][] nextCharMap(int n) {
      char[][] array = new char[n][];
      for (int i = 0; i < n; i++) array[i] = next().toCharArray();
      return array;
    }
  }
}

D

Problem - D - Codeforces

深さ優先探索した時に各頂点について、その頂点を探索する順番の期待値を求めよ。

解法

頂点 p の子 v, u について、v が u の後に探索される確率は 1/2 である。
よって v の順番の期待値は、以下の式で表せる。

[p の期待値] + [v 以外の p の子を根とする部分木のサイズ] /2 + 1.0

コード

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.NoSuchElementException;

/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            pass System Test!
*/

public class D {
  private static class Task {
    int[] children;
    double[] answer;
    ArrayList<Integer>[] tree;

    int childrenDfs(int v, int p) {
      if (children[v] >= 0) return children[v];
      int ret = 1;
      for (int u : tree[v]) {
        if (u == p) continue;
        ret += childrenDfs(u, v);
      }
      children[v] = ret;
      return ret;
    }

    void solveDfs(int v, int p) {
      if (answer[v] == 0) {
        double sibling = children[p] - 1 - children[v];
        sibling /= 2.0;
        answer[v] = answer[p] + 1.0 + sibling;
      }
      for (int u : tree[v]) {
        if (u == p) continue;
        solveDfs(u, v);
      }
    }

    void solve(FastScanner in, PrintWriter out) {
      int N = in.nextInt();
      tree = new ArrayList[N];
      for (int i = 0; i < N; i++) {
        tree[i] = new ArrayList<>();
      }
      for (int i = 0; i < N - 1; i++) {
        int p = in.nextInt() - 1;
        tree[p].add(i + 1);
      }
      children = new int[N];
      Arrays.fill(children, -1);
      childrenDfs(0, -1);

      answer = new double[N];
      answer[0] = 1.0;
      solveDfs(0, -1);

      for (double p : answer) {
        out.print(p + " ");
      }
      out.println();
    }
  }

  /**
   * ここから下はテンプレートです。
   */
  public static void main(String[] args) {
    OutputStream outputStream = System.out;
    FastScanner in = new FastScanner();
    PrintWriter out = new PrintWriter(outputStream);
    Task solver = new Task();
    solver.solve(in, out);
    out.close();
  }
  private static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int bufferLength = 0;

    private boolean hasNextByte() {
      if (ptr < bufferLength) {
        return true;
      } else {
        ptr = 0;
        try {
          bufferLength = in.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (bufferLength <= 0) {
          return false;
        }
      }
      return true;
    }

    private int readByte() {
      if (hasNextByte()) return buffer[ptr++];
      else return -1;
    }

    private static boolean isPrintableChar(int c) {
      return 33 <= c && c <= 126;
    }

    private void skipUnprintable() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
    }

    boolean hasNext() {
      skipUnprintable();
      return hasNextByte();
    }

    public String next() {
      if (!hasNext()) throw new NoSuchElementException();
      StringBuilder sb = new StringBuilder();
      int b = readByte();
      while (isPrintableChar(b)) {
        sb.appendCodePoint(b);
        b = readByte();
      }
      return sb.toString();
    }

    long nextLong() {
      if (!hasNext()) throw new NoSuchElementException();
      long n = 0;
      boolean minus = false;
      int b = readByte();
      if (b == '-') {
        minus = true;
        b = readByte();
      }
      if (b < '0' || '9' < b) {
        throw new NumberFormatException();
      }
      while (true) {
        if ('0' <= b && b <= '9') {
          n *= 10;
          n += b - '0';
        } else if (b == -1 || !isPrintableChar(b)) {
          return minus ? -n : n;
        } else {
          throw new NumberFormatException();
        }
        b = readByte();
      }
    }

    double nextDouble() {
      return Double.parseDouble(next());
    }

    double[] nextDoubleArray(int n) {
      double[] array = new double[n];
      for (int i = 0; i < n; i++) {
        array[i] = nextDouble();
      }
      return array;
    }

    double[][] nextDoubleMap(int n, int m) {
      double[][] map = new double[n][];
      for (int i = 0; i < n; i++) {
        map[i] = nextDoubleArray(m);
      }
      return map;
    }

    public int nextInt() {
      return (int) nextLong();
    }

    public int[] nextIntArray(int n) {
      int[] array = new int[n];
      for (int i = 0; i < n; i++) array[i] = nextInt();
      return array;
    }

    public long[] nextLongArray(int n) {
      long[] array = new long[n];
      for (int i = 0; i < n; i++) array[i] = nextLong();
      return array;
    }

    public String[] nextStringArray(int n) {
      String[] array = new String[n];
      for (int i = 0; i < n; i++) array[i] = next();
      return array;
    }

    public char[][] nextCharMap(int n) {
      char[][] array = new char[n][];
      for (int i = 0; i < n; i++) array[i] = next().toCharArray();
      return array;
    }
  }
}

E

Problem - E - Codeforces

3 つのカップを1列に並べる。最初、中央のカップにコインが入っている。「左右のどちらかのカップをランダムに選んで中央のカップと入れ替える」という操作を n 回行った後、中央にコインが入っている確率を求めよ。

解法

k 回目の操作のあと中央のカップにコインが入っている確率を p_k とする。

 a_0=1
 a_1=0
 a_{k+1}=(a_k+a_{k-1})/2

という漸化式が成り立つから、
https://www.wolframalpha.com/input/?i=a(n%2B1)%3D(a(n-1)%2Ba(n))%2F2,+a(0)%3D1,+a(1)%3D0 より、

   a_n = \frac{1}{3} \frac{2^n +2(-1)^n}{2^n}

であることが分かる。あとはこれを計算すれば良い。

Java には modInverse や modPow など計算に必要なライブラリが標準で含まれている。

コード

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.NoSuchElementException;

/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            pass System Test!
*/

public class E {
  private static class Task {
    BigInteger MOD = BigInteger.valueOf((int) 1e9 + 7);

    void solve(FastScanner in, PrintWriter out) {
      int N = in.nextInt();
      long[] a = new long[N];
      boolean allOne = true;
      boolean allOdd = true;
      for (int i = 0; i < N; i++) {
        a[i] = in.nextLong();
        if (a[i] % 2 == 0) allOdd = false;
        if (a[i] != 1) allOne = false;
      }

      if (allOne) {
        out.println("0/1");
        return;
      }

      //2^n
      BigInteger denominator = BigInteger.valueOf(2);
      for (long e : a) {
        denominator = denominator.modPow(BigInteger.valueOf(e), MOD);
      }

      BigInteger numerator = denominator;
      if (allOdd) {
        numerator = numerator.add(MOD);
        numerator = numerator.subtract(BigInteger.valueOf(2));
        numerator = numerator.mod(MOD);
      } else {
        numerator = numerator.add(BigInteger.valueOf(2));
        numerator = numerator.mod(MOD);
      }
      BigInteger invTwo = BigInteger.valueOf(2);
      invTwo = invTwo.modInverse(MOD);
      denominator = denominator.multiply(invTwo);
      numerator = numerator.multiply(invTwo);

      BigInteger invThree = BigInteger.valueOf(3);
      invThree = invThree.modInverse(MOD);
      numerator = numerator.multiply(invThree);

      numerator = numerator.mod(MOD);
      denominator = denominator.mod(MOD);
      out.println(numerator.toString() + "/" + denominator.toString());

    }
  }

  /**
   * ここから下はテンプレートです。
   */
  public static void main(String[] args) {
    OutputStream outputStream = System.out;
    FastScanner in = new FastScanner();
    PrintWriter out = new PrintWriter(outputStream);
    Task solver = new Task();
    solver.solve(in, out);
    out.close();
  }
  private static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int bufferLength = 0;

    private boolean hasNextByte() {
      if (ptr < bufferLength) {
        return true;
      } else {
        ptr = 0;
        try {
          bufferLength = in.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (bufferLength <= 0) {
          return false;
        }
      }
      return true;
    }

    private int readByte() {
      if (hasNextByte()) return buffer[ptr++];
      else return -1;
    }

    private static boolean isPrintableChar(int c) {
      return 33 <= c && c <= 126;
    }

    private void skipUnprintable() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
    }

    boolean hasNext() {
      skipUnprintable();
      return hasNextByte();
    }

    public String next() {
      if (!hasNext()) throw new NoSuchElementException();
      StringBuilder sb = new StringBuilder();
      int b = readByte();
      while (isPrintableChar(b)) {
        sb.appendCodePoint(b);
        b = readByte();
      }
      return sb.toString();
    }

    long nextLong() {
      if (!hasNext()) throw new NoSuchElementException();
      long n = 0;
      boolean minus = false;
      int b = readByte();
      if (b == '-') {
        minus = true;
        b = readByte();
      }
      if (b < '0' || '9' < b) {
        throw new NumberFormatException();
      }
      while (true) {
        if ('0' <= b && b <= '9') {
          n *= 10;
          n += b - '0';
        } else if (b == -1 || !isPrintableChar(b)) {
          return minus ? -n : n;
        } else {
          throw new NumberFormatException();
        }
        b = readByte();
      }
    }

    double nextDouble() {
      return Double.parseDouble(next());
    }

    double[] nextDoubleArray(int n) {
      double[] array = new double[n];
      for (int i = 0; i < n; i++) {
        array[i] = nextDouble();
      }
      return array;
    }

    double[][] nextDoubleMap(int n, int m) {
      double[][] map = new double[n][];
      for (int i = 0; i < n; i++) {
        map[i] = nextDoubleArray(m);
      }
      return map;
    }

    public int nextInt() {
      return (int) nextLong();
    }

    public int[] nextIntArray(int n) {
      int[] array = new int[n];
      for (int i = 0; i < n; i++) array[i] = nextInt();
      return array;
    }

    public long[] nextLongArray(int n) {
      long[] array = new long[n];
      for (int i = 0; i < n; i++) array[i] = nextLong();
      return array;
    }

    public String[] nextStringArray(int n) {
      String[] array = new String[n];
      for (int i = 0; i < n; i++) array[i] = next();
      return array;
    }

    public char[][] nextCharMap(int n) {
      char[][] array = new char[n][];
      for (int i = 0; i < n; i++) array[i] = next().toCharArray();
      return array;
    }
  }
}