CS Academy Round #34 Point in Kgon

解法

これを見ました。
http://kmjp.hatenablog.jp/entry/2017/06/23/0930


コード

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

public class Main {

  private final int MOD = (int) (1e9 + 7);
  private final Combination combination = new Combination(400001, MOD);

  private void solve(FastScanner in, PrintWriter out) {
    int N = in.nextInt();
    int K = in.nextInt();
    long[] X = new long[N * 2];
    long[] Y = new long[N * 2];
    for (int i = 0; i < N; i++) {
      X[i] = in.nextInt();
      Y[i] = in.nextInt();
    }

    int px = in.nextInt();
    int py = in.nextInt();
    for (int i = 0; i < N; i++) {
      X[i] -= px;
      Y[i] -= py;
      X[i + N] = X[i];
      Y[i + N] = Y[i];
    }

    long ans = combination.get(N, K);
    int right = 0;
    for (int left = 0; left < N; left++) {
      right = Math.max(right, left + 1);
      while (right < left + N && X[left] * Y[right] - Y[left] * X[right] >= 0) {
        right++;
      }
      ans += MOD - combination.get(right - left - 1, K - 1);
      ans %= MOD;
    }

    out.println(ans % MOD);
  }

  class Combination {

    private long[] fact;
    private long[] invFact;
    private int MOD;

    public Combination(int max, int MOD) {
      this.MOD = MOD;
      long[] inv = new long[max + 1];
      fact = new long[max + 1];
      invFact = new long[max + 1];
      inv[1] = 1;
      for (int i = 2; i <= max; i++) {
        inv[i] = inv[MOD % i] * (MOD - MOD / i) % MOD;
      }
      fact[0] = invFact[0] = 1;
      for (int i = 1; i <= max; i++) {
        fact[i] = fact[i - 1] * i % MOD;
      }
      for (int i = 1; i <= max; i++) {
        invFact[i] = invFact[i - 1] * inv[i] % MOD;
      }
    }

    public long get(int x, int y) {
      if (x < y || y < 0) {
        return 0;
      }
      return fact[x] * invFact[y] % MOD * invFact[x - y] % MOD;
    }
  }

  public static void main(String[] args) {
    PrintWriter out = new PrintWriter(System.out);
    new Main().solve(new FastScanner(), 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;
    }
  }
}

CS Academy Round #36 BBox Count

コード

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.NoSuchElementException;

public class Main {

  private static final int MAX = 2500;

  // 直線と直線の隙間にある点で作ることが出来る組合せを計算する
  private long intervalCount(ArrayList<Integer> lines, FenwickTree bit) {
    long ans = 0;
    for (int i = -1; i < lines.size(); i++) {
      int x1 = i >= 0 ? lines.get(i) + 1 : 0;
      int x2 = i + 1 < lines.size() ? lines.get(i + 1) : MAX;

      // lines[i] を下辺としたときの上辺の数
      // (lines.get(i), x2)
      if (x2 - x1 >= 2) {
        // (lines.get(i), lines.get(i+1)) の区間の点を選ぶ組み合わせの数
        long k = bit.sum(x1, x2);
        ans += k * (k - 1) / 2;
      }
    }
    return ans;
  }

