1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

競技プログラミング私的チートシート(Java)

Posted at

メモ。順次加筆。

余りを切り上げる

public static int roundUp(int a, int b) {
    return (a + b - 1) / b;
}

最大公約数

ユークリッドの互除法を使って計算を行う。

参考:
ユークリッドの互除法の証明と不定方程式 | 高校数学の美しい物語

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

例えば、a=370 b=273とすると、

Loop a b
1 370 273
2 273 370 % 273 = 117
3 117 273 % 117 = 39
4 39 117 % 39 = 0

b=0になったとき、return aによりaの値が返される。
その値が最大公約数である。

最小公倍数

最大公約数を利用して計算する。

参考:
最大公約数と最小公倍数の積の性質の2通りの証明 | 高校数学の美しい物語

private static long lcm(long a, long b) {
    return a * b / gcd(a, b);
}

回転行列

double rad = Math.toRadians(60);
double ux = (tx-sx)*Math.cos(rad) - (ty-sy)*Math.sin(rad)+sx;
double uy = (tx-sx)*Math.sin(rad) + (ty-sy)*Math.cos(rad)+sy;
Point u = new Point(ux, uy);

組み合わせの数

順列の数

順列の列挙

組み合わせの列挙

幅優先探索

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DFS {

    private class Graph {
        List<List<Integer>> graph;
        boolean[] seen;

        public Graph(int n) {
            graph = new ArrayList<>();
            seen = new boolean[n];
            for (int i = 0; i < n; i++) {
                graph.add(new ArrayList());
                seen[i] = false;
            }
        }

        public void add(int from, int to) {
            graph.get(from).add(to);
            graph.get(to).add(from);
        }

        public void search(int v) {
            seen[v] = true;

            for (int next : graph.get(v)) {
                if (seen[next]) continue;
                search(next);
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        final int N = sc.nextInt();
        final int M = sc.nextInt();

        Graph graph = new DFS().new Graph(N);

        for (int i = 0; i < M; i++) {
            final int A = Integer.valueOf(sc.next());
            final int B = Integer.valueOf(sc.next());
            graph.add(A, B);
        }

        graph.search(0);
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?