読者です 読者をやめる 読者になる 読者になる

Codeforces Round #363 (Div. 2) DE

競技プログラミング Codeforces

復習シリーズ

D. Fix a Tree

Problem - D - Codeforces

N 頂点の有向グラフがあり、頂点 i から頂点 a[i] に向かう辺があります。できるだけ少ない辺を張り替えてある1つの頂点に向かう有向木にしてください。

解法

連結成分内に閉路が含まれているとき、閉路は必ず先端にあるので、この内一つを終点に張り替えれば良いです。

コード

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;

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

public class D2 {
  private static class Task {
    void solve(FastScanner in, PrintWriter out) throws Exception {
      int N = in.nextInt();
      int[] parent = new int[N];
      for (int i = 0; i < N; i++) {
        parent[i] = in.nextInt() - 1;
      }

      ArrayList<ArrayList<Integer>> G = new ArrayList<>();
      for (int i = 0; i < N; i++) G.add(new ArrayList<>());
      for (int i = 0; i < N; i++) {
        G.get(parent[i]).add(i);
      }

      int[] d = decompose(G);

      for (int i = 0; i < N; i++) {
        G.get(i).add(parent[i]);
      }

      ArrayList<ArrayList<Integer>> cycles = new ArrayList<>();
      boolean[] vis = new boolean[N];
      ArrayDeque<Integer> deque = new ArrayDeque<>();
      for (int i = 0; i < N; i++) {
        if (vis[i]) continue;
        ArrayList<Integer> cycle = new ArrayList<>();
        deque.add(i);
        vis[i] = true;
        cycle.add(i);
        while (!deque.isEmpty()) {
          int v = deque.poll();
          for (int w : G.get(v)) {
            if (vis[w]) continue;
            vis[w] = true;
            deque.add(w);
            if (d[cycle.get(0)] < d[w]) continue;
            if (d[cycle.get(0)] > d[w]) cycle.clear();
            cycle.add(w);
          }
        }
        cycles.add(cycle);
      }

      int single = -1;
      for (ArrayList<Integer> cycle : cycles) if (cycle.size() == 1) single = cycle.get(0);
      if (single == -1) single = cycles.get(0).get(0);

      int cost = 0;
      for (ArrayList<Integer> cycle : cycles) {
        int v = cycle.get(0);
        if (parent[v] != single) cost++;
        parent[v] = single;
      }

      out.println(cost);
      for (int i = 0; i < N; i++) {
        if (i > 0) out.print(" ");
        out.print(parent[i] + 1);
      }

    }

    public int[] decompose(ArrayList<ArrayList<Integer>> G) {
      ArrayList<Integer> vs = new ArrayList<>();
      int V = G.size();
      int[] cmp = new int[V];

      ArrayList<ArrayList<Integer>> rG = new ArrayList<>(V);
      for (int i = 0; i < V; i++) rG.add(new ArrayList<Integer>());
      for (int i = 0; i < V; i++) for (int v : G.get(i)) rG.get(v).add(i);
      boolean[] used = new boolean[V];

      ArrayDeque<Integer> stack = new ArrayDeque<>();
      boolean[] added = new boolean[V];
      for (int i = 0; i < V; i++)
        if (!used[i]) {
          stack.addFirst(i);
          while (!stack.isEmpty()) {
            int v = stack.peekFirst();
            used[v] = true;
            boolean pushed = false;
            for (int j = G.get(v).size() - 1; j >= 0; j--) {
              int u = G.get(v).get(j);
              if (!used[u]) {
                stack.addFirst(u);
                pushed = true;
              }
            }
            if (!pushed) {
              stack.pollFirst();
              if (!added[v]) {
                vs.add(v);
                added[v] = true;
              }
            }
          }
        }

      used = new boolean[V];
      int k = 0;
      Collections.reverse(vs);
      for (int i : vs)
        if (!used[i]) {
          stack.push(i);
          used[i] = true;
          cmp[i] = k;
          while (!stack.isEmpty()) {
            int v = stack.peek();
            boolean pushed = false;
            for (int u : rG.get(v))
              if (!used[u]) {
                used[u] = true;
                cmp[u] = k;
                stack.push(u);
                pushed = true;
              }
            if (!pushed) stack.pop();
          }
          k++;
        }
      return cmp;
    }

  }

  /**
   * ここから下はテンプレートです。
   */
  public static void main(String[] args) throws Exception {
    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;
    }

    public int[][] nextIntMap(int n, int m) {
      int[][] map = new int[n][];
      for (int i = 0; i < n; i++) {
        map[i] = nextIntArray(m);
      }
      return map;
    }
  }
}

E. LRU

Problem - E - Codeforces

サイズ K のメモリと、N 個の要素があります。最初はメモリは空で、要素を選択してメモリに加える操作を行います。要素 i が選択される確率は p[i] です。メモリに K 個の要素が含まれていて、K+1個目が選択されたとき、メモリ内の最も古く選択された要素が削除されます。操作を無限に行ったとき、要素 i がメモリに含まれている確率を求めてください。

解法

コード

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

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

public class E2 {
  private static class Task {
    double[] solve(double[] p, int K) {
      int N = p.length;
      double[] dp = new double[1 << N];
      dp[0] = 1.0;
      for (int mask = 0; mask < (1 << N); mask++) {
        double remain = 0.0;
        for (int i = 0; i < N; i++) {
          if ((mask & (1 << i)) != 0) continue;
          remain += p[i];
        }
        for (int i = 0; i < N; i++) {
          if ((mask & (1 << i)) != 0) continue;
          int next = mask + (1 << i);
          if (Integer.bitCount(next) > K) continue;
          dp[next] += dp[mask] * (p[i] / remain);
        }
      }

      double[] ans = new double[N];
      for (int mask = 0; mask < (1 << N); mask++) {
        if (Integer.bitCount(mask) != K) continue;
        for (int i = 0; i < N; i++) {
          if ((mask & (1 << i)) != 0) {
            ans[i] += dp[mask];
          }
        }
      }
      return ans;
    }

    void solve(FastScanner in, PrintWriter out) throws Exception {
      int N = in.nextInt();
      int K = in.nextInt();
      double[] p = in.nextDoubleArray(N);
      int zero = 0;
      for (double q : p) if (q == 0.0) zero++;
      double[] q = new double[N - zero];
      int cur = 0;
      for (int i = 0; i < N; i++) {
        if (p[i] != 0.0) {
          q[cur] = p[i];
          cur++;
        }
      }

      double[] ans = solve(q, Math.min(K, q.length));
      cur = 0;
      for (int i = 0; i < N; i++) {
        if (i > 0) out.print(" ");
        if (p[i] == 0.0) {
          out.print(0.0);
        } else {
          out.print(ans[cur]);
          cur++;
        }
      }
    }
  }

  /**
   * ここから下はテンプレートです。
   */
  public static void main(String[] args) throws Exception {
    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;
    }

    public int[][] nextIntMap(int n, int m) {
      int[][] map = new int[n][];
      for (int i = 0; i < n; i++) {
        map[i] = nextIntArray(m);
      }
      return map;
    }
  }
}