  private void solve(FastScanner in, PrintWriter out) {
    int N = in.nextInt();
    ArrayList<Integer>[] xs = new ArrayList[MAX];
    for (int i = 0; i < MAX; i++) {
      xs[i] = new ArrayList<>();
    }
    for (int i = 0; i < N; i++) {
      int y = in.nextInt() - 1;
      int x = in.nextInt() - 1;
      xs[y].add(x);
    }

    for (ArrayList<Integer> list : xs) {
      Collections.sort(list);
    }

    long ans = 0;
    for (int left = 0; left < MAX; left++) {
      if (xs[left].isEmpty()) {
        continue;
      }
      boolean[] added = new boolean[MAX];
      FenwickTree bit = new FenwickTree(MAX);
      int addedCount = 0;
      for (int right = left; right < MAX; right++) {
        if (xs[right].isEmpty()) {
          continue;
        }

        for (int x : xs[right]) {
          if (!added[x]) {
            added[x] = true;
            bit.add(x, 1);
            addedCount++;
          }
        }

        if (right == left) {
          continue;
        }

        // xs[right] と xs[left] をマージしてソートしたリストを作る
        ArrayList<Integer> merged = new ArrayList<>(xs[left].size() + xs[right].size());
        for (int i = 0, j = 0; i < xs[left].size() || j < xs[right].size(); ) {
          int leftTop = i < xs[left].size() ? xs[left].get(i) : MAX;
          int rightTop = j < xs[right].size() ? xs[right].get(j) : MAX;

          if (leftTop == rightTop) {
            merged.add(leftTop);
            i++;
            j++;
          } else if (leftTop < rightTop) {
            merged.add(leftTop);
            i++;
          } else {
            merged.add(rightTop);
            j++;
          }
        }

        // 今あるやつ全部
        ans += addedCount * (addedCount - 1) / 2;

        // right が端点とならないものを全て抜く
        ans -= intervalCount(xs[left], bit);

        // left が端点とならないものを全て抜く
        ans -= intervalCount(xs[right], bit);

        // right および left が端点とならないもの (重複して引いた分) を足し込む
        ans += intervalCount(merged, bit);
      }
    }
    out.println(ans);
  }

  class FenwickTree {

    int N;
    long[] data;

    FenwickTree(int N) {
      this.N = N + 1;
      data = new long[N + 1];
    }

    void add(int k, long val) {
      for (int x = k; x < N; x |= x + 1) {
        data[x] += val;
      }
    }

    // [0, k)
    long sum(int k) {
      if (k >= N) {
        k = N - 1;
      }
      long ret = 0;
      for (int x = k - 1; x >= 0; x = (x & (x + 1)) - 1) {
        ret += data[x];
      }
      return ret;
    }

    // [l, r)
    long sum(int l, int r) {
      return sum(r) - sum(l);
    }
  }

  public static void main(String[] args) {
    PrintWriter out = new PrintWriter(System.out);
    new Main().solve(new FastScanner(), 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;
    }
  }
}

AOJ 1163 Cards

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1163

GCD + 二部マッチング

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

public class Main {

  private static long gcd(long a, long b) {
    return b == 0 ? a : gcd(b, a % b);
  }

  private void solve(FastScanner in, PrintWriter out) {
    while (true) {
      int m = in.nextInt();
      int n = in.nextInt();
      if (m == 0 && n == 0) {
        break;
      }
      int[] b = in.nextIntArray(m);
      int[] r = in.nextIntArray(n);

      Dinitz dinitz = new Dinitz(n + m + 2);
      int source = n + m;
      int sink = source + 1;
      for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
          if (gcd(b[i], r[j]) > 1) {
            dinitz.addEdge(i, j + m, 1);
          }
        }
      }

      for (int i = 0; i < m; i++) {
        dinitz.addEdge(source, i, 1);
      }
      for (int i = 0; i < n; i++) {
        dinitz.addEdge(i + m, sink, 1);
      }

      out.println(dinitz.maxFlow(source, sink));
    }
  }

  class Dinitz {

    class Edge {

      int to, rev;
      long cap;

      Edge(int to, long cap, int rev) {
        this.to = to;
        this.cap = cap;
        this.rev = rev;
      }
    }

    private ArrayDeque<Integer> deque = new ArrayDeque<>();
    private ArrayList<ArrayList<Edge>> g;
    private int[] level;
    private int[] iter;

    Dinitz(int V) {
      g = new ArrayList<>(V);
      for (int i = 0; i < V; i++) {
        g.add(new ArrayList<>());
      }
      level = new int[V];
      iter = new int[V];
    }

    void addEdge(int from, int to, long cap) {
      g.get(from).add(new Edge(to, cap, g.get(to).size()));
      g.get(to).add(new Edge(from, 0, g.get(from).size() - 1));
    }

    private long dfs(int v, int t, long f) {
      if (v == t) {
        return f;
      }
      for (; iter[v] < g.get(v).size(); iter[v]++) {
        Edge e = g.get(v).get(iter[v]);
        if (e.cap > 0 && level[v] < level[e.to]) {
          long d = dfs(e.to, t, Math.min(f, e.cap));
          if (d > 0) {
            e.cap -= d;
            g.get(e.to).get(e.rev).cap += d;
            return d;
          }
        }
      }
      return 0;
    }

    private void bfs(int s) {
      Arrays.fill(level, -1);
      level[s] = 0;
      deque.add(s);
      while (!deque.isEmpty()) {
        int v = deque.poll();
        for (Edge e : g.get(v)) {
          if (e.cap > 0 && level[e.to] < 0) {
            level[e.to] = level[v] + 1;
            deque.add(e.to);
          }
        }
      }
    }

    long maxFlow(int s, int t) {
      long flow = 0;
      for (; ; ) {
        bfs(s);
        if (level[t] < 0) {
          return flow;
        }
        Arrays.fill(iter, 0);
        long f;
        while ((f = dfs(s, t, Long.MAX_VALUE)) > 0) {
          flow += f;
        }
      }
    }
  }

  public static void main(String[] args) {
    PrintWriter out = new PrintWriter(System.out);
    new Main().solve(new FastScanner(), 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;
    }
  }
}

CS Academy Round #14 Subarrays Xor Sum

解法

eha くんに解説をしてもらってようやく理解した。

各ビットごとに独立なので、ビットごとに分ける。

0と1のみの数列の長さ k 以下の数列の xor の合計値をとりたい。 i 番目の数を末尾とする長さ k 以下の数列のうち、 xor が z となるものをカウントする。

コード

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

public class Main {

  private static final int MOD = (int) (1e9 + 7);

  /**
   * 長さ k 以下のものについて計算する
   */
  private long count(int[] bit, int k) {
    if (k == 0) {
      return 0;
    }

    int N = bit.length;
    long res = 0;

    // count[i] := 長さ k 以下の数列で、 xor が i となるものの数
    int[] count = new int[2];
    int[] imos = new int[N + 1];
    for (int i = 0; i < N; i++) {
      imos[i + 1] = imos[i] ^ bit[i];
    }

    for (int i = 0; i < N; i++) {
      // 末尾が 1 ならば、 xor が 0 の数列は 1 に、 1 の数列は 0 になる
      if (bit[i] == 1) {
        int t = count[0];
        count[0] = count[1];
        count[1] = t;
      }

      // 長さ 1 の数列を追加する
      if (bit[i] == 1) {
        count[1]++;
      } else {
        count[0]++;
      }

      // 長さ k+1 になってしまった列を取り除く
      if (i - k >= 0) {
        int w = imos[i + 1] ^ imos[i - k];
        if (w == 1) {
          count[1]--;
        } else {
          count[0]--;
        }
      }

      // i 番目を末尾とする、長さ k 以下の数列の個数のうち xor が 1 のものを足しておく
      res += count[1];
    }

    return res;
  }

  private void solve(FastScanner in, PrintWriter out) {

    int N = in.nextInt();
    int a = in.nextInt();
    int b = in.nextInt();
    int[] array = in.nextIntArray(N);

    long ans = 0;
    for (int bit = 0; bit < 31; bit++) {
      int[] tmp = new int[N];
      for (int i = 0; i < N; i++) {
        tmp[i] = (array[i] >> bit) & 1;
      }

      long count = (count(tmp, b) - count(tmp, a - 1));
      if (count < 0) {
        count += MOD;
      }
      count %= MOD;
      ans += count * (1 << bit);
      ans %= MOD;
    }

    out.println(ans);
  }

  public static void main(String[] args) {
    PrintWriter out = new PrintWriter(System.out);
    new Main().solve(new FastScanner(), 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;
    }
  }
}

Bitbucket サーバーにプッシュされたコードを Jenkins でビルドする

無意味にハマった。

Jenkins 側の設定

とりあえず Pipeline を使っているものとする。「ビルドのパラメータ化」にチェックを入れておくと、外部からのパラメータを受け取れるようになる。

f:id:kenkoooo:20170608161433p:plain

例えばパラメータ "branch" を定義していると、Pipeline Script の Groovy は変数 branch の中に値が入った状態で起動する。

Bitbucket Server 側の設定

うちの会社では Bitbucket Server を使っている。

HTTP-Request Hook for Bitbucket Server | Atlassian Marketplace

とりあえずこのプラグインを入れる。

HTTP-Request Hook for Bitbucket Server の設定

Method

POST にする。後述するように Post Data が空であるにも関わらずだ。

URL
JENKINS_URL/job/JOB_NAME/buildWithParameters?PARAMETER_NAME=PARAMETER_VALUE

の形式で書く。

例えば、プッシュされたブランチの名前が知りたければ、以下のように書く。

JENKINS_URL/job/JOB_NAME/buildWithParameters?branch=${refChange.refId}
Username / Password

Jenkins のユーザーネームと API トークンをそれぞれ書く。

Post Data

空のままで良い。

Closeable は Close しなければ閉じられない

非常に当たり前だが、以下のコードでは "closed" が出力されることはない。

package sandbox;

import java.io.Closeable;
import java.io.IOException;

public class Sandbox {

  public static void main(String[] args) throws Exception {
    String a = get();
    System.out.println(a);
  }

  private static String get() {
    return loadFromHoge(new HogeStream());
  }

  private static String loadFromHoge(HogeStream hogeStream) {
    return "load";
  }

  static class HogeStream implements Closeable {

    @Override
    public void close() throws IOException {
      System.out.println("closed");
    }
  }
}

明らかに get の中で一生を終えているので上手いこと閉じてほしいという気持ちではある。

AtCoder Grand Contest 013 C - Ants on a Circle

解法

解説の通りにやった。Rustでは map を使って for を消せることを学んだ。

コード

use std::fmt::Debug;
use std::io;
use std::io::{Read, Stdin};
use std::str;
use std::str::FromStr;
use std::usize;
use std::cmp;
use std::collections::vec_deque::VecDeque;
use std::i64::MAX;

fn main() {
    let mut sc = Scanner::new();
    let n = sc.parse::<usize>();
    let l = sc.parse::<i64>();
    let t = sc.parse::<i64>();

    let mut x: Vec<i64> = vec![0; n];
    let mut w: Vec<usize> = vec![0; n];

    for i in 0..n {
        x[i] = sc.parse::<i64>();
        w[i] = sc.parse::<usize>();
    }

    let cross_count = (0..n)
        .map(|i| {
            let w0 = w[0];
            let wi = w[i];
            if w0 == wi {
                return 0;
            }

            let interval;
            if w0 == 1 {
                interval = x[i] - x[0];
            } else {
                interval = x[0] + l - x[i];
            }

            if interval > t * 2 {
                return 0;
            }

            let time = t * 2 - interval;
            let count;
            if time % l == 0 && w[0] == 1 {
                count = time / l;
            } else {
                count = time / l + 1;
            }
            return count;
        })
        .collect::<Vec<i64>>();

    let count_sum: i64 = cross_count.iter().sum::<i64>() % (n as i64);
    let position;
    let num;
    if w[0] == 1 {
        position = (x[0] + t) % l;
        num = count_sum;

    } else {
        position = (x[0] - (t % l) + l) % l;
        num = (n as i64) - count_sum;
    }

    let mut positions: Vec<i64> = (0..n)
        .map(|i| {
            let p;
            if w[i] == 1 {
                p = (x[i] + t) % l;
            } else {
                p = (x[i] - (t % l) + l) % l;
            }
            return p;
        })
        .collect::<Vec<i64>>();
    positions.sort();

    let mut a = 0;
    for i in 0..n {
        if positions[i] == position {
            a = i;
            break;
        }
    }

    let ans = (0..n)
        .map(|idx| {
                 let i = (idx + n - ((num as usize) % n)) % n;
                 let p = (a + i as usize) % n;
                 return positions[p];
             })
        .collect::<Vec<i64>>();

    for a in &ans {
        println!("{}", a);
    }
}

struct Scanner {
    stdin: Stdin,
    buf: Vec<u8>,
}

impl Scanner {
    fn new() -> Scanner {
        Scanner {
            stdin: io::stdin(),
            buf: Vec::with_capacity(256),
        }
    }

    fn parse<T: FromStr>(&mut self) -> T
        where <T as FromStr>::Err: Debug
    {
        self.buf.clear();
        let mut it = self.stdin.lock().bytes();
        let mut c = it.next().unwrap().unwrap();
        while c == ' ' as u8 || c == '\n' as u8 {
            c = it.next().unwrap().unwrap();
        }
        while !(c == ' ' as u8 || c == '\n' as u8) {
            self.buf.push(c);
            c = it.next().unwrap().unwrap();
        }
        str::from_utf8(&self.buf).unwrap().parse::<T>().unwrap()
    }
}