group_id
stringlengths
12
18
problem_description
stringlengths
85
3.02k
candidates
listlengths
3
20
aoj_ALDS1_1_B_cpp
Greatest Common Divisor Write a program which finds the greatest common divisor of two natural numbers a and b Input a and b are given in a line sparated by a single space. Output Output the greatest common divisor of a and b . Constrants 1 ≤ a , b ≤ 10 9 Hint You can use the following observation: For integers x and y , if x ≥ y , then gcd( x , y ) = gcd( y , x % y ) Sample Input 1 54 20 Sample Output 1 2 Sample Input 2 147 105 Sample Output 2 21
[ { "submission_id": "aoj_ALDS1_1_B_10915851", "code_snippet": "#include <iostream>\nusing namespace std;\n\nint main(){\n int x, y; cin >> x >> y;\n int d = 2;\n int gcd = 1;\n\n while(d <= x && d <= y){\n if (x % d == 0 && y % d == 0){\n x = x / d;\n y = y / d;\n gcd = gcd * d;\n }\n else d++;\n }\n cout << gcd << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 260, "memory_kb": 3432, "score_of_the_acc": -2, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_1_B_10912277", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint main(){\n int x, y, ans, temp, i;\n cin >> x >> y;\n if(x < y){\n temp = x;\n x = y;\n y = temp;\n }\n\n if(x == y) ans = x;\n else{\n x %= y;\n for(i = x; i >= 1; i--){\n if(x%i == 0 and y%i == 0){\n ans = i;\n break;\n }\n }\n }\n\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 260, "memory_kb": 3432, "score_of_the_acc": -2, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_1_B_10892907", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint main(){\n int x, y, remain, ans, i;\n cin >> x >> y;\n \n if(x >= y){\n remain = x%y;\n if(remain == 0){\n ans = y;\n }\n else{\n for(i = remain-1; i >= 1; i--){\n if(remain%i == 0 and y%i == 0){\n ans = i;\n break;\n }\n }\n }\n }\n else{\n remain = y%x;\n if(remain == 0){\n ans = x;\n }\n else{\n for(i = remain-1; i >= 1; i--){\n if(remain%i == 0 and x%i == 0){\n ans = i;\n break;\n }\n }\n }\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 260, "memory_kb": 3420, "score_of_the_acc": -1, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_1_B_10881531", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint main(){\n int x, y, z, min, divisible, i;\n cin >> x >> y;\n\n if(x >= y){\n z = x % y;\n if(z == 0) divisible = y;\n else{\n if(y > z) min = z;\n else min = y;\n for(i = min; i >= 1; i--){\n if(y % i == 0 and z % i == 0){\n divisible = i;\n break;\n }\n }\n }\n cout << divisible << endl;\n }\n\n else{\n z = y % x;\n if(z == 0) divisible = y;\n else{\n if(x > z) min = z;\n else min = x;\n for(i = min; i >= 1; i--){\n if(x % i == 0 and z % i == 0){\n divisible = i;\n break;\n }\n }\n }\n cout << divisible << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 3424, "score_of_the_acc": -0.3333, "final_rank": 1 } ]
aoj_ALDS1_2_D_cpp
Shell Sort Shell Sort is a generalization of Insertion Sort (ALDS1_1_A) to arrange a list of $n$ elements $A$. 1 insertionSort(A, n, g) 2 for i = g to n-1 3 v = A[i] 4 j = i - g 5 while j >= 0 && A[j] > v 6 A[j+g] = A[j] 7 j = j - g 8 cnt++ 9 A[j+g] = v 10 11 shellSort(A, n) 12 cnt = 0 13 m = ? 14 G[] = {?, ?,..., ?} 15 for i = 0 to m-1 16 insertionSort(A, n, G[i]) A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$. Your task is to complete the above program by filling ? . Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements: $1 \leq m \leq 100$ $0 \leq G_i \leq n$ cnt does not exceed $\lceil n^{1.5}\rceil$ Input In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line. Output In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line. In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively. This problem has multiple solutions and the judge will be performed by a special validator. Constraints $1 \leq n \leq 1,000,000$ $0 \leq A_i \leq 10^9$ Sample Input 1 5 5 1 4 3 2 Sample Output 1 2 4 1 3 1 2 3 4 5 Sample Input 2 3 3 2 1 Sample Output 2 1 1 3 1 2 3
[ { "submission_id": "aoj_ALDS1_2_D_11015424", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n int reserve_capacity;\n if (capacity == 0)\n {\n reserve_capacity = 1;\n }\n else\n {\n reserve_capacity = capacity * 2 ;\n }\n reserve(reserve_capacity);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji) //\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 8664, "score_of_the_acc": -0.6225, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_2_D_11015398", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n int reserve_capacity;\n if (capacity == 0)\n {\n reserve_capacity = 1;\n }\n else\n {\n reserve_capacity = capacity *5 ;\n }\n reserve(reserve_capacity);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji) //\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 8804, "score_of_the_acc": -0.6584, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_2_D_11015395", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n int reserve_capacity;\n if (capacity == 0)\n {\n reserve_capacity = 1;\n }\n else\n {\n reserve_capacity = capacity * 2;\n }\n reserve(reserve_capacity);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji) //\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 8664, "score_of_the_acc": -0.6225, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_2_D_11001403", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n int new_capacity;\n if (capacity == 0)\n {\n new_capacity = 1;\n }\n else\n {\n new_capacity *1;\n }\n reserve(new_capacity);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji) //\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_11001398", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n int new_capacity;\n if (capacity == 0)\n {\n new_capacity = 1;\n }\n else\n {\n new_capacity * 2;\n }\n reserve(new_capacity);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji) //\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_11001395", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n int new_capacity;\n if (capacity == 0)\n {\n new_capacity = 1;\n }\n else\n {\n new_capacity + 10;\n }\n reserve(new_capacity);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji) //\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_11001391", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n int new_capacity;\n if (capacity == 0)\n {\n new_capacity = 1;\n }\n else\n {\n new_capacity +1;\n }\n reserve(new_capacity);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji) //\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_11001361", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量一杯\n {\n resize(n + 1);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji)//\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7564, "score_of_the_acc": -0.3401, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_2_D_10995190", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue) // push_back関数\n {\n if (n == capacity) // 容量満タン\n {\n resize(n + 1);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji)\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_10995157", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue)\n {\n if (n == capacity)\n {\n resize(newvalue);\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji)\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_10995085", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int newvalue)\n {\n if (n == capacity)\n {\n int push_size = n + 1;\n\n int *resized_a = new int[push_size];\n\n for (int i = 0; i < n; i++) // pushする数字以外をコピー\n {\n resized_a[i] = a[i];\n }\n delete[] a;\n a = resized_a;\n n = push_size;\n }\n a[n] = newvalue;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji)\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_10975752", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int pushback)\n {\n if (n >= capacity)\n {\n int push_size = n + 1;\n\n int *resized_a = new int[push_size];\n\n for (int i = 0; i < n; i++) // pushする数字以外をコピー\n {\n resized_a[i] = a[i];\n }\n delete[] a;\n a = resized_a;\n n = push_size;\n }\n a[n] = pushback;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji)\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_10962540", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass my_vector\n{\nprivate: // 隠すもの。外から見えない\n int *a; // 可変長配列\n int n; // 要素数\n int capacity; // 確保する容量\n\npublic: // 公開するもの\n my_vector() // vector定義 引数無し 初期化\n {\n a = new int[0];\n n = 0;\n capacity = 0;\n } // vector<int> a;\n\n my_vector(int size) // vector定義 要素あり\n {\n a = new int[size];\n n = size;\n capacity = size;\n } // vector<int> a(n);\n\n void reserve(int reserved_size) // reserve メモリの事前確保\n {\n int *reserved_a = new int[reserved_size];\n for (int i = 0; i < n; i++)\n {\n reserved_a[i] = a[i];\n }\n\n delete[] a;\n a = reserved_a;\n capacity = reserved_size; // サイズが変更された後のサイズを取得\n }\n\n void resize(int resized_size) // リサイズ関数\n {\n int *resized_a = new int[resized_size]; // aのサイズを変更\n\n int copysize = min(resized_size, n);\n\n for (int i = 0; i < copysize; i++)\n {\n resized_a[i] = a[i];\n }\n\n delete[] a;\n a = resized_a;\n n = resized_size; // サイズが変更された後のサイズを取得\n }\n\n void push_back(int pushback)\n {\n /* int push_size = n + 1;\n\n int *resized_a = new int[push_size];\n\n for (int i = 0; i < n; i++) // pushする数字以外をコピー\n {\n resized_a[i] = a[i];\n }\n resized_a[n] = pushback;\n\n delete[] a;\n a = resized_a;\n n = push_size; // サイズが変更された後のサイズを取得\n */\n // 容量が足りない場合は、倍にして再確保\n if (n >= capacity)\n {\n int new_capacity = (capacity == 0) ? 1 : capacity * 2;\n reserve(new_capacity);\n }\n\n a[n] = pushback;\n n++;\n }\n\n int size() const // サイズ取得\n {\n return n;\n }\n\n int &operator[](int soeji)\n {\n return a[soeji];\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n my_vector card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 7568, "score_of_the_acc": -0.3411, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_2_D_10960391", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint cnt;\nvector<int> g;\nvoid insertionSort(vector<int> &a, int g){\n int n = (int)a.size();\n for (int i = g; i < n; i++){\n int v = a[i];\n int j = i - g;\n while(j >= 0 && a[j] > v){\n a[j+g] = a[j];\n j -= g;\n cnt++;\n }\n a[j+g] = v;\n }\n}\n\nvoid shellSort(vector<int> &a, vector<int> &g){\n cnt = 0;\n for (int h = 1; h <= (int)a.size(); h = 3*h+1) g.push_back(h);\n reverse(g.begin(), g.end());\n for (int i = 0; i < (int)g.size(); i++){\n insertionSort(a, g[i]);\n }\n}\n\nint main(){\n int n; cin >> n;\n vector<int>a(n);\n for (int i = 0; i < n; i++) cin >> a[i];\n shellSort(a,g);\n\n cout << g.size() << '\\n';\n for (int i = 0; i < (int)g.size(); i++){\n if (i>0) cout << ' ';\n cout << g[i];\n }\n cout << '\\n';\n cout << cnt << '\\n';\n for (int i = 0; i < n; i++){\n cout << a[i] << '\\n';\n }\n\n\n}", "accuracy": 1, "time_ms": 380, "memory_kb": 6768, "score_of_the_acc": -0.2222, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_2_D_10955592", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstatic long long cnt = 0;\n\n// gap g の挿入ソート(疑似コードの insertionSort(A, n, g))\nvoid insertionSort(vector<long long> &A, int n, int g) {\n for (int i = g; i < n; i++) {\n long long v = A[i];\n int j = i - g;\n while (j >= 0 && A[j] > v) {\n A[j + g] = A[j];\n j -= g;\n cnt++; // 疑似コード 8行目:シフト回数をカウント\n }\n A[j + g] = v;\n }\n}\n\n// shellSort 本体(疑似コードの shellSort(A, n))\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n if (!(cin >> n)) return 0;\n vector<long long> A(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n\n // 1) G(Knuthの数列)作成:1, 4, 13, ... で n 以下まで\n vector<int> G;\n for (long long h = 1; h <= n; h = 3 * h + 1) G.push_back((int)h);\n reverse(G.begin(), G.end()); // 大きいものから使う(疑似コード 15-16行目の意図)\n\n // 2) 出力用 m\n int m = (int)G.size();\n cout << m << \"\\n\";\n for (int i = 0; i < m; i++) {\n if (i) cout << \" \";\n cout << G[i];\n }\n cout << \"\\n\";\n\n // 3) シェルソート実行\n cnt = 0;\n for (int g : G) insertionSort(A, n, g);\n\n // 4) cnt と、整列後の配列を出力\n cout << cnt << \"\\n\";\n for (int i = 0; i < n; i++) cout << A[i] << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 10664, "score_of_the_acc": -1, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_2_D_10946264", "code_snippet": "#include <iostream>\n#include <vector>\n#include <math.h>\n\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<int> card;\n //card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 7636, "score_of_the_acc": -0.3709, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_2_D_10946262", "code_snippet": "#include <iostream>\n#include <vector>\n#include <math.h>\n\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<int> card;\n card.reserve(n);\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 7436, "score_of_the_acc": -0.3196, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_2_D_10946257", "code_snippet": "#include <iostream>\n#include <vector>\n#include <math.h>\n\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<int> card;\n for (int i = 0; i < n; ++i)\n {\n int x;\n cin >> x;\n card.push_back(x);\n }\n\n // シェルソート\n int cnt = 0;\n int m = 1 + log2(n);\n cout << m << \"\\n\";\n\n for (int g = n; g > 0; g /= 2) // 挿入ソートをするたびgの値を半分にする\n {\n for (int i = g; i < n; i++) // card[g]をソート\n {\n int v = card[i]; // ソートするカード\n int j = i - g; // 比較するカード\n while (j >= 0 && card[j] > v) // 比較するカード>ソートするカード\n {\n card[j + g] = card[j]; // カードを入れ替える\n j = j - g;\n cnt++;\n }\n card[j + g] = v;\n }\n cout << g << \" \";\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n for (int i = 0; i < n; i++)\n {\n cout << card[i] << \"\\n\"; // カード表示\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 8656, "score_of_the_acc": -0.6204, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_2_D_10938908", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath> \nusing namespace std;\n\nint cnt = 0;\n\nvoid insertionSort(vector<int>& A, int n, int g) {\n for (int i = g; i < n; ++i) {\n int v = A[i];\n int j = i - g;\n while (j >= 0 && A[j] > v) {\n A[j + g] = A[j];\n j -= g;\n cnt++;\n }\n A[j + g] = v;\n }\n}\n\nint main() {\n int n;\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; ++i) {\n cin >> A[i];\n }\n\n int m = 1;\n while ((pow(3, m + 1) + 1) / 2 <= n) {\n ++m;\n }\n\n vector<int> G(m);\n for (int i = 0; i < m; ++i) {\n G[i] = (static_cast<int>(pow(3, i)) + 1) / 2;\n }\n\n for (int i = m - 1; i >= 0; --i) {\n insertionSort(A, n, G[i]);\n }\n \n cout << m << \"\\n\";\n for (int i = m - 1; i >= 0; --i) {\n cout << G[i];\n if (i != 0) cout << \" \";\n }\n cout << \"\\n\";\n cout << cnt << \"\\n\";\n for (int i = 0; i < n; ++i) {\n cout << A[i] << \"\\n\";\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 370, "memory_kb": 6820, "score_of_the_acc": -0.2232, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_2_D_10938832", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint insertionsort(vector<int> &A, int g)\n{\n int cnt = 0;\n int n = A.size();\n for (int i = g; i <= n - 1; i++)\n {\n int v = A[i];\n int j = i - g;\n while (j >= 0 && A[j] > v)\n {\n A[j + g] = A[j];\n j = j - g;\n cnt++;\n }\n A[j + g] = v;\n }\n return cnt;\n}\n\nint shellSort(vector<int> &A, vector<int> &G)\n{\n int cnt = 0; // 交換回数\n\n for (int g : G)\n {\n cnt += insertionsort(A, g);\n }\n return cnt;\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n int cnt;\n vector<int> A(n);\n for (int &a:A)\n {\n cin >> a;\n }\n vector<int> G;\n for (int i = n; i > 0; i /= 2)\n {\n G.push_back(i);\n }\n int m = G.size();\n\n cnt = shellSort(A, G);\n\n cout << m << endl;\n for (int g : G)\n {\n cout << g << \" \";\n }\n cout << endl\n << cnt << endl;\n for (int a : A)\n {\n cout << a << endl;\n }\n}", "accuracy": 1, "time_ms": 1010, "memory_kb": 6880, "score_of_the_acc": -1.0287, "final_rank": 20 } ]
aoj_ALDS1_1_D_cpp
Maximum Profit You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen. Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ . Input The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order. Output Print the maximum value in a line. Constraints $2 \leq n \leq 200,000$ $1 \leq R_t \leq 10^9$ Sample Input 1 6 5 3 1 3 4 3 Sample Output 1 3 Sample Input 2 3 4 3 2 Sample Output 2 -1
[ { "submission_id": "aoj_ALDS1_1_D_11066075", "code_snippet": "#include<iostream>\nusing namespace std;\nint main ( ) {\n\tint n = 0, min = 0, result = -1000000000, temp = 0;\n\tcin >> n;\n\tcin >> min;\n\tfor (int i = 0; i < n-1; i++) {\n\t\tcin >> temp;\n\t\tif (temp - min > result) {\n\t\t\tresult = temp - min;\n\t\t}\n\t\tif (temp < min) {\n\t\t\tmin = temp;\n\t\t}\n\t\t\n\t}\n\tcout << result << endl;\n\t\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3440, "score_of_the_acc": -1.2275, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_1_D_11064399", "code_snippet": "#include<bits/stdc++.h> \nusing namespace std;\nint gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\nint lcm(int a, int b) {\n return a / gcd(a, b) * b;\n}\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n ; \n cin>>n;\n int a[n] , result = INT_MIN;\n for(int i = 0 ; i<n ; i++){\n cin>>a[i];\n }\n int b[n];\n b[0] = a[0] ;\n for(int i = 1 ; i < n ; i++){\n b[i] = min(b[i-1] , a[i]);\n }\n for(int i = 1 ; i < n ; i++){\n result = max(result , a[i] - b[i-1]);\n }\n cout<<result<<\"\\n\";\n }", "accuracy": 1, "time_ms": 10, "memory_kb": 5016, "score_of_the_acc": -1, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_1_D_11057125", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n ll n;\n cin>>n;\n ll num;\n cin>>num;\n ll ans = -100000000000000;\n ll now = num;\n for (int i = 1; i < n; i++) {\n cin>>num;\n ans = max(ans, num-now);\n now = min(now, num);\n }\n cout<<ans<<\"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3584, "score_of_the_acc": -0.9647, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_1_D_11055774", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint main(){\n int n;\n cin>>n;\n int minprice=2000000001,maxpr=-1000000001;\n for(int i=0;i<n;i++){\n int a;\n cin>>a;\n maxpr=max(maxpr,a-minprice);\n minprice=min(a,minprice);\n }\n cout<<maxpr<<endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3436, "score_of_the_acc": -1.2255, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_1_D_11027237", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <iomanip>\nusing namespace std;\n\nint main() {\n\tint n ;\n\tcin >> n;\n\tlong ans= -9999999999,min;\n\tcin>>min;\n\tfor (int i = 0; i < n-1; i++) {\n\t\t\tlong a;\n\t\t\tcin>>a;\n\t\t\tif(ans<(a-min)){ans=a-min;}\n\t\t\tif(a<=min){min=a;}\n\t\t}\n\t\tcout<<ans<<endl;\n\t\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3436, "score_of_the_acc": -1.2255, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_1_D_11025444", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <iomanip>\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\tlong t = -999999999999999, a[10000];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t cin>>a[i];\n\t\t}\n\tfor (int i = 0; i < n; i++) {\n\t int j = i+1;\n\t\t while(j<=n-1)\n\t\t {\n\t\t if(a[j]- a[i]>t){t=a[j]- a[i];}\n\t\t j++;\n\t\t }\n\t\t}\n\t\tcout<<fixed<<setprecision(21);\n\t\tcout<<t<<endl;\n\t\treturn 0;\n}", "accuracy": 0.875, "time_ms": 20, "memory_kb": 3440, "score_of_the_acc": -0.5608, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_1_D_11013992", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int n;cin >> n;\n vector<int>v(n);\n for(int i=0;i<n;i++){\n cin >> v.at(i);\n }\n int minv = v.at(0);\n int maxv = v[1]-v[0];\n for(int i=1;i<n;i++){\n maxv=max(maxv,v.at(i)-minv);\n minv=min(minv,v.at(i));\n }\n cout << maxv << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3864, "score_of_the_acc": -1.4353, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_1_D_11009041", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint n;\nint a[200005];\nint mx=-2000005,mn=0x3f3f3f3f;\nint main(){\n\tcin>>n;\n\tfor(int i=1;i<=n;i++)cin>>a[i];\n\tmx=-2000000005;\n\tmn=a[1];\n\tfor(int i=2;i<=n;i++){\n\t\tmx=max(mx,a[i]-mn);\n\t\tmn=min(mn,a[i]);\n\t}\n\tcout<<mx<<endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4116, "score_of_the_acc": -1.5588, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_1_D_11003818", "code_snippet": "#include <iostream>\nusing namespace std;\n\nint main(){\n int n, R[200000];\n cin >> n >> R[0];\n\n int minv = R[0], maxv = -1e9;\n\n for(int i = 1; i < n; i++){\n cin >> R[i];\n maxv = maxv > (R[i] - minv) ? maxv : R[i] - minv;\n minv = R[i] < minv ? R[i] : minv; \n }\n cout << maxv << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4144, "score_of_the_acc": -1.5725, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_1_D_11003798", "code_snippet": "#include <iostream>\nusing namespace std;\n\nint main(){\n int n;\n cin >> n;\n int R[200000];\n for(int i = 0; i < n; i++)\n cin >> R[i];\n\n int minv = R[0], maxv = -1e9;\n\n for(int j = 1; j < n; j++){\n maxv = maxv > (R[j] - minv) ? maxv : R[j] - minv;\n minv = R[j] < minv ? R[j] : minv; \n }\n cout << maxv << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4216, "score_of_the_acc": -1.6078, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_1_D_11003164", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n vector<int> v(n);\n for (int i = 0; i < n; i++) cin >> v[i];\n\n int minv = v[0];\n int maxv = v[1] - v[0]; // 最初の2つの差を初期値に\n for (int i = 1; i < n; i++) {\n maxv = max(maxv, v[i] - minv);\n minv = min(minv, v[i]);\n }\n cout << maxv << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3760, "score_of_the_acc": -1.3843, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_1_D_10998577", "code_snippet": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n int ans = INT32_MIN, bruh;\n cin >> bruh;\n for (int i=0, tmp; i<(n-1); i++)\n {\n cin >> tmp;\n ans = max(ans, tmp-bruh);\n bruh = (bruh > tmp)? tmp : bruh;\n }\n cout << ans << \"\\n\";\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3480, "score_of_the_acc": -1.2471, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_1_D_10995725", "code_snippet": "/*10.28*/\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n int maxv, minv;\n\n int n;\n \n cin >> n;\n\n int rt[n];\n\n for (int i = 0;i < n;i++) cin >> rt[i];\n\n\n maxv = rt[1] - rt[0];\n minv = rt[0];\n for (int j = 1; j < n;j++) {\n maxv = max(maxv, rt[j] - minv);\n minv = min(minv, rt[j]);\n }\n\n cout << maxv << endl;\n\n\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4212, "score_of_the_acc": -1.6059, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_1_D_10970206", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint main(){\n int n, max, min, i;\n int ex[200'000];\n cin >> n;\n for(i = 0; i < n; i++) cin >> ex[i];\n\n min = ex[0];\n max = ex[1]-min;\n for(i = 1; i < n; i ++){\n if(ex[i]-min > max) max = ex[i]-min;\n if(ex[i] < min) min = ex[i];\n }\n\n cout << max << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4216, "score_of_the_acc": -1.6078, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_1_D_10965557", "code_snippet": "#include<iostream>\nusing namespace std;\nint main(void){\n int n,minnn=1000000001,maxxx=-1000000001;\n cin>>n;\n int a[200000]={0};\n for(int i=0;i<n;i++){\n cin>>a[i];\n }\n minnn=min(minnn,a[0]);\n for(int i=1;i<n;i++){\n maxxx=max(maxxx,a[i]-minnn);\n minnn=min(minnn,a[i]);\n }\n cout<<maxxx<<endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4216, "score_of_the_acc": -1.6078, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_1_D_10955968", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nint main(void){\n int n;\n cin >> n;\n\n vector<int> a;\n for(int i = 0; i < n; i++){\n int x;\n cin >> x;\n a.push_back(x);\n }\n\n int maxv = -1000000000;\n int minv = a[0];\n\n\n for (int i = 1; i < n; i++)\n {\n maxv = max(maxv , a[i] - minv);\n minv = min(minv , a[i]);\n }\n \n cout << maxv << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4128, "score_of_the_acc": -1.5647, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_1_D_10951640", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n#define rep(i, N) for (int i = 0; i < N; ++i)\n\nint main() {\n int n;\n cin >> n;\n vector<int> R(n);\n rep(i, n) cin >> R[i];\n\n int currmin = R[0];\n int res = INT_MIN;\n for (int i = 1; i < n; ++i) {\n res = max(res, R[i] - currmin);\n currmin = min(currmin, R[i]);\n }\n\n cout << res << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3872, "score_of_the_acc": -1.4392, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_1_D_10941339", "code_snippet": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n \n int R[200000];\n for (int i = 0; i < n; i++) {\n cin >> R[i];\n }\n \n int minv = R[0];\n int maxv = R[1] - R[0];\n \n for (int j = 1; j < n; j++) {\n maxv = max(maxv, R[j] - minv);\n minv = min(minv, R[j]);\n }\n \n cout << maxv << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4212, "score_of_the_acc": -1.6059, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_1_D_10941337", "code_snippet": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nint main(){\n int n;\n cin >> n;\n \n int R[200000];\n for (int i = 0; i < n; i++) {\n cin >> R[i];\n }\n \n int minv = R[0];\n int maxv = R[1] - R[0];\n \n for (int j = 1; j < n; j++){\n maxv = max(maxv, R[j]-minv);\n minv = min(minv, R[j]);\n }\n \n cout << maxv << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4100, "score_of_the_acc": -1.551, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_1_D_10940926", "code_snippet": "#include <stdio.h>\n#include <limits.h>\n\nusing namespace std;\n\nint main(){\n\tint n,tmp,min=INT_MAX,max=INT_MIN;\n\tscanf(\"%d\",&n);\n\tfor(int i = 0; i < n; i++){\n\t\tscanf(\"%d\",&tmp);\n\t\tif(max < tmp-min) max = tmp - min;\n\t\tif(min > tmp) min = tmp;\n\t}\n\tprintf(\"%d\\n\",max);\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2976, "score_of_the_acc": 0, "final_rank": 1 } ]
aoj_ALDS1_1_C_cpp
Prime Numbers A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7. Write a program which reads a list of N integers and prints the number of prime numbers in the list. Input The first line contains an integer N , the number of elements in the list. N numbers are given in the following lines. Output Print the number of prime numbers in the given list. Constraints 1 ≤ N ≤ 10000 2 ≤ an element of the list ≤ 10 8 Sample Input 1 5 2 3 4 5 6 Sample Output 1 3 Sample Input 2 11 7 8 9 10 11 12 13 14 15 16 17 Sample Output 2 4
[ { "submission_id": "aoj_ALDS1_1_C_11063301", "code_snippet": "#include<bits/stdc++.h> \nusing namespace std;\nint gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\nint lcm(int a, int b) {\n return a / gcd(a, b) * b;\n}\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int t ; \n cin>>t;\n int result = 0 ;\n for(int i = 0 ; i < t ; i++){\n long long n ; \n cin>>n;\n if(n==2 || n==3 || n==5 || n==7 || n==11 ){\n result++;\n continue;\n }\n else if(n<2){\n continue;\n }\n else if(n%2==0 || n%3==0 || n%5==0 || n%7==0 || n%11==0){\n continue;\n }\n else{\n for(int i = 13 ; i*i <= n ; i+=2){\n if(n%i==0){\n result--;\n break;\n }\n }\n }\n result++;\n }\n cout<<result<<\"\\n\";\n }", "accuracy": 1, "time_ms": 10, "memory_kb": 3448, "score_of_the_acc": -0.0369, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_1_C_11057463", "code_snippet": "#include <stdio.h>\nint main()\n{\n int n,c=0;\n scanf(\"%d\",&n);\n int a[n];\n for(int i=0; i<n;i++)\n {\n scanf(\"%d\",&a[i]);\n int p=1;\n if(a[i]<2)\n {\n p=0;\n }\n for(int j=2; j*j<=a[i]; j++)\n {\n if(a[i]%j==0)\n {\n p=0;\n break;\n }\n }\n if(p==1)\n {\n c++;\n }\n }\n printf(\"%d\\n\",c);\n\n return 0;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2992, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_1_C_11025314", "code_snippet": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\tint t = 0;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tint a;\n\t\tint b = 1;\n\t\tbool isPrime =true;\n\t\tcin >> a;\n\t\twhile (b < sqrt(a - 1)) {\n\t\t\tb++;\n\t\t\tif (a % b == 0) {\n\t\t\t\tisPrime = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (isPrime==true) {\n\t\t\tt++;\n\t\t}\n\t}\n\tcout<<t<<endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3436, "score_of_the_acc": -0.0744, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_1_C_11011921", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nbool isPrime(int x){\n if(x<=1)return false;\n if(x==2)return true;\n for(int i=2;i<=sqrt(x);i++){\n if(x%i==0)return false;\n }\n return true;\n}\nint main(){\n int count = 0;\n int n; cin >> n;\n for(int i=0;i<n;i++){\n int m;\n cin >> m;\n if(isPrime(m)){\n count+=1;\n }\n }\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3348, "score_of_the_acc": -0.0288, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_1_C_10998606", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n \n int ans = 0;\n for (int i=0; i<n; i++)\n {\n long long tmp;\n cin >> tmp;\n bool isPrime = (tmp%2 == 0 && tmp != 2)? false : true;\n if (isPrime)\n {\n long long lim = sqrt(tmp);\n for (int i=3; i<=lim; i+=2)\n {\n if (tmp%i == 0)\n {\n isPrime = false;\n break;\n }\n }\n }\n if (isPrime)\n ans++;\n }\n cout << ans << \"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3436, "score_of_the_acc": -0.0359, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_1_C_10997644", "code_snippet": "#include <iostream>\n\nusing namespace std;\n\nint is_prime(int n) {\n \n if (n == 2) return 1;\n\n else if (!(n % 2)) return 0;\n \n // 合成数の判定\n int i = 3;\n \n while (i * i <= n) {\n if (!(n % i)) return 0;\n i++;// 3 --> 5 --> 7 .......\n }\n return 1;\n\n}\n\nint main() {\n \n int n,p_count = 0;\n cin >> n;\n\n int no[n];\n\n for (int i = 0;i < n;i++) {\n cin >> no[i];\n p_count += is_prime(no[i]);\n }\n\n cout << p_count << endl;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3372, "score_of_the_acc": -0.0307, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_1_C_10997396", "code_snippet": "#include <iostream>\n#include <vector>\n\nstatic const int MAX = 1000000;\n\nstd::vector<bool> sieve(int limit) {\n std::vector<bool> is_prime(limit + 1, true);\n is_prime[0] = is_prime[1] = false;\n for (int i = 2; i * i <= limit; ++i) {\n if (is_prime[i]) {\n for (int j = i * i; j <= limit; j += i)\n is_prime[j] = false;\n }\n }\n return is_prime;\n}\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<int> X(n);\n for (int i = 0; i < n; ++i) std::cin >> X[i];\n\n int max_val = 0;\n for (int x : X) if (x > max_val) max_val = x;\n auto is_prime = sieve(max_val);\n\n int count = 0;\n for (int x : X)\n if (x >= 2 && is_prime[x]) ++count;\n\n std::cout << count << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 270, "memory_kb": 15360, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_1_C_10965549", "code_snippet": "#include<iostream>\n#include<cmath>\nusing namespace std;\n\nint isprime(int);\n\nint main(){\n int n, total, i;\n int num[10'000];\n cin >> n;\n\n total = 0;\n for(i = 0; i < n; i++){\n cin >> num[i];\n\n total += isprime(num[i]);\n }\n cout << total << endl;\n return 0;\n}\n\nint isprime(int n){\n int i;\n\n if(n == 2) return 1;\n else if(n == 1 or n%2 == 0) return 0;\n else{\n for(i = 3; i <= sqrt(n); i++){\n if(n%i == 0) return 0;\n }\n return 1;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3444, "score_of_the_acc": -0.0365, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_1_C_10964994", "code_snippet": "#include<iostream>\n#include<cmath>\nusing namespace std;\nint main(void){\n int c,cnt=0,t=0;\n while(cin>>c){\n if(c%2==0 or c==1){\n if(c!=2){\n cnt++;\n }\n }\n else{for(int i=3;i<=sqrt(c);i+=2){\n if(c%i==0){\n cnt++;\n break;\n }\n }\n }\n \n t++;\n }\n cout<<t-cnt<<endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3364, "score_of_the_acc": -0.0301, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_1_C_10937655", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool is_prime(int N){\n for (int i = 2; i*i <= N; i++) if (N%i == 0) return false;\n return true;\n}\n\nint main(){\n int N, A, count = 0;\n cin >> N;\n \n for (int _ = 0; _ < N; _++){\n cin >> A;\n if (is_prime(A)) count++;\n }\n \n cout << count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3364, "score_of_the_acc": -0.0301, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_1_C_10933872", "code_snippet": "using namespace std;\n#include <iostream>\n#include <vector>\n\nint main() {\n int n;\n cin >> n;\n vector<int> x(n);\n for (int i = 0; i < n; ++i) cin >> x[i];\n\n int c = 0;\n for (int i = 0; i < n; ++i) {\n if (x[i] < 2) continue; \n bool prime = true;\n for (int j = 2; j * j <= x[i]; ++j) {\n if (x[i] % j == 0) {\n prime = false;\n break;\n }\n }\n if (prime) c += 1;\n }\n\n cout << c << \"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3436, "score_of_the_acc": -0.0359, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_1_C_10923933", "code_snippet": "#include <iostream>\nusing namespace std;\n\nbool isPrime(int x){\n if (x < 2) return false;\n for (int i = 2; i*i <= x; i++){\n if (x % i == 0) return false;\n //else return true; これやるとbreakと同じになってしまう\n }\n return true;\n}\n\nint main(){\n int N; cin >> N;\n int ans = 0;\n int V[N];\n for (int i = 0; i < N; i++) cin >> V[i];\n for (int i = 0; i < N; i++) if (isPrime(V[i])) ans++;\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3360, "score_of_the_acc": -0.0298, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_1_C_10923918", "code_snippet": "#include <iostream>\nusing namespace std;\n\nint main(){\n int N; cin >> N;\n int V[N];\n int ans = 0;\n for (int i = 0; i < N; i++){\n cin >> V[i];\n \n for (int j = 2; j * j <= V[i]; j++){\n if (V[i] % j == 0){\n ans += 1;\n break;\n }\n } \n }\n cout << N - ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3352, "score_of_the_acc": -0.0291, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_1_C_10912290", "code_snippet": "#include<iostream>\n#include<cmath>\nusing namespace std;\n\nint isDigit(int);\n\nint main(){\n int n, check, i;\n int num[10000];\n int count = 0;\n cin >> n;\n for(i = 0; i < n; i++) cin >> num[i];\n\n for(i = 0; i < n; i++){\n check = isDigit(num[i]);\n count += check;\n }\n\n cout << count << endl;\n return 0;\n}\n\nint isDigit(int n){\n int i;\n if(n == 2) return 1;\n else if(n == 1 or n%2 == 0) return 0;\n else{\n for(i = 3; i <= sqrt(n); i++){\n if(n%i == 0) return 0;\n }\n\n return 1;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3404, "score_of_the_acc": -0.0333, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_1_C_10909552", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)\n#define rep2(i, s, n) for (ll i = (ll)(s); i < (ll)(n); i++)\n\n\n// vectorを出力する\nvoid vec1print(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid vec2print(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<ll> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<ll> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll x, ll y, ll limit_x, ll limit_y) {\n return 0 <= x and x < limit_x and 0 <= y and y < limit_y;\n}\n\n// main\nvoid solve() {\n ll n;\n cin >> n;\n ll ans = 0;\n rep(i,n) {\n ll x;\n cin >> x;\n bool ok = true;\n ll root_x = sqrt(x);\n for (ll i = 2; i <= root_x; ++i) {\n if (x % i == 0) {\n ok =false;\n }\n }\n if (ok) ans += 1;\n }\n cout << ans << endl;\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 3456, "score_of_the_acc": -0.5375, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_1_C_10881546", "code_snippet": "#include<iostream>\n#include<cmath>\nusing namespace std;\n\nint isprime(int);\n\nint main(){\n int n, x, check, i, j;\n int count = 0;\n cin >> n;\n for(i = 0; i < n; i++){\n cin >> x;\n check = isprime(x);\n if(check == 1) count++;\n }\n cout << count << endl;\n return 0;\n}\n\nint isprime(int x){\n int i;\n if(x == 2) return 1;\n else if(x == 1 or x%2 == 0) return 0;\n else{\n for(i = 3; i <= sqrt(x); i++){\n if(x%i == 0) return 0;\n }\n return 1;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3352, "score_of_the_acc": -0.0291, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_1_C_10879683", "code_snippet": "#include<iostream>\n#include<math.h>\nusing namespace std;\n\nint main(){\n int n, num = 0, count = 0; cin >> n;\n for(int i=0;i<n;i++){\n bool flag = true;\n cin >> num;\n int sqrt_num = sqrt(num);\n for(int j=2;j<=sqrt_num;j++){\n if(num % j == 0){\n flag = false;\n break;\n }\n }\n if(flag == true){\n count++;\n }\n }\n cout << count << endl; \n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3348, "score_of_the_acc": -0.0288, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_1_C_10879537", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint is_prime(int n) {\n if (n <= 1) return 0;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) return 0;\n }\n return 1;\n}\n\nint main() {\n int n;\n int ans = 0;\n cin >> n;\n vector<int> primes(n);\n for (int i = 0; i < n; i++) {\n cin >> primes[i];\n }\n for (int i = 0; i < n; i++) {\n if (is_prime(primes[i])) {\n ans++;\n }\n }\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3368, "score_of_the_acc": -0.0304, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_1_C_10877020", "code_snippet": "//\n// main.cpp\n// MyCp\n//\n// Created by 今井青波 on 2025/08/27.\n//\n\n// ===== begin my_bits.hpp =====\n//\n// my_bits.hpp\n// MyCp\n//\n// Created by 今井青波 on 2025/08/28.\n//\n\n#pragma once\n#include <bits/stdc++.h>\nusing namespace std;\n\n// ---------------- macro ----------------\n#define rep(i,x,limit) for (int i = (int)x; i < (int)limit; i++)\n#define REP(i,x,limit) for (int i = (int)x; i <= (int)limit; i++)\n#define repd(i,x,limit) for (int i = (int)x; i > (int)limit; i--)\n#define REPD(i,x,limit) for (int i = (int)x; i >= (int)limit; i--)\n#define ifRange(x,a,b) if (x>=a && x<=b)\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\n#define el '\\n'\n#define spa \" \"\n#define Yes cout << \"Yes\" << el\n#define No cout << \"No\" << el\n#define YES cout << \"YES\" << el\n#define NO cout << \"NO\" << el\n#define eps (1e-10)\n#define Equals(a,b) (fabs((a) - (b)) < eps )\n#ifdef DEBUG\n#define debug(x) cerr << \"----- DEBUG ----- \" << #x << \" = \" << x << el\n#else\n#define debug(x)\n#endif\n\ninline void setup_io(bool input=true) {\n // spped up cin/cout\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n // local only\n#ifdef DEBUG\n cerr << \"----- INFO ----- Hello world at Src!\" << el;\n filesystem::path currentPath = filesystem::current_path();\n cerr << \"----- INFO ----- Current directory: \" << currentPath.string() << el;\n if (input) {\n freopen(\"input.in\", \"r\", stdin);\n cerr << \"----- INFO ----- input.in read!\" << el;\n }\n#endif\n}\n\n// ---------------- type alias ----------------\nusing ll = long long;\nusing ull = unsigned long long;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\n\n// ---------------- numbers/ strings ----------------\nconst double pi = 3.141592653589793238;\nconst int inf = 1073741823;\nconst ll infl = 1LL << 60;\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\n// ===== end my_bits.hpp =====\n\nint main() {\n setup_io(); // (false): not open input.txt\n \n // insert code here...\n int n,a, cnt=0;cin>>n;\n rep(i,0,n) {\n cin>>a;debug(a);\n if (a%2==0) {\n if(a==2) cnt++;\n continue;\n }\n int j=3;\n bool b=true;\n while (j<=sqrt(a)) {\n if(a%j==0) {\n b=false;\n break;\n }\n j+=2;\n }\n if(b) cnt++;\n }\n cout<<cnt<<el;\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3364, "score_of_the_acc": -0.0301, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_1_C_10875930", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main() {\n ll N,n,a =0;\n cin >> N;\n bool b =1;\n for (ll i = 0; i < N; i++) {\n cin >> n;\n for (ll j = 2;j*j <= n;j++) {\n if (n%j == 0) {\n b = 0;\n break;\n }\n }\n if (b) {\n a++;\n }else {\n b = 1;\n }\n }\n cout << a << endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3412, "score_of_the_acc": -0.1109, "final_rank": 18 } ]
aoj_ALDS1_4_C_cpp
Search III Your task is to write a program of a simple dictionary which implements the following instructions: insert str : insert a string str in to the dictionary find str : if the distionary contains str , then print ' yes ', otherwise print ' no ' Input In the first line n , the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format. Output Print yes or no for each find instruction in a line. Constraints A string consists of ' A ', ' C ', ' G ', or ' T ' 1 ≤ length of a string ≤ 12 n ≤ 1000000 Sample Input 1 5 insert A insert T insert C find G find A Sample Output 1 no yes Sample Input 2 13 insert AAA insert AAC insert AGA insert AGG insert TTT find AAA find CCC find CCC insert CCC find CCC insert T find TTT find T Sample Output 2 yes no no yes yes yes Notes Template in C
[ { "submission_id": "aoj_ALDS1_4_C_11057022", "code_snippet": "// ██████████████████╗█████╗███╗ ██╗ ██████╗ █████╗████╗ ██╗█████╗███╗ ██╗\n// ╚══██╔══██╚══██╔══██╔══██████╗ ██║ ██╔══████╔══████╚██╗ ██╔██╔══██████╗ ██║\n// ██║ ██║ ██║ █████████╔██╗ ██║ ██████╔█████████║╚████╔╝█████████╔██╗ ██║\n// ██║ ██║ ██║ ██╔══████║╚██╗██║ ██╔══████╔══████║ ╚██╔╝ ██╔══████║╚██╗██║\n// ██║ ██║ ██║ ██║ ████║ ╚████║ ██║ ████║ ████║ ██║ ██║ ████║ ╚████║\n// ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╚═╝ ╚═══╝ ╚═╝ ╚═╚═╝ ╚═╚═╝ ╚═╝ ╚═╝ ╚═╚═╝ ╚═══╝\n// GitHub: https://github.com/raiyan/cp-template\n\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;typedef unsigned long long ull;typedef long double ld;typedef pair<int,int> pii;typedef pair<ll,ll> pll;typedef vector<int> vi;typedef vector<ll> vll;typedef vector<pii> vpii;typedef vector<pll> vpll;\n#define all(x) (x).begin(),(x).end()\n#define rall(x) (x).rbegin(),(x).rend()\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define sz(x) (int)(x).size()\n\n#ifndef NDEBUG\nnamespace dbg{string s(int x){return to_string(x);}string s(long long x){return to_string(x);}string s(unsigned long long x){return to_string(x);}string s(double x){return to_string(x);}string s(long double x){return to_string(x);}string s(char x){return \"'\"+string(1,x)+\"'\";}string s(string x){return '\"'+x+'\"';}string s(bool x){return x?\"true\":\"false\";}string s(const char*x){return'\"'+string(x)+'\"';}template<class A,class B>string s(pair<A,B>p){return\"(\"+s(p.first)+\",\"+s(p.second)+\")\";}template<class T>string s(T v){string r=\"{\";for(auto x:v)r+=(r==\"{\"?\"\":\",\"),r+=s(x);return r+\"}\";}template<class T>string s(stack<T>st){string r=\"{\";while(!st.empty())r+=(r==\"{\"?\"\":\",\"),r+=s(st.top()),st.pop();return r+\"}\";}template<class T>string s(queue<T>q){string r=\"{\";while(!q.empty())r+=(r==\"{\"?\"\":\",\"),r+=s(q.front()),q.pop();return r+\"}\";}template<class T>string s(priority_queue<T>pq){string r=\"{\";while(!pq.empty())r+=(r==\"{\"?\"\":\",\"),r+=s(pq.top()),pq.pop();return r+\"}\";}void p(const char*n){cerr<<\"\\n\";}template<class T>void p(const char*n,T v){cerr<<n<<\"=\"<<s(v)<<\"\\n\";}template<class T,class...A>void p(const char*n,T v,A...a){for(;*n!=',';n++)cerr<<*n;cerr<<\"=\"<<s(v)<<\", \";p(n+1,a...);}}\n#define debug(...) cerr<<\"[L\"<<__LINE__<<\"]: \",dbg::p(#__VA_ARGS__,__VA_ARGS__)\n#else\n#define debug(...)\n#endif\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int n; cin >> n;\n\n set<string> a;\n\n while (n--) {\n string s; string c;\n\n cin >> s >> c;\n\n if (s == \"insert\") {\n a.insert(c);\n } else {\n auto it = a.find(c);\n if (it != a.end()) {\n cout << \"yes\\n\";\n } else {\n cout << \"no\\n\";\n }\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 24900, "score_of_the_acc": -0.4506, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_4_C_11046388", "code_snippet": "#include <iostream>\n#include <unordered_set>\n\nint main() {\n int n;\n std::cin >> n;\n\n std::unordered_set<std::string> dictionary;\n std::string command, word;\n\n for (int i = 0; i < n; ++i) {\n std::cin >> command >> word;\n if (command == \"insert\") {\n dictionary.insert(word);\n } else if (command == \"find\") {\n if (dictionary.count(word)) {\n std::cout << \"yes\\n\";\n } else {\n std::cout << \"no\\n\";\n }\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 680, "memory_kb": 23664, "score_of_the_acc": -0.6117, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_4_C_11046375", "code_snippet": "#include <iostream>\n#include <unordered_set>\n\n\nint main() {\n int n;\n std::cin >> n;\n\n std::unordered_set<std::string> dictionary;\n std::string command, word;\n\n for (int i = 0; i < n; ++i) {\n std::cin >> command >> word;\n if (command == \"insert\") {\n dictionary.insert(word);\n } else if (command == \"find\") {\n if (dictionary.count(word)) {\n std::cout << \"yes\\n\";\n } else {\n std::cout << \"no\\n\";\n }\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 23844, "score_of_the_acc": -0.6204, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_4_C_11046370", "code_snippet": "#include <iostream>\n#include <unordered_set>\n#include <string>\n\nint main() {\n int n;\n std::cin >> n;\n\n std::unordered_set<std::string> dictionary;\n std::string command, word;\n\n for (int i = 0; i < n; ++i) {\n std::cin >> command >> word;\n if (command == \"insert\") {\n dictionary.insert(word);\n } else if (command == \"find\") {\n if (dictionary.count(word)) {\n std::cout << \"yes\\n\";\n } else {\n std::cout << \"no\\n\";\n }\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 23736, "score_of_the_acc": -0.6256, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_4_C_11017719", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TABLE_SIZE 16777216\n#define ORDER_LENGTH 7\n#define STR_LENGTH 13\n\nusing namespace std;\n\nint array[128];\n\nint translateStr(char buf[]){\n int sum = -1,mult = 1;\n for(int i = 0; buf[i] != '\\0'; i++){\n sum += array[buf[i]]*mult;\n mult *= 4;\n }\n return sum;\n}\n\nint main(){\n\n array['A']=1,array['C']=2,array['G']=3,array['T']=4;\n\n int n;\n scanf(\"%d\",&n);\n char order[ORDER_LENGTH],str[STR_LENGTH];\n\n char* check_table = new char[TABLE_SIZE];\n\n for(int i = 0; i < n; i++){\n scanf(\"%s %s\",order,str);\n if(order[0] == 'i'){\n check_table[translateStr(str)] = 'Y';\n }else{\n if(check_table[translateStr(str)] == 'Y'){\n printf(\"yes\\n\");\n }else{\n printf(\"no\\n\");\n }\n }\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 6680, "score_of_the_acc": -0.0077, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_4_C_11017616", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 1000003\n#define L 14\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int x;\n x = key % M;\n return x;\n}\n \nint h2(int key){\n int y;\n y = 1 + (key % (M-1));\n return y;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0 ;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n if (!find(str)){\n insert(str);\n }\n }else{\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n return 0;\n}", "accuracy": 0.2, "time_ms": 490, "memory_kb": 17024, "score_of_the_acc": -0.4047, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_4_C_11017603", "code_snippet": "#include <iostream>\nusing namespace std;\n\nlong long change_acgt_string(string s);\nlong long change_acgt(char c);\n\nvoid insert(string s, bool S[]);\nbool find(string s, bool S[]);\n\nint main(){\n bool S[1 << 25] = {};\n long long n;\n cin >> n;\n for(long long i=0; i<n; ++i){\n string ask, str;\n cin >> ask >> str;\n if(ask == \"insert\"){\n insert(str, S);\n }\n if(ask == \"find\"){\n if(find(str, S)){\n cout << \"yes\";\n }\n else{\n cout << \"no\";\n }\n cout << \"\\n\";\n }\n }\n\n return 0;\n}\n\nlong long change_acgt_string(string s){\n long long a = 0;\n int i;\n for(i=0; i<s.size(); ++i){\n a |= (long long)change_acgt(s[i]) << i*2;\n }\n a |= 1 << i*2;\n return a;\n}\n\nlong long change_acgt(char c){\n if(c == 'A') return 0b00;\n else if(c == 'C') return 0b01;\n else if(c == 'G') return 0b10;\n else return 0b11;\n}\n\nvoid insert(string s, bool S[]){\n S[change_acgt_string(s)] = true;\n}\n\nbool find(string s, bool S[]){\n return S[change_acgt_string(s)];\n}", "accuracy": 1, "time_ms": 470, "memory_kb": 36392, "score_of_the_acc": -0.6331, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_4_C_11017553", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\nusing namespace std;\n\nbool isPrime(int a) {\n if (a <= 1) {\n return false;\n }\n if (a == 2) {\n return true;\n }\n if (a % 2 == 0) {\n return false;\n }\n int limit = static_cast<int>(std::sqrt(a)); \n for (int i = 3; i <= limit; i += 2) {\n if (a % i == 0) {\n return false;\n }\n }\n return true;\n}\n\nint findNextPrime(int b){\n int p = b + 1;\n while(!isPrime(p)){\n p += 1;\n }\n return p;\n}\n\nint h_1(long long key,int m){\n return key%m;\n}\n\nint h_2(long long key,int m){\n return (1 + (key%(m-1)));\n}\n\nint h_3(long long key, int i,int m){\n return ((h_1(key,m) + (long long)i*h_2(key,m))%m);\n}\n\nint ch_to_it(char ch){\n if(ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n}\n\nlong long ch_sm(string str){\n long long p = 1;\n long long sum = 0;\n for(char c: str){\n int x = ch_to_it(c);\n sum += p*x;\n p = p*5;\n }\n return sum;\n}\nvoid insert(string str,vector<string>& H,int m){\n long long key = ch_sm(str);\n for(int i = 0; i < m; i++){\n int hash1 = h_3(key,i,m);\n if(H[hash1].empty()){\n H[hash1] = str;\n return;\n }\n }\n}\n\nvoid find(string str,const vector<string>& H,int m){\n long long key = ch_sm(str);\n\n for(int i = 0; i < m; i++){\n int hash1 = h_3(key,i,m);\n if(H[hash1].empty()){\n cout << \"no\" << endl;\n return;\n }else if(H[hash1] == str){\n cout << \"yes\" << endl;\n return;\n }\n }\n cout << \"no\" << endl;\n}\n\nint main(){\n int n;\n cin >> n;\n\n int m = findNextPrime(n);\n vector<string> vec_str(m);\n\n string insfin,str;\n\n for(int i = 0; i <= (n-1); i++){\n cin >> insfin >> str;\n if(insfin == \"insert\"){\n insert(str,vec_str,m);\n }else if(insfin == \"find\"){\n find(str,vec_str,m);\n }\n }\n\n \n return 0;\n}", "accuracy": 1, "time_ms": 760, "memory_kb": 34368, "score_of_the_acc": -0.7974, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_4_C_11017508", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 2000003\n#define L 14\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int x;\n x = key % M;\n return x;\n}\n \nint h2(int key){\n int y;\n y = 1 + (key % (M-1));\n return y;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L+1], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.2, "time_ms": 1150, "memory_kb": 30688, "score_of_the_acc": -1.0064, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_4_C_11017505", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 1000003\n#define L 14\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int x;\n x = key % M;\n return x;\n}\n \nint h2(int key){\n int y;\n y = 1 + (key % (M-1));\n return y;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L+1], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.2, "time_ms": 490, "memory_kb": 17108, "score_of_the_acc": -0.4057, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_4_C_11017498", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 1000003\n#define L 14\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int x;\n x = key % M;\n return x;\n}\n \nint h2(int key){\n int y;\n y = 1 + (key % (M-1));\n return y;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < M; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.2, "time_ms": 480, "memory_kb": 17116, "score_of_the_acc": -0.3993, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_4_C_11017288", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\nlong long hs(long long x, int m, int i){\n long long h1 = x % m;\n long long h2 = 1 + x % (m - 1);\n return (h1 + i * h2) % m;\n}\n\nlong long encode(const string& s){\n long long val = 0;\n for (char c : s){\n val *= 5;\n switch(c){\n case 'A': val += 1; break;\n case 'T': val += 2; break;\n case 'G': val += 3; break;\n case 'C': val += 4; break;\n }\n }\n return val;\n}\n\nint main(){\n int n;\n string cmd, s;\n cin >> n;\n vector<long long> H(n, 0);\n vector<string> A;\n\n for (int i=0; i<n; i++){\n cin >> cmd >> s;\n long long x = encode(s);\n\n if (cmd == \"insert\"){\n for (int j=0; j<n; j++){\n long long h = hs(x, n, j);\n if (H[h]==0){\n H[h] = x;\n break;\n }\n if (H[h]==x) break; // 既に存在する場合は挿入しない\n }\n }else{ // find\n bool found = false;\n for (int j=0; j<n; j++){\n long long h = hs(x, n, j);\n if (H[h]==0) break; // 空セルに当たったら終了\n if (H[h]==x){\n A.push_back(\"yes\");\n found = true;\n break;\n }\n }\n if (!found) A.push_back(\"no\");\n }\n }\n\n for (string& ans : A){\n cout << ans << endl;\n }\n}", "accuracy": 1, "time_ms": 650, "memory_kb": 28736, "score_of_the_acc": -0.6553, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_4_C_11017287", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\nlong long hs(long long x, int m, int i){\n long long h1 = x%m;\n long long h2 = 1+x%(m-1);\n long long h;\n h = (h1 + i * h2) % m;\n return h;\n}\n\nint main(){\n int n;\n string cmd, s;\n cin >> n;\n vector<int> H(n);\n vector<string> A;\n for (int i=0;i<n;i++){\n cin >> cmd >> s;\n string s2=\"\";\n for (char i:s){\n switch(i){\n case 'A': s2.push_back('1'); break;\n case 'T': s2.push_back('2'); break;\n case 'G': s2.push_back('3'); break;\n case 'C': s2.push_back('4'); break;\n }\n }\n long long x = stoll(s2);\n int j=0;\n if (cmd == \"insert\"){\n for(int l=0;l<n;l++){\n long long h = hs(x, n, j);\n if (H[h]==0){\n H[h] = x;\n break;\n }\n j+=1;\n }\n }else{\n bool found = false;\n for (int j=0;j<n;j++){\n long long h = hs(x, n, j);\n if (H[h]==0) break;\n if (H[h]==x){\n //Yes\n A.push_back(\"yes\");\n found = true;\n break;\n }\n }\n if (!found) A.push_back(\"no\");\n }\n }\n for (int k=0;k<A.size();k++){\n cout << A[k] << endl;\n }\n}", "accuracy": 0.8, "time_ms": 710, "memory_kb": 24972, "score_of_the_acc": -0.6476, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_4_C_11017209", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <cstdlib>\n#include <cstring> \n#include <unordered_set>\n\nusing namespace std;\n\n\nint main(){\n int n,i,k,f;\n cin >> n;\n string fnc[n];\n string val[n];\n unordered_set<string> dex;\n \n for (i=0;i<n;i++){\n cin >> fnc[i] >> val[i];\n }\n \n \n for (i=0;i<n;i++){\n if (fnc[i]==\"insert\"){\n dex.insert(val[i]);\n }\n \n \n if (fnc[i]==\"find\"){\n if (dex.count(val[i])){\n cout << \"yes\" << endl;\n } else {\n cout << \"no\" << endl;\n }\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 86260, "score_of_the_acc": -1.4052, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_4_C_11017166", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 100003\n#define L 100\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int h1;\n h1 = key % M;\n return h1;\n}\n \nint h2(int key){\n int h2;\n h2 = 1 + (key % (M-1));\n return h2;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.8, "time_ms": 970, "memory_kb": 14904, "score_of_the_acc": -0.692, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_4_C_11017160", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 78583\n#define L 200\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int h1;\n h1 = key % M;\n return h1;\n}\n \nint h2(int key){\n int h2;\n h2 = 1 + (key % (M-1));\n return h2;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.8, "time_ms": 1610, "memory_kb": 20304, "score_of_the_acc": -1.1776, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_4_C_11017154", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 78583\n#define L 100\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int h1;\n h1 = key % M;\n return h1;\n}\n \nint h2(int key){\n int h2;\n h2 = 1 + (key % (M-1));\n return h2;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.8, "time_ms": 1060, "memory_kb": 12760, "score_of_the_acc": -0.7241, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_4_C_11017151", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 78583\n#define L 20\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int h1;\n h1 = key % M;\n return h1;\n}\n \nint h2(int key){\n int h2;\n h2 = 1 + (key % (M-1));\n return h2;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.8, "time_ms": 700, "memory_kb": 7696, "score_of_the_acc": -0.4256, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_4_C_11017148", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 78583\n#define L 14\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int h1;\n h1 = key % M;\n return h1;\n}\n \nint h2(int key){\n int h2;\n h2 = 1 + (key % (M-1));\n return h2;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.8, "time_ms": 670, "memory_kb": 6212, "score_of_the_acc": -0.3875, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_4_C_11017113", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <set>\n#define M 76927\n#define L 14\nusing namespace std;\n\nchar H[M][L];\n\nint getChar(char ch){\n if (ch == 'A'){\n return 1;\n }else if(ch == 'C'){\n return 2;\n }else if(ch == 'G'){\n return 3;\n }else if(ch == 'T'){\n return 4;\n }\n return 0;\n}\n\nlong long getKey(char str[]){\n long long sum,p;\n sum = 0;\n p = 1;\n for(int i = 0; i < strlen(str); i++){\n sum += p*(getChar(str[i]));\n p *= 5;\n }\n return sum;\n}\n\nint h1(int key){\n int h1;\n h1 = key % M;\n return h1;\n}\n \nint h2(int key){\n int h2;\n h2 = 1 + (key % (M-1));\n return h2;\n}\n\nint find(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(strcmp(H[hash],str) == 0){\n return 1;\n }\n }\n return 0;\n}\n\nint insert(char str[]){\n int hash,h_1,h_2,key;\n key = getKey(str);\n h_1 = h1(key);\n h_2 = h2(key);\n for(int i = 0;i < L; ++i){\n hash = (h_1 + i*h_2) % M;\n if(H[hash][0] == '\\0'){\n strcpy(H[hash],str);\n return 1;\n }\n }\n return 0;\n}\n\n\nint main(){\n int n,h;\n vector<int> result;\n char str[L], com[9];\n for(int i = 0; i < M; ++i){\n H[i][0] = '\\0';\n }\n\n cin >> n;\n\n for(int i = 0; i < n; ++i){\n cin >> com >> str;\n if(com[0] == 'i'){ \n //入力がinsertなら\n if (!find(str)){\n insert(str);\n }\n }else{\n //入力がfindなら\n if (find(str) == 1){\n result.push_back(1);\n }else{\n result.push_back(0);\n }\n }\n }\n for(int j = 0; j < result.size(); ++j){\n if (result[j] == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.8, "time_ms": 690, "memory_kb": 6060, "score_of_the_acc": -0.3987, "final_rank": 11 } ]
aoj_ALDS1_4_B_cpp
Search II You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S. Input In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given. Output Print C in a line. Constraints Elements in S is sorted in ascending order n ≤ 100000 q ≤ 50000 0 ≤ an element in S ≤ 10 9 0 ≤ an element in T ≤ 10 9 Sample Input 1 5 1 2 3 4 5 3 3 4 1 Sample Output 1 3 Sample Input 2 3 1 2 3 1 5 Sample Output 2 0 Sample Input 3 5 1 1 2 2 3 2 1 2 Sample Output 3 2 Notes
[ { "submission_id": "aoj_ALDS1_4_B_11066403", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n\nint main() {\n int n,q; cin>>n;\n int s[n+5], t;\n int count=0;\n\n for(int i =1; i<=n;i++){\n cin>>s[i];\n }\n cin>>q;\n for(int i=1;i<=q;i++){\n cin>>t;\n int l = 1, r=n; \n while(l <= r){\n int mid = (l+r)/2;\n if(t == s[mid]){\n count++;\n break;\n }\n else if(t < s[mid]) {\n r = mid-1;\n }\n else {\n l = mid + 1;\n }\n }\n }\n cout<<count<<endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3516, "score_of_the_acc": -0.5605, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_4_B_11036791", "code_snippet": "#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\nusing ll = long long;\nusing ld = long double;\nll inf = 2e18;\n#define rep(i,n) for(ll i = 0; i < (n); i++)\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\n#define el '\\n'\n#define sp \" \"\n#define Yes cout << \"Yes\" << el\n#define No cout << \"No\" << el\n#define YN {cout<<\"Yes\"<<endl;}else{cout<<\"No\"<<endl;}\n#define next_p(v) next_permutation(v.begin(),v.end())\n#define mod(a,d) (a%d+d)%d\nvector<ll> dx = { 1,0,-1,0 };\nvector<ll> dy = { 0,1,0,-1 };\nbool out_grid(ll i, ll j, ll h, ll w) {//trueならcontinue\n return (!(0 <= i && i < h && 0 <= j && j < w));\n}\n\nvoid solve(){\n\n ll n;\n cin >> n;\n vector<ll> s(n);\n rep(i,n) cin >> s[i];\n ll q;\n cin >> q;\n vector<ll> t(q);\n rep(i,q) cin >> t[i];\n\n ll ans = 0;\n rep(i,q){\n ll target = t[i];\n ll left = 0;\n ll right = n-1;\n if(s[left]==target){\n ans ++;\n continue;\n }\n if(s[right]==target){\n ans ++;\n continue;\n }\n ll key = 0;\n while(right-left>1){\n ll mid = left + (right-left)/2;\n if(s[mid]==target){\n ans ++;\n key = 1;\n break;\n }else if(s[mid]>target){\n right = mid;\n }else{\n left = mid;\n }\n }\n if(key==0) continue;\n }\n\n cout << ans << el;\n\n}\n\nint main(){\n\n ll t = 1;\n //cin >> t;\n rep(i,t) solve();\n\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4104, "score_of_the_acc": -0.8007, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_4_B_11021855", "code_snippet": "#include <iostream> // cout, endl, cin\n#include <string> // string, to_string, stoi\n#include <vector> // vector\n#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound\n#include <utility> // pair, make_pair\n#include <tuple> // tuple, make_tuple\n#include <cstdint> // int64_t, int*_t\n#include <cstdio> // printf\n#include <map> // map\n#include <queue> // queue, priority_queue\n#include <set> // set\n#include <stack> // stack\n#include <deque> // deque\n#include <unordered_map> // unordered_map\n#include <unordered_set> // unordered_set\n#include <bitset> // bitset\n#include <cctype> // isupper, islower, isdigit, toupper, tolower\n#include <cmath> // sqrt\n\nusing namespace std;\n\n// 二分探索\nint main() {\n int n;\n cin >> n;\n vector<int64_t> s(n);\n for(int i = 0; i < n; i++){\n cin >> s.at(i);\n }\n\n int q;\n cin >> q;\n\n int ans = 0;\n for(int i = 0; i < q; i++){\n int64_t t;\n cin >> t;\n\n int left = 0;\n int right = n;\n while(left < right){\n // cout << \"be:\" << left << \" \" << right << endl;\n int mid = (left + right)/2;\n if(t == s.at(mid)){\n ans++;\n break;\n }else if(t < s.at(mid)){\n right = mid;\n }else if(t > s.at(mid)){\n left = mid + 1;\n }\n // cout << \"af:\" << left << \" \" << right << endl;\n }\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3768, "score_of_the_acc": -0.6634, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_4_B_11017787", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\nusing namespace std;\nint main(){\n int n,q,count,key;\n \n cin >> n;\n vector<int> S(n);\n for(int i = 0;i < n; ++i){\n cin >> S[i];\n }\n\n cin >> q;\n vector<int> T(q);\n for(int j = 0; j < q; ++j){\n cin >> T[j];\n }\n\n int left,right,mid;\n count = 0;\n\n for(int k = 0; k <= q-1; ++k){\n left = 0;\n right = n;\n key = T[k];\n while(left < right){\n mid = (left + right)/2;\n if(S[mid] == key){\n count += 1;\n break;\n }else if(key < S[mid]){\n right = mid;\n }else {\n left = mid +1;\n } \n }\n }\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3436, "score_of_the_acc": -0.5278, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_4_B_11017656", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint a[1000000];\nint main(void){\n int n,m,ans=0;\n cin>>n;\n for(int i=0;i<n;i++){\n int b;\n cin>>b;\n a[b%1000000]=1;\n }\n cin>>m;\n for(int i=0;i<m;i++){\n int b;\n cin>>b;\n ans+=a[b%1000000];\n }\n cout<<ans<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3368, "score_of_the_acc": -0.5, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_4_B_11017593", "code_snippet": "#include <iostream>\nusing namespace std;\n\nint main(){\n long long n;\n cin >> n;\n long long S[n];\n for(long long i=0; i<n; ++i){\n cin >> S[i];\n }\n long long q;\n cin >> q;\n long long T[q];\n for(long long i=0; i<q; ++i){\n cin >> T[i];\n }\n\n long long _count = 0;\n\n for(int i=0; i<q; ++i){\n if((S[0] <= T[i]) || (T[i] <= S[n-1])){\n long long left = 0;\n long long right = n;\n for(long long mid=(left+right)/2; S[mid]!=T[i];mid=(left+right)/2){\n if(T[i]<S[mid]){\n right = mid;\n }\n else left = mid+1;\n if(mid==(left+right)/2){\n --_count; break;\n }\n }\n ++_count;\n }\n }\n\n cout << _count << endl;\n \n \n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4608, "score_of_the_acc": -0.5065, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_4_B_11017577", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\nusing namespace std;\nint main(){\n int n,q,count,key;\n \n cin >> n;\n vector<int> S(n);\n for(int i = 0;i < n; ++i){\n cin >> S[i];\n }\n\n cin >> q;\n vector<int> T(q);\n for(int j = 0; j < q; ++j){\n cin >> T[j];\n }\n\n int left,right,mid;\n count = 0;\n\n for(int k = 0; k <= q-1; ++k){\n left = 0;\n right = n;\n key = T[k];\n while(left < right){\n mid = (left + right)/2;\n if(S[mid] == key){\n count += 1;\n break;\n }else if(key < S[mid]){\n right = mid;\n }else {\n left = mid +1;\n } \n }\n }\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3472, "score_of_the_acc": -0.5425, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_4_B_11017108", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <cstdlib>\n#include <cstring> \n#include <cmath>\n\nusing namespace std;\n\nint main(){\n int n;\n int S[100000];\n int q;\n int T[50000];\n \n int i;\n int F=0;\n \n cin >> n;\n for (i=0;i<n;i++){\n cin >> S[i];\n }\n cin >> q;\n for (i=0;i<q;i++){\n cin >> T[i];\n }\n\n F=0;\n float L=0;\n float R=n-1;\n int M;\n int M2=-1;\n int A=0;\n M=floor((L+R)/2);\n \n for (i=0;i<q;i++){\n F = 0;\n L=0;\n R=n-1;\n M=floor((L+R)/2);\n M2=-1;\n \n \n while(F==0){\n if (S[M]==T[i]){\n A = A + 1;\n F=1;\n } else if(S[M]<T[i]){\n L=M+1;\n M=floor((L+R)/2);\n F=0;\n } else {\n R=M-1;\n M=floor((L+R)/2);\n F=0;\n }\n if (F==0 and M==M2){\n F=1;\n }\n M2=M;\n }\n }\n\n\n\n cout << A << endl; \n\n\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3948, "score_of_the_acc": -1.2369, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_4_B_11017081", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\n// 二分探索(閉区間版)\nbool binarySearch(const vector<int>& A, int key) {\n int left = 0;\n int right = A.size() - 1;\n while (left <= right) {\n int mid = (left + right) / 2;\n if (A[mid] == key) return true;\n else if (key < A[mid]) right = mid - 1;\n else left = mid + 1;\n }\n return false;\n}\n\nint main() {\n int n, q;\n cin >> n;\n vector<int> S(n);\n for (int i = 0; i < n; i++) cin >> S[i];\n\n cin >> q;\n vector<int> T(q);\n for (int i = 0; i < q; i++) cin >> T[i];\n\n int count = 0;\n for (int i = 0; i < q; i++) {\n if (binarySearch(S, T[i])) count++;\n }\n\n cout << count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3536, "score_of_the_acc": -0.5686, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_4_B_11016105", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint binary_search(int v[],int n,int target){\n //インデックスを名づける\n int left = 0;\n int right = n-1;\n while(left<=right){\n int mid = (left+right)/2;\n if(target==v[mid])return mid;\n if(target<v[mid]){\n right = mid-1;\n }\n else{\n left = mid+1;\n }\n }\n return -1;\n}\n\n\nint main(){\n int n;cin >> n;\n vector<int>x(n);\n for(int i=0;i<n;i++){\n cin >> x[i];\n }\n int m;cin >> m;\n vector<int>y(m);\n for(int i=0;i<m;i++){\n cin >> y[i];\n }\n \n sort(y.begin(),y.end());\n set<int>unique_x(x.begin(),x.end());\n int count=0;\n for(int val : unique_x){\n if(binary_search(y.data(), m, val) != -1) count++;\n }\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5668, "score_of_the_acc": -1.4395, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_4_B_11008335", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\nusing namespace std;\nint main(){\n int n,q,count,key;\n \n cin >> n;\n vector<int> S(n);\n for(int i = 0;i < n; ++i){\n cin >> S[i];\n }\n\n cin >> q;\n vector<int> T(q);\n for(int j = 0; j < q; ++j){\n cin >> T[j];\n }\n\n int left,right,mid;\n count = 0;\n\n for(int k = 0; k <= q-1; ++k){\n left = 0;\n right = n;\n key = T[k];\n while(left < right){\n mid = (left + right)/2;\n if(S[mid] == key){\n count += 1;\n break;\n }else if(key < S[mid]){\n right = mid;\n }else {\n left = mid +1;\n } \n }\n }\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3536, "score_of_the_acc": -0.5686, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_4_B_11007265", "code_snippet": "#include <iostream>\n#include <vector>\n#include <unordered_set>\nusing namespace std;\n\nint main() {\n int n, q;\n cin >> n;\n vector<int> S(n);\n for (int i = 0; i < n; ++i) {\n cin >> S[i];\n }\n\n cin >> q;\n vector<int> T(q);\n for (int i = 0; i < q; ++i) {\n cin >> T[i];\n }\n\n unordered_set<int> s_set(S.begin(), S.end());\n int count = 0;\n for (int i = 0; i < q; ++i) {\n if (s_set.count(T[i])) {\n ++count;\n }\n }\n\n cout << count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5816, "score_of_the_acc": -1.5, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_4_B_11004772", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint main(){\n int n;\n cin >> n;\n\n int S[n];\n for(int i=0;i<n;i++){\n cin >> S[i];\n //cout << S[i] << endl;\n }\n\n int q, m, mid;\n int count=0;\n int left=0;\n int right=n;\n cin >> q;\n\n int T[q];\n for(int i=0;i<q;i++){\n cin >> T[i];\n //cout << T[i] << endl;\n }\n\n for(int i=0;i<q;i++){\n m = T[i];\n left = 0;\n right = n;\n while(left < right){\n mid = (left+right)/2;\n if(m == S[mid]){\n count++;\n break;\n } else if(m < S[mid]){\n right = mid;\n } else{\n left = mid+1;\n }\n }\n }\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3920, "score_of_the_acc": -0.7255, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_4_B_10998304", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\nint main()\n{\n int n, q, num, count = 0;\n cin >> n;\n vector<int> S, T;\n for (int i = 0; i < n; i++)\n {\n cin >> num;\n S.push_back(num);\n }\n cin >> q;\n for (int i = 0; i < q; i++)\n {\n cin >> num;\n T.push_back(num);\n }\n\n for (int i = 0; i < q; i++)\n {\n int left = 0;\n int right = n;\n int mid;\n int key = T[i];\n\n while (left < right)\n {\n mid = (left + right) / 2;\n\n if (S[mid] == key)\n {\n count++;\n break;\n }\n else if (S[mid] > key)\n {\n right = mid;\n }\n else\n\n {\n left = mid + 1;\n }\n }\n }\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3684, "score_of_the_acc": -0.6291, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_4_B_10998246", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\n\nint main(){\n int n,q;\n cin >> n;\n vector<int> S(n);\n\n for (int i=0;i<n;i++){\n cin >> S[i];\n }\n cin >> q;\n vector<int> T(q);\n for (int i=0;i<q;i++){\n cin >> T[i];\n }\n \n int C=0;\n for (int i=0;i<q;i++){\n int left=0, right=n;\n while (left<right){\n int mid=(left+right)/2;\n if (S[mid]==T[i]){\n C+=1;\n break;\n }\n else if(T[i]<S[mid]){\n right=mid;\n }\n else{\n left=mid+1;\n }\n }\n }\n \n cout << C << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3504, "score_of_the_acc": -0.5556, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_4_B_10998211", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\n\nusing namespace std;\n\nbool Nibun_Tansaku(vector<int>&array, int N, int key,int&swap_count){\n int left = 0;\n int right = N-1;\n while(left <= right){\n swap_count ++;\n int mid = (left + right) / 2;\n if (array[mid] == key){\n return true;\n }else if(key < array[mid]){\n right = mid - 1;\n }else{\n left = mid + 1;\n }\n }\n return false;\n\n}\nint main(){\n int x;\n cin >> x;\n vector<int>S(x);\n for(int i = 0; i < x; i++ ){\n int n;\n cin >> n;\n S[i] = n;\n } \n sort(S.begin(), S.end());\n int y;\n cin >> y;\n vector<int>T(y);\n for(int j = 0; j < y; j++){\n int m;\n cin >> m;\n T[j] = m;\n }\n int match_count = 0;\n int swap_count = 0;\n for(int key : T){\n if (Nibun_Tansaku(S, x, key,swap_count)){\n match_count++;\n }\n }\n cout << match_count << endl;\n return 0;\n \n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3524, "score_of_the_acc": -0.5637, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_4_B_10998174", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\nint main(){\n int n;\n cin >> n;\n vector<int> S(n);\n for (int i =0; i<n; ++i){\n cin >> S[i];\n }\n int q;\n cin >> q;\n vector<int> T(q);\n for (int i=0; i<q; ++i){\n cin >> T[i];\n }\n sort(S.begin(), S.end());\n int count = 0;\n for (int i=0; i<q; ++i){\n int key = T[i];\n int left = 0;\n int right =n;\n bool found = false;\n \n while(left<right){\n int mid = (left + right)/2;\n if(S[mid] == key){\n found = true;\n break;\n }\n else if (key < S[mid]){\n right = mid;\n }\n else {\n left = mid + 1;\n }\n }\n if (found) ++count;\n }\n \n cout << count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3440, "score_of_the_acc": -0.5294, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_4_B_10998087", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\n\nint main(){\n vector<int> S,T;\n int SN,TN,sum=0;\n cin>>SN;\n for(int i=0;i<SN;i++){\n int tmp;\n cin >>tmp;\n S.push_back(tmp);\n }\n cin>>TN;\n for(int i=0;i<TN;i++){\n int tmp;\n cin >>tmp;\n T.push_back(tmp);\n }\n for(int i=0;i<TN;i++){\n int left = 0;\n int right = SN;\n while(left<right){\n int mid = (left+right)/2;\n if (S[mid]==T[i]){\n sum++;break;\n }else if(S[mid]<T[i]){\n left=mid+1;\n }else{\n right=mid;\n }\n }\n }\n cout<<sum<<endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3712, "score_of_the_acc": -0.6405, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_4_B_10998066", "code_snippet": "using namespace std;\n#include <iostream>\n#include <algorithm>\n\n\nint binarySearch(int A[], int n, int key){\n int left = 0;\n int right = n;\n while (left < right){\n int mid = (left + right) / 2;\n if(A[mid] == key){\n return mid;\n }\n else if (key < A[mid]){\n right = mid;\n }else{\n left = mid + 1;\n }\n }\n return -1;\n}\n \nint main(){\n int n;\n cin >> n;\n int S[n];\n for(int i; i < n; i++){\n cin >> S[i];\n }\n int q;\n cin >> q;\n int T[q];\n for(int i; i < q; i++){\n cin >> T[i];\n }\n int a = 0;\n for(int i = 0; i < q; i++){\n if (binarySearch(S, n, T[i]) != -1) {\n a++;\n }\n }\n cout << a << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3928, "score_of_the_acc": -0.7288, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_4_B_10998055", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\n\nint A[10000000],n;\n\nint binarySearch(int key){\n int left = 0;\n int right = n;\n int mid;\n while(left < right){\n mid = (left + right)/2;\n if(A[mid]==key) return mid;\n if(key<A[mid])right=mid;\n else if(key>A[mid])left=mid+1;\n }\n return 0;\n}\n\nint main(){\n int i,q,k,sum=0;\n cin >> n;\n for(i=0;i<n;i++){\n cin >> A[i];\n }\n \n cin >> q;\n for(i=0;i<q;i++){\n cin >> k;\n if(binarySearch(k)) \n sum++;\n }\n cout << sum << endl;\n \n return 0;\n \n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3732, "score_of_the_acc": -0.6487, "final_rank": 13 } ]
aoj_ALDS1_3_C_cpp
Doubly Linked List Your task is to implement a double linked list. Write a program which performs the following operations: insert x: insert an element with key x into the front of the list. delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything. deleteFirst: delete the first element from the list. deleteLast: delete the last element from the list. Input The input is given in the following format: n command 1 command 2 ... command n In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format: insert x delete x deleteFirst deleteLast Output Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space. Constraints The number of operations ≤ 2,000,000 The number of delete operations ≤ 20 0 ≤ value of a key ≤ 10 9 The number of elements in the list does not exceed 10 6 For a delete, deleteFirst or deleteLast operation, there is at least one element in the list. Sample Input 1 7 insert 5 insert 2 insert 3 insert 1 delete 3 insert 6 delete 5 Sample Output 1 6 1 2 Sample Input 2 9 insert 5 insert 2 insert 3 insert 1 delete 3 insert 6 delete 5 deleteFirst deleteLast Sample Output 2 1
[ { "submission_id": "aoj_ALDS1_3_C_11042443", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, x;\nstring s;\nlist<int> l;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0); cout.tie(0);\n\n cin >> n;\n while(n--) {\n cin >> s;\n if(s == \"insert\") {\n cin >> x;\n l.push_front(x);\n }else if(s == \"delete\") {\n cin >> x;\n for(auto it = l.begin(); it != l.end(); it++) {\n if(*it == x) {\n l.erase(it);\n break;\n }\n }\n }else if(s == \"deleteFirst\") l.pop_front();\n else l.pop_back();\n }\n\n for(auto it = l.begin(); it != l.end();) {\n cout << *it;\n if(++it != l.end()) cout << ' ';\n }\n cout << '\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 34648, "score_of_the_acc": -0.7448, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_3_C_11014277", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define ld long double\n#define all(x) x.begin(), x.end()\n\n\nvoid solaiman(){\n int n; cin >> n;\n\n deque<int> dq;\n while(n--){\n string s; cin >> s;\n if(s == \"insert\"){\n int x; cin >> x;\n dq.push_front(x);\n }\n else if(s == \"delete\"){\n int x; cin >> x;\n\n if(!dq.empty()){\n auto it = find(dq.begin(), dq.end(), x);\n\n if(it != dq.end()){\n dq.erase(it);\n }\n }\n }\n else if(s == \"deleteFirst\"){\n if(!dq.empty()){\n dq.pop_front();\n }\n }\n else{\n if(!dq.empty()){\n dq.pop_back();\n }\n }\n }\n\n for(size_t i = 0; i < dq.size(); i++){\n cout << dq[i];\n if(i + 1 < dq.size()) cout << ' ';\n }\n cout << '\\n';\n}\n\nint main(){\n ios::sync_with_stdio(false); cin.tie(0);\ncout.tie(0);\n\n int T = 1; \n for(int i = 0; i < T; i++){\n solaiman();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 7132, "score_of_the_acc": -0.0294, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_3_C_11014248", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n; \n if (!(cin >> n)) return 0;\n list<int> Q;\n\n for (int i = 0; i < n; ++i) {\n string cmd; \n cin >> cmd;\n if (cmd == \"insert\") {\n int x; cin >> x;\n Q.push_front(x);\n } else if (cmd == \"delete\") {\n int x; cin >> x;\n auto it = find(Q.begin(), Q.end(), x);\n if (it != Q.end()) Q.erase(it); // 最初の1個だけ削除\n } else if (cmd == \"deleteFirst\") {\n if (!Q.empty()) Q.pop_front();\n } else if (cmd == \"deleteLast\") {\n if (!Q.empty()) Q.pop_back();\n }\n }\n\n // 出力:要素間のみスペース、末尾は改行のみ\n for (auto it = Q.begin(); it != Q.end(); ) {\n cout << *it;\n if (++it != Q.end()) cout << ' ';\n }\n cout << '\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 34620, "score_of_the_acc": -0.7441, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_3_C_11010345", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n list<int> l;\n\n for (int i = 0; i < n; i++) {\n string cmd;\n cin >> cmd;\n\n if (cmd == \"insert\") \n {\n int x;\n cin >> x;\n l.push_front(x); // 先頭に挿入\n }\n\n else if (cmd == \"delete\") \n {\n int x;\n cin >> x;\n auto it = find(l.begin(), l.end(), x);//検索\n if (it != l.end()) \n {\n l.erase(it);//削除\n }\n }\n\n else if (cmd == \"deleteFirst\") \n {\n if (!l.empty()) \n {\n l.pop_front();\n }\n }\n\n else if (cmd == \"deleteLast\") \n {\n if(!l.empty()) \n {\n l.pop_back();\n }\n }\n }\n\n bool first = true;\n for (int x : l) {\n if (!first) cout << \" \";\n cout << x;\n first = false;\n }\n cout << endl;\n\n return 0;\n}\n\n\n// vectorを使わない理由\n//vector<int> v = {2, 3, 4};\n//v.insert(v.begin(), 1); // 先頭に 1 を追加 → 既存要素を全て後ろに移動", "accuracy": 1, "time_ms": 550, "memory_kb": 34588, "score_of_the_acc": -1.6215, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_3_C_11010312", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n list<int> l;\n\n for (int i = 0; i < n; i++) {\n string cmd;\n cin >> cmd;\n if (cmd == \"insert\") {\n int x;\n cin >> x;\n l.push_front(x); // 先頭に挿入\n }\n else if (cmd == \"delete\") {\n int x;\n cin >> x;\n auto it = find(l.begin(), l.end(), x);\n if (it != l.end()) l.erase(it);\n }\n else if (cmd == \"deleteFirst\") {\n if (!l.empty()) l.pop_front();\n }\n else if (cmd == \"deleteLast\") {\n if (!l.empty()) l.pop_back();\n }\n }\n\n bool first = true;\n for (int x : l) {\n if (!first) cout << \" \";\n cout << x;\n first = false;\n }\n cout << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 550, "memory_kb": 34612, "score_of_the_acc": -1.622, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_3_C_10990258", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n int t;\n cin >> t;\n list<int> l;\n while(t--){\n string op;\n cin >> op;\n if (op == \"insert\"){\n int x;\n cin>>x;\n l.push_front(x);\n }else if(op == \"delete\"){\n int x;\n cin >> x;\n auto it = find(l.begin(),l.end(),x);\n if (it != l.end()) l.erase(it);\n }else if (op == \"deleteFirst\"){\n l.pop_front();\n }else if (op == \"deleteLast\"){\n l.pop_back();\n }\n }\n for (auto it = l.begin();it!=l.end();it++){\n if(it != l.begin()) cout<<\" \";\n cout<<*it;\n }\n cout<<'\\n';\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 34404, "score_of_the_acc": -0.7393, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_3_C_10986831", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\nstruct Node {\n unsigned int key;\n Node* next;\n Node* prev;\n};\n\nNode* sentinel;\n\nvoid init(){\n sentinel = new Node();\n sentinel->next = sentinel;\n sentinel->prev = sentinel;\n}\n\nNode* listSearch(unsigned int key){\n Node* current = sentinel->next;\n while (current != sentinel){\n if (current->key == key) return current; // ← ここを == に修正\n current = current->next;\n }\n return sentinel;\n}\n\nvoid deleteNode(Node* t){\n if (t == sentinel) return;\n t->prev->next = t->next;\n t->next->prev = t->prev;\n delete t;\n}\n\nvoid deleteFirst(){\n Node* t = sentinel->next;\n if (t == sentinel) return;\n deleteNode(t);\n}\n\nvoid deleteLast(){\n Node* t = sentinel->prev;\n if (t == sentinel) return;\n deleteNode(t);\n}\n\nvoid deleteKey(unsigned int key) {\n Node* t = listSearch(key);\n if (t != sentinel) deleteNode(t);\n}\n\nvoid insertFront(unsigned int key) {\n Node* x = new Node();\n x->key = key;\n\n // sentinel の直後(先頭)に挿入\n x->next = sentinel->next; // (1) x の右隣は旧先頭\n x->prev = sentinel; // (2) x の左隣は sentinel\n sentinel->next->prev = x; // (3) 旧先頭の左隣を x に\n sentinel->next = x; // (4) sentinel の右隣を x に(= x が新先頭)\n}\n\nvoid printList() {\n Node* cur = sentinel->next;\n bool first = true;\n while (cur != sentinel) {\n if (!first) cout << ' ';\n cout << cur->key;\n first = false;\n cur = cur->next;\n }\n cout << '\\n';\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n init();\n\n for (int i = 0; i < n; ++i) {\n string com;\n cin >> com;\n\n if (com == \"insert\") {\n unsigned int x; cin >> x;\n insertFront(x);\n } \n else if (com == \"delete\") {\n unsigned int x; cin >> x;\n deleteKey(x);\n } \n else if (com == \"deleteFirst\") {\n deleteFirst();\n } \n else if (com == \"deleteLast\") {\n deleteLast();\n }\n }\n\n printList();\n delete sentinel;\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 34644, "score_of_the_acc": -0.7203, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_3_C_10934380", "code_snippet": "#include <iostream>\n#include <list>\n#include <string>\nusing namespace std;\n\nclass Solution {\npublic:\n int n;\n list<int> lst;\n Solution() {\n cin >> n;\n }\n ~Solution() { }\n\n void solution() {\n for (int i = 0; i < n; ++i) {\n string str;\n int val;\n cin >> str;\n if (str == \"insert\") {\n cin >> val;\n lst.push_front(val);\n } else if (str == \"deleteFirst\") {\n lst.pop_front();\n } else if (str == \"deleteLast\") {\n lst.pop_back();\n } else if (str == \"delete\") {\n cin >> val;\n delete_node(val);\n }\n }\n print();\n }\n void delete_node(int val) {\n for (list<int>::iterator it = lst.begin(); it != lst.end(); ++it) {\n if (*it == val) {\n lst.erase(it);\n break;\n }\n }\n }\n void print() {\n for (auto it = lst.begin(); it != lst.end(); ++it) {\n list<int>::iterator next = it;\n if ((++next) != lst.end()) {\n cout << *it << ' ';\n } else {\n cout << *it << '\\n';\n }\n }\n }\n} ;\nint main() {\n Solution solute;\n solute.solution();\n return 0;\n}", "accuracy": 1, "time_ms": 550, "memory_kb": 34688, "score_of_the_acc": -1.6237, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_3_C_10934379", "code_snippet": "#include <iostream>\n#include <list>\n#include <string>\nusing namespace std;\n\nclass Solution {\npublic:\n int n;\n list<int> lst;\n Solution() {\n cin >> n;\n }\n ~Solution() { }\n\n void solution() {\n for (int i = 0; i < n; ++i) {\n string str;\n int val;\n cin >> str;\n if (str == \"insert\") {\n cin >> val;\n lst.push_front(val);\n } else if (str == \"deleteFirst\") {\n lst.pop_front();\n } else if (str == \"deleteLast\") {\n lst.pop_back();\n } else if (str == \"delete\") {\n cin >> val;\n delete_node(val);\n }\n }\n print();\n }\n void delete_node(int val) {\n list<int>::iterator it;\n for (it = lst.begin(); it != lst.end(); ++it) {\n if (*it == val) {\n lst.erase(it);\n break;\n }\n }\n }\n void print() {\n for (auto it = lst.begin(); it != lst.end(); ++it) {\n list<int>::iterator next = it;\n if ((++next) != lst.end()) {\n cout << *it << ' ';\n } else {\n cout << *it << '\\n';\n }\n }\n }\n} ;\nint main() {\n Solution solute;\n solute.solution();\n return 0;\n}", "accuracy": 1, "time_ms": 550, "memory_kb": 34572, "score_of_the_acc": -1.6211, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_3_C_10934363", "code_snippet": "#include <iostream>\nusing namespace std;\n\nclass Solution {\npublic:\n struct Node {\n int value;\n Node *prev, *next;\n Node() {}\n Node(int V) : value(V), prev(nullptr), next(nullptr) {}\n Node(int V, Node *P, Node *N) : value(V), prev(P), next(N) {}\n } ;\n int n;\n Node *head, *tail;\n Solution() {\n cin >> n;\n head = nullptr, tail = nullptr;\n }\n ~Solution() { }\n\n void solution() {\n for (int i = 0; i < n; ++i) {\n string str;\n int val;\n cin >> str;\n if (str == \"insert\") {\n cin >> val;\n insert(val);\n } else if (str == \"deleteFirst\") {\n delete_first();\n } else if (str == \"deleteLast\") {\n delete_last();\n } else if (str == \"delete\") {\n cin >> val;\n delete_node(val);\n }\n }\n print();\n }\n void insert(int val) {\n Node *node = new Node(val, nullptr, head);\n if (head == nullptr) {\n head = node;\n tail = node;\n } else {\n head = node;\n head->next->prev = head;\n }\n }\n void delete_node(int val) {\n Node *node(head);\n while (node != nullptr && node->value != val) {\n node = node->next;\n }\n if (node == nullptr) {\n return;\n }\n if (node == head) {\n delete_first();\n } else if (node == tail) {\n delete_last();\n } else {\n node->prev->next = node->next;\n node->next->prev = node->prev;\n delete node;\n }\n }\n void delete_first() {\n Node *node = head;\n head = node->next;\n if (head != nullptr) {\n head->prev = nullptr;\n } else {\n tail = nullptr;\n }\n delete node;\n }\n void delete_last() {\n Node *node = tail;\n tail = node->prev;\n if (tail != nullptr) {\n tail->next = nullptr;\n } else {\n head = nullptr;\n }\n delete node;\n }\n void print() {\n Node *node = head;\n while (node->next != nullptr) {\n cout << node->value << ' ';\n node = node->next;\n }\n cout << node->value << '\\n';\n }\n} ;\nint main() {\n Solution solute;\n solute.solution();\n return 0;\n}", "accuracy": 1, "time_ms": 550, "memory_kb": 34452, "score_of_the_acc": -1.6184, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_3_C_10922605", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)\n#define rep2(i, s, n) for (ll i = (ll)(s); i < (ll)(n); i++)\n\n\n// vectorを出力する\nvoid vec1print(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid vec2print(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<ll> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<ll> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll x, ll y, ll limit_x, ll limit_y) {\n return 0 <= x and x < limit_x and 0 <= y and y < limit_y;\n}\nstruct linked_list {\n ll prev;\n ll next;\n ll key;\n};\n\nlinked_list l[2000000];\nll head = -1;\nll tail = -1;\nll unused = 0;\n\nvoid insert(ll x) {\n if (head == -1) {\n l[0].key = x;\n l[0].prev = -1;\n l[0].next = -1;\n head = 0;\n tail = 0;\n unused = 1;\n }\n else {\n l[unused].key = x;\n l[unused].prev = -1;\n l[unused].next = head;\n l[head].prev = unused;\n head = unused;\n unused++;\n }\n}\n\nvoid delete_node(ll x) {\n ll target = head;\n while (target != -1) {\n if (l[target].key == x) {\n ll prev = l[target].prev;\n ll next = l[target].next;\n\n if (prev != -1) {\n l[prev].next = next;\n }\n else {\n head = next;\n }\n if (next != -1) {\n l[next].prev = prev;\n }\n else {\n tail = prev;\n }\n break;\n }\n target = l[target].next;\n }\n}\n\nvoid deleteFirst() {\n if (head == -1) return;\n ll next = l[head].next;\n if (next != -1) {\n l[next].prev = -1;\n }\n else {\n tail = -1;\n }\n head = next;\n}\n\nvoid deleteLast() {\n if (tail == -1) return;\n ll prev = l[tail].prev;\n if (prev != -1) {\n l[prev].next = -1;\n }\n else {\n head = -1;\n }\n tail = prev;\n}\n\nvoid print_list() {\n if (head == -1) return;\n ll target = head;\n while (target != -1) {\n cout << l[target].key;\n target = l[target].next;\n if (target != -1) cout << \" \";\n }\n cout << endl;\n}\n\n\n// main\nvoid solve() {\n ll n;\n cin >> n;\n rep(i,n) {\n string s;\n ll x;\n cin >> s;\n if (s == \"insert\") {\n cin >> x;\n insert(x);\n }\n else if (s == \"delete\") {\n cin >> x;\n delete_node(x);\n }\n else if (s == \"deleteFirst\") {\n deleteFirst();\n }\n else if (s == \"deleteLast\") {\n deleteLast();\n }\n }\n print_list();\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 380, "memory_kb": 30140, "score_of_the_acc": -1.107, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_3_C_10920197", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\nlong long ar[200005];\nint main()\n{\n optimize();\n long long n,m,i;\n cin>>n;\n list<long long>li;\n while(n--)\n {\n string s;\n cin>>s;\n if(s==\"insert\")\n {\n cin>>m;\n li.push_front(m);\n }\n else if(s==\"delete\")\n {\n cin>>m;\n auto it=find(li.begin(),li.end(),m);\n if(it != li.end())\n {\n li.erase(it);\n }\n }\n else if(s==\"deleteFirst\")\n {\n li.pop_front();\n }\n else if (s==\"deleteLast\")\n {\n li.pop_back();\n }\n }\n for(auto it=li.begin(); it!=li.end();it++)\n {\n if(it!=li.begin())\n {\n cout<<\" \";\n }\n cout<<*it;\n }\n cout<<\"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 34412, "score_of_the_acc": -0.7151, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_3_C_10918318", "code_snippet": "# include <iostream>\n# include <list>\nusing namespace std;\n\nint main() {\n \n list<int> lst;\n\n int n; cin >> n;\n while (n--) {\n string cmd; cin >> cmd;\n if (cmd == \"insert\") { //头部插入节点\n int x; cin >> x;\n lst.insert(lst.begin(), x);\n }\n else if (cmd == \"delete\") { //删除第一个值为x的节点\n int x; cin >> x;\n //遍历list,list不支持随机访问必须用迭代器遍历\n for (auto it = lst.begin(); it != lst.end(); it++)\n {\n if (*it == x) {\n //迭代器删除\n //不能用值删除,会删除所有val==x的节点\n lst.erase(it);\n break;\n }\n }\n }\n else if (cmd == \"deleteFirst\") { //删除头部元素\n lst.pop_front();\n }\n else { //删除尾部元素\n lst.pop_back();\n }\n }\n\n for (auto it = lst.begin(); it != lst.end(); it++)\n {\n if (it != lst.begin()) cout << \" \";\n cout << *it;\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 550, "memory_kb": 34288, "score_of_the_acc": -1.6147, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_3_C_10903986", "code_snippet": "using namespace std;\n#include <iostream>\n#include <string>\n#include <vector>\nstruct TNode\n{\n TNode *Next;\n TNode *Previous;\n int Element;\n};\nclass TList\n{\nprivate:\n TNode *Top = nullptr;\n TNode *Last = nullptr;\n\npublic:\n void Insert(int &Element)\n {\n TNode *NewNodeptr = new TNode{Top, nullptr, Element};\n if (Top == nullptr && Last == nullptr)\n { /// 初期状態の処理を記述\n Last = NewNodeptr;\n }\n else\n {\n Top->Previous = NewNodeptr;\n }\n Top = NewNodeptr;\n }\n void DeleteOperation(TNode *Target)\n {\n if (Target == nullptr)\n {\n return;\n }\n if (Target == Top)\n {\n Top = Top->Next;\n }\n else\n {\n Target->Previous->Next = Target->Next;\n }\n if (Target == Last)\n {\n Last = Last->Previous;\n }\n else\n {\n Target->Next->Previous = Target->Previous;\n }\n delete Target;\n return;\n }\n TNode *Find(int Element)\n {\n for (TNode *Current = Top; Current != nullptr; Current = Current->Next)\n {\n if (Current->Element == Element)\n {\n return Current;\n }\n }\n return nullptr;\n }\n void Delete(int &Element)\n {\n DeleteOperation(Find(Element));\n }\n void DeleteFirst()\n {\n DeleteOperation(Top);\n }\n void DeleteLast()\n {\n DeleteOperation(Last);\n }\n void ShowAllElements()\n {\n if (Top == nullptr || Last == nullptr)\n {\n return;\n }\n while (Top->Next != nullptr)\n {\n cout << Top->Element << \" \";\n Top = Top->Next;\n }\n cout << Top->Element << \"\\n\";\n }\n}\n;\n\nint main()\n{\n int N;\n cin >> N;\n TList list;\n for (int index = 0; index < N; index++)\n {\n string Command;\n cin >> Command;\n if (Command == \"insert\")\n {\n int Element;\n cin >> Element;\n list.Insert(Element);\n }\n else if (Command == \"delete\")\n {\n int Element;\n cin >> Element;\n list.Delete(Element);\n }\n else if (Command == \"deleteFirst\")\n {\n list.DeleteFirst();\n }\n else\n {\n list.DeleteLast();\n }\n }\n list.ShowAllElements();\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 34816, "score_of_the_acc": -1.2851, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_3_C_10899432", "code_snippet": "#include <bits/stdc++.h>\n\n\ntemplate <typename T>\nclass Node{\n public:\n T value_;\n Node<T>* prev_;\n Node<T>* next_;\n\n Node(T v, Node<T>* prev, Node<T>* next): value_(v), prev_(prev), next_(next){} \n};\n\ntemplate <typename T>\nclass List{\n Node<T> lSentinel = Node<T>(T(),nullptr, nullptr);\n Node<T> rSentinel = Node<T>(T(),nullptr, nullptr);\n\n public:\n List(){\n lSentinel.next_ = &rSentinel;\n rSentinel.prev_ = &lSentinel;\n }\n \n void push_front(T value){\n Node<T>* newNode = new Node<T>(value, &lSentinel, lSentinel.next_);\n\n lSentinel.next_->prev_ = newNode;\n lSentinel.next_ = newNode;\n }\n\n void push_back(T value){\n Node<T>* newNode = new Node<T>(value, rSentinel.prev_, &rSentinel);\n\n rSentinel.prev_->next_ =newNode;\n rSentinel.prev_ = newNode;\n }\n\n void delete_node(T v){\n Node<T>* node = lSentinel.next_;\n while(node != &rSentinel){\n if(node->value_ == v){\n node->prev_->next_ = node->next_;\n node->next_->prev_ = node->prev_;\n delete node;\n break;\n }\n node = node->next_;\n }\n }\n\n void pop_front(){\n if(lSentinel.next_ == &rSentinel) return;\n\n Node<T>* target = lSentinel.next_;\n lSentinel.next_ = target->next_;\n target->next_->prev_ = &lSentinel;\n delete target;\n }\n\n void pop_back(){\n if(rSentinel.prev_ == &lSentinel) return;\n\n Node<T>* target = rSentinel.prev_;\n rSentinel.prev_ = target->prev_;\n target->prev_->next_ = &rSentinel;\n delete target;\n }\n\n class Itarator{\n Node<T>* node_;\n public:\n Itarator(Node<T>* node):node_(node){}\n T& operator*(){return node_->value_;}\n Itarator& operator++(){node_ = node_->next_; return *this;}\n bool operator!=(const Itarator& other)const {return node_ != other.node_;}\n };\n\n Itarator begin(){return Itarator(lSentinel.next_);}\n Itarator end(){return Itarator(&rSentinel);}\n};\n\nint main(){\n int n;\n std::cin >> n;\n List<long long> list;\n for (int i = 0; i < n; i++){\n std::string c; std::cin >> c;\n if(c ==\"insert\"){\n int x; std::cin >> x;\n list.push_front(x);\n }else if(c == \"delete\"){\n int x; std::cin >> x;\n list.delete_node(x);\n }else if(c == \"deleteFirst\"){\n list.pop_front();\n }else if(c == \"deleteLast\"){\n list.pop_back();\n }\n }\n std::string ans;\n for(auto value: list){\n ans += std::to_string(value) + \" \";\n }\n ans.pop_back();\n std::cout << ans << std::endl;\n}", "accuracy": 1, "time_ms": 550, "memory_kb": 34724, "score_of_the_acc": -1.6245, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_3_C_10898226", "code_snippet": "#include <cstdio>\n\nstruct Node {\n int key;\n Node *next;\n Node *prev;\n};\n\nNode* nil = nullptr;\n\nNode* listSearch(int key) {\n Node* cur = nil->next;\n while (cur != nil && cur->key != key) {\n cur = cur->next;\n }\n return cur;\n}\n\nvoid init() {\n nil = new Node();\n nil->next = nil;\n nil->prev = nil;\n}\n\nvoid printList() {\n Node* cur = nil->next;\n bool first = true;\n while (cur != nil) {\n if (!first) printf(\" \");\n printf(\"%d\", cur->key);\n first = false;\n cur = cur->next;\n }\n printf(\"\\n\");\n}\n\nvoid deleteNode(Node* t) {\n if (t == nil) return;\n t->prev->next = t->next;\n t->next->prev = t->prev;\n delete t;\n}\n\nvoid deleteFirst() {\n deleteNode(nil->next);\n}\n\nvoid deleteLast() {\n deleteNode(nil->prev);\n}\n\nvoid deleteKey(int key) {\n deleteNode(listSearch(key));\n}\n\nvoid insert(int key) {\n Node* x = new Node();\n x->key = key;\n x->next = nil->next;\n nil->next->prev = x;\n nil->next = x;\n x->prev = nil;\n}\n\nint main() {\n int n;\n scanf(\"%d\", &n);\n\n init();\n\n for (int i = 0; i < n; i++) {\n char com[20];\n int key;\n scanf(\"%s\", com);\n\n if (com[0] == 'i') {\n scanf(\"%d\", &key);\n insert(key);\n } else if (com[0] == 'd') {\n if (com[6] == 'F') {\n deleteFirst();\n } else if (com[6] == 'L') {\n deleteLast();\n } else {\n scanf(\"%d\", &key);\n deleteKey(key);\n }\n }\n }\n\n printList();\n\n // 最後に番兵も解放\n delete nil;\n\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 34032, "score_of_the_acc": -0.7065, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_3_C_10897583", "code_snippet": "#include <bits/stdc++.h>\n#include <cstddef>\nusing namespace std;\n\nconst int CAPACITY = 2000000;\n\ntemplate <typename T> struct DataLink {\n T data;\n DataLink *pre;\n DataLink *next;\n\n DataLink() : data{}, pre{nullptr}, next{nullptr} {}\n DataLink(T i, DataLink *pre, DataLink *next)\n : data{i}, pre{pre}, next{next} {}\n};\n\ntemplate <typename T> struct LinkedList {\n array<DataLink<T>, CAPACITY> link_stack;\n int stack_tail = 0;\n DataLink<T> *first = nullptr;\n DataLink<T> *last = nullptr;\n int count = 0;\n\n void scan_pre(DataLink<T> *&d) { d = d->pre; }\n void scan_next(DataLink<T> *&d) { d = d->next; }\n\n bool is_empty() { return count == 0; }\n\n void insert(const T &data) {\n link_stack[stack_tail] = (DataLink<T>(data, nullptr, first));\n DataLink<T> *new_data = &link_stack[stack_tail];\n stack_tail++;\n\n if (is_empty()) {\n last = new_data;\n } else {\n first->pre = new_data;\n }\n first = new_data;\n count++;\n }\n\n void del_first() {\n if (count == 1) {\n first = nullptr;\n last = nullptr;\n } else {\n first->next->pre = nullptr;\n first = first->next;\n }\n count--;\n }\n void del_last() {\n if (count == 1) {\n first = nullptr;\n last = nullptr;\n } else {\n last->pre->next = nullptr;\n last = last->pre;\n }\n count--;\n }\n void del(const T &del_data) {\n DataLink<T> *seek = first;\n while (seek->data != del_data) {\n scan_next(seek);\n if (seek == nullptr) {\n return;\n }\n }\n\n if (seek == first) {\n del_first();\n } else if (seek == last) {\n del_last();\n } else {\n seek->pre->next = seek->next;\n seek->next->pre = seek->pre;\n count--;\n }\n }\n};\n\nint main() {\n int n;\n cin >> n;\n LinkedList<int> l;\n for (int i = 0; i < n; i++) {\n char buf[15];\n int key;\n scanf(\"%s\", buf);\n string command = buf;\n if (command == \"insert\") {\n cin >> key;\n l.insert(key);\n } else if (command == \"delete\") {\n cin >> key;\n l.del(key);\n } else if (command == \"deleteFirst\")\n l.del_first();\n else if (command == \"deleteLast\")\n l.del_last();\n }\n\n DataLink<int> *seek = l.first;\n for (int i = 0; i < l.count; i++) {\n if (i == l.count - 1)\n cout << seek->data << endl;\n else\n cout << seek->data << \" \";\n\n if (seek->next != nullptr)\n l.scan_next(seek);\n }\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 50360, "score_of_the_acc": -1.3659, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_3_C_10897582", "code_snippet": "#include <bits/stdc++.h>\n#include <cstddef>\nusing namespace std;\n\nconst int CAPACITY = 100000;\n\ntemplate <typename T> struct DataLink {\n T data;\n DataLink *pre;\n DataLink *next;\n\n DataLink() : data{}, pre{nullptr}, next{nullptr} {}\n DataLink(T i, DataLink *pre, DataLink *next)\n : data{i}, pre{pre}, next{next} {}\n};\n\ntemplate <typename T> struct LinkedList {\n array<DataLink<T>, CAPACITY> link_stack;\n int stack_tail = 0;\n DataLink<T> *first = nullptr;\n DataLink<T> *last = nullptr;\n int count = 0;\n\n void scan_pre(DataLink<T> *&d) { d = d->pre; }\n void scan_next(DataLink<T> *&d) { d = d->next; }\n\n bool is_empty() { return count == 0; }\n\n void insert(const T &data) {\n link_stack[stack_tail] = (DataLink<T>(data, nullptr, first));\n DataLink<T> *new_data = &link_stack[stack_tail];\n stack_tail++;\n\n if (is_empty()) {\n last = new_data;\n } else {\n first->pre = new_data;\n }\n first = new_data;\n count++;\n }\n\n void del_first() {\n if (count == 1) {\n first = nullptr;\n last = nullptr;\n } else {\n first->next->pre = nullptr;\n first = first->next;\n }\n count--;\n }\n void del_last() {\n if (count == 1) {\n first = nullptr;\n last = nullptr;\n } else {\n last->pre->next = nullptr;\n last = last->pre;\n }\n count--;\n }\n void del(const T &del_data) {\n DataLink<T> *seek = first;\n while (seek->data != del_data) {\n scan_next(seek);\n if (seek == nullptr) {\n return;\n }\n }\n\n if (seek == first) {\n del_first();\n } else if (seek == last) {\n del_last();\n } else {\n seek->pre->next = seek->next;\n seek->next->pre = seek->pre;\n count--;\n }\n }\n};\n\nint main() {\n int n;\n cin >> n;\n LinkedList<int> l;\n for (int i = 0; i < n; i++) {\n char buf[15];\n int key;\n scanf(\"%s\", buf);\n string command = buf;\n if (command == \"insert\") {\n cin >> key;\n l.insert(key);\n } else if (command == \"delete\") {\n cin >> key;\n l.del(key);\n } else if (command == \"deleteFirst\")\n l.del_first();\n else if (command == \"deleteLast\")\n l.del_last();\n }\n\n DataLink<int> *seek = l.first;\n for (int i = 0; i < l.count; i++) {\n if (i == l.count - 1)\n cout << seek->data << endl;\n else\n cout << seek->data << \" \";\n\n if (seek->next != nullptr)\n l.scan_next(seek);\n }\n}", "accuracy": 0.9, "time_ms": 230, "memory_kb": 5824, "score_of_the_acc": -0.1951, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_3_C_10894193", "code_snippet": "using namespace std;\n#include <iostream>\n#include <string>\n#include <vector>\nstruct TNode\n{\n TNode *Next;\n TNode *Previous;\n int Element;\n};\nclass TList\n{\nprivate:\n TNode *Top = nullptr;\n TNode *Last = nullptr;\n\npublic:\n void Insert(int &Element)\n {\n TNode *NewNodeptr = new TNode{Top, nullptr, Element};\n if (Top == nullptr && Last == nullptr)\n { /// 初期状態の処理を記述\n Last = NewNodeptr;\n }\n else\n {\n Top->Previous = NewNodeptr;\n }\n Top = NewNodeptr;\n }\n void DeleteOperation(TNode *Target)\n {\n if (Target == nullptr)\n {\n return;\n }\n else\n {\n if (Target == Top)\n {\n Top = Top->Next;\n }\n else\n {\n Target->Previous->Next = Target->Next;\n }\n if (Target == Last)\n {\n Last = Last->Previous;\n }\n else\n {\n Target->Next->Previous = Target->Previous;\n }\n delete Target;\n return;\n }\n }\n TNode *Find(int Element)\n {\n for (TNode *Current = Top; Current != nullptr; Current = Current->Next)\n {\n if (Current->Element == Element)\n {\n return Current;\n }\n }\n return nullptr;\n }\n void Delete(int &Element)\n {\n DeleteOperation(Find(Element));\n }\n void DeleteFirst()\n {\n DeleteOperation(Top);\n }\n void DeleteLast()\n {\n DeleteOperation(Last);\n }\n void ShowAllElements()\n {\n if (Top != nullptr && Last != nullptr)\n {\n while (Top->Next != nullptr)\n {\n cout << Top->Element << \" \";\n Top = Top->Next;\n }\n cout << Top->Element << \"\\n\";\n }\n }\n};\n\nint main()\n{\n int N;\n cin >> N;\n TList list;\n for (int index = 0; index < N; index++)\n {\n string Command;\n cin >> Command;\n if (Command == \"insert\")\n {\n int Element;\n cin >> Element;\n list.Insert(Element);\n }\n else if (Command == \"delete\")\n {\n int Element;\n cin >> Element;\n list.Delete(Element);\n }\n else if (Command == \"deleteFirst\")\n {\n list.DeleteFirst();\n }\n else\n {\n list.DeleteLast();\n }\n }\n list.ShowAllElements();\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 34688, "score_of_the_acc": -1.2823, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_3_C_10891197", "code_snippet": "#include <bits/stdc++.h>\n\n\nint main(){\n int N;\n std::cin >> N;\n std::list<int> A;\n for (int i = 0; i < N; i++){\n std::string cmd;\n std::cin >> cmd;\n if(cmd == \"insert\"){\n int v; std::cin >> v;\n A.push_front(v);\n }else if(cmd == \"delete\"){\n int v; std::cin >> v;\n auto it = std::find(A.begin(), A.end(), v);\n if(it != A.end()) A.erase(it);\n }else if( cmd == \"deleteFirst\"){\n A.pop_front();\n }else if( cmd == \"deleteLast\"){\n A.pop_back();\n }\n }\n\n std::string ans = \"\";\n for(auto v: A){\n ans += std::to_string(v) + \" \";\n } \n ans.pop_back();\n std::cout << ans << std::endl;\n}", "accuracy": 1, "time_ms": 560, "memory_kb": 34416, "score_of_the_acc": -1.642, "final_rank": 19 } ]
aoj_ALDS1_4_D_cpp
Allocation You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load $P$. Write a program which reads $n$, $k$ and $w_i$, and reports the minimum value of the maximum load $P$ to load all packages from the belt conveyor. Input In the first line, two integers $n$ and $k$ are given separated by a space character. In the following $n$ lines, $w_i$ are given respectively. Output Print the minimum value of $P$ in a line. Constraints $1 \leq n \leq 100,000$ $1 \leq k \leq 100,000$ $1 \leq w_i \leq 10,000$ Sample Input 1 5 3 8 1 7 3 9 Sample Output 1 10 If the first truck loads two packages of $\{8, 1\}$, the second truck loads two packages of $\{7, 3\}$ and the third truck loads a package of $\{9\}$, then the minimum value of the maximum load $P$ shall be 10. Sample Input 2 4 2 1 2 2 6 Sample Output 2 6 If the first truck loads three packages of $\{1, 2, 2\}$ and the second truck loads a package of $\{6\}$, then the minimum value of the maximum load $P$ shall be 6.
[ { "submission_id": "aoj_ALDS1_4_D_10995248", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nint main(){\n int BaggageCount, TrackCount;\n cin >> BaggageCount >> TrackCount;\n vector<int> BaggageWeights(BaggageCount);\n for (int i = 0; i < BaggageCount; i++){\n cin >> BaggageWeights.at(i);\n }\n int MinimumCapacity = *max_element(begin(BaggageWeights), end(BaggageWeights)) - 1;\n int MaximumCapacity = 1000000000;\n while (MaximumCapacity - MinimumCapacity > 1){\n int MidiumCapacity = (MinimumCapacity + MaximumCapacity)/2;\n int NowTrackIndex = 0;\n int NowTotalWeight = 0;\n for (int i = 0; i < BaggageCount; i++){\n if (NowTotalWeight + BaggageWeights.at(i) <= MidiumCapacity){\n NowTotalWeight += BaggageWeights.at(i);\n }\n else{\n NowTrackIndex++;\n NowTotalWeight = BaggageWeights.at(i);\n }\n }\n if (NowTrackIndex >= TrackCount){\n MinimumCapacity = MidiumCapacity;\n }\n else{\n MaximumCapacity = MidiumCapacity;\n }\n }\n cout << MaximumCapacity << \"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3636, "score_of_the_acc": -0.5215, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_4_D_10937289", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\nvl w;\nll k, n;\nll r, l;\n\n// pは何個積めるのか\nll check(ll p) {\n ll i = 0;\n nfor (j, 0, k) {\n ll s = 0;\n while (s + w[i] <= p) {\n s += w[i];\n i++;\n if (i == n) return n;\n }\n }\n return i;\n}\n\n\n// main\nvoid solve() {\n cin >> n >> k;\n w.resize(n);\n rep(i,n) {\n cin >> w[i];\n }\n l = 0;\n r = 100000 * 10000;\n ll mid;\n while (r - l > 1) {\n mid = (l + r) / 2;\n ll v = check(mid);\n if (v >= n) {\n r = mid;\n }\n else {\n l = mid;\n }\n }\n cout << r << endl;\n\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4096, "score_of_the_acc": -0.901, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_4_D_10886736", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\nint n, k;\nvector<int>w;\nbool isok(int mid) {\n int P = mid; //p = 残りの荷物\n int truck = 0;\n for (int i = 0; i < n; i++) {\n if ( mid < w[i])\n return false;\n if (P >= w[i])\n P -= w[i];\n else {\n ++truck;\n P = mid - w[i];\n }\n }\n truck++;\n return truck <= k;\n}\nint main()\n{\n cin >> n >> k;\n for (int i = 0; i < n; i++) {\n int temp;\n cin >> temp;\n w.push_back(temp);\n }\n\n int ng = 0;\n int ok = 1000000000;\n //めぐる式\n while(abs(ok - ng) > 1) {\n int mid = (ok + ng) / 2;\n if(isok(mid))\n ok = mid;\n else \n ng = mid;\n }\n \n cout << ok << endl;\n return 0;\n \n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3748, "score_of_the_acc": -0.6139, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_4_D_10851441", "code_snippet": "#include <iostream>\nusing namespace std;\ntypedef long long ll;\nconst int N=1e5+5;\nint n,k;\nll t[N];\nint check(ll p)\n{\n int i=0;\n for(int j=0;j<k;j++)\n {\n ll s=0;\n while(s+t[i]<=p)\n {\n s+=t[i];\n i++;\n if(i==n)\n return n;\n }\n }\n return i;\n}\nll solve()\n{\n ll left=0;\n ll right=100000*10000;\n ll mid;\n while(right-left>1)\n {\n mid=(right+left)/2;\n int v=check(mid);\n if(v>=n) right =mid;\n else left=mid;\n }\n return right;\n}\nint main()\n{\n cin>>n>>k;\n for(int i=0;i<n;i++) cin>>t[i];\n ll ans=solve();\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4136, "score_of_the_acc": -0.934, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_4_D_10803674", "code_snippet": "#include <bits/stdc++.h>\n#include <numeric>\n#define rep(i,a,b) for(ll i = (a); i < (b); i++)\n#define vec1 vector<int>\n#define vec2 vector<vector<int>>\n#define vec3 vector<vector<vector<int>>>\n#define svec vector<char>\n#define svec2 vector<vector<char>>\n#define svec3 vector<vector<vector<char>>>\nusing ll = long long;\nusing namespace std;\n\nint main() {\n int n,k;\n cin >> n >> k;\n vec1 data(n);\n rep(i,0,n){\n cin >> data[i];\n }\n ll maxum = 10000 * 100000;\n int left = 1;\n int right = maxum;\n while(left != right){\n int count = 0;\n int mid = (left + right)/2;\n rep(i,0,k){\n int r = mid;\n while(count != n && r- data[count] >= 0 ){\n r -= data[count];\n count++;\n }\n \n }\n if(count == n){\n right = mid;\n }else{\n left = mid +1;\n }\n }\n cout << left << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3644, "score_of_the_acc": -0.5281, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_4_D_10793311", "code_snippet": "#include <cstdio>\n\nint v[100000];\n\nint main(){\n int n, k;\n scanf(\"%d %d\",&n, &k);\n int max = 1;\n int sum = 0;\n int *p = v;\n for(int i = 0; i < n; i++){\n scanf(\"%d\",p);\n if(max < *p) max = *p;\n sum += *p;\n p++;\n }\n\n int avg = (sum / k) + ((sum % k > 0) ? 1 : 0);\n int b = (max > avg) ? max : avg;\n\n while(b <= sum){\n int l = 0;\n int m = 1;\n for(int i = 0; i < n; i++){\n l += v[i];\n if(l > b){\n m++;\n if(m > k) break;\n l = v[i];\n }\n }\n if(m <= k) break;\n b++;\n }\n \n printf(\"%d\\n\",b);\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 3308, "score_of_the_acc": -0.6308, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_4_D_10793303", "code_snippet": "#include <cstdio>\n#include <vector>\n\nint v[100000];\n\nint main(){\n int n, k;\n scanf(\"%d %d\",&n, &k);\n std::vector<int> v;\n v.reserve(n);\n int max = 1;\n int sum = 0;\n for(int i = 0; i < n; i++){\n int val;\n scanf(\"%d\",&val);\n if(max < val) max = val;\n sum += val;\n v[i] = val;\n }\n\n int avg = (sum / k) + ((sum % k > 0) ? 1 : 0);\n int b = (max > avg) ? max : avg;\n\n while(b <= sum){\n int l = 0;\n int m = 1;\n for(int i = 0; i < n; i++){\n l += v[i];\n if(l > b){\n m++;\n if(m > k) break;\n l = v[i];\n }\n }\n if(m <= k) break;\n b++;\n }\n\n printf(\"%d\\n\",b);\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 3004, "score_of_the_acc": -0.66, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_4_D_10793302", "code_snippet": "#include <iostream>\n#include <vector>\n\nint main(){\n int n, k;\n std::cin >> n >> k;\n std::vector<int> v;\n v.reserve(n);\n int max = 1;\n int sum = 0;\n for(int i = 0; i < n; i++){\n int val;\n std::cin >> val;\n if(max < val) max = val;\n sum += val;\n v.push_back(val);\n }\n\n int avg = (sum / k) + ((sum % k > 0) ? 1 : 0);\n int b = (max > avg) ? max : avg;\n\n while(b <= sum){\n int l = 0;\n int m = 1;\n for(int i = 0; i < n; i++){\n l += v[i];\n if(l > b){\n m++;\n if(m > k) break;\n l = v[i];\n }\n }\n if(m <= k) break;\n b++;\n }\n\n std::cout<<b<<std::endl;\n\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 3612, "score_of_the_acc": -1.1617, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_4_D_10752770", "code_snippet": "#include<iostream>\n#include<list>\n#include<vector>\n#include<algorithm>\n#include<numeric>\n#include<climits>\nusing namespace std;\n\nbool f(int n, int A[], int k, int max){\n int T[k];\n for(int i=0; i<k; i++){\n T[i] = 0;\n }\n\n int j = 0;\n for(int i=0; i<n; i++){\n if(max < T[j] + A[i]){\n j++;\n i--;\n }else{\n T[j] += A[i];\n }\n if(k <= j)\n return false;\n }\n return true;\n}\n\nint main(){\n int n, k;\n cin >> n >> k;\n int A[n];\n int ave = 0;\n int input;\n for(int i=0; i<n; i++){\n cin >> A[i];\n ave += A[i];\n }\n ave /= k;\n while(!f(n, A, k, ave)){\n ave++;\n }\n cout << ave << endl;\n}", "accuracy": 1, "time_ms": 510, "memory_kb": 4096, "score_of_the_acc": -1.901, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_4_D_10732508", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n// 入力データ\nint n, k;\nvector<int> w;\n\n// 判定関数:Pを上限として荷物を積んだとき、トラックがk台以内に収まるか\nbool canLoad(int P) {\n int trucks = 1; // 現在使っているトラック数\n int current = 0; // 今のトラックの積載量\n\n for (int i = 0; i < n; ++i) {\n if (w[i] > P) return false; // 荷物が一つでも超えたら無理\n\n if (current + w[i] <= P) {\n current += w[i]; // 今のトラックに積める\n } else {\n trucks++; // 新しいトラックを使う\n current = w[i];\n }\n }\n\n return trucks <= k;\n}\n\nint main() {\n cin >> n >> k;\n w.resize(n);\n for (int i = 0; i < n; ++i) {\n cin >> w[i];\n }\n\n // 二分探索範囲\n int left = 0;\n int right = 1e9; // 最大は荷物合計まで\n\n while (left < right) {\n int mid = (left + right) / 2;\n if (canLoad(mid)) {\n right = mid; // より小さいPがあるか探す\n } else {\n left = mid + 1; // Pが小さすぎて無理\n }\n }\n\n cout << left << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3600, "score_of_the_acc": -0.4917, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_4_D_10732460", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nbool can_split(const vector<int>& w, int k, int max_load) {\n int count = 1, sum = 0;\n for (int wi : w) {\n if (wi > max_load) return false;\n if (sum + wi <= max_load) {\n sum += wi;\n } else {\n count++;\n sum = wi;\n }\n }\n return count <= k;\n}\n\nint main() {\n int n, k;\n cin >> n >> k;\n vector<int> w(n);\n int total = 0, maxw = 0;\n for (int i = 0; i < n; i++) {\n cin >> w[i];\n total += w[i];\n maxw = max(maxw, w[i]);\n }\n int left = maxw, right = total, ans = total;\n while (left <= right) {\n int mid = (left + right) / 2;\n if (can_split(w, k, mid)) {\n ans = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3644, "score_of_the_acc": -0.5281, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_4_D_10708948", "code_snippet": "#include<iostream>\nusing namespace std;\nint n, k, w[100000];\n\nint check(long long P) {\n int j = 0;\n for (int i = 0; i < k; i++) {\n int s = 0;\n while (j < n && s + w[j] <= P) {\n s += w[j];\n j++;\n }\n }\n return j;\n}\n\nint binarySearch() {\n long long left = 0;\n long long right = 10000*100000;\n while (left < right) {\n int mid = (left + right)/2;\n int v = check(mid);\n if (v >= n) right = mid;\n else left = mid + 1;\n }\n return right;\n}\n\nint main() {\n cin >> n >> k;\n for (int i = 0; i < n; i++) cin >> w[i];\n int ans = binarySearch();\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3752, "score_of_the_acc": -0.6172, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_4_D_10660068", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\nusing ll = long long;\n\nint main()\n{\n int n, k;\n cin >> n >> k;\n vector<int> w(n);\n rep(i,n) cin >> w[i];\n auto load = [&] (int p) -> ll {\n ll ans = 0;\n int cnt_track = 1;\n ll tmp_sum = 0;\n rep(i,n) {\n // cout << \"cnt_track = \" << cnt_track << endl;\n if (p < w[i]) {\n // cout << \"return 1\" << endl;\n return ans;\n }\n if (p < tmp_sum+w[i]) {\n tmp_sum = w[i];\n cnt_track++;\n } else {\n tmp_sum += w[i];\n }\n if (cnt_track > k) {\n // cout << \"return 2\" << endl;\n return ans;\n }\n ans++;\n }\n // cout << ans << endl;\n return ans;\n };\n\n int wa=0, ac=1e9;\n while (abs(ac-wa)>1) {\n ll wj = (wa+ac)/2;\n // cout << \"wj = \" << wj << '\\n';\n if (load(wj) < n) wa = wj;\n else ac = wj;\n }\n cout << ac << '\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3636, "score_of_the_acc": -0.5215, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_4_D_10636664", "code_snippet": "#include <stdio.h>\n\nbool load(int p, int k, const int* w, int n) {\n int wi = 0;\n for (int i = 0; i < k; i++) {\n int sum = 0;\n while (wi < n && sum <= p) {\n sum += w[wi];\n if (sum <= p) wi++;\n }\n }\n if (wi == n) return true;\n else return false;\n}\n\nint main() {\n int n, k;\n scanf(\"%d %d\", &n, &k);\n\n int w[n];\n int total = 0;\n for (int i = 0; i < n; i++) {\n scanf(\"%d\", w+i);\n total += w[i];\n }\n \n int lb = 0;\n int hb = total;\n while (lb < hb) {\n if (load((lb + hb) / 2, k, w, n)) {\n hb = (lb + hb) / 2;\n } else {\n lb = (lb + hb + 1) / 2;\n }\n }\n printf(\"%d\\n\", hb);\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3368, "score_of_the_acc": -0.3003, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_4_D_10624495", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nbool canCarry(const std::vector<int> &w, const int k, const int p)\n{\n int trucks = 1; // 現在使っているトラックの数\n int currentLoad = 0; // 現在のトラックの積載量\n\n for (size_t i = 0; i < w.size(); ++i)\n {\n // 単体で積めない荷物があるなら即NG\n if (w[i] > p)\n return false;\n\n if (currentLoad + w[i] <= p)\n {\n currentLoad += w[i]; // 同じトラックに積む\n }\n else\n {\n ++trucks; // 新しいトラックを使う\n currentLoad = w[i]; // 新しいトラックにこの荷物を積む\n }\n }\n\n //if (trucks <= k)\n //{\n // return true;\n //}\n //else\n //{\n // return false;\n //}\n return trucks <= k;\n}\n\nint binarySearch(const std::vector<int> &A, const int K)\n{\n int left = *min_element(A.begin(), A.end()); // 探索範囲の最小値: 荷物の重量の最小値\n int right = accumulate(A.begin(), A.end(), 0); // 探索範囲の最大値: 荷物の重量の合計\n\n while (right > left)\n {\n int mid = (left + right) / 2;\n if (canCarry(A, K, mid))\n {\n right = mid; // より小さい容量で運べるか試す\n }\n else\n {\n left = mid + 1; // この容量では無理なので増やす\n }\n }\n\n return left;\n}\n\nint main()\n{\n int n, k; // n:荷物の数 k:トラックの台数\n cin >> n >> k;\n\n vector<int> w(n); // 荷物の重さ\n for (int &var : w)\n {\n cin >> var;\n }\n\n int p = binarySearch(w, k);\n\n cout << p << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3608, "score_of_the_acc": -0.4983, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_4_D_10600996", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define N 100000\n\nint search(int n,vector<int> W,int k,int key){\n int j=0;\n for(int i=0;i<k;i++){\n int p = key;\n while(1){\n if(j==n) return 1;\n if(W[j]>p) break;\n p -= W[j];\n j++;\n }\n }\n return 0;\n}\n\nint main(){\n int n,k;\n ll min=0,max,sum=0;\n cin >> n >> k;\n vector<int> W(n);\n for(int i=0;i<n;i++){\n cin >> W[i];\n min = min>W[i]? min:W[i];\n sum += W[i];\n }\n sum /= k;\n max = n*min/k;\n min = min>sum? min:sum;\n while(max-min){\n ll mid = (max + min)/2;\n if(search(n,W,k,mid)) max = mid;\n else min = mid+1;\n }\n cout << min << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3876, "score_of_the_acc": -0.7195, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_4_D_10575997", "code_snippet": "#include<iostream>\nusing namespace std;\n#define MAX 100000\ntypedef long long llong;\n\nint n,k;\nllong T[MAX];\n\nint check (llong P){\n int i =0;\n for (int j=0; j < k; j++){\n llong s = 0;\n while (s + T[i] <= P){\n s += T[i];\n i++;\n if (i == n){\n return n;\n }\n }\n }\n return i;\n}\n\nint solve(){\n llong left = 0;\n llong right = 100000 * 10000;\n llong mid;\n while ( right - left >1){\n mid = (left + right) / 2 ;\n int v = check(mid);\n if (v >= n) {\n right = mid;\n } else {\n left = mid;\n }\n }\n return right ;\n}\n\n\nint main(){\n cin >> n >> k;\n for (int i =0; i < n; i++){\n cin >> T[i];\n }\n llong ans = solve();\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4216, "score_of_the_acc": -1, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_4_D_10568482", "code_snippet": "#include <iostream>\n#include <climits>\n#include <vector>\n#include <stack>\n#include <algorithm>\n#include <memory>\n#include <string>\nusing namespace std;\n\nint solve(int p, int t, const vector<int> & v)\n{\n int max_cn = 0;\n int sum = 0;\n int t_num = 0;\n for(int i = 0; i < v.size(); ++i)\n {\n int cal = sum + v[i];\n if (v[i] > p)\n {\n return i;\n }\n if (cal > p)\n {\n ++t_num;\n //cout << t_num << endl;\n if (t_num == t)\n {\n //cout << \"i=\" << i << endl;\n return i;\n }\n sum = v[i];\n }\n else\n {\n sum = cal;\n }\n }\n return v.size();\n}\n\nint main()\n{\n int t = 0;\n int cn = 0, c = 0;\n int p = 1;\n vector<int> cs;\n cin >> cn;\n cin >> t;\n for (int i = 0; i < cn; ++i)\n {\n cin >> c;\n cs.push_back(c);\n }\n while (solve(p, t, cs) < cn)\n {\n p = p * 2;\n }\n //cout << \"p=\" << p << endl;\n int left = 1;\n int right = p + 1;\n\n while (left < right)\n {\n int mid = (left + right) / 2;\n //cout << \"mid=\" << mid << endl;\n if (solve(mid, t, cs) < cn)\n {\n left = mid + 1;\n //cout << \"left=\" << left << endl;\n }\n else\n {\n right = mid;\n //cout << \"right=\" << right << endl;\n }\n }\n cout << left << endl;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3744, "score_of_the_acc": -0.6106, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_4_D_10554403", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (n); ++i)\nusing ll = long long;\n\nint main() {\n set<string> s;\n int n, k;\n cin >> n >> k;\n vector<ll> w(n);\n rep(i, n) cin >> w[i];\n auto check = [&](ll p) -> bool {\n ll sum = 0;\n int cnt = 1;\n rep(i, n) {\n if (sum + w[i] > p) {\n ++cnt;\n if (w[i] > p) {\n cnt = INT_MAX;\n break;\n }\n sum = w[i];\n } else\n sum += w[i];\n }\n return (cnt <= k);\n };\n ll l = 0, r = LONG_LONG_MAX;\n while (r - l > 1) {\n ll m = (l + r) / 2;\n if (check(m))\n r = m;\n else\n l = m;\n }\n cout << r << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3876, "score_of_the_acc": -0.7195, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_4_D_10553042", "code_snippet": "#include <iostream>\nusing namespace std;\n\nconst int MAX = 100000;\ntypedef long long llong; \nint n, k; llong T[MAX]; \n\nint check(llong P) { \n int i = 0;\n for ( int j = 0; j < k; j++ ) { \n llong s = 0;\n while( s + T[i] <= P ) { \n s += T[i];\n i++;\n if ( i == n ) {\n return n; \n }\n }\n } \n return i;\n} \n\nint solve() {\n llong left = 0;\n llong right = 100000 * 10000;\n llong mid;\n while ( right - left > 1 ) { \n mid = (left + right) / 2;\n int v = check(mid);\n if ( v >= n ) {\n right = mid;\n }else {\n left = mid; \n }\n } \n return right;\n}\n\nint main() {\n cin >> n >> k;\n for ( int i = 0; i < n; i++ ) {\n cin >> T[i];\n }\n llong ans = solve();\n cout << ans << endl; \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4216, "score_of_the_acc": -1, "final_rank": 17 } ]
aoj_ALDS1_3_B_cpp
There are n processes in a queue. Each process has name i and time i . The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue. For example, we have the following queue with the quantum of 100ms. A(150) - B(80) - C(200) - D(200) First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms). B(80) - C(200) - D(200) - A(50) Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue. C(200) - D(200) - A(50) Your task is to write a program which simulates the round-robin scheduling . Input n q name 1 time 1 name 2 time 2 ... name n time n In the first line the number of processes n and the quantum q are given separated by a single space. In the following n lines, names and times for the n processes are given. name i and time i are separated by a single space. Output For each process, prints its name and the time the process finished in order. Constraints 1 ≤ n ≤ 100000 1 ≤ q ≤ 1000 1 ≤ time i ≤ 50000 1 ≤ length of name i ≤ 10 1 ≤ Sum of time i ≤ 1000000 Sample Input 1 5 100 p1 150 p2 80 p3 200 p4 350 p5 20 Sample Output 1 p2 180 p5 400 p1 450 p3 550 p4 800 Notes Template in C
[ { "submission_id": "aoj_ALDS1_3_B_11064149", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\nconst int mod = 1000000007;\n#define srt(v) sort(v.begin(), v.end());\n#define srt_Dec(v) sort(v.begin(), v.end(), greater<int>());\n\nint solve1(){\n\n return 0;\n}\nint32_t main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n\n int n, time;\n cin >> n >> time;\n\n int total_time = 0;\n queue<pair<string, int>> q;\n\n while(n--){\n string s;\n int t;\n\n cin >> s >> t;\n q.push({s, t});\n }\n\n // while(q.size()!=0){\n // cout << q.front().first << \" \" << q.front().second << \"\\n\";\n // q.pop();\n // }\n\n vector<pair<int, string>> v;\n while(q.size()!=0){\n if(q.front().second>time){\n total_time += time;\n\n q.front().second -= time;\n\n q.push(q.front());\n q.pop();\n }\n\n else if(q.front().second<=time){\n total_time += q.front().second;\n\n v.push_back({total_time, q.front().first});\n q.pop();\n }\n }\n\n\n\n\n srt(v);\n for (int i = 0; i < v.size();i++){\n cout << v[i].second << \" \" << v[i].first << \"\\n\";\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7712, "score_of_the_acc": -0.4637, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_3_B_11059065", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n,qnt;\n cin >> n >> qnt;\n\n string name[100005];\n int time[100005];\n\n for(int i=0;i<n;i++)\n {\n cin >> name[i] >> time[i];\n }\n\n int q[200005];\n int head=0,tail=0;\n\n for(int i=0;i<n;i++)\n {\n q[tail++]=i;\n }\n\n int currentTime=0;\n\n while(head<tail)\n {\n int idx=q[head++];\n\n if(time[idx]<=qnt)\n {\n currentTime+=time[idx];\n cout << name[idx] << \" \" << currentTime << endl;\n }\n else\n {\n currentTime+=qnt;\n time[idx]-=qnt;\n q[tail++]=idx;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 7304, "score_of_the_acc": -0.9019, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_3_B_11057483", "code_snippet": "// ██████████████████╗█████╗███╗ ██╗ ██████╗ █████╗████╗ ██╗█████╗███╗ ██╗\n// ╚══██╔══██╚══██╔══██╔══██████╗ ██║ ██╔══████╔══████╚██╗ ██╔██╔══██████╗ ██║\n// ██║ ██║ ██║ █████████╔██╗ ██║ ██████╔█████████║╚████╔╝█████████╔██╗ ██║\n// ██║ ██║ ██║ ██╔══████║╚██╗██║ ██╔══████╔══████║ ╚██╔╝ ██╔══████║╚██╗██║\n// ██║ ██║ ██║ ██║ ████║ ╚████║ ██║ ████║ ████║ ██║ ██║ ████║ ╚████║\n// ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╚═╝ ╚═══╝ ╚═╝ ╚═╚═╝ ╚═╚═╝ ╚═╝ ╚═╝ ╚═╚═╝ ╚═══╝\n// GitHub: https://github.com/raiyansarker/cp\n\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;typedef unsigned long long ull;typedef long double ld;typedef pair<int,int> pii;typedef pair<ll,ll> pll;typedef vector<int> vi;typedef vector<ll> vll;typedef vector<pii> vpii;typedef vector<pll> vpll;\n#define all(x) (x).begin(),(x).end()\n#define rall(x) (x).rbegin(),(x).rend()\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define sz(x) (int)(x).size()\n\n#ifndef NDEBUG\nnamespace dbg{string s(int x){return to_string(x);}string s(long long x){return to_string(x);}string s(unsigned long long x){return to_string(x);}string s(double x){return to_string(x);}string s(long double x){return to_string(x);}string s(char x){return \"'\"+string(1,x)+\"'\";}string s(string x){return '\"'+x+'\"';}string s(bool x){return x?\"true\":\"false\";}string s(const char*x){return'\"'+string(x)+'\"';}template<class A,class B>string s(pair<A,B>p){return\"(\"+s(p.first)+\",\"+s(p.second)+\")\";}template<class T>string s(T v){string r=\"{\";for(auto x:v)r+=(r==\"{\"?\"\":\",\"),r+=s(x);return r+\"}\";}template<class T>string s(stack<T>st){string r=\"{\";while(!st.empty())r+=(r==\"{\"?\"\":\",\"),r+=s(st.top()),st.pop();return r+\"}\";}template<class T>string s(queue<T>q){string r=\"{\";while(!q.empty())r+=(r==\"{\"?\"\":\",\"),r+=s(q.front()),q.pop();return r+\"}\";}template<class T>string s(priority_queue<T>pq){string r=\"{\";while(!pq.empty())r+=(r==\"{\"?\"\":\",\"),r+=s(pq.top()),pq.pop();return r+\"}\";}void p(const char*n){cerr<<\"\\n\";}template<class T>void p(const char*n,T v){cerr<<n<<\"=\"<<s(v)<<\"\\n\";}template<class T,class...A>void p(const char*n,T v,A...a){for(;*n!=',';n++)cerr<<*n;cerr<<\"=\"<<s(v)<<\", \";p(n+1,a...);}}\n#define debug(...) cerr<<\"[L\"<<__LINE__<<\"]: \",dbg::p(#__VA_ARGS__,__VA_ARGS__)\n#else\n#define debug(...)\n#endif\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int n, tl; cin >> n >> tl;\n\n // queue for processing\n queue<pair<int, string>> q;\n // storing time taken to solve\n map<string, int> m;\n\n // set to sort again\n set<pair<int, string>> s;\n\n for (int i = 0; i < n; i++) {\n string s; int x;\n cin >> s >> x;\n q.push(mp(x, s));\n m[s] = 0;\n }\n\n ll prefix_sum = 0;\n while (!q.empty()) {\n // per batch size\n int s = sz(q);\n \n for (int i = 0; i < s; i++) {\n auto node = q.front();\n if (node.first <= tl) {\n prefix_sum += node.first;\n m[node.second] = prefix_sum;\n } else {\n prefix_sum += tl;\n m[node.second] += prefix_sum;\n q.push(mp(node.first - tl, node.second));\n }\n\n q.pop();\n }\n }\n\n for (auto d : m) s.insert(mp(d.second, d.first));\n\n for (auto d : s) {\n cout << d.second << \" \" << d.first << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 11256, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_3_B_11053825", "code_snippet": "// ✝\n#include <bits/stdc++.h>\n#define IOS \\\n ios_base::sync_with_stdio(0); \\\n cin.tie(NULL); \\\n cout.tie(NULL);\n#define ll int\n#define ld long double\n#define E '\\n'\n#define read(v, n) \\\nfor (int i = 0; i < n; i++) \\\ncin >> v[i];\n#define cout(v, n) \\\nfor (int i = 0; i < n; i++) \\\ncout << v[i] << \" \";\n#define all(v) v.begin() , v.end()\n#define rall(v) v.rbegin() , v.rend()\n\n\nusing namespace std;\n\n \nvoid file()\n{\n #ifndef ONLINE_JUDGE\n freopen(\"C:\\\\Users\\\\hp\\\\Desktop\\\\c++\\\\input.txt\",\"r\", stdin);\n freopen(\"C:\\\\Users\\\\hp\\\\Desktop\\\\c++\\\\output.txt\",\"w\", stdout);\n #endif \n}\n\n\n\nint main() {\n IOS \n\n \n ll t = 1 ;\n //cin >> t ; \n while(t--){\n ll n , m ; cin >> n >> m;\n queue<pair<string,ll>> qu ;\n for(int i = 0 ; i < n ; i++){\n string s ; cin >> s ;\n ll x ; cin >> x ;\n qu.push({s,x});\n }\n ll c = 0 ;\n while(!qu.empty()){\n ll d = qu.front().second - m;\n if(d>0){\n qu.push({qu.front().first,d});\n c += m ;\n qu.pop();\n }\n else{\n c += qu.front().second ;\n cout << qu.front().first << \" \" << c << E ;\n qu.pop();\n \n }\n }\n\n \n }\n return 0;\n}\n/*\n10\n1 2 3 4 5 4 3 2 1 6\n1 2 3 4 5 6 7 8 9 10\n6 4 4 3 3 2 2 1 1 1 \n\n10 1 1 10 => 1\n7 1 2 7 => 2\n5 1 3 5 => 3\n3 1 4 3 => 4\n1 1 5 1 => 5\n1 2 4 2 => 4\n1 4 3 4 => 3\n1 6 2 6 => 2\n2 8 1 8 => 1\n1 1 6 1 => 6\n\n6 4 4 3 3 2 2 1 - 1\n\n5 3 2\n*/", "accuracy": 1, "time_ms": 10, "memory_kb": 5372, "score_of_the_acc": -0.1096, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_3_B_11050862", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define nl '\\n'\ntypedef long long ll;\n\nint main()\n{\n int n,q;\n cin>>n>>q;\n map<string,int> procesos;\n queue<string> cola;\n for(int i=0;i<n;i++)\n {\n string a;\n int b;\n cin>>a>>b;\n procesos[a]=b;\n cola.push(a);\n }\n vector<string> ordenados;\n int tiempototal=0;\n while(!cola.empty())\n {\n string b=cola.front();\n if(procesos[b]>q)\n {\n procesos[b]=procesos[b]-q;\n cola.push(b);\n cola.pop();\n tiempototal+=q;\n } \n else\n {\n ordenados.push_back(b);\n cola.pop();\n int z=procesos[b];\n procesos[b]=tiempototal+procesos[b];\n tiempototal+=z;\n\n }\n }\n for(int i=0;i<n;i++)\n {\n cout<<ordenados[i]<<\" \"<<procesos[ordenados[i]]<<nl;\n }\n\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 10528, "score_of_the_acc": -1.8898, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_3_B_11036676", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long int\nusing namespace std;\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);cout.tie(nullptr);\n\n int n,time;\n cin>>n>>time;\n\n queue<pair<string,int>>que;\n for(int i=0; i<n; i++){\n string s;\n int t;\n cin>>s>>t;\n que.push({s,t});\n }\n\n ll total=0;\n\n while (!que.empty())\n {\n auto curr=que.front();\n que.pop();\n string pname=curr.first;\n int tm=curr.second;\n \n if(tm>time){\n total+=time;\n que.push({curr.first,tm-time});\n }\n else{\n total+=curr.second;\n cout<<pname<<\" \"<<total<<endl;\n }\n\n }\n \n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5424, "score_of_the_acc": -0.6174, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_3_B_11033550", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, q;\nqueue<pair<string, int>> Q;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0); cout.tie(0);\n\n cin >> n >> q;\n for(int i = 0; i < n; i++) {\n string name;\n int t;\n cin >> name >> t;\n Q.push({name, t});\n }\n\n int curTime = 0;\n while(!Q.empty()) {\n auto [name, t] = Q.front();\n Q.pop();\n\n curTime += min(q, t);\n t -= min(q, t);\n\n if(!t) cout << name << ' ' << curTime << '\\n';\n else Q.push({name, t});\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5224, "score_of_the_acc": -0.0872, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_3_B_11011998", "code_snippet": "#include <iostream>\n#include <queue>\n#include <string>\n#include <vector>\nusing namespace std;\n\nint main() {\n int N, Q;\n cin >> N >> Q;\n\n vector<string> names(N);\n vector<int> times(N);\n queue<int> Que;\n\n for (int i = 0; i < N; ++i) {\n cin >> names[i] >> times[i];\n Que.push(i);\n }\n int current_time = 0;\n while (!Que.empty()) {\n int idx = Que.front();\n Que.pop();\n if (times[idx] > Q) {\n current_time += Q;\n times[idx] -= Q;\n Que.push(idx);\n } else {\n current_time += times[idx];\n cout << names[idx] << \" \" << current_time << endl;\n }\n }\n\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5100, "score_of_the_acc": -0.5684, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_3_B_11010268", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint head, tail, MAX;\n\nvoid initialize() { head = tail = 0; }\n\nbool isEmpty() { return head == tail; }\n\nbool isFull() { return head == (tail + 1) % MAX; }\n\n\n//配列に入れる\nvoid enqueue(vector<pair<string,int>>& Q, string s,int x) {\n if (isFull()) {\n cout << \"error\" << endl;\n return;\n }\n Q[tail].first = s;\n Q[tail].second = x;\n if(tail + 1 == MAX)\n {\n tail = 0;\n }\n else\n {\n tail++;\n }\n}\n\n\n//先頭の要素を取り出す\npair<string,int> dequeue(vector<pair<string,int>>& Q) {\n if (isEmpty()) {\n cout << \"error\" << endl;\n return {\"\", -1};\n }\n string s = Q[head].first;\n int x = Q[head].second;\n\n if(head + 1 == MAX)\n {\n head = 0;\n }\n else\n {\n head++;\n }\n return {s, x};\n}\n\nint main() {\n int n,q;\n cin >> n >> q;\n MAX = n + 1;\n vector<pair<string,int>> Q(MAX);\n\n initialize();//初期化\n for (int i = 0; i < n; i++) {\n string s;\n int x;\n cin >> s >> x;\n enqueue(Q, s,x);//配列に入れる\n }\n \n int time = 0;\n while (!isEmpty()) {\n pair<string,int> p = dequeue(Q);\n string s = p.first;\n int x = p.second;\n\n //cout << \" While \" << s << ' ' << x << endl;\n if(x<=q)\n {\n //この時点で配列に入れないから自動的に消える\n time += x;\n cout << s << ' ' << time << endl;\n }\n else\n {\n x -= q;\n time += q;\n // cout << \"else \" << time << endl;\n enqueue(Q, s,x);\n }\n }\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4892, "score_of_the_acc": -0.7036, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_3_B_11010266", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint head, tail, MAX;\n\nvoid initialize() { head = tail = 0; }\n\nbool isEmpty() { return head == tail; }\n\nbool isFull() { return head == (tail + 1) % MAX; }\n\n\n//配列に入れる\nvoid enqueue(vector<pair<string,int>>& Q, string s,int x) {\n if (isFull()) {\n cout << \"error\" << endl;\n return;\n }\n Q[tail].first = s;\n Q[tail].second = x;\n if(tail + 1 == MAX)\n {\n tail = 0;\n }\n else\n {\n tail++;\n }\n}\n\n\n//先頭の要素を取り出す\npair<string,int> dequeue(vector<pair<string,int>>& Q) {\n if (isEmpty()) {\n cout << \"error\" << endl;\n return {\"\", -1};\n }\n string s = Q[head].first;\n int x = Q[head].second;\n\n if(head + 1 == MAX)\n {\n head = 0;\n }\n else\n {\n head++;\n }\n return {s, x};\n}\n\nint main() {\n int n, q;\n cin >> n >> q;\n MAX = n + 1;\n vector<pair<string,int>> Q(MAX);\n initialize();\n\n for (int i = 0; i < n; i++) {\n string s; int x;\n cin >> s >> x;\n enqueue(Q, s, x);\n }\n\n int time = 0;\n while (!isEmpty()) {\n pair<string,int> p = dequeue(Q);\n string s = p.first;\n int x = p.second;\n\n if (x <= q) {\n time += x;\n cout << s << ' ' << time << '\\n';\n } else {\n x -= q;\n time += q;\n enqueue(Q, s, x);\n }\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4876, "score_of_the_acc": -0.2012, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_3_B_11010262", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint head, tail, MAX;\n\nvoid initialize() { head = tail = 0; }\n\nbool isEmpty() { return head == tail; }\nbool isFull() { return head == (tail + 1) % MAX; }\n\nvoid enqueue(vector<pair<string,int>>& Q, string s, int x) {\n if (isFull()) {\n cout << \"error\" << endl;\n return;\n }\n Q[tail].first = s;\n Q[tail].second = x;\n tail = (tail + 1) % MAX;\n}\n\npair<string,int> dequeue(vector<pair<string,int>>& Q) {\n if (isEmpty()) {\n cout << \"error\" << endl;\n return {\"\", -1};\n }\n string s = Q[head].first;\n int x = Q[head].second;\n head = (head + 1) % MAX;\n return {s, x}; // ← ここが安全\n}\n\nint main() {\n int n, q;\n cin >> n >> q;\n MAX = n + 1;\n vector<pair<string,int>> Q(MAX);\n initialize();\n\n for (int i = 0; i < n; i++) {\n string s; int x;\n cin >> s >> x;\n enqueue(Q, s, x);\n }\n\n int time = 0;\n while (!isEmpty()) {\n pair<string,int> p = dequeue(Q);\n string s = p.first;\n int x = p.second;\n\n if (x <= q) {\n time += x;\n cout << s << ' ' << time << '\\n';\n } else {\n x -= q;\n time += q;\n enqueue(Q, s, x);\n }\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4932, "score_of_the_acc": -0.2096, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_3_B_11009844", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Process {\n string name;\n int time;\n};\n\nint main() {\n int n, q;\n cin >> n >> q;\n \n queue<Process> Q;\n \n // プロセスをキューに追加\n for (int i = 0; i < n; i++) {\n string name;\n int time;\n cin >> name >> time;\n Q.push({name, time});\n }\n \n int current_time = 0;\n \n // ラウンドロビンスケジューリング\n while (!Q.empty()) {\n Process p = Q.front();\n Q.pop();\n \n if (p.time <= q) {\n // プロセスが完了\n current_time += p.time;\n cout << p.name << \" \" << current_time << endl;\n } else {\n // まだ処理が残っている\n current_time += q;\n p.time -= q;\n Q.push(p);\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5420, "score_of_the_acc": -0.6168, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_3_B_11009843", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Process {\n string name;\n int time;\n};\n\nint head, tail, MAX;\nvector<Process> Q;\n\nvoid initialize(int n) {\n head = tail = 0;\n MAX = n + 1;\n Q.resize(MAX);\n}\n\nbool isEmpty() { return head == tail; }\nbool isFull() { return head == (tail + 1) % MAX; }\n\nvoid enqueue(const Process& p) {\n if (isFull()) {\n cout << \"error: queue full\\n\";\n return;\n }\n Q[tail] = p;\n tail = (tail + 1) % MAX;\n}\n\nProcess dequeue() {\n if (isEmpty()) {\n cout << \"error: queue empty\\n\";\n return {\"\", -1};\n }\n Process p = Q[head];\n head = (head + 1) % MAX;\n return p;\n}\n\nint main() {\n int n, q;\n cin >> n >> q;\n initialize(n);\n\n for (int i = 0; i < n; i++) {\n string name;\n int t;\n cin >> name >> t;\n enqueue({name, t});\n }\n\n int elapsed = 0;\n while (!isEmpty()) {\n Process p = dequeue();\n if (p.time > q) {\n elapsed += q;\n p.time -= q;\n enqueue(p);\n } else {\n elapsed += p.time;\n cout << p.name << \" \" << elapsed << \"\\n\";\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4648, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_3_B_11001669", "code_snippet": "#include <iostream>\n#include <queue>\n#include <string>\n#include <vector>\n#include <cstdint>\n\nint main() {\n int N;\n int Q;\n std::cin >> N >> Q;\n\n std::vector<std::string> names(N);\n std::vector<int> times(N);\n std::queue<int> Que;\n\n for (int i = 0; i < N; ++i) {\n std::cin >> names[i] >> times[i];\n Que.push(i);\n }\n\n int tmp;\n int idx;\n int t = 0;\n\n while (!Que.empty()) {\n idx = Que.front();\n Que.pop();\n tmp = times[idx];\n\n if (tmp <= Q) {\n t += tmp;\n std::cout << names[idx] << \" \" << t << '\\n';\n } else {\n times[idx] = tmp - Q;\n t += Q;\n Que.push(idx);\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5084, "score_of_the_acc": -0.066, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_3_B_10998887", "code_snippet": "#include <iostream>\n#include <queue>\n#include <string>\n#include <vector>\nusing namespace std;\n\nint main(){\nint N, Q;\n cin >> N >> Q;\n vector<string> names(N);\n vector<int> times(N);\n queue<int> Que;\n for (int i=0; i<N; ++i) {\n cin >> names[i] >> times[i];\n Que.push(i);\n }\n int passtime = 0;\n while(!Que.empty()){\n int task = Que.front();\n Que.pop();\n if(times[task] > Q) {\n times[task] -= Q;\n passtime += Q;\n Que.push(task);\n }\n else {\n passtime += times[task];\n cout << names[task] << ' ' << passtime << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5172, "score_of_the_acc": -0.5793, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_3_B_10998834", "code_snippet": "#include <iostream> \n#include <queue> \n#include <string> \n#include <vector> \nusing namespace std; \n\nint main(){ \n int N, Q; \n cin >> N >> Q; \n vector<string> names(N); \n vector<int> times(N); \n queue<int> Que; \n for (int i=0; i<N; ++i) { \n cin >> names[i] >> times[i]; \n Que.push(i); \n }\n int time = 0;\n while (!Que.empty()) {\n int i = Que.front();\n Que.pop();\n if (times[i] <= Q) {\n time += times[i];\n cout << names[i] << \" \" << time << endl;\n } else {\n time += Q;\n times[i] -= Q;\n Que.push(i);\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5024, "score_of_the_acc": -0.5569, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_3_B_10998707", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cassert>\n#include <queue>\nusing namespace std;\n\nint main(){\n int n,q;\n cin >> n >> q;\n vector<string> names(n);\n vector<int> times(n);\n queue<int> que;\n int t = 0;\n for(int i=0; i<n; i++){\n cin >> names[i] >> times[i];\n que.push(i);\n }\n while(!que.empty()){\n int i = que.front();\n que.pop();\n if (times[i] > q){\n times[i] -= q;\n t += q;\n que.push(i);\n }else{\n t += times[i];\n cout << names[i] << \" \" << t << endl;\n times[i] = 0; // アルゴリズム的には不要\n }\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5068, "score_of_the_acc": -0.5636, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_3_B_10997291", "code_snippet": "#include <iostream>\n#include <queue>\n#include <string>\nusing namespace std;\n\nstruct Process {\n string name; // プロセス名\n int time; // 残りの処理時間\n};\n\nint main() {\n int n, q;\n cin >> n >> q; // n: プロセス数, q: クオンタム(1回の処理時間)\n\n queue<Process> Q; // プロセスを管理するキュー\n\n // プロセス情報を読み込み\n for (int i = 0; i < n; i++) {\n Process p;\n cin >> p.name >> p.time;\n Q.push(p);\n }\n\n int elapsed = 0; // 経過時間\n\n // キューが空になるまで処理を繰り返す\n while (!Q.empty()) {\n Process current = Q.front(); // 先頭のプロセスを取り出す\n Q.pop();\n\n if (current.time <= q) {\n // 残り時間がクオンタム以下 → 完了\n elapsed += current.time;\n cout << current.name << \" \" << elapsed << endl;\n } else {\n // まだ残りがある → qだけ処理して末尾に戻す\n elapsed += q;\n current.time -= q;\n Q.push(current);\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5516, "score_of_the_acc": -0.6314, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_3_B_10997282", "code_snippet": "#include <iostream>\n#include <queue>\n#include <string>\nusing namespace std;\n\nstruct Process {\n string name;\\\n int time;\n};\n\nint main() {\n int n, q;\n cin >> n >> q;\n\n queue<Process> Q;\n\n for (int i = 0; i < n; i++) {\n Process p;\n cin >> p.name >> p.time;\n Q.push(p);\n }\n\n int elapsed = 0;\n\n while (!Q.empty()) {\n Process current = Q.front();\n Q.pop();\n\n if (current.time <= q) {\n elapsed += current.time;\n cout << current.name << \" \" << elapsed << endl;\n } else {\n elapsed += q;\n current.time -= q;\n Q.push(current);\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5408, "score_of_the_acc": -0.615, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_3_B_10997260", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n int n, q;\n int total_time = 0;\n queue<string> name;\n queue<int> time;\n\n cin >> n >> q;\n\n \n for(int i=0; i<n; ++i){\n string str;\n int j;\n cin >> str >> j;\n name.push(str);\n time.push(j);\n }\n \n while(!time.empty()){\n int headtime = time.front();\n string headname = name.front();\n if(headtime-q>0){\n name.pop();\n time.pop();\n name.push(headname);\n time.push(headtime-q);\n total_time += q;\n }\n else{\n name.pop();\n time.pop();\n \n total_time += headtime;\n\n cout << headname << \" \" << total_time << endl;\n }\n\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5308, "score_of_the_acc": -0.5999, "final_rank": 12 } ]
aoj_ALDS1_5_A_cpp
Exhaustive Search Write a program which reads a sequence A of n elements and an integer M , and outputs " yes " if you can make M by adding elements in A , otherwise " no ". You can use an element only once. You are given the sequence A and q questions where each question contains M i . Input In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers ( M i ) are given. Output For each question M i , print yes or no . Constraints n ≤ 20 q ≤ 200 1 ≤ elements in A ≤ 2000 1 ≤ M i ≤ 2000 Sample Input 1 5 1 5 7 10 21 8 2 4 17 8 22 21 100 35 Sample Output 1 no no yes yes yes yes no no Notes You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions: solve(0, M) solve(1, M-{sum created from elements before 1st element}) solve(2, M-{sum created from elements before 2nd element}) ... The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations. For example, the following figure shows that 8 can be made by A[0] + A[2].
[ { "submission_id": "aoj_ALDS1_5_A_11061393", "code_snippet": "# include <stdio.h>\n\nstatic int N, A[50];\n\nstatic int solve(int i, int m)\n{\n if (m == 0)\n return 1;\n if (i >= N)\n return 0;\n\n /* A[i]を使用するか、しないか */\n int res = (solve(i + 1, m) || solve(i + 1, m - A[i]));\n return res;\n}\n\nint main(void)\n{\n int q, M, i;\n\n scanf(\"%d\", &N);\n for (i = 0; i < N; i++)\n scanf(\"%d\", &A[i]);\n\n scanf(\"%d\", &q);\n for (i = 0; i < q; i++)\n {\n scanf(\"%d\", &M);\n if (solve(0, M))\n printf(\"yes\\n\");\n else\n printf(\"no\\n\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 2908, "score_of_the_acc": -0.0633, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_5_A_11061320", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n\n vector<int> A(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n \n unordered_set<int> possible;\n int total = 1 << n;\n \n for (int bit = 0; bit < total; bit++) {\n int sum = 0;\n for (int i = 0; i < n; i++) {\n if (bit & (1 << i)) sum += A[i];\n }\n possible.insert(sum);\n }\n\n int q;\n cin >> q;\n while (q--) {\n int m;\n cin >> m;\n if (possible.count(m)) {\n cout << \"yes\\n\";\n } else {\n cout << \"no\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3480, "score_of_the_acc": -0.0684, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_5_A_11060843", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\nint n;\nint a[30];\nbool rec(int d,int t){\n if(t==0) return true;\n if(d==n||t<0) return false;\n return rec(d+1,t)||rec(d+1,t-a[d]);\n}\nsigned main(){\n cin>>n;\n for(int i=0;i<n;i++) cin>>a[i];\n int q;\n cin>>q;\n int m[q];\n for(int i=0;i<q;i++) cin>>m[i];\n for(int i=0;i<q;i++) cout<<(rec(0,m[i])?\"yes\":\"no\")<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 3360, "score_of_the_acc": -0.1316, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_5_A_11060480", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n;\nvector<int> A;\n\nbool solve(int i, int M) {\n if (M == 0) return true;\n\n if (i > n) return false;\n\n bool res = solve(i + 1, M) || solve(i + 1, M - A[i]); \n return res;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n cin >> n;\n A.resize(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n\n int q; cin >> q;\n while (q--) {\n int m; cin >> m;\n if (solve(0, m)) cout << \"yes\\n\";\n else cout << \"no\\n\";\n }\n}", "accuracy": 1, "time_ms": 680, "memory_kb": 3460, "score_of_the_acc": -0.1966, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_5_A_11060447", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n if(!(cin >> n)) return 0;\n vector<long long> A(n);\n for(int i = 0; i < n; ++i) cin >> A[i];\n int q; cin >> q;\n vector<long long> M(q);\n for(int i = 0; i < q; ++i) cin >> M[i];\n\n unordered_set<long long> sums;\n sums.reserve(1 << min(n, 20));\n long long total = 1LL << n;\n for(long long mask = 0; mask < total; ++mask){\n long long s = 0;\n for(int j = 0; j < n; ++j){\n if((mask >> j) & 1LL) s += A[j];\n }\n sums.insert(s);\n }\n\n for(int i = 0; i < q; ++i){\n cout << (sums.count(M[i]) ? \"yes\" : \"no\") << '\\n';\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 11276, "score_of_the_acc": -1, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_5_A_11060445", "code_snippet": "#include<iostream>\n\nusing namespace std;\n\nbool solve(int i, int X, int A[], int n){\n if(X==0){\n return true;\n }\n else if(X<0){\n return false;\n }\n if(i>=n){\n return false;\n }\n bool res = solve(i+1, X, A, n) || solve(i+1, X-A[i], A, n);\n return res;\n}\n\nint main(){\n int n;\n cin >> n;\n int A[n];\n for(int i=0;i<n;i++){\n cin >> A[i];\n }\n \n int q;\n cin >> q;\n int M[q];\n for(int j=0;j<q;j++){\n cin >> M[j];\n }\n \n for(int k=0;k<q;k++){\n bool y = solve(0, M[k], A, n);\n if(y==true){\n cout << \"yes\" << endl;\n }\n else cout << \"no\" << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 3364, "score_of_the_acc": -0.1157, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_5_A_11059908", "code_snippet": "#include<iostream>\n\nusing namespace std;\n\nbool solve(int i, int X, int A[], int n){\n if(X==0){\n return true;\n }\n else if(X<0){\n return false;\n }\n if(i>=n){\n return false;\n }\n bool res = solve(i+1, X, A, n) || solve(i+1, X-A[i], A, n);\n return res;\n}\n\nint main(){\n int n;\n cin >> n;\n int A[n];\n for(int i=0;i<n;i++){\n cin >> A[i];\n }\n \n int q;\n cin >> q;\n int M[q];\n for(int j=0;j<q;j++){\n cin >> M[j];\n }\n \n for(int k=0;k<q;k++){\n bool y = solve(0, M[k], A, n);\n if(y==true){\n cout << \"yes\" << endl;\n }\n else cout << \"no\" << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 3432, "score_of_the_acc": -0.1238, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_5_A_11059026", "code_snippet": "#include <iostream>\n#include <vector>\n\n// グローバル変数として扱うことで、再帰関数に毎回渡す手間を省きます\nint n;\nstd::vector<int> A;\n\n// 再帰関数: `index`番目の要素以降を使って `target` を作れるか判定する\nbool solve(int index, int target) {\n // ベースケース1: `target` が0になったら、指定の和が作れたということ\n if (target == 0) {\n return true;\n }\n // ベースケース2: `index` が `n` (数列の末尾) に到達し、かつ `target` が0でない場合\n // これ以上要素がないので `target` を作れない\n if (index == n) {\n return false;\n }\n\n // 再帰ステップ: 以下の2つのケースを試す\n // 1. `A[index]` を選ばずに、次の要素 `A[index + 1]` 以降で `target` を作る\n // 2. `A[index]` を選び、残りの要素 `A[index + 1]` 以降で `target - A[index]` を作る\n return solve(index + 1, target) || solve(index + 1, target - A[index]);\n}\n\nint main() {\n std::cin >> n;\n A.resize(n); \n for (int i = 0; i < n; ++i) {\n std::cin >> A[i];\n }\n\n int q;\n std::cin >> q;\n for (int i = 0; i < q; ++i) {\n int m;\n std::cin >> m;\n if (solve(0, m)) { \n std::cout << \"yes\" << std::endl;\n } else {\n std::cout << \"no\" << std::endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 3444, "score_of_the_acc": -0.1375, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_5_A_11058643", "code_snippet": "#include <iostream>\nusing namespace std;\n\nbool solve(long long i, long long M, long long A[], long long n){\n if(M==0) return true;\n else if(M<0) return false;\n if(i >= n) return false;\n bool res = solve(i+1, M, A, n) || solve(i+1, M-A[i], A, n);\n return res;\n}\n\nint main(){\n long long n;\n cin >> n;\n long long A[n];\n for(long long i=0; i<n; ++i){\n cin >> A[i];\n }\n long long q;\n cin >> q;\n for(long long i=0; i<q; ++i){\n int m;\n cin >> m;\n if(solve(0, m, A, n)) cout << \"yes\\n\";\n else cout << \"no\\n\";\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 3584, "score_of_the_acc": -0.1196, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_5_A_11058623", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nbool solve(int i,int M,int n,vector<int>& A){\n if (M==0){\n return true;\n }\n else if (M<0){\n return false;\n }\n if (i>=n){\n return false;\n }\n int res = solve(i+1,M,n,A) || solve(i+1,M-A[i],n,A);\n return res;\n}\n\nint main(){\n int n,q;\n cin >> n;\n vector<int> A(n);\n for (int i=0;i<n;i++){\n cin >> A[i];\n }\n cin >> q;\n vector<int> m(q);\n for (int i=0;i<q;i++){\n cin >> m[i];\n }\n for (int i=0;i<q;i++){\n if (solve(0,m[i],n,A)){\n cout << \"yes\" << endl;\n }\n else {\n cout << \"no\" << endl;\n }\n \n }\n\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 3376, "score_of_the_acc": -0.1294, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_5_A_11058291", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint n;\nvector<int> A;\n\nbool solve(int i, int m){\n if (m == 0)return true;\n if (i >= n)return false;\n bool res = solve(i + 1, m) || solve(i + 1, m - A[i]);\n return res;\n}\n\nint main(){\n int q;\n vector<int> M;\n \n cin >> n;\n A.resize(n);\n for (int i = 0; i < n; i++ ){cin >> A[i];}\n cin >> q;\n M.resize(q);\n for (int i = 0; i < q; i++ ){cin >> M[i];}\n\n for (int i=0; i < q; i++){\n if (solve(0,M[i])) cout << \"yes\" << endl;\n else cout << \"no\" << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 3444, "score_of_the_acc": -0.1294, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_5_A_11054866", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <cstdlib>\n#include <cstring> \n\nusing namespace std;\n\n\nint solve(int I,int B[2000],int M, int N){\n int ans;\n if (M==0){\n return 1;\n } else if (M<0){\n return 0;\n }\n if (I > N){\n return 0;\n }\n ans = solve(I+1,B,M,N) or solve(I+1,B,M-B[I],N);\n return ans;\n}\n\n\nint main(){\n int n,q,i,sum;\n int A[2000];\n int m[2000];\n \n cin >> n;\n for (i=0;i<n;i++){\n cin >> A[i];\n }\n \n cin >> q;\n for (i=0;i<q;i++){\n cin >> m[i];\n }\n \n \n \n \n for (i=0;i<q;i++){\n \n if (solve(0,A,m[i],n)==1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n return 0; \n}", "accuracy": 1, "time_ms": 800, "memory_kb": 3444, "score_of_the_acc": -0.2192, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_5_A_11046465", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint A[20];\nbool solve(int i,int m,const int A[], int n){\n if (m==0){\n return true;\n }else if(m<0){\n return false;\n }\n if(i >= n){\n return false;\n }\n bool res = solve(i+1,m,A,n) || solve(i+1,m-A[i],A,n);\n return res;\n}\nint main() {\n int n,q;\n cin >> n; \n int A[n];\n for(int i=0;i<n;i++){\n cin >> A[i];\n } \n cin >> q;\n int m_i[q];\n for(int i=0;i<q;i++){\n cin >> m_i[i];\n }\n for(int i=0;i<q;i++){\n if(solve(0,m_i[i],A,n)){\n cout << \"yes\" <<endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 3440, "score_of_the_acc": -0.1248, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_5_A_11046359", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint slove(int i, int M, vector<int> A)\n{\n if (M == 0)\n {\n return true;\n }\n if (M < 0)\n {\n return false;\n }\n if (i >= A.size())\n {\n return false;\n }\n int res = slove(i + 1, M, A) || slove(i + 1, M - A[i], A);\n return res;\n}\nint main()\n{\n int n, q;\n\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; i++)\n {\n cin >> A[i];\n }\n cin >> q;\n vector<int> M(q);\n for (int i = 0; i < q; i++)\n {\n cin >> M[i];\n }\n for (int i = 0; i < q; i++)\n {\n if (slove(0, M[i], A))\n {\n cout << \"yes\" << endl;\n }\n else\n {\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 4580, "memory_kb": 3448, "score_of_the_acc": -0.9911, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_5_A_11046352", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint slove(int i, int M, vector<int> A)\n{\n if (M == 0)\n {\n return true;\n }\n if (M < 0)\n {\n return false;\n }\n if (i > A.size())\n {\n return false;\n }\n int res = slove(i + 1, M, A) || slove(i + 1, M - A[i], A);\n return res;\n}\nint main()\n{\n int n, q;\n\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; i++)\n {\n cin >> A[i];\n }\n cin >> q;\n vector<int> M(q);\n for (int i = 0; i < q; i++)\n {\n cin >> M[i];\n }\n for (int i = 0; i < q; i++)\n {\n if (slove(0, M[i], A))\n {\n cout << \"yes\" << endl;\n }\n else\n {\n cout << \"no\" << endl;\n }\n }\n}", "accuracy": 0.8, "time_ms": 1100, "memory_kb": 3448, "score_of_the_acc": -0.2809, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_5_A_11046324", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint n;\nvector<int> A;\n\nbool solve(int i, int m){\n if(m == 0){\n return true;\n } else if(m < 0){\n return false;\n }\n \n if(i >= n){\n return false;\n }\n \n bool res = solve(i + 1, m) || solve(i + 1, m - A[i]);\n return res;\n}\n\nint main(){\n cin >> n;\n A.resize(n);\n for (int i=0; i<n; i++){\n cin >> A[i];\n }\n \n int q;\n cin >> q;\n vector<int> m(q);\n for(int i=0; i<q; i++){\n cin >> m[i]; \n }\n \n \n for(int i=0; i<q; i++){\n if(solve(0, m[i]) == true){\n cout << \"yes\" << endl;\n } else {\n cout << \"no\" << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 3444, "score_of_the_acc": -0.1396, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_5_A_11045335", "code_snippet": "using namespace std;\n#include <iostream>\n\nint n;\nint A[2000];\n\nint solve(int i, int m){\n if(m == 0){\n return true;\n }\n if(i >= n){\n return false;\n }\n int res = solve(i + 1,m) || solve(i+1, m-A[i]);\n return res;\n}\n\n\nint main (){\n cin >> n;\n for(int i = 0; i < n; i++){\n cin >> A[i];\n }\n int q;\n cin >> q;\n int M;\n for(int i = 0; i < q; i++){\n cin >> M;\n if(solve(0,M)){\n cout << \"yes\" << endl;\n }\n else{\n cout << \"no\" << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 3368, "score_of_the_acc": -0.1203, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_5_A_11045323", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\nint solve(int i,int M,int n,const vector<int>& A){\n if (M == 0){\n return 1;\n }else if(M < 0){\n return 0;\n }\n if (i >= n){\n return 0;\n }\n int res,res2;\n res = solve(i+1,M,n,A);\n res2 = solve(i+1,M-A[i],n,A);\n if (res == 0 && res2 == 0){\n return 0;\n }else{\n return 1;\n } \n}\n\nint main(){\n int n,q,input_1,input_2;\n vector<int>A,m_i;\n cin >> n;\n for(int i = 0;i < n; ++i){\n cin >> input_1;\n A.push_back(input_1);\n }\n cin >> q;\n for(int j = 0;j < q; ++j){\n cin >> input_2;\n m_i.push_back(input_2);\n }\n for(int k = 0;k < q; ++k){\n int key = m_i[k];\n if (solve(0,key,n,A) == 1){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n\n}", "accuracy": 1, "time_ms": 630, "memory_kb": 3440, "score_of_the_acc": -0.184, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_5_A_11045313", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n int n;\n cin >> n;\n\n int A[n];\n for(int i = 0; i < n; i++){\n cin >> A[i];\n }\n\n int q;\n cin >> q;\n\n int m[q];\n for(int i = 0; i < q; i++){\n cin >> m[i];\n }\n\n \n\n for(int j = 0; j < q; j++){\n int s = 0;\n for (int bits = 0; bits < (1 << n); bits++) {\n int sum = 0;\n for (int i = 0; i < n; i++) {\n if (bits & (1 << i)) {\n sum += A[i];\n }\n }\n if (sum == m[j]) {\n cout << \"yes\" << endl;\n s = sum;\n break;\n }\n }\n if (s != m[j]){\n cout << \"no\" << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 4940, "memory_kb": 3440, "score_of_the_acc": -1.0636, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_5_A_11045290", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint n;\nvector<int> A;\n\nbool solve(int i, int M){\n if (M == 0){\n return true;\n }\n else if (M < 0){\n return false; \n }\n \n if (i >= n){\n return false;\n }\n bool res = solve(i+1, M) || solve(i+1, M - A[i]);\n return res;\n}\n\nint main(){\n cin >> n;\n A.resize(n);\n for (int i = 0; i<n ; i++){\n cin >> A[i];\n }\n int q;\n cin >> q;\n for (int i= 0; i<q ;i++){\n int m;\n cin >> m;\n if (solve(0,m)){\n cout << \"yes\" << endl; \n } else {\n cout << \"no\" << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 3440, "score_of_the_acc": -0.1391, "final_rank": 12 } ]
aoj_ALDS1_5_B_cpp
Merge Sort Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function. Merge(A, left, mid, right) n1 = mid - left; n2 = right - mid; create array L[0...n1], R[0...n2] for i = 0 to n1-1 do L[i] = A[left + i] for i = 0 to n2-1 do R[i] = A[mid + i] L[n1] = SENTINEL R[n2] = SENTINEL i = 0; j = 0; for k = left to right-1 if L[i] <= R[j] then A[k] = L[i] i = i + 1 else A[k] = R[j] j = j + 1 Merge-Sort(A, left, right){ if left+1 < right then mid = (left + right)/2; call Merge-Sort(A, left, mid) call Merge-Sort(A, mid, right) call Merge(A, left, mid, right) Input In the first line n is given. In the second line, n integers are given. Output In the first line, print the sequence S. Two consequtive elements should be separated by a space character. In the second line, print the number of comparisons. Constraints n ≤ 500000 0 ≤ an element in S ≤ 10 9 Sample Input 1 10 8 5 9 2 6 3 7 1 10 4 Sample Output 1 1 2 3 4 5 6 7 8 9 10 34 Notes
[ { "submission_id": "aoj_ALDS1_5_B_11061501", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong long cnt = 0;\n\nvoid merge(vector<int> &A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n\n vector<int> L(n1 + 1), R(n2 + 1);\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int i = 0; i < n2; i++) R[i] = A[mid + i];\n\n L[n1] = 999999999;\n R[n2] = 999999999;\n\n int i = 0, j = 0;\n\n for (int k = left; k < right; k++) {\n if (L[i] < R[j]) {\n A[k] = L[i];\n i++;\n } else {\n A[k] = R[j];\n j++;\n }\n cnt++;\n }\n}\n\nvoid mergeSort(vector<int> &A, int left, int right) {\n if (left + 1 < right) {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\n\nint main() {\n int n;\n cin >> n;\n\n vector<int> A(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n\n mergeSort(A, 0, n);\n\n for (int i = 0; i < n; i++) {\n cout << A[i];\n if (i != n - 1) cout << \" \";\n }\n cout << endl;\n\n cout << cnt << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 7012, "score_of_the_acc": -0.8615, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_5_B_11061395", "code_snippet": "# include <stdio.h>\n# define MAX 500000\nint count;\n\nvoid print_array(int array[], int array_len)\n{\n for (int i = 0; i < array_len; i++)\n {\n printf(\"%d\", array[i]);\n if (i != array_len - 1)\n printf(\" \");\n }\n printf(\"\\n\");\n}\n\nvoid merge_sort(int A[], int left, int right)\n{\n int i, j, k, mid;\n int work[MAX];\n\n if (left < right)\n {\n mid = (left + right) / 2;\n merge_sort(A, left, mid);\n merge_sort(A, mid + 1, right);\n\n for (i = mid; i >= left; i--)\n work[i] = A[i];\n\n for (j = mid + 1; j <= right; j++)\n work[right - (j - (mid + 1))] = A[j];\n\n i = left;\n j = right;\n for (k = left; k <= right; k++)\n {\n count++;\n if (work[i] < work[j])\n A[k] = work[i++];\n else\n A[k] = work[j--];\n }\n }\n}\n\nint main(void)\n{\n int N;\n int A[MAX];\n\n scanf(\"%d\", &N);\n for (int i = 0; i < N; i++)\n scanf(\"%d\", &A[i]);\n\n merge_sort(A, 0, N - 1);\n print_array(A, N);\n printf(\"%d\\n\", count);\n\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 41788, "score_of_the_acc": -1.0909, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_5_B_11061326", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstatic const long long INFTY = LLONG_MAX;\nlong long cnt = 0;\n\nvoid merge_vec(vector<long long> &A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n\n vector<long long> L(n1 + 1), R(n2 + 1);\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int i = 0; i < n2; i++) R[i] = A[mid + i];\n\n L[n1] = INFTY;\n R[n2] = INFTY;\n\n int i = 0, j = 0;\n\n for (int k = left; k < right; k++) {\n cnt++;\n if (L[i] <= R[j]) {\n A[k] = L[i];\n i++;\n } else {\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(vector<long long> &A, int left, int right) {\n if (left + 1 < right) {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge_vec(A, left, mid, right);\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n vector<long long> A(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n\n mergeSort(A, 0, n);\n\n for (int i = 0; i < n; i++) {\n if (i) cout << \" \";\n cout << A[i];\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 10688, "score_of_the_acc": -0.3263, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_5_B_11060938", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint mergeSort(int left, int right)\n{\n if(left + 1 < right) {\n int mid = (left + right) >> 1;\n return (mergeSort(left, mid) + mergeSort(mid, right) + right - left);\n } else {\n return (0);\n }\n}\n\nint main()\n{\n int N, A[500000];\n scanf(\"%d\", &N);\n for(int i = 0; i < N; i++) scanf(\"%d\", &A[i]);\n sort(A, A + N);\n for(int i = 0; i < N; i++) {\n if(i > 0) putchar(' ');\n printf(\"%d\", A[i]);\n }\n putchar('\\n');\n printf(\"%d\\n\", mergeSort(0, N));\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5436, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_5_B_11060592", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long INF = (1LL << 60); \nlong long cnt = 0; \n\nvoid merge(vector<long long> &A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n\n vector<long long> L(n1 + 1), R(n2 + 1);\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int j = 0; j < n2; j++) R[j] = A[mid + j];\n\n L[n1] = INF;\n R[n2] = INF;\n\n int i = 0, j = 0;\n for (int k = left; k < right; k++) {\n cnt++; \n if (L[i] <= R[j]) {\n A[k] = L[i];\n i++;\n } else {\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(vector<long long> &A, int left, int right) {\n if (left + 1 < right) { \n int mid = (left + right) / 2;\n mergeSort(A, left, mid); \n mergeSort(A, mid, right); \n merge(A, left, mid, right); \n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n vector<long long> S(n);\n for (int i = 0; i < n; i++) cin >> S[i];\n\n mergeSort(S, 0, n);\n\n for (int i = 0; i < n; i++) {\n if (i) cout << ' ';\n cout << S[i];\n }\n cout << '\\n';\n\n cout << cnt << '\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 10824, "score_of_the_acc": -0.33, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_5_B_11060540", "code_snippet": "#include <vector>\n#include <iostream>\nusing namespace std;\n\nvoid Merge(vector<unsigned int> &Sequence, int LeftIndex, int MidIndex, int RightIndex, int &CompareCount)\n{\n int LeftSequenceCount = MidIndex - LeftIndex;\n int RightSequenceCount = RightIndex - MidIndex;\n unsigned int Infty = 1000000001; //十分大きな整数値\n vector<unsigned int> LeftSequence(LeftSequenceCount + 1);\n vector<unsigned int> RightSequence(RightSequenceCount + 1);\n \n for (int i = 0; i < LeftSequenceCount; i++)\n {\n LeftSequence.at(i) = Sequence.at(LeftIndex + i);\n }\n LeftSequence.back() = Infty;\n \n for (int i = 0; i < RightSequenceCount; i++)\n {\n RightSequence.at(i) = Sequence.at(MidIndex + i);\n }\n RightSequence.back() = Infty;\n \n int NowLeftSequenceIndex = 0;\n int NowRightSequenceIndex = 0;\n for (int i = LeftIndex; i < RightIndex; i++)\n {\n if (LeftSequence.at(NowLeftSequenceIndex) <= RightSequence.at(NowRightSequenceIndex))\n {\n Sequence.at(i) = LeftSequence.at(NowLeftSequenceIndex);\n NowLeftSequenceIndex ++;\n }\n else\n {\n Sequence.at(i) = RightSequence.at(NowRightSequenceIndex);\n NowRightSequenceIndex ++; \n }\n CompareCount ++;\n }\n}\n\nvoid MergeSort(vector<unsigned int> &Sequence, int LeftIndex, int RightIndex, int &CompareCount)\n{\n if (RightIndex - LeftIndex > 1)\n {\n int MidIndex = (LeftIndex + RightIndex) / 2;\n MergeSort(Sequence, LeftIndex, MidIndex, CompareCount);\n MergeSort(Sequence, MidIndex, RightIndex, CompareCount);\n Merge(Sequence, LeftIndex, MidIndex, RightIndex, CompareCount);\n }\n else\n {\n }\n}\nint main(){\n int ElementCount;\n cin >> ElementCount;\n vector<unsigned int> Sequence(ElementCount);\n for (int i = 0; i < ElementCount; i++){\n cin >> Sequence.at(i);\n }\n int CompareCount = 0;\n MergeSort(Sequence, 0, ElementCount, CompareCount);\n \n for (int i = 0; i < ElementCount - 1; i++){\n cout << Sequence.at(i) << \" \";\n }\n cout << Sequence.back() << \"\\n\";\n cout << CompareCount << \"\\n\";\n \n}", "accuracy": 1, "time_ms": 190, "memory_kb": 6984, "score_of_the_acc": -1.0426, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_5_B_11060442", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint count = 0;\n\nvoid merge(int A[], int left, int mid, int right){\n int n1 = mid - left;\n int n2 = right - mid;\n int L[n1+1];\n int R[n2+1];\n for(int i=0;i<n1;i++){\n L[i] = A[left+i];\n }\n for(int j=0;j<n2;j++){\n R[j] = A[mid+j];\n }\n L[n1] = 1000000000;\n R[n2] = 1000000000;\n int i = 0;\n int j = 0;\n for(int k=left;k<right;k++){\n count++;\n if(L[i] <= R[j]){\n A[k] = L[i];\n i++;\n }\n else{\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(int A[], int left, int right){\n if(left+1 < right){\n int mid = (left + right)/2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\nint main(){\n int n;\n cin >> n;\n \n int S[n];\n for(int x=0;x<n;x++){\n cin >> S[x];\n }\n \n mergeSort(S, 0, n);\n \n for(int y=0;y<n;y++){\n if(y!=n-1){\n cout << S[y] << \" \";\n }\n else{\n cout << S[y] << endl;\n }\n }\n \n cout << count << endl;\n \n}", "accuracy": 1, "time_ms": 170, "memory_kb": 7268, "score_of_the_acc": -0.8686, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_5_B_11060440", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint count = 0;\n\nvoid merge(int A[], int left, int mid, int right){\n int n1 = mid - left;\n int n2 = right - mid;\n int L[n1+1];\n int R[n2+1];\n for(int i=0;i<n1;i++){\n L[i] = A[left+i];\n }\n for(int j=0;j<n2;j++){\n R[j] = A[mid+j];\n }\n L[n1] = 100000000;\n R[n2] = 100000000;\n int i = 0;\n int j = 0;\n for(int k=left;k<right;k++){\n count++;\n if(L[i] <= R[j]){\n A[k] = L[i];\n i++;\n }\n else{\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(int A[], int left, int right){\n if(left+1 < right){\n int mid = (left + right)/2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\nint main(){\n int n;\n cin >> n;\n \n int S[n];\n for(int x=0;x<n;x++){\n cin >> S[x];\n }\n \n mergeSort(S, 0, n);\n \n for(int y=0;y<n;y++){\n if(y!=n-1){\n cout << S[y] << \" \";\n }\n else{\n cout << S[y] << endl;\n }\n }\n \n cout << count << endl;\n \n}", "accuracy": 0.9, "time_ms": 150, "memory_kb": 7272, "score_of_the_acc": -0.6869, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_5_B_11060439", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint count = 0;\n\nvoid merge(int A[], int left, int mid, int right){\n int n1 = mid - left;\n int n2 = right - mid;\n int L[n1+1];\n int R[n2+1];\n for(int i=0;i<n1;i++){\n L[i] = A[left+i];\n }\n for(int j=0;j<n2;j++){\n R[j] = A[mid+j];\n }\n L[n1] = 10000000;\n R[n2] = 10000000;\n int i = 0;\n int j = 0;\n for(int k=left;k<right;k++){\n count++;\n if(L[i] <= R[j]){\n A[k] = L[i];\n i++;\n }\n else{\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(int A[], int left, int right){\n if(left+1 < right){\n int mid = (left + right)/2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\nint main(){\n int n;\n cin >> n;\n \n int S[n];\n for(int x=0;x<n;x++){\n cin >> S[x];\n }\n \n mergeSort(S, 0, n);\n \n for(int y=0;y<n;y++){\n if(y!=n-1){\n cout << S[y] << \" \";\n }\n else{\n cout << S[y] << endl;\n }\n }\n \n cout << count << endl;\n \n}", "accuracy": 0.9, "time_ms": 150, "memory_kb": 7272, "score_of_the_acc": -0.6869, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_5_B_11060402", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nstatic const ll INFTY = LLONG_MAX;\n\nlong long cnt = 0; // 比較回数\n\nvoid merge_vec(vector<ll> &A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n vector<ll> L(n1 + 1), R(n2 + 1);\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int i = 0; i < n2; i++) R[i] = A[mid + i];\n\n L[n1] = INFTY;\n R[n2] = INFTY;\n\n int i = 0, j = 0;\n\n for (int k = left; k < right; k++) {\n cnt++; // 比較回数をカウント\n if (L[i] <= R[j]) {\n A[k] = L[i];\n i++;\n } else {\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(vector<ll> &A, int left, int right) {\n if (left + 1 < right) {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge_vec(A, left, mid, right);\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n vector<ll> A(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n\n mergeSort(A, 0, n);\n\n // 出力\n for (int i = 0; i < n; i++) {\n if (i) cout << \" \";\n cout << A[i];\n }\n cout << \"\\n\";\n\n cout << cnt << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 10804, "score_of_the_acc": -0.3295, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_5_B_11060089", "code_snippet": "#include <iostream>\n#include <climits>\nusing namespace std;\n\nlong long cnt = 0;\n\nvoid merge(int A[], int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n\n int* L = new int[n1 + 1];\n int* R = new int[n2 + 1];\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int i = 0; i < n2; i++) R[i] = A[mid + i];\n\n L[n1] = INT_MAX; \n R[n2] = INT_MAX;\n\n int i = 0, j = 0;\n\n for (int k = left; k < right; k++) {\n cnt++; \n if (L[i] <= R[j]) A[k] = L[i++];\n else A[k] = R[j++];\n }\n\n delete[] L;\n delete[] R;\n}\n\nvoid mergeSort(int A[], int left, int right) {\n if (left + 1 < right) {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\n\nint main() {\n int n;\n cin >> n;\n int S[n];\n for (int i = 0; i < n; i++) cin >> S[i];\n\n mergeSort(S, 0, n);\n\n // ★末尾に空白を出力しない★\n for (int i = 0; i < n; i++) {\n if (i) cout << \" \";\n cout << S[i];\n }\n cout << endl;\n\n cout << cnt << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 7116, "score_of_the_acc": -0.9553, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_5_B_11059080", "code_snippet": "#include <iostream>\n#include <vector>\n#include <limits> // for numeric_limits\n\nlong long comparisonCount = 0; // 比較回数をグローバル変数で管理\n\nvoid merge(std::vector<int>& A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n\n std::vector<int> L(n1 + 1);\n std::vector<int> R(n2 + 1);\n\n for (int i = 0; i < n1; ++i) {\n L[i] = A[left + i];\n }\n for (int i = 0; i < n2; ++i) {\n R[i] = A[mid + i];\n }\n\n L[n1] = std::numeric_limits<int>::max(); // 番兵\n R[n2] = std::numeric_limits<int>::max(); // 番兵\n\n int i = 0;\n int j = 0;\n\n for (int k = left; k < right; ++k) {\n comparisonCount++; // ここで比較が行われる\n if (L[i] <= R[j]) {\n A[k] = L[i];\n i++;\n } else {\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(std::vector<int>& A, int left, int right) {\n if (left + 1 < right) {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\n\nint main() {\n std::ios_base::sync_with_stdio(false); // 高速化\n std::cin.tie(NULL); // 高速化\n\n int n;\n std::cin >> n;\n\n std::vector<int> S(n);\n for (int i = 0; i < n; ++i) {\n std::cin >> S[i];\n }\n\n mergeSort(S, 0, n);\n\n for (int i = 0; i < n; ++i) {\n std::cout << S[i] << (i == n - 1 ? \"\" : \" \");\n }\n std::cout << std::endl;\n\n std::cout << comparisonCount << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 6992, "score_of_the_acc": -0.2246, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_5_B_11058864", "code_snippet": "#include<iostream>\n#include<vector>\n\nusing namespace std;\n\nvoid merge(vector<int>&A,int left, int mid, int right, int&Hikaku_count){\n int n1;\n int n2;\n n1 = mid - left;\n n2 = right - mid;\n vector<int> L(n1+1);\n vector<int> R(n2+1);\n for(int i = 0; i < n1; i++){\n L[i] = A[left + i];\n }\n for(int j = 0; j < n2; j++){\n R[j] = A[mid + j];\n }\n int INFTY = 1000000000;\n L[n1] = INFTY;\n R[n2] = INFTY ; \n int i = 0;\n int j = 0;\n for(int k = left; k < right; k++ ){\n Hikaku_count ++;\n if(L[i] <= R[j]){\n A[k] = L[i];\n i = i + 1;\n }else{\n A[k] = R[j];\n j = j+1;\n }\n }\n}\n\nvoid mergeSort(vector<int>&A, int left, int right, int&Hikaku_count){\n int mid;\n if(left + 1 < right){\n mid = (left + right) / 2;\n mergeSort(A, left, mid,Hikaku_count);\n mergeSort(A, mid, right,Hikaku_count);\n merge(A, left, mid, right,Hikaku_count);\n }\n}\n\nint main(){\n int x;\n cin >> x;\n vector<int>S(x);\n for(int i = 0; i < x; i++){\n int y;\n cin >> y;\n S[i] = y;\n }\n int Hikaku_count = 0;\n mergeSort(S,0,x,Hikaku_count);\n for(int i = 0; i < x; i++){\n cout << S[i];\n if(i != x-1){\n cout << \" \";\n }\n }\n cout << endl;\n cout << Hikaku_count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 6968, "score_of_the_acc": -0.9512, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_5_B_11058861", "code_snippet": "#include<iostream>\n#include<vector>\n#include<cmath>\n\nusing namespace std;\n\nvoid merge(vector<int>&A,int left, int mid, int right, int&Hikaku_count){\n int n1;\n int n2;\n n1 = mid - left;\n n2 = right - mid;\n vector<int> L(n1+1);\n vector<int> R(n2+1);\n for(int i = 0; i < n1; i++){\n L[i] = A[left + i];\n }\n for(int j = 0; j < n2; j++){\n R[j] = A[mid + j];\n }\n int INFTY = 1000000000;\n L[n1] = INFTY;\n R[n2] = INFTY ; \n int i = 0;\n int j = 0;\n for(int k = left; k < right; k++ ){\n Hikaku_count ++;\n if(L[i] <= R[j]){\n A[k] = L[i];\n i = i + 1;\n }else{\n A[k] = R[j];\n j = j+1;\n }\n }\n}\n\nvoid mergeSort(vector<int>&A, int left, int right, int&Hikaku_count){\n int mid;\n if(left + 1 < right){\n mid = (left + right) / 2;\n mergeSort(A, left, mid,Hikaku_count);\n mergeSort(A, mid, right,Hikaku_count);\n merge(A, left, mid, right,Hikaku_count);\n }\n}\n\nint main(){\n int x;\n cin >> x;\n vector<int>S(x);\n for(int i = 0; i < x; i++){\n int y;\n cin >> y;\n S[i] = y;\n }\n int Hikaku_count = 0;\n mergeSort(S,0,x,Hikaku_count);\n for(int i = 0; i < x; i++){\n cout << S[i];\n if(i != x-1){\n cout << \" \";\n }\n }\n cout << endl;\n cout << Hikaku_count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 6940, "score_of_the_acc": -0.9505, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_5_B_11058829", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint count =0;\nvoid merge(vector<int>& A,int left,int mid,int right){\n int n1=mid-left;\n int n2=right-mid;\n vector<int> L(n1+1),R(n2+1);\n for (int i=0;i<n1;i++){\n L[i]=A[left+i];\n }\n for (int j=0;j<n2;j++){\n R[j]=A[mid+j];\n }\n\n L[n1]=1000000000;\n R[n2]=1000000000;\n int i=0;\n int j=0;\n for (int k=left;k<right;k++){\n if (L[i]<=R[j]){\n A[k]=L[i];\n i+=1;\n }\n else{\n A[k]=R[j];\n j+=1;\n }\n count+=1;\n }\n}\n\nvoid mergeSort(vector<int>& A,int left,int right){\n if (left+1<right){\n int mid = (left+right)/2;\n mergeSort(A,left,mid);\n mergeSort(A,mid,right);\n merge(A,left,mid,right);\n }\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> S(n);\n for (int i=0;i<n;i++){\n cin >> S[i];\n }\n\n mergeSort(S,0,n);\n for (int i=0;i<n;i++){\n if(i>0) cout <<\" \";\n cout << S[i];\n }\n cout << endl << count << endl;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 7184, "score_of_the_acc": -1.0481, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_5_B_11058715", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long INFTY = (1LL << 60); // 番兵として十分大きい値\nlong long cnt = 0; // 比較回数\n\nvoid mergeVec(vector<long long> &A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n\n vector<long long> L(n1 + 1), R(n2 + 1);\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int i = 0; i < n2; i++) R[i] = A[mid + i];\n\n L[n1] = INFTY; // 番兵\n R[n2] = INFTY; // 番兵\n\n int i = 0, j = 0;\n\n for (int k = left; k < right; k++) {\n cnt++; // ★ 比較回数 L[i] <= R[j] を数える\n if (L[i] <= R[j]) {\n A[k] = L[i];\n i++;\n } else {\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid mergeSort(vector<long long> &A, int left, int right) {\n if (left + 1 < right) {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n mergeVec(A, left, mid, right);\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n vector<long long> A(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n\n mergeSort(A, 0, n);\n\n // 整列済みの数列を出力\n for (int i = 0; i < n; i++) {\n if (i) cout << \" \";\n cout << A[i];\n }\n cout << \"\\n\";\n\n // 比較回数\n cout << cnt << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 10792, "score_of_the_acc": -0.3292, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_5_B_11058700", "code_snippet": "#include <iostream>\n#include <vector>\n#include <limits>\n\nusing namespace std;\n\nvector<int> L, R;\n\nint merge(vector<int>& A,int left,int mid,int right, int& cnt){\n const int INF = numeric_limits<int>::max();\n int n1 = mid - left;\n int n2 = right - mid;\n\n for (int i=0;i<n1;i++){\n L[i] = A[left+i];\n }\n for (int j=0;j<n2;j++){\n R[j] = A[mid+j];\n }\n L[n1] = INF;\n R[n2] = INF;\n\n int i = 0;\n int j = 0;\n for (int k=left;k<right;k++){\n cnt ++;\n if (L[i]<=R[j]){\n A[k] = L[i];\n i ++;\n } else {\n A[k] = R[j];\n j ++;\n }\n }\n return 0;\n}\n\nint mergeSort(vector<int>& A,int left,int right, int& cnt){\n if (left+1 < right){\n int mid = (left + right)/2;\n mergeSort(A, left, mid, cnt);\n mergeSort(A, mid, right, cnt);\n merge(A, left, mid, right, cnt);\n }\n return 0;\n}\n\nint main(){\n int n;\n cin >> n;\n int a;\n vector<int> A(n);\n L.resize(n);\n R.resize(n);\n for (int i=0;i<n;i++){\n cin >> a;\n A[i] = a;\n }\n int cnt = 0;\n mergeSort(A,0,n,cnt);\n for (int i=0;i<n;i++){\n if (i > 0){\n cout << \" \" << A[i];\n } else {\n cout << A[i];\n }\n }\n cout << endl;\n cout << cnt << endl;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 8920, "score_of_the_acc": -0.914, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_5_B_11058694", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nvector<int> L, R;\n\nint merge(vector<int>& A,int left,int mid,int right, int& cnt){\n int n1 = mid - left;\n int n2 = right - mid;\n\n for (int i=0;i<n1;i++){\n L[i] = A[left+i];\n }\n for (int j=0;j<n2;j++){\n R[j] = A[mid+j];\n }\n L[n1] = 1000000;\n R[n2] = 1000000;\n\n int i = 0;\n int j = 0;\n for (int k=left;k<right;k++){\n cnt ++;\n if (L[i]<=R[j]){\n A[k] = L[i];\n i ++;\n } else {\n A[k] = R[j];\n j ++;\n }\n }\n return 0;\n}\n\nint mergeSort(vector<int>& A,int left,int right, int& cnt){\n if (left+1 < right){\n int mid = (left + right)/2;\n mergeSort(A, left, mid, cnt);\n mergeSort(A, mid, right, cnt);\n merge(A, left, mid, right, cnt);\n }\n return 0;\n}\n\nint main(){\n int n;\n cin >> n;\n int a;\n vector<int> A(n);\n L.resize(n);\n R.resize(n);\n for (int i=0;i<n;i++){\n cin >> a;\n A[i] = a;\n }\n int cnt = 0;\n mergeSort(A,0,n,cnt);\n for (int i=0;i<n;i++){\n if (i > 0){\n cout << \" \" << A[i];\n } else {\n cout << A[i];\n }\n }\n cout << endl;\n cout << cnt << endl;\n}", "accuracy": 0.9, "time_ms": 140, "memory_kb": 8720, "score_of_the_acc": -0.6358, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_5_B_11058653", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\nint count = 0;\nvoid merge(vector<int> &A, int left, int mid, int right)\n{\n int n1 = mid - left;\n int n2 = right - mid;\n vector<int> L(n1 + 1), R(n2 + 1);\n for (int i = 0; i < n1; i++)\n {\n L[i] = A[left + i];\n }\n for (int i = 0; i < n2; i++)\n {\n R[i] = A[mid + i];\n }\n L[n1] = 1000000000;\n R[n2] = 1000000000;\n int i = 0;\n int j = 0;\n for (int k = left; k < right; k++)\n {\n count++;\n if (L[i] <= R[j])\n {\n A[k] = L[i];\n i++;\n }\n else\n {\n A[k] = R[j];\n j++;\n }\n }\n}\nvoid mergeSort(vector<int> &A, int left, int right)\n{\n if (left + 1 < right)\n {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\nint main()\n{\n int n;\n cin >> n;\n vector<int> S(n);\n for (int i = 0; i < n; i++)\n {\n cin >> S[i];\n }\n mergeSort(S, 0, n);\n for (int i = 0; i < n - 1; i++)\n {\n cout << S[i] << \" \";\n }\n cout << S[n - 1] << endl;\n cout << count << endl;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 7156, "score_of_the_acc": -0.9564, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_5_B_11058648", "code_snippet": "#include <iostream>\nusing namespace std;\n\nlong long _count = 0;\n\nvoid merge_sort(long long S[], long long n, long long left, long long right){\n // printf(\"left: %lld, right: %lld\\n\", left, right);\n if(left==right) return;\n long long mid = (left + right) /2;\n // cout << mid << '\\n';\n merge_sort(S, n, left, mid);\n merge_sort(S, n, mid+1, right);\n\n // printf(\"Re left: %lld, right: %lld\\n\", left, right);\n \n long long n_1 = mid-left+1;\n long long n_2 = right-mid;\n // printf(\"n_1=%lld, n_2=%lld\\n\", n_1, n_2);\n long long L_1[n_1+1];\n long long L_2[n_2+1];\n for(long long i=0; i<n_1; i++){\n L_1[i] = S[i+left];\n // printf(\"L_1[%lld]: %lld\", i, L_1[i]);printf(\"\\n\");\n }\n L_1[n_1] = 0x7fffffffffffffff;\n for(long long i=0; i<n_2; i++){\n L_2[i] = S[i+mid+1];\n // printf(\"L_2[%lld]: %lld\", i, L_2[i]);printf(\"\\n\");\n }\n L_2[n_2] = 0x7fffffffffffffff;\n \n\n long long j=0, k=0;\n // cout << L_1[0] << \"\\t\" << L_2[0] << \"\\n\";\n for(long long i=0; i<right-left+1; ++i){\n if(L_1[j]<L_2[k]){\n S[i+left] = L_1[j];\n // cout << \"S[\" << i+left << \"] = \" << S[i+left] << \"\\n\";\n ++j;\n }\n else{\n S[i+left] = L_2[k];\n // cout << \"S[\" << i+left << \"] = \" << S[i+left] << \"\\n\";\n ++k;\n }\n ++_count;\n }\n return;\n \n}\n\n\n\nint main(){\n\n long long n;\n cin >> n;\n long long S[n];\n for(long long i=0; i<n; ++i) cin >> S[i];\n merge_sort(S, n, 0, n-1);\n for(long long i=0; i<n-1; ++i){\n cout << S[i] << ' ';\n }\n cout << S[n-1] << endl;\n cout << _count << endl;\n \n \n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 11392, "score_of_the_acc": -0.6184, "final_rank": 7 } ]
aoj_ALDS1_6_B_cpp
Partition Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q. In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r). Your task is to read a sequence A and perform the Partition based on the following pseudocode: Partition(A, p, r) 1 x = A[r] 2 i = p-1 3 for j = p to r-1 4 do if A[j] <= x 5 then i = i+1 6 exchange A[i] and A[j] 7 exchange A[i+1] and A[r] 8 return i+1 Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r]. Input The first line of the input includes an integer n , the number of elements in the sequence A. In the second line, A i ( i = 1,2,..., n ), elements of the sequence are given separated by space characters. Output Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [ ] . Constraints 1 ≤ n ≤ 100,000 0 ≤ A i ≤ 100,000 Sample Input 1 12 13 19 9 5 12 8 7 4 21 2 6 11 Sample Output 1 9 5 8 7 4 2 6 [11] 21 13 19 12
[ { "submission_id": "aoj_ALDS1_6_B_11066645", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint partition(vector<int>& A, int p, int r) {\n int x = A[r]; // pivot\n int i = p - 1;\n for (int j = p; j <= r - 1; j++) {\n if (A[j] <= x) {\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n return i + 1;\n}\n\nint main() {\n int n;\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; i++) cin >> A[i];\n\n int q = partition(A, 0, n - 1);\n\n for (int i = 0; i < n; i++) {\n if (i == q) {\n cout << \"[\" << A[i] << \"]\";\n } else {\n cout << A[i];\n }\n if (i != n - 1) cout << \" \";\n }\n cout << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3468, "score_of_the_acc": -0.2212, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_6_B_11062480", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint partition(vector<int>&A,int p,int r){\n int x = A[r];\n int i = p-1;\n for(int j = p;j<=r-1;++j){\n if(A[j] <= x){\n i = i+1;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n return i+1;\n }\n\nint main(){\n int n;\n cin >> n;\n vector<int> A(n);\n for(int i=0;i<n;++i){\n cin >> A[i];\n }\n int x = partition(A,0,n-1);\n for(int j=0;j<x;++j){\n cout << A[j] << \" \";\n }\n cout << \"[\" << A[x] << \"]\";\n for(int k=x+1;k<n;++k){\n cout << \" \" << A[k];\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3396, "score_of_the_acc": -0.0619, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_6_B_11062437", "code_snippet": "#include<iostream>\n#include<vector>\n\nusing namespace std;\n\nint partition(vector<int>&A, int p, int r){\n int x;\n int i;\n x = A[r];\n i = p-1;\n for(int j = p; j < r; j++){\n if(A[j] <= x){\n i = i + 1;\n swap(A[i] , A[j]);\n }\n }\n swap(A[i+1] , A[r]);\n return i + 1;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int>S(n);\n for(int i = 0;i < n;i++){\n int j;\n cin >> j;\n S[i] = j;\n }\n\n int pivot_index = partition(S, 0, n-1);\n\n for(int i = 0; i < n; i++){\n if(i == pivot_index){\n cout << \"[\" << S[i] << \"]\";\n }else{\n cout << S[i];\n }\n if(i != n-1){\n cout << \" \" ;\n }\n }\n cout << endl;\n return 0;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3440, "score_of_the_acc": -0.1593, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_6_B_11061900", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint partition(vector<int>& A, int p, int r){\n int x = A[r];\n int i = p - 1;\n for(int j=p; j<=r-1; j++){\n if(A[j]<=x){\n i += 1;\n int k = A[i];\n A[i] = A[j];\n A[j] = k;\n }\n }\n int l = A[i+1];\n A[i+1] = A[r];\n A[r] = l;\n return i+1;\n}\n\n\nint main(){\n int n;\n cin >> n;\n vector<int>A(n);\n for(int i=0; i<n; i++){\n cin >> A[i];\n }\n\n int o = partition(A, 0, n-1);\n \n for(int i=0; i<n-1; i++){\n if(i==o){\n cout << \"[\" << A[i] << \"]\" << \" \";\n }\n else{\n cout << A[i] << \" \";\n }\n }\n \n if(n-1==o){\n cout << \"[\" << A[n-1] << \"]\";\n }\n else{\n cout << A[n-1];\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3576, "score_of_the_acc": -0.4602, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_6_B_11061812", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint partition(int A[], int p, int r){\n int x = A[r];\n int i = p-1;\n for(int j=p;j<r;j++){\n if(A[j]<=x){\n i++;\n int s=A[i];\n A[i] = A[j];\n A[j] = s;\n }\n }\n int s = A[i+1];\n A[i+1] = A[r];\n A[r] = s;\n return i+1;\n}\n\n\nint main(){\n int n;\n cin >> n;\n \n int A[n];\n for(int k=0;k<n;k++){\n cin >> A[k];\n }\n \n int x = partition(A, 0, n-1);\n \n for(int j=0;j<n;j++){\n if(j==x){\n cout << \"[\" << A[j] << \"]\" << \" \";\n }\n else if(j!=n-1){\n cout << A[j] << \" \";\n }\n else{\n cout << A[j] << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3708, "score_of_the_acc": -0.7522, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_6_B_11061803", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint pertition(vector<int>& A, int p, int r){\n int x = A[r];\n int i = p - 1;\n for (int j = p; j < r; j++){\n if (A[j] <= x){\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n\n return i + 1;\n}\n\nint main(void){\n int n;\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; i++){\n cin >> A[i];\n }\n\n int t = pertition(A, 0, n - 1);\n\n for (int i = 0; i < n; i++){\n if (i == n - 1){\n cout << A[i] << endl;\n } else if (i == t){\n cout << \"[\" << A[i] << \"] \";\n } else {\n cout << A[i] << \" \";\n }\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3604, "score_of_the_acc": -1.5221, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_6_B_11061800", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint Partition(vector<int> &A, int p, int r){\n int x = A[r];\n int i = p - 1;\n for(int j=p;j<r;j++){\n if(A[j] <= x){\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n return i+1;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> A(n);\n for(int i=0;i<n;i++){\n cin >> A[i];\n }\n int q = Partition(A, 0, n-1);\n for(int i=0;i<n-1;i++){\n if(i == q){\n cout << \"[\" << A[i] << \"] \";\n }\n else{\n cout << A[i] << \" \";\n }\n }\n cout << A[n-1] << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3484, "score_of_the_acc": -0.2566, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_6_B_11061797", "code_snippet": "#include <iostream>\n#include <vector>\n#include <utility>\n\nusing namespace std;\n\nint partition(vector<int> &A, int p, int r){\n int x = A[r];\n int i = p-1;\n for (int j=p; j<r; j++){\n if (A[j] <= x){\n i = i+1;\n swap(A[i],A[j]);\n }\n }\n swap(A[i+1],A[r]);\n\n return i+1;\n}\n\nint main(){\n int n,x1,pa;\n vector<int> A;\n\n cin >> n;\n for (int k=0; k<n; k++){\n cin >> x1;\n A.push_back(x1);\n if (k == n-1){\n pa = x1;\n }\n }\n int s = partition(A,0,n-1);\n\n for (int t=0; t<n; t++){\n if (t == s){\n cout << \"[\" << A[t] << \"]\" << \" \";\n } else if (t == n-1){\n cout << A[t] << \"\\n\";\n } else {\n cout << A[t] << \" \";\n }\n\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3584, "score_of_the_acc": -0.4779, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_6_B_11061779", "code_snippet": "#include<iostream>\nusing namespace std;\n\nint cnt = 0;\n\nint partition(int A[], int p, int r){\n int x = A[r];\n int i = p-1;\n for(int j=p;j<r;j++){\n if(A[j]<=x){\n cnt++;\n i++;\n int s=A[i];\n A[i] = A[j];\n A[j] = s;\n }\n }\n int s = A[i+1];\n A[i+1] = A[r];\n A[r] = s;\n return i+1;\n}\n\n\nint main(){\n int n;\n cin >> n;\n \n int A[n];\n for(int k=0;k<n;k++){\n cin >> A[k];\n }\n \n int x = A[n-1];\n \n partition(A, 0, n-1);\n \n for(int j=0;j<n;j++){\n if(j==cnt){\n cout << \"[\" << A[j] << \"]\" << \" \";\n }\n else if(j!=n-1){\n cout << A[j] << \" \";\n }\n else{\n cout << A[j] << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3820, "score_of_the_acc": -1, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_6_B_11061760", "code_snippet": "#include<iostream>\n\nusing namespace std;\n\nint partition(int A[],int p,int r){\n int x=A[r];\n int i=p-1;\n for (int j=p;j<r;j++){\n if(A[j]<=x){\n i=i+1;\n swap(A[i],A[j]);\n }\n }\n swap(A[i+1],A[r]);\n return i+1;\n}\n\nint main(){\n int n;\n cin >> n;\n int A[n];\n for (int i=0;i<n;i++){\n cin >> A[i];\n }\n\n int p=partition(A,0,n-1);\n \n for(int i=0;i<n;i++){\n if(i==p){\n cout << \"[\" << A[i] << \"]\";\n }else{\n cout << A[i];\n }\n if (i !=n-1){\n cout << \" \";\n }\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3740, "score_of_the_acc": -0.823, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_6_B_11061753", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint partition(vector<int> &A, int p, int r){\n int x = A[r];\n int i = p - 1;\n\n for(int j = p; j < r; ++j){\n if(A[j] <= x){\n ++i;\n swap(A[i], A[j]);\n }\n }\n\n swap(A[i + 1], A[r]);\n return i + 1;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> A(n);\n\n for(int k = 0; k < n; ++k){\n cin >> A[k];\n }\n\n int s = partition(A, 0, n - 1);\n\n for(int k = 0; k < s; ++k){\n cout << A[k] << \" \";\n }\n\n cout << \"[\" << A[s] << \"] \";\n\n for(int k = s + 1; k < n; ++k){\n cout << A[k];\n if(k != n - 1) cout << \" \";\n }\n\n cout << \"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3612, "score_of_the_acc": -0.5398, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_6_B_11061745", "code_snippet": "#include <iostream>\n#include <vector>\n#include <utility>\nusing namespace std;\nint partition(vector<int>&A,int p, int r){\n int i,x;\n x = A[r];\n i = p-1;\n for(int j = p; j < r; ++j){\n if (A[j] <= x){\n i += 1;\n swap(A[i], A[j]);\n } \n }\n swap(A[i+1], A[r]);\n return i+1;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> A(n);\n for(int i = 0;i < n;++i){\n cin >> A[i];\n }\n int q;\n q = partition(A, 0, n-1);\n for(int k = 0; k < q; ++k){\n cout << A[k] << \" \"; \n }\n cout << \"[\" << A[q] << \"]\" << \" \";\n for(int l = q+1 ; l < n; ++l){\n if (l != n-1){\n cout << A[l] << \" \";\n }else{\n cout << A[l] << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3640, "score_of_the_acc": -0.6018, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_6_B_11061744", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint partition(vector<int>& A, int p, int r){\n int x = A[r];\n int i = p-1;\n for (int j = p; j < r; j++) {\n if (A[j] <= x) {\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n return i+1;\n}\n\nint main() {\n int n, s;\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; i++) {\n cin >> A[i];\n }\n \n s = partition(A, 0, n-1);\n\n for (int i = 0; i < s; i++) {\n cout << A[i] << \" \";\n }\n cout << \"[\" << A[s] << \"] \";\n for (int j = s+1; j < n; j++) {\n cout << A[j];\n if (j != n-1) {\n cout << \" \";\n } else {\n cout << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3368, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_6_B_11061741", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint partition(vector<int>& A, int p, int r) {\n int x = A[r]; // pivot\n int i = p - 1;\n\n for (int j = p; j < r; j++) {\n if (A[j] <= x) {\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n return i + 1; // pivot の位置\n}\n\nint main() {\n int n;\n cin >> n;\n vector<int> S(n);\n\n for (int i = 0; i < n; i++) {\n cin >> S[i];\n }\n\n int pivot_index = partition(S, 0, n - 1);\n\n // 出力形式:\n // 左 side, [pivot], right side\n for (int j = 0; j < pivot_index; j++) {\n cout << S[j] << \" \";\n }\n\n cout << \"[\" << S[pivot_index] << \"] \";\n\n for (int k = pivot_index + 1; k < n; k++) {\n cout << S[k];\n if (k != n - 1) cout << \" \";\n }\n\n cout << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3504, "score_of_the_acc": -0.3009, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_6_B_11061720", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std; \n\nint partition(vector<int>&A, int p, int r){\n int x = A[r];\n int i = p - 1;\n for (int j = p; j < r; j++){\n if (A[j] <= x){\n i = i + 1;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1],A[r]);\n return i+1;\n}\n\nint main(){\n int n; cin >> n;\n vector<int> A(n);\n for (int i = 0;i < n; i++){\n cin >> A[i];\n }\n \n int q = partition (A,0,n-1);\n\n for (int i = 0; i < n; i++ ){\n if(i == q)cout << \"[\" << A[i] << \"]\";\n else cout << A[i];\n if (i != n-1)cout << \" \";\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3684, "score_of_the_acc": -1.6991, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_6_B_11061717", "code_snippet": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(){\n \n int n;\n cin >> n;\n vector<int> A(n);\n\n for(int i=0;i<n;++i){\n cin >> A[i];\n }\n\n int p = 0;\n int r = n-1;\n int x = A[r];\n int i = p-1;\n \n for(int j=p;j<r;++j){\n if(A[j]<=x){\n i = i+1;\n int temp = A[i];\n A[i] = A[j];\n A[j] = temp;\n }\n }\n int temp = A[i+1];\n A[i+1] = A[r];\n A[r] = temp;\n \n int q = i+1;\n \n for (int k = 0; k < n; k++) {\n if (k == q){\n cout << \"[\" << A[k] << \"]\";\n }else{\n cout << A[k];\n }\n if (k != n - 1) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3636, "score_of_the_acc": -0.5929, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_6_B_11061716", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n// 以下の擬似コードを書く\n\nint partition(vector<int> &A, int p, int r) {\n int x = A[r];\n int i = p - 1;\n for (int j = p; j <= r - 1; j++) {\n if (A[j] <= x) {\n i = i + 1;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n return i + 1;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; i++) {\n cin >> A[i];\n }\n \n int q = partition(A, 0, n - 1);\n\n for (int i = 0; i < n; i++) {\n if (i) cout << \" \";\n if (i==q){\n cout << '['<<A[i]<<']' ; \n }\n else{\n cout << A[i];\n }\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3556, "score_of_the_acc": -0.4159, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_6_B_11061710", "code_snippet": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(){\n \n int n;\n cin >> n;\n vector<int> A(n);\n\n for(int i=0;i<n;++i){\n cin >> A[i];\n }\n\n int p = 0;\n int r = n-1;\n int x = A[r];\n int i = p-1;\n \n for(int j=p;j<r;++j){\n if(A[j]<=x){\n i = i+1;\n int temp = A[i];\n A[i] = A[j];\n A[j] = temp;\n }\n }\n int temp = A[i+1];\n A[i+1] = A[r];\n A[r] = temp;\n \n int q = i+1;\n \n for (int k = 0; k < n; k++) {\n if (k == q)\n cout << \"[\" << A[k] << \"]\";\n else\n cout << A[k];\n \n if (k != n - 1) cout << \" \";\n }\n cout << \"\\n\";\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3636, "score_of_the_acc": -0.5929, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_6_B_11061707", "code_snippet": "using namespace std;\n#include <iostream>\n#include <vector>\n\nint partition(int A[], int p, int r){\n int x = A[r];\n int i = p-1;\n for(int j = p; j < r; j++){\n if(A[j] <= x){\n i = i+1;\n int a = A[i];\n A[i] = A[j];\n A[j] = a;\n }\n }\n int b = A[i+1];\n A[i+1] = A[r];\n A[r] = b;\n return i+1;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> A(n);\n for(int i = 0; i < n; i++){\n cin >> A[i]; \n }\n int c = partition(A.data(),0,n-1);\n for(int i = 0; i < n; i++){\n if (i > 0){\n cout << \" \";\n }\n if(i == c){\n cout << \"[\" << A[i] << \"]\";\n }else{\n cout << A[i];\n }\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3608, "score_of_the_acc": -0.531, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_6_B_11061705", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint partition(vector<int>& A, int p, int r){\n int x =A[r];\n int i = p-1;\n \n for (int j =p; j<= r-1; ++j){\n if (A[j] <= x){\n ++i;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n return i+1;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> S(n);\n \n for (int i = 0; i<n; i++){\n cin >> S[i];\n }\n \n int pI = partition(S, 0, n-1);\n for (int i = 0; i < n; ++i) {\n if (i == pI) {\n cout << \"[\" << S[i] << \"]\";\n } else {\n cout << S[i];\n }\n\n if (i < n - 1) {\n cout << \" \";\n }\n }\n\n cout << endl;\n\n return 0;\n\n \n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3444, "score_of_the_acc": -0.1681, "final_rank": 4 } ]
aoj_ALDS1_6_C_cpp
Quick Sort Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode: Partition(A, p, r) 1 x = A[r] 2 i = p-1 3 for j = p to r-1 4 do if A[j] <= x 5 then i = i+1 6 exchange A[i] and A[j] 7 exchange A[i+1] and A[r] 8 return i+1 Quicksort(A, p, r) 1 if p < r 2 then q = Partition(A, p, r) 3 run Quicksort(A, p, q-1) 4 run Quicksort(A, q+1, r) Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers. Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance). Input The first line contains an integer n , the number of cards. n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space. Output In the first line, print the stability (" Stable " or " Not stable ") of this output. In the following lines, print the arranged cards in the same manner of that of the input. Constraints 1 ≤ n ≤ 100,000 1 ≤ the number of a card ≤ 10 9 There are no identical card in the input Sample Input 1 6 D 3 H 2 D 1 S 3 D 2 C 1 Sample Output 1 Not stable D 1 C 1 D 2 H 2 D 3 S 3 Sample Input 2 2 S 1 H 1 Sample Output 2 Stable S 1 H 1
[ { "submission_id": "aoj_ALDS1_6_C_11066665", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Card {\n char suit;\n int value;\n};\n\n// partition (ALDS1_6_B 準拠)\nint partition(vector<Card> &A, int p, int r) {\n int x = A[r].value;\n int i = p - 1;\n for (int j = p; j < r; j++) {\n if (A[j].value <= x) {\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n return i+1;\n}\n\nvoid quicksort(vector<Card> &A, int p, int r) {\n if (p < r) {\n int q = partition(A, p, r);\n quicksort(A, p, q-1);\n quicksort(A, q+1, r);\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n vector<Card> A(n), B(n);\n\n for (int i = 0; i < n; i++) {\n cin >> A[i].suit >> A[i].value;\n B[i] = A[i]; // コピー\n }\n\n // クイックソート\n quicksort(A, 0, n-1);\n\n // 安定ソート (std::stable_sort)\n stable_sort(B.begin(), B.end(), [](const Card &c1, const Card &c2){\n return c1.value < c2.value;\n });\n\n // 安定性判定\n bool stable = true;\n for (int i = 0; i < n; i++) {\n if (A[i].suit != B[i].suit) {\n stable = false;\n break;\n }\n }\n\n cout << (stable ? \"Stable\" : \"Not stable\") << \"\\n\";\n for (int i = 0; i < n; i++) {\n cout << A[i].suit << \" \" << A[i].value << \"\\n\";\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4912, "score_of_the_acc": -0.0917, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_6_C_11065941", "code_snippet": "#include <iostream>\nusing namespace std;\n\ntypedef struct\n{\n char c;\n int num;\n} Card;\n\nbool flag = 1;\n\nint partition(Card *A, int p, int r)\n{\n Card temp;\n int x = A[r].num;\n int i = p - 1;\n for (int j = p; j < r; j++)\n {\n if (A[j].num <= x)\n {\n i++;\n temp = A[j];\n A[j] = A[i];\n A[i] = temp;\n }\n }\n\n // for (int j = i + 2; j <= r; j++)\n // {\n // if (A[i + 1].num == A[j].num)\n // {\n // flag = 0;\n // }\n // }\n\n temp = A[i + 1];\n A[i + 1] = A[r];\n A[r] = temp;\n return i + 1;\n}\n\nvoid quicksort(Card *A, int p, int r)\n{\n if (p < r)\n {\n int q = partition(A, p, r);\n quicksort(A, p, q - 1);\n quicksort(A, q + 1, r);\n }\n}\n\nint main()\n{\n int n;\n cin >> n;\n Card A[n];\n Card Old[n];\n\n for (int i = 0; i < n; i++)\n {\n cin >> A[i].c >> A[i].num;\n }\n for (int i = 0; i < n; i++)\n {\n Old[i] = A[i];\n }\n\n quicksort(A, 0, n - 1);\n\n int pre_num = A[0].num;\n int k;\n char pre_char = A[0].c;\n for (int i = 1; i < n; i++)\n {\n if (A[i].num == pre_num)\n {\n k = 0;\n while (true)\n {\n if (Old[k].num == pre_num && Old[k].c == pre_char)\n {\n break;\n }\n else if (Old[k].num == A[i].num && Old[k].c == A[i].c)\n {\n flag = 0;\n break;\n }\n k++;\n }\n }\n if (!flag)\n {\n break;\n }\n pre_num = A[i].num;\n pre_char = A[i].c;\n }\n\n if (flag)\n {\n cout << \"Stable\" << endl;\n }\n else\n {\n cout << \"Not stable\" << endl;\n }\n\n for (int i = 0; i < n; i++)\n {\n cout << A[i].c << \" \" << A[i].num << endl;\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4804, "score_of_the_acc": -0.7496, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_6_C_11065929", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint partition(vector<pair<char,int>> &A, int p, int r) {\n int x = A[r].second;\n int i = p - 1;\n for (int j = p; j <= r - 1; j++) {\n if (A[j].second <= x) {\n i = i + 1;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n return i + 1;\n}\n\nvoid quicksort(vector<pair<char,int>> &A, int p, int r) {\n if (p < r) {\n int q = partition(A, p, r);\n quicksort(A, p, q - 1);\n quicksort(A, q + 1, r);\n }\n}\n\nint main(){\n int n;\n cin >> n;\n vector<pair<char,int>> A;\n for (int i = 0; i < n; i++) {\n char tempchar;\n int tempint;\n cin >> tempchar >> tempint;\n A.push_back({tempchar,tempint});\n }\n\n vector<pair<char,int>> B = A; \n \n quicksort(A, 0, n - 1);\n\n\n stable_sort(B.begin(), B.end(), [](const pair<char, int>& a, const pair<char, int>& b) {\n return a.second < b.second;\n });\n\n if(A == B){\n cout << \"Stable\" << endl;\n }\n else{\n cout << \"Not stable\" << endl;\n }\n\n for (int i = 0; i < n; i++) {\n cout << A[i].first << \" \" << A[i].second << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5512, "score_of_the_acc": -0.9181, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_6_C_11065810", "code_snippet": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstruct trump {\n char c;\n int n;\n int order;\n};\n\nint partition(vector<trump>& A, int p, int r){\n int x = A[r].n;\n int i = p-1;\n for (int j=p;j<r;j++){\n if (A[j].n <= x){\n i = i+1;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n return i+1;\n}\n\nvoid Qs(vector<trump>& A, int p, int r){\n if (p < r){\n int q = partition(A, p, r);\n Qs(A, p, q-1);\n Qs(A, q+1, r);\n }\n}\n\nint main(){\n int n, p;\n cin >> n;\n vector<trump> A(n);\n for (int i=0;i<n;i++){\n cin >> A[i].c;\n cin >> A[i].n;\n A[i].order = i;\n }\n Qs(A, 0, n-1);\n\n bool check = true;\n p = 0;\n for (int i=0;i<n;i++){\n if (i < p) {continue;}\n if (!check) {\n \n break;\n }\n for (int j=i+1;j<n;j++){\n if (A[i].n == A[j].n){\n if (A[i].order > A[j].order){\n // cout << i << \",\" << j << endl;\n check = false;\n break;\n }\n } else {\n p = j;\n break;\n }\n }\n }\n\n if (check){\n cout << \"Stable\" << endl;\n }else{\n cout << \"Not stable\" << endl;\n }\n\n for (int i=0;i<n;i++){\n cout << A[i].c << \" \" << A[i].n << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 4136, "score_of_the_acc": -0.8066, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_6_C_11065727", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Card {\n char suit;\n int value;\n int id; // 入力順を保持して安定性判定に使用\n};\n\nint partition(vector<Card> &A, int p, int r) {\n int x = A[r].value;\n int i = p - 1;\n for (int j = p; j < r; j++) {\n if (A[j].value <= x) {\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n return i + 1;\n}\n\nvoid quickSort(vector<Card> &A, int p, int r) {\n if (p < r) {\n int q = partition(A, p, r);\n quickSort(A, p, q - 1);\n quickSort(A, q + 1, r);\n }\n}\n\n// 比較のための安定ソート(C++ の stable_sort)\nvector<Card> stableSorted(const vector<Card> &A) {\n vector<Card> B = A;\n stable_sort(B.begin(), B.end(),\n [](const Card &c1, const Card &c2) {\n return c1.value < c2.value;\n });\n return B;\n}\n\nint main() {\n int n;\n cin >> n;\n vector<Card> A(n);\n\n for (int i = 0; i < n; i++) {\n cin >> A[i].suit >> A[i].value;\n A[i].id = i; // 入力順を覚える\n }\n\n vector<Card> quick = A;\n quickSort(quick, 0, n - 1);\n\n vector<Card> stable = stableSorted(A);\n\n // 安定性チェック\n bool isStable = true;\n for (int i = 0; i < n; i++) {\n // 値も同じ、スートも同じ、そして stable_sort の順序と一致するか\n if (quick[i].suit != stable[i].suit ||\n quick[i].value != stable[i].value) {\n isStable = false;\n break;\n }\n }\n\n cout << (isStable ? \"Stable\" : \"Not stable\") << endl;\n for (int i = 0; i < n; i++) {\n cout << quick[i].suit << \" \" << quick[i].value << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 7076, "score_of_the_acc": -1.0449, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_6_C_11065450", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\nint partition(vector<int>&A,vector<char>&B,vector<int>&C,int p, int r){\n int i,x;\n x = A[r];\n i = p-1;\n for(int j = p; j < r; ++j){\n if (A[j] <= x){\n i += 1;\n swap(A[i], A[j]);\n swap(B[i], B[j]);\n swap(C[i], C[j]);\n } \n }\n swap(A[i+1], A[r]);\n swap(B[i+1], B[r]);\n swap(C[i+1], C[r]);\n return i+1;\n}\nvoid quick_sort(vector<int>&A,vector<char>&B,vector<int>&C,int p, int r){\n int q;\n if(p < r){\n q = partition(A, B, C, p, r);\n quick_sort(A, B, C, p, q-1);\n quick_sort(A, B, C, q+1, r);\n }\n}\nint main(){\n int n;\n cin >> n;\n vector<int> A(n); \n vector<char> B(n);\n vector<int> C(n);\n for(int i = 0; i < n; ++i){\n cin >> B[i] >> A[i];\n C[i] = i;\n }\n quick_sort(A, B, C, 0, n-1);\n \n\n int result = 1;\n for(int i = 0; i < n; ++i){\n for(int j = 0;j < 3; ++j){\n if(A[i] == A[i+j] && C[i] > C[i+j]){\n result = 0;\n break;\n }\n }\n }\n if(result == 0){\n cout << \"Not stable\" << endl;\n }else{\n cout << \"Stable\" << endl;\n }\n\n for(int i = 0; i < n; ++i){\n cout << B[i] << \" \" << A[i] << endl;\n }\n \n}", "accuracy": 1, "time_ms": 90, "memory_kb": 3880, "score_of_the_acc": -0.7859, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_6_C_11063807", "code_snippet": "#include <iostream>\n#include <vector>\n#include <utility>\n\nusing namespace std;\n\nstruct card {\n char suut;\n int num;\n int order;\n};\n\nint partition(vector<card> &c, int p, int r){\n int x = c[r].num;\n int i = p-1;\n for (int j=p; j<r; j++){\n if (c[j].num <= x){\n i = i+1;\n swap(c[i],c[j]);\n }\n }\n swap(c[i+1],c[r]);\n\n return i+1;\n}\n\nvoid quickSort(vector<card> &c, int p, int r){\n if (p < r){\n int q = partition(c,p,r);\n quickSort(c,p,q-1);\n quickSort(c,q+1,r);\n }\n}\n\nint main(){\n char x0;\n int n,x1;\n vector<card> c;\n bool s = true;\n\n cin >> n;\n for (int k=0; k<n; k++){\n cin >> x0 >> x1;\n c.push_back({x0,x1,k});\n }\n\n quickSort(c,0,n-1);\n\n for(int i=1; i<n; i++){\n if(c[i].num==c[i-1].num && c[i].order<c[i-1].order){\n s = false;\n break;\n }\n }\n if (s == true){\n cout << \"Stable\" << \"\\n\";\n } else {\n cout << \"Not stable\" << \"\\n\";\n }\n\n for (int t=0; t<n; t++){\n cout << c[t].suut << \" \" << c[t].num << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 4792, "score_of_the_acc": -0.1931, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_6_C_11062890", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\nusing namespace std;\nconst int INFTY = std::numeric_limits<int>::max();\n\nstruct Card{\n char s; // suit\n int n; // number\n};\n\nint partition(vector<Card>& A, int p, int r){\n int x = A[r].n;\n int i = p-1;\n for (int j = p; j < r; j++) {\n if (A[j].n <= x) {\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r]);\n return i+1;\n}\n\nvoid quickSort(vector<Card>& A, int p, int r) {\n if (p < r) {\n int q = partition(A, p, r);\n quickSort(A, p, q-1);\n quickSort(A, q+1, r);\n }\n}\n\nvoid merge(vector<Card> &A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n\n vector<Card> L(n1 + 1);\n vector<Card> R(n2 + 1);\n\n for (int i = 0; i < n1; i++) {\n L[i] = A[left + i];\n }\n for (int j = 0; j < n2; j++) {\n R[j] = A[mid + j];\n }\n\n L[n1].n = INFTY;\n R[n2].n = INFTY;\n\n int i = 0;\n int j = 0;\n\n for (int k = left; k < right; k++) {\n if (L[i].n <= R[j].n) {\n A[k] = L[i];\n i += 1;\n } else {\n A[k] = R[j];\n j += 1;\n }\n }\n}\n\nvoid mergeSort(vector<Card> &A, int left, int right) {\n if (left+1 < right) {\n int mid = (left + right) / 2;\n\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\n\nint main() {\n int n;\n cin >> n;\n vector<Card> A(n), B(n);\n for (int i = 0; i < n; i++) {\n cin >> A[i].s;\n cin >> A[i].n;\n }\n\n B = A;\n\n quickSort(A, 0, n-1);\n mergeSort(B, 0, n);\n\n int Nst = 0; // Not stable\n\n for (int i = 0; i < n; i++) {\n if (A[i].s != B[i].s) {\n Nst = 1;\n break;\n }\n }\n\n if (Nst == 1) {\n cout << \"Not stable\" << endl;\n } else {\n cout << \"Stable\" << endl;\n }\n\n for (int i = 0; i < n; i++) {\n cout << A[i].s << \" \" << A[i].n << endl;\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5336, "score_of_the_acc": -1.015, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_6_C_11062466", "code_snippet": "using namespace std;\n#include <iostream>\n#include <climits>\n#include <vector>\n\nstruct Card {\n char suit;\n int value;\n};\n\nvoid merge(vector<Card>& A, int left, int mid, int right){\n int n1 = mid - left;\n int n2 = right - mid;\n vector<Card> L(n1 + 1);\n vector<Card> R(n2 + 1);\n for(int i = 0; i < n1; i++){\n L[i] = A[left + i];\n }\n for(int i = 0; i < n2; i++){\n R[i] = A[mid + i];\n }\n L[n1].value = INT_MAX;\n R[n2].value = INT_MAX;\n int i = 0;\n int j = 0;\n for(int k = left; k < right; k++){\n if(L[i].value <= R[j].value){\n A[k] = L[i];\n i = i + 1;\n }else{\n A[k] = R[j];\n j = j + 1;\n }\n }\n}\n\nint partition(vector<Card>& A, int p, int r){\n int x = A[r].value;\n int i = p-1;\n for(int j = p; j < r; j++){\n if(A[j].value <= x){\n i = i+1;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n return i+1;\n}\n\nvoid mergeSort(vector<Card>& A, int left, int right){\n if(left+1 < right){\n int mid = (left + right)/2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\n\nvoid quicksort(vector<Card>& A, int p, int r){\n if(p < r){\n int q = partition(A, p, r);\n quicksort(A, p, q-1);\n quicksort(A, q+1, r);\n }\n}\n\nbool isStable(const vector<Card>& mergeSorted, const vector<Card>& quickSorted,int n){\n for(int i = 0; i < n; i++){\n if(mergeSorted[i].suit != quickSorted[i].suit || mergeSorted[i].value != quickSorted[i].value){\n return false;\n }\n }\n return true;\n}\n\n\nint main(){\n int n;\n cin >> n;\n vector<Card> cards(n);\n for(int i = 0; i < n; i++){\n cin >> cards[i].suit >> cards[i].value;\n }\n vector<Card> sorted = cards;\n quicksort(sorted,0,n-1);\n mergeSort(cards,0,n);\n \n if(isStable(cards, sorted,n)){\n cout << \"Stable\" << endl;\n } else {\n cout << \"Not stable\" << endl;\n }\n\n for(int i = 0; i < n; i++){\n cout << sorted[i].suit << \" \" << sorted[i].value << endl;\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5404, "score_of_the_acc": -1.0205, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_6_C_11062464", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint pertition(vector<char>& A, vector<int>& B, vector<int>& C, int p, int r){\n int x = B[r];\n int i = p - 1;\n for (int j = p; j < r; j++){\n if (B[j] <= x){\n i++;\n swap(A[i], A[j]);\n swap(B[i], B[j]);\n swap(C[i], C[j]);\n }\n }\n swap(A[i + 1], A[r]);\n swap(B[i + 1], B[r]);\n swap(C[i + 1], C[r]);\n\n return i + 1;\n}\n\nvoid quicksort(vector<char>& A, vector<int>& B, vector<int>& C, int p, int r){\n if (p < r) {\n int q = pertition(A, B, C, p, r);\n quicksort(A, B, C, p, q - 1);\n quicksort(A, B, C, q + 1, r);\n }\n}\n\nint main(void){\n int n;\n cin >> n;\n vector<char> A_suit(n);\n vector<int> A_value(n);\n vector<int> A_order(n);\n\n for(int i = 0; i < n; i++){\n cin >> A_suit[i] >> A_value[i];\n A_order[i] = i;\n }\n\n quicksort(A_suit, A_value, A_order, 0, n - 1);\n\n bool stable = true;\n int j = 0;\n while(stable){\n j++;\n if (A_value[j - 1] == A_value[j]) {\n if (A_order[j - 1] > A_order[j]) {\n stable = false;\n }\n }\n if (j == n) {\n break;\n }\n }\n\n if (stable) {\n cout << \"Stable\" << endl;\n } else {\n cout << \"Not stable\" << endl;\n }\n\n for (int i = 0; i < n; i++) {\n cout << A_suit[i] << \" \" << A_value[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 3780, "score_of_the_acc": -0.7778, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_6_C_11062389", "code_snippet": "#include<iostream>\n#include <climits>\nusing namespace std;\n\nstruct Card{\n char al;\n int num;\n};\n\nvoid merge( struct Card A[], int left, int mid, int right){\n int n1 = mid - left;\n int n2 = right - mid;\n Card L[n1+1];\n Card R[n2+1];\n \n for(int i = 0; i < n1; i++){\n L[i] = A[left + i];\n }\n for(int i = 0; i < n2; i++){\n R[i] = A[mid + i]; \n }\n L[n1].num = INT_MAX;\n R[n2].num = INT_MAX;\n int i = 0;\n int j = 0;\n for(int k = left; k < right; k++){\n if (L[i].num <= R[j].num){\n A[k] = L[i];\n i = i + 1;\n }else{ \n A[k] = R[j];\n j = j + 1;\n }\n }\n}\n\nvoid mergeSort(struct Card A[], int left, int right){\n int mid = (left + right)/2;\n if(left+1 < right){\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n }\n merge(A, left, mid, right);\n}\n\n\nint partition(struct Card A[],int p,int r){\n int x = A[r].num;\n int i = p-1;\n for(int j = p; j < r;j++){\n if(A[j].num<=x){\n i++;\n Card b;\n b = A[j];\n A[j] = A[i];\n A[i] = b;\n }\n }\n Card c = A[i+1];\n A[i+1] = A[r];\n A[r] = c;\n return i+1;\n}\nvoid quicksort(struct Card A[],int p,int r){\n if(p<r){\n int q = partition(A,p,r);\n quicksort(A,p,q-1);\n quicksort(A,q+1,r);\n }\n}\n\nint main(){\n int n;\n cin >> n;\n Card A[n],B[n];\n for(int i = 0;i<n;i++){\n cin >> A[i].al >> A[i].num;\n B[i] = A[i];\n }\n quicksort(A,0,n-1);\n mergeSort(B,0,n);\n \n bool Stable = true;\n for(int i = 0; i < n; i++ ){\n if(A[i].al != B[i].al){\n Stable = false;\n break;\n }\n }\n if(Stable){\n cout << \"Stable\" << endl;\n }else{\n cout << \"Not stable\" << endl;\n }\n \n for(int i = 0; i<n;i++){\n cout << A[i].al << \" \" << A[i].num << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5776, "score_of_the_acc": -0.9395, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_6_C_11062388", "code_snippet": "#include <iostream>\n#include <vector>\n#include <utility>\nusing namespace std;\n\nstruct Card{\n char style;\n int num;\n int index;\n};\n\nint partition(vector<Card>&A,int p,int r){\n int x=A[r].num;\n int i=p-1;\n for(int j=p; j<r; j++){\n if(A[j].num<=x){\n i++;\n swap(A[i],A[j]);\n }\n }\n swap(A[i+1],A[r]);\n return i+1;\n}\n\nvoid quickSort(vector<Card>&A,int p,int r){\n if (p < r){\n int q = partition(A,p,r);\n quickSort(A,p,q-1);\n quickSort(A,q+1,r);\n }\n}\n\nbool isStableDirect(vector<Card>&A) {\n for (int i = 1; i < A.size(); i++) {\n if (A[i-1].num == A[i].num) {\n if (A[i-1].index > A[i].index) {\n return false;\n }\n }\n }\n return true;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<Card> card(n); \n for(int i=0;i<n;i++){\n cin >> card[i].style >> card[i].num;\n card[i].index = i;\n }\n\n quickSort(card,0,n-1);\n\n if(isStableDirect(card)){\n cout << \"Stable\" << endl;\n }\n else{\n cout << \"Not stable\" << endl;\n }\n for(int i=0;i<n;i++){\n cout << card[i].style << \" \" << card[i].num << endl;\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4044, "score_of_the_acc": -0.6881, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_6_C_11062381", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\n\n\nstruct card{\n char s;\n int v;\n};\n\nconst int INF =2000000000;\nint partition(vector<card>&A, int p, int r){\n card x = A[r];\n int i = p - 1;\n for (int j = p; j < r; j++){\n if (A[j].v <= x.v){\n i = i + 1;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1],A[r]);\n return i+1;\n}\n\nvoid quicksort(vector<card>&A,int p,int r){\n if (p < r){\n int q = partition(A,p,r);\n quicksort(A,p,q-1);\n quicksort(A,q+1,r);\n }\n\n}\n\nvoid merge(vector<card> &A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n vector<card> L(n1 + 1), R(n2 + 1);\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int i = 0; i < n2; i++) R[i] = A[mid + i];\n L[n1].v = INF;\n R[n2].v = INF; // 番兵\n\n int i = 0, j = 0;\n for (int k = left; k < right; k++) {\n if (L[i].v <= R[j].v) {\n A[k] = L[i++];\n } else {\n A[k] = R[j++];\n }\n }\n}\n\nvoid mergeSort(vector<card> &A, int left, int right) {\n if (left + 1 < right) {\n int mid = (left + right) / 2;\n mergeSort(A, left, mid);\n mergeSort(A, mid, right);\n merge(A, left, mid, right);\n }\n}\n\nint main(){\n int n;\n cin >> n;\n vector<card> A(n), B(n);\n for (int i = 0; i < n; i++){\n cin >> A[i].s >> A[i].v;\n B[i] = A[i];\n }\n quicksort(A,0,n-1);\n mergeSort(B,0,n);\n\n bool stable =true;\n for (int i =0; i < n; i++ ){\n if (A[i].v != B[i].v || A[i].s != B[i].s) {\n stable = false;\n stable = false;\n }\n }\n\n if(stable == true)cout << \"Stable\";\n else cout << \"Not stable\";\n cout << endl;\n for(int i = 0; i < n; i++){\n cout << A[i].s << \" \" << A[i].v << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5352, "score_of_the_acc": -1.0163, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_6_C_11062375", "code_snippet": "#include <iostream>\n#include <unordered_map>\n#include <utility>\n#include <vector>\nusing namespace std;\n\nint partition(vector<pair<char, int>>& A, int p, int r) {\n int x = A[r - 1].second;\n int i = p - 1;\n for (int j = p; j < r - 1; ++j) {\n if (A[j].second <= x) {\n ++i;\n swap(A[i], A[j]);\n }\n }\n swap(A[i + 1], A[r - 1]);\n return i + 1;\n}\n\nvoid quickSort(vector<pair<char, int>>& A, int p, int r) {\n if (p < r - 1) {\n int q = partition(A, p, r);\n quickSort(A, p, q);\n quickSort(A, q + 1, r);\n }\n}\n\nint main() {\n int n;\n cin >> n;\n vector<pair<char, int>> A(n);\n unordered_map<int, string> M;\n for (int i = 0; i < n; ++i) {\n cin >> A[i].first >> A[i].second;\n M[A[i].second] += A[i].first;\n }\n\n bool isStable = true;\n quickSort(A, 0, A.size());\n int num = A[0].second;\n string ord = \"\";\n for (int i = 0; i < n; ++i) {\n if (A[i].second != num) {\n if (M[num] != ord) {\n isStable = false;\n break;\n }\n num = A[i].second;\n ord = \"\";\n }\n ord += A[i].first;\n }\n\n if (isStable) {\n cout << \"Stable\" << endl;\n } else {\n cout << \"Not stable\" << endl;\n }\n\n for (int i = 0; i < n; ++i) {\n cout << A[i].first << \" \" << A[i].second << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5752, "score_of_the_acc": -0.9376, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_6_C_11062278", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Card {\n char suit;\n int value;\n};\n\nint partition(vector<Card> &A, int p, int r){\n int x = A[r].value;\n int i = p-1;\n \n for(int j=p;j<r;++j){\n if(A[j].value<=x){\n i = i+1;\n swap(A[i],A[j]);\n }\n }\n swap(A[i+1],A[r]);\n \n return i+1;\n}\n\nvoid quickSort(vector<Card> &A, int p, int r){\n if(p<r){\n int q = partition(A,p,r); \n quickSort(A, p, q-1);\n quickSort(A, q+1, r);\n }\n}\n\nbool isStable(const vector<Card> &quicked, const vector<Card> &stable){\n int n = quicked.size();\n for(int i = 0;i<n;++i){\n if(quicked[i].suit != stable[i].suit){\n return false;\n }\n }\n return true;\n}\n\nint main(){\n int n;\n cin >> n;\n \n vector<Card> A(n);\n vector<Card> B(n);\n \n for(int i=0;i<n;++i){\n cin >> A[i].suit >> A[i].value;\n B[i] = A[i];\n }\n \n stable_sort(B.begin(), B.end(), [](const Card &a, const Card &b) {\n return a.value < b.value;\n });\n\n quickSort(A, 0, n-1);\n \n if(isStable(A,B)){\n cout << \"Stable\" << endl;\n }else{\n cout << \"Not stable\" << endl;\n }\n\n\n for(int i=0;i<n;i++){\n cout << A[i].suit << \" \" << A[i].value << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 4884, "score_of_the_acc": -0.9784, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_6_C_11062105", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\n\nint partition(vector<int> &A,vector<char>& v,int p,int r){\n int i = p-1;\n for(int j=p;j<r;j++){\n if(A[j]<=A[r]){\n i++;\n swap(A[i],A[j]);\n swap(v[i],v[j]);\n }\n }\n swap(A[i+1],A[r]);\n swap(v[i+1],v[r]);\n return i+1;\n}\nvoid quicksort(vector<int> &A,vector<char> &v,int p,int r){\n if(p<r){\n int q = partition(A,v,p,r);\n quicksort(A,v,p,q-1);\n quicksort(A,v,q+1,r);\n }\n}\nbool isStable(vector<int> &A,vector<int> &A1,vector<char> &v,vector<char> &v1){\n int N=A.size();\n for(int i=0;i<N;i++){\n for(int j=0;j<A1.size();j++){\n if(A[i]==A1[j]){\n if(v[i]==v1[j]){\n v1.erase(v1.begin()+j);\n A1.erase(A1.begin()+j);\n break;\n }else{\n return false;\n }\n }\n }\n }\n return true;\n }\n\nint main(){\n int N,tmp;\n char tmpc;\n vector<int> A;\n vector<int> A1;\n vector<char> v;\n vector<char> v1;\n cin>>N;\n for (int i=0;i<N;i++){\n cin>>tmpc;\n v.push_back(tmpc);\n v1.push_back(tmpc);\n cin>>tmp;\n A.push_back(tmp);\n A1.push_back(tmp);\n \n }\n quicksort(A,v,0,N-1);\n\n\n if(isStable(A,A1,v,v1)){\n cout<<\"Stable\"<<endl;\n }else{\n cout<<\"Not stable\"<<endl;\n }\n \n for(int k=0;k<N;k++){\n cout<< v[k]<<\" \"<<A[k]<<endl;\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4096, "score_of_the_acc": -0.6923, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_6_C_11061973", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint partition(vector<int>& A, vector<char>& B,vector<int>& C, int p, int r){\n int x = A[r];\n int i = p - 1;\n for(int j = p; j <= r - 1; j++){\n if(A[j] <= x){\n i = i + 1;\n int q1 = A[j];\n char o1 = B[j];\n int s1 = C[j];\n A[j] = A[i];\n A[i] = q1;\n B[j] = B[i];\n B[i] = o1;\n C[j] = C[i];\n C[i] = s1;\n }\n }\n int q2 = A[i + 1];\n char o2 = B[i + 1];\n int s2 = C[i + 1];\n A[i + 1] = A[r];\n A[r] = q2;\n B[i + 1] = B[r];\n B[r] = o2;\n C[i + 1] = C[r];\n C[r] = s2;\n\n return i + 1;\n}\n\nvoid quickSort(vector<int>& A,vector<char>& B,vector<int>& C,int p, int r){\n if(p < r){\n int q = partition(A, B, C, p, r);\n quickSort(A, B, C, p, q - 1);\n quickSort(A, B, C, q + 1, r);\n }\n}\n\n\nint main(){\n int n;\n cin >> n;\n vector<int> A(n);\n vector<char> B(n);\n vector<int> memo(n);\n for(int i = 0; i < n; i++){\n cin >> B[i] >> A[i];\n memo[i] = i;\n }\n\n quickSort(A,B, memo, 0, n - 1);\n\n int Stability = 0;\n\n for(int i = 0; i < n - 1; i++){\n if((A[i] == A[i + 1]) && (memo[i] > memo[i + 1])){\n Stability = Stability - 1;\n }\n }\n\n if(Stability >= 0){\n cout << \"Stable\" << endl;\n }else{\n cout << \"Not stable\" << endl;\n }\n\n for(int i = 0; i < n; i++){\n cout << B[i] << \" \" << A[i] << endl;\n }\n\n return 0;\n\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 3820, "score_of_the_acc": -0.6699, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_6_C_11061968", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n//#include \"atcoder/dsu.hpp\"\nstruct cww{cww(){ios::sync_with_stdio(false);cin.tie(0);}}star;\nusing ll= long long;\nusing ull=unsigned long long;\nusing ldo =long double;\ntemplate<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }\ntemplate<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }\n#define all(...) std::begin(__VA_ARGS__), std::end(__VA_ARGS__)\n#define rall(...) std::rbegin(__VA_ARGS__), std::rend(__VA_ARGS__)\n#define OVERLOAD_sum(_1, _2, _3,_4, name, ...) name\ntemplate<typename T>ll sum1(T &a){ll ans = 0;for(ll i=0;i<a.size();i++)ans+=a[i];return ans;}\ntemplate<typename T>ll sum2(T &a,ll start){ll ans = 0;for(ll i=start;i<a.size();i++)ans+=a[i];return ans;}\ntemplate<typename T>ll sum3(T &a,ll start,ll en){ll ans = 0;for(ll i=start;i<en;i++)ans+=a[i];return ans;}\ntemplate<typename T>ll sum4(T &a,ll start,ll en,ll tolerance){ll ans = 0;for(ll i=start;i<en;i+=tolerance)ans+=a[i];return ans;}\n#define sum(...) OVERLOAD_sum(__VA_ARGS__,sum4, sum3, sum2, sum1)(__VA_ARGS__)\n#define OVERLOAD_rep(_1, _2, _3,_4, name, ...) name\n#define rep(i,n,k) for(ll i = k; i < (ll)(n); i++)\n\nint partition(vector<pair<char,int>> &A, int p, int r){\n int x = A[r].second;\n int i = p-1;\n for(int j = p; j<r; j++){\n if(A[j].second <= x){\n i = i+1;\n swap(A[i],A[j]);\n }\n }\n swap(A[i+1],A[r]);\n return i+1;\n }\n \nvoid quicksort(vector<pair<char,int>> &A,int p,int r){\n if (p < r) {\n int q=partition(A,p,r);\n quicksort(A,p,q-1);\n quicksort(A,q+1,r);\n }\n}\n \nint main(){\n int n;\n cin>>n;\n vector<pair<char,int>>A(n);\n map<int,vector<char>> al;\n for(int i=0;i<n;i++){\n char a;\n int b;\n cin>>a>>b;\n al[b].push_back(a);\n A[i]=make_pair(a,b);\n }\n quicksort(A,0,n-1);\n map<int,vector<char>>al_a;\n for(int i=0;i<n;i++)al_a[A[i].second].push_back(A[i].first);\n bool ch=true;\n for(auto it = al.begin(); it != al.end(); ++it) {\n int key = it->first;\n vector<char> old_vec = it->second;\n vector<char> new_vec = al_a[key];\n for(int j = 0;j<al_a[key].size();j++){\n if(old_vec[j] != new_vec[j]){\n ch = false;\n break;\n }\n }\n if(!ch)break;\n }\n if(ch)cout<<\"Stable\"<<endl;\n else cout<<\"Not stable\"<<endl;\n \n for(int i=0;i<n;i++)cout<<A[i].first<<\" \"<<A[i].second<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 9288, "score_of_the_acc": -1.3352, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_6_C_11061929", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <utility>\n#include <tuple>\nusing namespace std;\n\nint partition(vector<pair<string, int>>& A, int p, int r) {\n int x = A[r].second;\n int i = p-1;\n for (int j = p; j < r; j++) {\n if (A[j].second <= x) {\n i++;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n \n return i+1;\n}\n\nvoid quicksort(vector<pair<string, int>>& A, int p, int r) {\n if (p < r) {\n int q = partition(A, p, r);\n quicksort(A, p, q-1);\n quicksort(A, q+1, r);\n }\n}\n\nbool comparePairs(const pair<string, int>& a, const pair<string, int>& b) {\n return a.second < b.second;\n}\n\nint main() {\n int n;\n cin >> n;\n vector<pair<string, int>> card_quick;\n\n for (int i = 0; i < n; i++) {\n string a;\n int num;\n cin >> a >> num;\n card_quick.push_back(make_pair(a, num));\n }\n\n vector<pair<string, int>> card_stable = card_quick;\n quicksort(card_quick, 0, n-1);\n stable_sort(card_stable.begin(), card_stable.end(), comparePairs);\n \n bool is_stable = true;\n for (int i = 0; i < n; i++) {\n if (card_quick[i] != card_stable[i]) {\n is_stable = false;\n break;\n }\n }\n\n if (is_stable) {\n cout << \"Stable\" << endl;\n } else {\n cout << \"Not stable\" << endl;\n }\n\n for (int i = 0; i < n-1; i++) {\n string a;\n int num;\n tie(a, num) = card_quick.at(i);\n cout << card_quick[i].first << \" \" << card_quick[i].second << endl;\n }\n\n cout << card_quick[n-1].first << \" \" << card_quick[n-1].second << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 16120, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_6_C_11061890", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Card{\n char value;\n int num;\n};\n\nint partition(vector<Card>& A, int p, int r){\n int x =A[r].num;\n int i = p-1;\n \n for (int j =p; j<= r-1; ++j){\n if (A[j].num <= x){\n ++i;\n swap(A[i], A[j]);\n }\n }\n swap(A[i+1], A[r]);\n return i+1;\n}\n\nvoid quickSort(vector<Card>& A, int p, int r){\n if(p<r){\n int q = partition(A, p, r);\n quickSort(A, p, q-1);\n quickSort(A, q+1, r);\n }\n}\n\nbool isStable(vector<Card>& Sort, vector<Card>& Stable){\n int a = Sort.size();\n for (int i= 0; i<a ; ++i){\n if (Sort[i].value != Stable[i].value){\n return false;\n }\n }\n return true;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<Card> S(n), S_c(n);\n \n for (int i = 0; i<n; i++){\n cin >> S[i].value >> S[i].num;\n S_c[i] = S[i];\n }\n \n quickSort(S, 0, n-1);\n \n stable_sort(S_c.begin(), S_c.end(), [](const Card& a, const Card& b) {\n return a.num < b.num;\n });\n \n if (isStable(S, S_c)) {\n cout << \"Stable\" << endl;\n } else {\n cout << \"Not stable\" << endl;\n }\n \n for (int i = 0; i<n ; ++i){\n cout << S[i].value << \" \" << S[i].num << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 4784, "score_of_the_acc": -0.8591, "final_rank": 10 } ]
aoj_ALDS1_5_D_cpp
The Number of Inversions For a given sequence $A = \{a_0, a_1, ... a_{n-1}\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program: bubbleSort(A) cnt = 0 // the number of inversions for i = 0 to A.length-1 for j = A.length-1 downto i+1 if A[j] < A[j-1] swap(A[j], A[j-1]) cnt++ return cnt For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded. Input In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters. output Print the number of inversions in a line. Constraints $ 1 \leq n \leq 200,000$ $ 0 \leq a_i \leq 10^9$ $a_i$ are all different Sample Input 1 5 3 5 2 1 4 Sample Output 1 6 Sample Input 2 3 3 1 2 Sample Output 2 2
[ { "submission_id": "aoj_ALDS1_5_D_11047972", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n\n//最小全域木\nll Kruskal(const WeightedGraph &G) {\n return 0;\n}\n\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n, sz;\n vector<long long> node;\n\n SegTree(vector<long long> a) {\n sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = max(node[2*i+1], node[2*i+2]);\n }\n //[a,b)における最大値\n long long getmax(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return -INF;\n if(a <= l and r <= b) return node[k];\n\n long long vl = getmax(a, b, 2*k+1, l, (l+r)/2);\n long long vr = getmax(a, b, 2*k+2, (l+r)/2, r);\n return max(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = max(node[2*i+1], node[2*i+2]);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int getminindex(int a, int b, long long x, int l = 0, int r = -1) {\n return 0;\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n lazy.resize(2*n-1, 0);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = node[2*i+1] + node[2*i+2];\n }\n\n void eval(int k, int l, int r) {\n if(lazy[k] != 0) {\n node[k] += lazy[k];\n\n if(r - l > 1) {\n lazy[2*k+1] += lazy[k]/2;\n lazy[2*k+2] += lazy[k]/2;\n }\n\n lazy[k] = 0;\n }\n }\n //区間[a,b)に値xを加算\n void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n \n eval(k, l, r);\n\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] += (r-l)*x;\n eval(k, l, r);\n }else {\n add(a, b, x, 2*k+1, l, (l+r)/2);\n add(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = node[2*k+1] + node[2*k+2];\n }\n }\n //区間[a,b)の和を取得\n ll getsum(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return 0;\n\n eval(k, l, r);\n if(a <= l and r <= b) return node[k];\n ll vl = getsum(a, b, 2*k+1, l, (l+r)/2);\n ll vr = getsum(a, b, 2*k+2, (l+r)/2, r);\n return vl + vr;\n }\n};\n//平方分割\nstruct Backet {\n vector<ll> array;\n vector<ll> backet;\n int N, M;\n\n Backet(vector<ll> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n //a_i + ... + a_j\n void add(int i, ll x) {\n array[i] += x;\n backet[i/M] += x;\n }\n ll getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n ll s = 0;\n if(l > r) {\n REP(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n REP(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N; cin >> N;\n vi A(N);\n rep(i,0,N) {\n cin >> A[i];\n }\n A = compress(A);\n ll ans = 0;\n BIT tree(N);\n rep(i,0,N) {\n ans += i - tree.sum(A[i]);\n tree.add(A[i], 1);\n }\n cout << ans << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 6292, "score_of_the_acc": -0.4263, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_5_D_10995999", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\n// ALDS1_5_Bよりマージソート\nll merge(vector<ll> &A, ll left, ll mid, ll right) {\n ll n1 = mid - left, n2 = right - mid;\n vector<ll> L(n1+1);\n vector<ll> R(n2+1);\n for(int i = 0; i < n1; i++) {\n L[i] = A[left + i];\n }\n for(int i = 0; i < n2; i++) {\n R[i] = A[mid + i];\n }\n L[n1] = INF;\n R[n2] = INF;\n ll i = 0, j = 0, cnt=0;\n for(int k = left; k < right; k++) {\n if (L[i] <= R[j]) {\n A[k] = L[i];\n i++;\n }\n else {\n A[k] = R[j];\n j++;\n cnt += n1 - i;\n }\n }\n return cnt;\n}\nll mergesort(vector<ll> &A, ll left, ll right) {\n ll v1=0, v2=0, v3=0;\n if (left + 1 < right) {\n ll mid = (left + right) / 2;\n v1 = mergesort(A, left, mid);\n v2 = mergesort(A, mid, right);\n v3 = merge(A, left, mid, right);\n }\n return v1 + v2 + v3;\n}\n\n// main\nvoid solve() {\n ll n;\n cin >> n;\n vector<ll> A(n);\n nfor(i, 0, n) {\n cin >> A[i];\n }\n ll ans = mergesort(A, 0, n);\n cout << ans << endl;\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 6636, "score_of_the_acc": -0.3276, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_5_D_10945957", "code_snippet": "#include <iostream>\nusing namespace std;\n\n#define MAX 200000\n#define SENTINEL 2000000000\ntypedef long long llong;\n\nint L[MAX / 2 + 2], R[MAX / 2 + 2];\n\nllong merge(int A[], int n, int left, int mid, int right) {\n int i, j, k;\n llong cnt = 0;\n int n1 = mid - left;\n int n2 = right - mid;\n for ( i = 0; i < n1; i++ ) L[i] = A[left + i];\n for ( i = 0; i < n2; i++ ) R[i] = A[mid + i];\n L[n1] = R[n2] = SENTINEL;\n i = j = 0;\n for ( k = left; k < right; k++ ) {\n if ( L[i] <= R[j] ) {\n A[k] = L[i++];\n } else {\n A[k] = R[j++];\n cnt += n1 - i;\n }\n }\n return cnt;\n}\n\nllong mergeSort(int A[], int n, int left, int right) {\n int mid;\n llong v1, v2, v3;\n if ( left + 1 < right ) {\n mid = (left + right) / 2;\n v1 = mergeSort(A, n, left, mid);\n v2 = mergeSort(A, n, mid, right);\n v3 = merge(A, n, left, mid, right);\n return v1 + v2 + v3;\n } else return 0;\n}\n\nint main() {\n int A[MAX], n, i;\n\n cin >> n;\n for ( i = 0; i < n; i++ ) {\n cin >> A[i];\n }\n\n llong ans = mergeSort(A, n, 0, n);\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4972, "score_of_the_acc": -0.2675, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_5_D_10928536", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nint main(){\n ll n; cin>>n;\n vector<ll> a(n);\n for(ll& a1:a) cin>>a1;\n\n vector<ll> sorted=a;\n sort(sorted.begin(),sorted.end());\n for(ll& a1:a) a1=lower_bound(sorted.begin(),sorted.end(),a1)-sorted.begin()+1;\n\n vector<ll> A(n+1,0);\n ll ans=0;\n for(int i=0;i<n;i++){\n ll idx=a[i];\n while(idx<=n){\n A[idx]+=1;\n idx+=idx&-idx;\n }\n\n ll t=a[i]-1;\n ll sum=0;\n while(t>0){\n sum+=A[t];\n t-=t&-t;\n }\n ans+=a[i]-sum-1;\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 7816, "score_of_the_acc": -0.4813, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_5_D_10828469", "code_snippet": "#include <cstdio>\n#include <cstdint>\n#include <cinttypes>\n\n#define N (300000)\n\nstatic int v[2][N];\n\nstatic constexpr bool isR(int lc, int rc, int lv, int rv){\n if(lc <= 0) return true;\n if(rc <= 0) return false;\n if(lv <= rv) return false;\n return true;\n}\n\nint main(){\n int n;\n scanf(\"%d\", &n);\n for(int i = 0; i < n; i++) scanf(\"%d\", &v[0][i]);\n int w = 1, w2 = w << 1, k = 0;\n int lc, rc;\n int *out;\n uint64_t scnt = 0;\n while(w < n){\n int *lp = v[k], *rp = v[k] + w;\n k = (k == 1) ? 0 : 1;\n out = v[k];\n int i = w2;\n while(i < n){\n lc = w;\n rc = w;\n for(int j = w2; j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n lp += w;\n rp += w;\n i += w2;\n }\n if(i - w > n){\n lc = w2 - (i - n); \n rc = 0;\n }\n else {\n lc = w;\n rc = w - (i - n);\n }\n for(int j = n - (i - w2); j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n w <<= 1;\n w2 <<= 1;\n }\n printf(\"%\" PRIu64 \"\\n\", scnt);\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4488, "score_of_the_acc": -0.0833, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_5_D_10828463", "code_snippet": "#include <cstdio>\n#include <cstdint>\n#include <cinttypes>\n\n#define N (300000)\n\nstatic int v[2][N];\n\nstatic constexpr bool isR(int lc, int rc, int lv, int rv){\n if(lc <= 0) return true;\n if(rc <= 0) return false;\n if(lv <= rv) return false;\n return true;\n}\n\nint main(){\n int n;\n scanf(\"%d\", &n);\n for(int i = 0; i < n; i++) scanf(\"%d\", &v[0][i]);\n int w = 1, w2 = w << 1, k = 0;\n int lc, rc;\n int *out;\n uint64_t scnt = 0;\n while(w < n){\n int *lp = v[k], *rp = v[k] + w;\n k = (k == 1) ? 0 : 1;\n out = v[k];\n int i = w2;\n while(i < n){\n lc = w;\n rc = w;\n for(int j = w2; j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n lp += w;\n rp += w;\n i += w2;\n }\n if(i - w > n){\n lc = w2 - (i - n); \n rc = 0;\n }\n else {\n lc = w;\n rc = w - (i - n);\n }\n //printf(\"A: %d, %d\\n\", i - w2, n - (i - w2));\n for(int j = n - (i - w2); j > 0; j--){\n //printf(\"A: %d, %d\\n\", lc, rc);\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n w <<= 1;\n w2 <<= 1;\n //printf(\"%d: \", w);\n //for(int i = 0; i < n; i++) printf(\"%d \", v[k][i]);\n //printf(\"\\n\");\n }\n printf(\"%\" PRIu64 \"\\n\", scnt);\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4468, "score_of_the_acc": -0.0826, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_5_D_10828450", "code_snippet": "#include <cstdio>\n#include <cstdint>\n#include <cinttypes>\n\n#define N (200001)\n\nstatic int v[2][N];\n\nstatic constexpr bool isR(int lc, int rc, int lv, int rv){\n if(lc <= 0) return true;\n if(rc <= 0) return false;\n if(lv <= rv) return false;\n return true;\n}\n\nint main(){\n int n;\n scanf(\"%d\", &n);\n uint64_t scnt = 0;\n for(int i = 0; i < n; i++) scanf(\"%d\", &v[0][i]);\n int w = 1, w2 = w << 1, k = 0;\n int lc, rc;\n int *out;\n while(w < n){\n int *lp = v[k], *rp = v[k] + w;\n k = (k == 1) ? 0 : 1;\n out = v[k];\n int i = w2;\n while(i < n){\n lc = w;\n rc = w;\n for(int j = w2; j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n lp += w;\n rp += w;\n i += w2;\n }\n if(i - w > n){\n lc = w2 - (i - n); \n rc = 0;\n }\n else {\n lc = w;\n rc = w - (i - n);\n }\n for(int j = n - (i - w2); j > 0; j--){\n //printf(\"A: %d, %d\\n\", lc, rc);\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n w <<= 1;\n w2 <<= 1;\n //printf(\"%d: \", w);\n //for(int i = 0; i < n; i++) printf(\"%d \", v[k][i]);\n //printf(\"\\n\");\n }\n printf(\"%\" PRIu64 \"\\n\", scnt);\n}", "accuracy": 0.8333333333333334, "time_ms": 10, "memory_kb": 3764, "score_of_the_acc": -0.0016, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_5_D_10828448", "code_snippet": "#include <cstdio>\n#include <cstdint>\n#include <cinttypes>\n\n#define N (210000)\n\nstatic int v[2][N];\n\nstatic constexpr bool isR(int lc, int rc, int lv, int rv){\n if(lc <= 0) return true;\n if(rc <= 0) return false;\n if(lv <= rv) return false;\n return true;\n}\n\nint main(){\n int n;\n scanf(\"%d\", &n);\n uint64_t scnt = 0;\n for(int i = 0; i < n; i++) scanf(\"%d\", &v[0][i]);\n int w = 1, w2 = w << 1, k = 0;\n int lc, rc;\n int *out;\n while(w < n){\n int *lp = v[k], *rp = v[k] + w;\n k = (k == 1) ? 0 : 1;\n out = v[k];\n int i = w2;\n while(i < n){\n lc = w;\n rc = w;\n for(int j = w2; j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n lp += w;\n rp += w;\n i += w2;\n }\n if(i - w > n){\n lc = w2 - (i - n); \n rc = 0;\n }\n else {\n lc = w;\n rc = w - (i - n);\n }\n for(int j = n - (i - w2); j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n w <<= 1;\n w2 <<= 1;\n //printf(\"%d: \", w);\n //for(int i = 0; i < n; i++) printf(\"%d \", v[k][i]);\n //printf(\"\\n\");\n }\n //printf(\"%\" PRIu64 \"\\n\", rcnt);\n printf(\"%\" PRIu64 \"\\n\", scnt);\n}", "accuracy": 0.8333333333333334, "time_ms": 10, "memory_kb": 3760, "score_of_the_acc": -0.0014, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_5_D_10828446", "code_snippet": "#include <cstdio>\n#include <cstdint>\n#include <cinttypes>\n\n#define N (200000)\n\nstatic int v[2][N];\nstatic uint64_t rcnt = 0;\n\nstatic constexpr bool isR(int lc, int rc, int lv, int rv){\n if(lc <= 0) return true;\n if(rc <= 0) return false;\n if(lv <= rv) return false;\n return true;\n}\n\nint main(){\n int n;\n scanf(\"%d\", &n);\n uint64_t scnt = 0;\n for(int i = 0; i < n; i++) scanf(\"%d\", &v[0][i]);\n int w = 1, w2 = w << 1, k = 0;\n int lc, rc;\n int *out;\n while(w < n){\n int *lp = v[k], *rp = v[k] + w;\n k = (k == 1) ? 0 : 1;\n out = v[k];\n int i = w2;\n while(i < n){\n lc = w;\n rc = w;\n for(int j = w2; j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n lp += w;\n rp += w;\n i += w2;\n }\n if(i - w > n){\n lc = w2 - (i - n); \n rc = 0;\n }\n else {\n lc = w;\n rc = w - (i - n);\n }\n for(int j = n - (i - w2); j > 0; j--){\n if(isR(lc, rc, *lp, *rp)){\n *out = *rp;\n rp++;\n rc--;\n scnt += lc;\n }\n else {\n *out = *lp;\n lp++;\n lc--;\n }\n out++;\n }\n w <<= 1;\n w2 <<= 1;\n //printf(\"%d: \", w);\n //for(int i = 0; i < n; i++) printf(\"%d \", v[k][i]);\n //printf(\"\\n\");\n }\n //printf(\"%\" PRIu64 \"\\n\", rcnt);\n printf(\"%\" PRIu64 \"\\n\", scnt);\n}", "accuracy": 0.8333333333333334, "time_ms": 10, "memory_kb": 3720, "score_of_the_acc": 0, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_5_D_10809566", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std ;\n#define pb push_back\n#define ll long long \n#define ld long double\n#define pii pair<int,int>\n#define N 200100\n\n\nll mid(ll l , ll r){\n return (l+r)/2;\n}\n\nll t[4*N] , arr[N];\n\n\n\n\n\nvoid build(ll ind , ll l , ll r){\n if(l==r){\n t[ind] = 0;\n return;\n }\n ll m = mid(l,r);\n build(2*ind,l,m);\n build(2*ind+1,m+1,r);\n t[ind] = 0;\n // cout<<\"ind: \"<<ind<<\" l: \"<<l<<\" r: \"<<r<<\" ans: \"<<t[ind].ans<<endl;\n}\n\nvoid update(ll ind , ll l , ll r , ll pos){\n if(pos<l or pos>r)return;\n if(l==r){\n t[ind]++;\n return;\n }\n ll m = mid(l,r);\n if(m>=pos)update(2*ind,l,m,pos);\n else update(2*ind+1,m+1,r,pos);\n\n t[ind] = t[2*ind] + t[2*ind+1];\n}\n\n\nll sum(ll ind, ll l , ll r, ll ql , ll qr){\n if(r<ql or l>qr)return 0;\n if(l>=ql and r<=qr)return t[ind];\n ll m = mid(l,r);\n return sum(2*ind,l,m,ql,qr) + sum(2*ind+1,m+1,r,ql,qr);\n}\n\nvoid solve(){\n\n ll n;\n cin>>n;\n set<ll>s;\n map<ll,ll>mp;\n for(ll i=1;i<=n;i++){\n cin>>arr[i];\n s.insert(arr[i]);\n }\n ll ind = 0;\n for(auto x: s){\n mp[x] = ind+1;\n ind++;\n }\n\n for(ll i=1;i<=n;i++){\n arr[i] = mp[arr[i]];\n // cout<<arr[i]<<\" \";\n }\n // cout<<endl;\n // cout<<ind<<endl;\n\n ll ans = 0;\n build(1,1,ind);\n\n for(ll i=1;i<=n;i++){\n ll val = arr[i];\n ans += (i-1) - sum(1,1,ind,1,val);\n update(1,1,ind,val);\n }\n\n cout<<ans<<endl;\n\n\n\n\n}\n\n\n\nint main(){\n\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int t =1;\n // cin>>t;\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 31400, "score_of_the_acc": -2, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_5_D_10807961", "code_snippet": "#include <cstdio>\n\n#define N (1<<(30-5))\n\nint v[N], w[N];\n\nint main(){\n int n, m;\n scanf(\"%d\", &n);\n int cnt = 0;\n int a, b, max_a = 0;\n for(int i = 0; i < n; i++){\n scanf(\"%d\", &m);\n a = m >> 5;\n b = m & 31;\n v[a] |= (1 << b);\n w[a] += 1;\n if(max_a < a) max_a = a;\n for(int j = max_a; j > a; j--) cnt += w[j];\n for(int j = 31; j > b; j--) cnt += (v[a] & (1 << j)) ? 1 : 0;\n }\n printf(\"%d\\n\",cnt);\n}", "accuracy": 0.6, "time_ms": 50, "memory_kb": 5032, "score_of_the_acc": -0.2696, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_5_D_10801278", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong long mergeAndCount(vector<long long>& arr, int left, int mid, int right) {\n vector<long long> leftArr(arr.begin() + left, arr.begin() + mid + 1);\n vector<long long> rightArr(arr.begin() + mid + 1, arr.begin() + right + 1);\n\n int i = 0, j = 0, k = left;\n long long swaps = 0;\n\n while (i < leftArr.size() && j < rightArr.size()) {\n if (leftArr[i] <= rightArr[j]) {\n arr[k++] = leftArr[i++];\n } else {\n arr[k++] = rightArr[j++];\n swaps += (leftArr.size() - i); // all remaining left elements are greater\n }\n }\n\n while (i < leftArr.size()) arr[k++] = leftArr[i++];\n while (j < rightArr.size()) arr[k++] = rightArr[j++];\n\n return swaps;\n}\n\nlong long mergeSortAndCount(vector<long long>& arr, int left, int right) {\n if (left >= right) return 0;\n\n int mid = left + (right - left) / 2;\n long long count = 0;\n\n count += mergeSortAndCount(arr, left, mid);\n count += mergeSortAndCount(arr, mid + 1, right);\n count += mergeAndCount(arr, left, mid, right);\n\n return count;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n vector<long long> arr(n);\n for (int i = 0; i < n; i++) cin >> arr[i];\n\n cout << mergeSortAndCount(arr, 0, n - 1) << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 6156, "score_of_the_acc": -0.1991, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_5_D_10747471", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\n\n#define MAX 200000\n#define SENTINEL 2000000000\nusing ll = long long;\n\n\nint L[MAX / 2 + 2], R[MAX / 2 + 2];\n\nll merge(int A[], int n, int left, int mid, int right) {\n ll cnt = 0;\n int n1 = mid - left;\n int n2 = right - mid;\n\n rep(i,n1) L[i] = A[left+i];\n rep(i,n2) R[i] = A[mid+i];\n L[n1] = R[n2] = SENTINEL;\n int i = 0, j = 0;\n for (int k=left; k<right; k++) {\n if (L[i] <= R[j]) {\n A[k] = L[i++];\n } else {\n // 配列LとRでswapが起こったらcntをn1-iだけ増やす\n A[k] = R[j++];\n cnt += n1 - i;\n }\n }\n return cnt;\n}\n\nll mergeSort(int A[], int n, int left, int right) {\n int mid;\n ll v1, v2, v3;\n if (left+1 < right) {\n mid = (left + right) / 2;\n v1 = mergeSort(A, n, left, mid);\n v2 = mergeSort(A, n, mid, right);\n v3 = merge(A, n, left, mid, right);\n return v1 + v2 + v3;\n } else return 0;\n}\n\nint main() {\n int A[MAX], n, i;\n\n cin >> n;\n for (int i=0; i<n; i++) {\n cin >> A[i];\n }\n\n ll ans = mergeSort(A,n,0,n);\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4924, "score_of_the_acc": -0.2657, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_5_D_10737286", "code_snippet": "#include <stdio.h>\n\n#define MAX 200000\n#define INFTY 2000000000\n\nint L[MAX/2 + 2], R[MAX/2 + 2];\n\nlong long merge(int A[], int left, int mid, int right) {\n long long cnt = 0;\n int n1 = mid - left;\n int n2 = right - mid;\n\n for (int i = 0; i < n1; i++) L[i] = A[left + i];\n for (int i = 0; i < n2; i++) R[i] = A[mid + i];\n L[n1] = INFTY;\n R[n2] = INFTY;\n\n int i = 0, j = 0;\n for (int k = left; k < right; k++) {\n if (L[i] <= R[j]) {\n A[k] = L[i++];\n } else {\n A[k] = R[j++];\n // L[i] > R[j] の場合、L[i]以降の左側配列の要素は全てR[j]より大きい\n // よって、その個数(n1 - i)を反転数に加算する\n cnt += (n1 - i);\n }\n }\n return cnt;\n}\n\nlong long mergeSort(int A[], int left, int right) {\n // 要素が1つ以下なら反転数は0\n if (left + 1 >= right) {\n return 0;\n }\n \n long long v1, v2, v3;\n int mid = (left + right) / 2;\n \n // 再帰的に左右の部分配列の反転数を計算\n v1 = mergeSort(A, left, mid);\n v2 = mergeSort(A, mid, right);\n \n // マージする際の、左右の部分配列間に存在する反転数を計算\n v3 = merge(A, left, mid, right);\n \n return v1 + v2 + v3;\n}\n\nint main() {\n int n;\n int A[MAX];\n\n scanf(\"%d\", &n);\n for (int i = 0; i < n; i++) {\n scanf(\"%d\", &A[i]);\n }\n \n long long ans = mergeSort(A, 0, n);\n \n printf(\"%lld\\n\", ans);\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4480, "score_of_the_acc": -0.083, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_5_D_10737270", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\n// 反転数を数えるためのマージ処理\nlong long mergeAndCount(vector<int>& A, int left, int mid, int right) {\n int n1 = mid - left;\n int n2 = right - mid;\n vector<int> L(n1), R(n2);\n for (int i = 0; i < n1; ++i) L[i] = A[left + i];\n for (int i = 0; i < n2; ++i) R[i] = A[mid + i];\n\n long long inv = 0;\n int i = 0, j = 0;\n for (int k = left; k < right; ++k) {\n if (i < n1 && (j >= n2 || L[i] <= R[j])) {\n A[k] = L[i++];\n } else {\n A[k] = R[j++];\n inv += n1 - i; // L[i] > R[j] のとき反転が発生\n }\n }\n return inv;\n}\n\n// 再帰的に反転数を数える\nlong long countInversions(vector<int>& A, int left, int right) {\n if (right - left <= 1) return 0;\n int mid = (left + right) / 2;\n long long inv = 0;\n inv += countInversions(A, left, mid);\n inv += countInversions(A, mid, right);\n inv += mergeAndCount(A, left, mid, right);\n return inv;\n}\n\nint main() {\n int n;\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; ++i) cin >> A[i];\n\n long long result = countInversions(A, 0, n);\n cout << result << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4652, "score_of_the_acc": -0.3114, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_5_D_10737242", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\ntypedef long long ll;\n\nll mergeCount(vector<int>& A, int left, int right) {\n if (right - left <= 1) return 0;\n\n int mid = (left + right) / 2;\n ll count = 0;\n\n count += mergeCount(A, left, mid);\n count += mergeCount(A, mid, right);\n\n vector<int> sorted;\n int i = left, j = mid;\n\n while (i < mid && j < right) {\n if (A[i] <= A[j]) {\n sorted.push_back(A[i++]);\n } else {\n sorted.push_back(A[j++]);\n count += mid - i; // i番目以降すべてに対して反転\n }\n }\n\n while (i < mid) sorted.push_back(A[i++]);\n while (j < right) sorted.push_back(A[j++]);\n\n for (int k = 0; k < sorted.size(); ++k) {\n A[left + k] = sorted[k];\n }\n\n return count;\n}\n\n\n\nint main() {\n int n;\n cin >> n;\n vector<int> A(n);\n for (int i = 0; i < n; ++i) cin >> A[i];\n\n cout << mergeCount(A, 0, n) << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5444, "score_of_the_acc": -0.3956, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_5_D_10720959", "code_snippet": "// #ifndef ONLINE_JUDGE\n// #define _GLIBCXX_DEBUG//[]で配列外参照をするとエラーにしてくれる。上下のやつがないとTLEになるので注意 ABC311Eのサンプル4みたいなデバック中のTLEは防げないので注意\n// #endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n// #include <atcoder/all>\n// using namespace atcoder;\n\n\ntemplate<typename T> using vc = vector<T>;//prioriy_queueに必要なのでここにこれ書いてます\ntemplate<typename T> using vv = vc<vc<T>>;\n\n//-------------1.型系---------------\nusing ll = long long;\nll INF = 2e18;\n\n// #include <boost/multiprecision/cpp_int.hpp>//インストール的なのをしてないとできないので注意\n// namespace multip = boost::multiprecision;\n// //using lll = multip::cpp_int;//無制限を使いたいときはこっちを使う\n// using lll = multip::int128_t;\n\nusing ld = long double;\nusing bl = bool;\n// using mint = modint998244353;\n//using mint = modint1000000007;\n//using mint = modint;//使うときはコメントアウトを外す\n//mint::set_mod(m);//使うときはコメントアウトを外す\n\ntemplate<class T> using pq = priority_queue<T, vc<T>>;//大きい順\ntemplate<class T> using pq_g = priority_queue<T, vc<T>, greater<T>>;//小さい順\n//-----------------------------------\n\n\n\n//-------------2.配列系--------------\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\nusing vb = vc<bl>; using vvb = vv<bl>; using vvvb = vv<vb>;\nusing vld = vc<ld>; using vvld = vv<ld>; using vvvld = vv<vld>;\nusing pii = pair<int, int>;\nusing pll = pair<ll, ll>;\n// using vmint = vc<mint>; using vvmint = vv<mint>; using vvvmint = vv<vmint>;\n\n//配列外参照対策のやつは一番上の行にあります\n\n#define rep(i,n) for(ll i = 0; i < (n); ++i)//↓でrepを使うので書いてます\ntemplate<class T>istream& operator>>(istream& i, vc<T>& v) { rep(j, size(v))i >> v[j]; return i; }\n\nusing ar2 = array<ll, 2>;\n\n//----------------------------------\n\n\n\n//--------3.コード短縮化とか---------\n#define rep(i,n) for(ll i = 0; i < (n); ++i)\n#define rrep(i,n) for(ll i = 1; i <= (n); ++i)\n#define drep(i,n) for(ll i = (n)-1; i >= 0; --i)\n#define nfor(i,s,n) for(ll i=s;i<n;i++)//i=s,s+1...n-1 ノーマルfor\n#define dfor(i,s,n) for(ll i = (s)-1; i>=n;i--)//s-1スタートでnまで落ちる\n\n#define nall(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n\n#define chmax(x,y) x = max(x,y)\n#define chmin(x,y) x = min(x,y)\n\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n\n\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\n#define YN {cout<<\"Yes\"<<endl;}else{cout<<\"No\"<<endl;}// if(a==b)YN;\n#define dame cout<<-1<<endl\n\n\n#define vc_unique(v) v.erase( unique(v.begin(), v.end()), v.end() );\n#define vc_rotate(v) rotate(v.begin(),v.begin()+1,v.end());\n\n#define pop_cnt(s) ll(popcount(uint64_t(s)))\n\n#define next_p(v) next_permutation(v.begin(),v.end())\n\n//if (regex_match(s, regex(\"\")))YN;//文字列sの判定を行う。コメントアウトを外して「\"\"」の中に判定する内容を入れる\n\n//-------------------------------\n\n\n\n\n//---------4.グリッド系----------\nvl di = { 0,1,0,-1 };//vl di={0,1,1,1,0,-1,-1,-1};\nvl dj = { 1,0,-1,0 };//vl dj={1,1,0,-1,-1,-1,0,1};\n\nbool out_grid(ll i, ll j, ll h, ll w) {//trueならcontinue\n return (!(0 <= i && i < h && 0 <= j && j < w));\n}\n\n#define vvl_kaiten_r(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//時計回りに90°回転\n#define vvl_kaiten_l(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//反時計周りに90°回転\n\n#define vs_kaiten_r(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//文字列版 時計回りに90°回転\n#define vs_kaiten_l(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//文字列版 反時計周りに90°回転\n\n\n#define vvl_tenti(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][i]=v[i][j];swap(nx,v);}\n#define vs_tenti(v) {ll n = size(v); vs nx(n, string(n,'.')); rep(i, n)rep(j, n)nx[j][i] = v[i][j]; swap(nx, v);}\n\n//--------------------------------\n\n\n\n\n//-----------5.数学系--------------\n#define yu_qurid(x,y) ((x)*(x)+(y)*(y))//ユークリッド距離 sqrtはしてないなので注意\n#define mannhattan(x1,x2,y1,y2) (abs(x1-x2)+abs(y1-y2)) // マンハッタン距離 = |x1-x2|+|y1-y2|\n\ntemplate<class T>T tousa_sum1(T l, T d, T r) {//初項,公差,末項 で総和を求める\n T wide = (r - l) / d + 1;\n return (l + r) * wide / 2;\n}\ntemplate<class T>T tousa_sum2(T a, T d, T n) {//初項,交差,項数 で総和を求める\n return (a * 2 + d * (n - 1)) * n / 2;\n}\nll kousa_kousuu(ll l, ll r, ll d) {//初項,末項,交差 で等差数列の項数を求める\n return (r - l) / d + 1;\n}\n// mint touhi_sum(mint a, mint r, ll n) {//初項,公比,項数で等比数列の総和を求める\n// if (r == 1) {\n// return a * n;\n// }\n// mint bunsi = a * (r.pow(n) - mint(1));\n// mint bunbo = r - 1;\n// return bunsi / bunbo;\n// }\n\nll nc2(ll x) { return x * (x - 1) / 2; }\nll nc3(ll x) { return x * (x - 1) * (x - 2) / 6; }\n\n//----------------------------------------------\n\n\n\n\n//-----------6.デバックや出力系------------------\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\nvoid mukou_debug(vvl to, bool yukou) {//GRAPH × GRAPH用の無向グラフを出力する\n ll n = size(to); ll cnt = 0;//辺の本数\n vc<pair<ll, ll>>v; rep(i, n)for (ll t : to[i]) if (i < t || yukou)cnt++, v.eb(i + 1, t + 1);//有向グラフなら全部OK、違うなら無向なのでf<tのみ見る、using Pのやつを別のにしたいときのためにPを使わずにpair<ll,ll>にしてる\n cout << n << ' ' << cnt << endl; for (auto [f, t] : v)cout << f << ' ' << t << endl;\n}\n\n#define vc_cout(v){ll n = size(v);rep(i,n)cout<<v[i]<<endl;}//一次元配列を出力する\n#define vv_cout(v){ll n = size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<' ';}cout<<endl;}}//二次元配列を出力する\n\ntemplate <typename T>\nstruct BIT {\n int n; // 配列の要素数(数列の要素数+1)\n vector<T> bit; // データの格納先\n BIT(int n_) : n(n_ + 1), bit(n, 0) {}\n void add(int i, T x) {\n i++;\n for (int idx = i; idx < n; idx += (idx & -idx)) {\n bit[idx] += x;\n }\n }\n // 0番目からl-1番目までの累積和\n T sum(int i) {\n T s(0);\n for (int idx = i; idx > 0; idx -= (idx & -idx)) {\n s += bit[idx];\n }\n return s;\n }\n // [l, r)の要素の総和\n T sum(int l, int r){\n T ret_l = sum(l);\n T ret_r = sum(r);\n return ret_r - ret_l;\n }\n\n // 累積和が x 以上になる最小のインデックスを返す(x >= 0)\n int lower_bound(T x) {\n int idx = 0;\n int k = 1;\n while (k * 2 < n) k *= 2; // 最大の 2^k\n\n for (; k > 0; k /= 2) {\n if (idx + k < n && bit[idx + k] < x) {\n x -= bit[idx + k];\n idx += k;\n }\n }\n return idx; // 0-indexed int idx = 0;\n }\n};\n\nint main(){\n ll n;\n cin >> n;\n vl a(n);\n rep(i, n) cin >> a[i];\n\n vl b = a;\n sort(nall(b));\n vc_unique(b);\n rep(i, n){\n a[i] = lower_bound(nall(b), a[i]) - b.begin() + 1;\n }\n\n BIT<ll> bit(n);\n ll ans = 0;\n rep(j, n){\n ans += j - bit.sum(a[j]);\n bit.add(a[j]-1, 1);\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 7832, "score_of_the_acc": -0.4819, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_5_D_10719833", "code_snippet": "#include<iostream>\n#define SENTINEL 2000000000\n#define MAX 200000\n\nint L[MAX/2+1], R[MAX/2+1];\nlong long cnt;\n\nvoid merge(int left, int right, int A[]) {\n int mid = (left + right)/2;\n for (int i = 0; i < mid-left; i++) L[i] = A[left+i];\n for (int i = 0; i < right-mid; i++) R[i] = A[mid+i];\n L[mid-left] = R[right-mid] = SENTINEL;\n int i = 0, j= 0;\n for (int k = left; k < right; k++) {\n if (L[i] < R[j]) {\n A[k] = L[i];\n i++;\n }\n else {\n A[k] = R[j];\n j++;\n cnt += (mid-left)-i;\n }\n }\n}\n\nvoid mergeSort(int left, int right, int A[]) {\n int mid = (left+right)/2;\n if (left+1 < right) {\n mergeSort(left, mid, A);\n mergeSort(mid, right, A);\n merge(left, right, A);\n }\n}\n\nint main() {\n int n;\n std::cin >> n;\n int A[n];\n for (int i = 0; i < n; i++) std::cin >> A[i];\n\n cnt = 0;\n mergeSort(0, n, A);\n std::cout << cnt << std::endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5000, "score_of_the_acc": -0.2685, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_5_D_10719825", "code_snippet": "#include<iostream>\n#define SENTINEL 2000000000\n#define MAX 200000\n\nint L[MAX/2+1], R[MAX/2+1];\nint cnt;\n\nvoid merge(int left, int right, int A[]) {\n int mid = (left + right)/2;\n for (int i = 0; i < mid-left; i++) L[i] = A[left+i];\n for (int i = 0; i < right-mid; i++) R[i] = A[mid+i];\n L[mid-left] = R[right-mid] = SENTINEL;\n int i = 0, j= 0;\n for (int k = left; k < right; k++) {\n if (L[i] < R[j]) {\n A[k] = L[i];\n i++;\n }\n else {\n A[k] = R[j];\n j++;\n cnt += (mid-left)-i;\n }\n }\n}\n\nvoid mergeSort(int left, int right, int A[]) {\n int mid = (left+right)/2;\n if (left+1 < right) {\n mergeSort(left, mid, A);\n mergeSort(mid, right, A);\n merge(left, right, A);\n }\n}\n\nint main() {\n int n;\n std::cin >> n;\n int A[n];\n for (int i = 0; i < n; i++) std::cin >> A[i];\n\n cnt = 0;\n mergeSort(0, n, A);\n std::cout << cnt << std::endl;\n}", "accuracy": 0.6, "time_ms": 10, "memory_kb": 4132, "score_of_the_acc": -0.0149, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_5_D_10719824", "code_snippet": "#include<iostream>\n#define SENTINEL 2000000000\n#define MAX 200000\n\nint L[MAX/2+1], R[MAX/2+1];\nint cnt;\n\nvoid merge(int left, int right, int A[]) {\n int mid = (left + right)/2;\n for (int i = 0; i < mid-left; i++) L[i] = A[left+i];\n for (int i = 0; i < right-mid; i++) R[i] = A[mid+i];\n L[mid-left] = R[right-mid] = SENTINEL;\n int i = 0, j= 0;\n for (int k = left; k < right; k++) {\n if (L[i] < R[j]) {\n A[k] = L[i];\n i++;\n }\n else {\n A[k] = R[j];\n j++;\n if (i != mid-left) cnt += (mid-left)-i;\n }\n }\n}\n\nvoid mergeSort(int left, int right, int A[]) {\n int mid = (left+right)/2;\n if (left+1 < right) {\n mergeSort(left, mid, A);\n mergeSort(mid, right, A);\n merge(left, right, A);\n }\n}\n\nint main() {\n int n;\n std::cin >> n;\n int A[n];\n for (int i = 0; i < n; i++) std::cin >> A[i];\n\n cnt = 0;\n mergeSort(0, n, A);\n std::cout << cnt << std::endl;\n}", "accuracy": 0.6, "time_ms": 10, "memory_kb": 4116, "score_of_the_acc": -0.0143, "final_rank": 18 } ]
aoj_ALDS1_6_A_cpp
Counting Sort Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail: Counting-Sort(A, B, k) 1 for i = 0 to k 2 do C[i] = 0 3 for j = 1 to length[A] 4 do C[A[j]] = C[A[j]]+1 5 /* C[i] now contains the number of elements equal to i */ 6 for i = 1 to k 7 do C[i] = C[i] + C[i-1] 8 /* C[i] now contains the number of elements less than or equal to i */ 9 for j = length[A] downto 1 10 do B[C[A[j]]] = A[j] 11 C[A[j]] = C[A[j]]-1 Write a program which sorts elements of given array ascending order based on the counting sort. Input The first line of the input includes an integer n , the number of elements in the sequence. In the second line, n elements of the sequence are given separated by spaces characters. Output Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. Constraints 1 ≤ n ≤ 2,000,000 0 ≤ A[ i ] ≤ 10,000 Sample Input 1 7 2 5 1 3 2 3 0 Sample Output 1 0 1 2 2 3 3 5
[ { "submission_id": "aoj_ALDS1_6_A_11013399", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<int> counting_sort(vector<int>& a, int k)\n{\n vector<int> c;\n c.assign(k+1, 0);\n\n for (int j = 0; j < a.size(); j++)\n c[a[j]]++;\n\n for (int i = 0; i <= k; i++)\n c[i] = c[i] + c[i-1];\n\n vector<int> b(k);\n for (int j = a.size()-1; j >= 0; j--)\n {\n b[c[a[j]]-1] = a[j];\n c[a[j]]--;\n }\n return b;\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<int> a(n);\n for(int i = 0; i < n; i++)\n cin >> a[i];\n int k = 2000000;\n \n vector<int> v = counting_sort(a, k);\n for(int i = 0; i < n; i++)\n {\n cout << v[i];\n if(i != n-1)\n cout << \" \";\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 26556, "score_of_the_acc": -1.1053, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_6_A_11013398", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<int> counting_sort(vector<int>& a, int k)\n{\n vector<int> c;\n c.assign(k+1, 0);\n\n for (int j = 0; j < a.size(); j++)\n c[a[j]]++;\n\n for (int i = 0; i <= k; i++)\n c[i] = c[i] + c[i-1];\n\n vector<int> b(k);\n for (int j = 0; j < a.size(); j++)\n {\n b[c[a[j]]-1] = a[j];\n c[a[j]]--;\n }\n return b;\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<int> a(n);\n for(int i = 0; i < n; i++)\n cin >> a[i];\n int k = 2000000;\n \n vector<int> v = counting_sort(a, k);\n for(int i = 0; i < n; i++)\n {\n cout << v[i];\n if(i != n-1)\n cout << \" \";\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 26604, "score_of_the_acc": -1.106, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_6_A_10990147", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n#define VMAX 10000\n\nvoid CountingSort(vector<int>& num) {\n\tint n = num.size();\n\tvector<int> tmp(n + 1), cnt(VMAX + 1);\n\tfor (int i = 0; i < n; i++) {\n\t\tcnt[num[i]]++;\n\t}\n\tfor (int i = 1; i < VMAX + 1; i++) {\n\t\tcnt[i] += cnt[i - 1];\n\t}\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\ttmp[cnt[num[i]]] = num[i];\n\t\tcnt[num[i]]--;\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tnum[i] = tmp[i+1];\n\t}\n}\n\n\nint main() {\n\tint n;\n\tcin >> n;\n\tvector<int> num(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> num[i];\n\t}\n\tCountingSort(num);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (i)\n\t\t\tcout << \" \";\n\t\tcout << num[i];\n\t}\n\tcout << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 18644, "score_of_the_acc": -0.9411, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_6_A_10985201", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\n// 計数ソート(要素の最大値がk, 要素数がn)\nvector<ll> countingsort(vector<ll> A, vector<ll> &B, ll k) {\n vector<ll> C(k, 0);\n ll n = A.size();\n\n /* C[i]にiの出現数を記録する */\n nfor(j, 0, n) {\n C[A[j]]++;\n }\n\n /* C[i]にi以下の数の出現数を記録する(累積和を取る) */\n nfor(i, 1, k) {\n C[i] = C[i] + C[i-1];\n }\n\n for(int j = n-1; j >= 0; j--) {\n B[C[A[j]]-1] = A[j];\n C[A[j]]--;\n }\n return B;\n}\n\n\n// main\nvoid solve() {\n ll n;\n cin >> n;\n vector<ll> A(n);\n ll maxv;\n nfor(i,0,n) {\n cin >> A[i];\n if (i == 0) maxv = A[i];\n else maxv = max(maxv, A[i]);\n }\n vector<ll> B(n);\n B = countingsort(A, B, maxv+1);\n nfor(i,0,n) {\n cout << B[i];\n if (i + 1 == n) cout << endl;\n else cout << \" \";\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 270, "memory_kb": 65904, "score_of_the_acc": -1.3846, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_6_A_10938641", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\n#define MAX 2000001\n#define VMAX 10000\n\nint main() {\n int n;\n cin >> n;\n\n vector<unsigned short> A(n + 1), B(n + 1);\n vector<int> C(VMAX + 1, 0);\n\n for (int i = 1; i <= n; i++) {\n cin >> A[i];\n C[A[i]]++;\n }\n\n for (int i = 1; i <= VMAX; i++)\n C[i] += C[i - 1];\n\n for (int j = n; j >= 1; j--) {\n B[C[A[j]]] = A[j];\n C[A[j]]--;\n }\n\n for (int i = 1; i <= n; i++) {\n if (i > 1) cout << \" \";\n cout << B[i];\n }\n cout << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 10864, "score_of_the_acc": -0.7789, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_6_A_10903179", "code_snippet": "// 2025/09/30 Tazoe\n\n#include <iostream>\nusing namespace std;\n\nvoid CountingSort(int A[], int B[], int n, int k)\n{\n\tint C[10001];\n\tfor(int i=0; i<=k; i++){\n\t\tC[i] = 0;\n\t}\n\t\n\t// C[i]にiの出現数を記録する\n\tfor(int j=0; j<n; j++){\n\t\tC[A[j]]++;\n\t}\n\t\n\t// C[i]にi以下の数の出現数を記録する\n\tfor(int i=1; i<=k; i++){\n\t\tC[i] = C[i]+C[i-1];\n\t}\n\t\n\tfor(int j=n-1; j>=0; j--){\n\t\tB[C[A[j]]-1] = A[j];\n\t\tC[A[j]]--;\n\t}\n}\n\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\t\n\tint A[2000000];\n\tint B[2000000];\n\tfor(int i=0; i<n; i++){\n\t\tcin >> A[i];\n\t}\n\t\n\tCountingSort(A, B, n, 10000);\n\t\n\tfor(int i=0; i<n; i++){\n\t\tcout << B[i];\n\t\tif(i==n-1){\n\t\t\tcout << endl;\n\t\t}\n\t\telse{\n\t\t\tcout << ' ';\n\t\t}\n\t}\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 19076, "score_of_the_acc": -0.9864, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_6_A_10897636", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n vector<int> A(n + 1), B(n + 1);\n int k = 10000;\n vector<int> C(k + 1, 0);\n\n for (int i = 1; i <= n; i++) cin >> A[i];\n\n for (int i = 0; i <= k; i++) C[i] = 0;\n\n for (int j = 1; j <= n; j++) C[A[j]]++;\n\n for (int i = 1; i <= k; i++) C[i] += C[i - 1];\n\n for (int j = n; j >= 1; j--) {\n B[C[A[j]]] = A[j];\n C[A[j]]--;\n }\n\n for (int i = 1; i <= n; i++) {\n if (i > 1) cout << \" \";\n cout << B[i];\n }\n cout << \"\\n\";\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 18724, "score_of_the_acc": -0.9423, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_6_A_10885491", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n int N;\n cin >> N;\n int A[N];\n for(int i=0; i<N; i++){\n cin >> A[i];\n }\n int K = 10000;\n int C[K+1];\n for(int i=0; i<=K; i++){\n C[i] = 0;\n }\n for(int i=0; i<N; i++){\n C[A[i]]++;\n }\n for(int i=1; i<=K; i++){\n C[i] = C[i] + C[i-1];\n }\n sort(A, A + N, greater<int>());\n for(int i=N-1; i>=0; i--){\n cout << A[i];\n if(i != 0){\n cout << ' ';\n }\n C[A[i]]--;\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 11176, "score_of_the_acc": -1.0916, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_6_A_10876989", "code_snippet": "#include <iostream>\n#include <vector>\n#include <sstream>\nusing namespace std;\n\nvoid CountingSort(vector<int>& A) {\n const int max = A.size();\n vector<int> B(max);\n vector<int> C(10001,0);\n \n for(int j=0; j<max; j++) {\n C[A[j]]++;\n }\n for(int i=1; i<=10000; i++) {\n C[i] = C[i] + C[i-1];\n }\n for(int j=max-1; j>=0; j--) {\n B[C[A[j]]-1] = A[j];\n C[A[j]]--;\n }\n for(int i=0; i<max; i++) {\n if(i>0) {\n cout << \" \";\n }\n cout << B[i];\n }\n cout << endl;\n}\n\nint main() {\n int n;\n cin >> n;\n cin.ignore(); // 改行文字を読み飛ばす\n vector<int> A(n);\n string line;\n getline(cin, line);\n stringstream ss(line);\n for (int i = 0; i < n; i++) {\n ss >> A[i];\n // cout << A[i] << \" \";\n }\n // cout << endl;\n CountingSort(A);\n return 0;\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 39756, "score_of_the_acc": -1.0074, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_6_A_10863293", "code_snippet": "#include <bits/stdc++.h>\n#include <cerrno>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\n\nint main() {\n int n;\n cin >> n;\n vector<int> a(n);\n rep(i,n) cin >> a[i];\n\n sort(a.begin(), a.end());\n rep(i,n) {\n if(i == n-1) cout << a[i] << endl;\n else cout << a[i] << \" \";\n }\n return 0;\n}", "accuracy": 1, "time_ms": 430, "memory_kb": 10676, "score_of_the_acc": -1.1221, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_6_A_10825892", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < n; ++i)\n\n\nint main() {\n int n;\n cin >> n;\n vector<int> a(n);\n rep(i,n) cin >> a[i];\n sort(a.begin(), a.end());\n rep(i,n) {\n if(n-1 == i) cout << a[i] << endl;\n else cout << a[i] << \" \";\n }\n return 0;\n}", "accuracy": 1, "time_ms": 430, "memory_kb": 10828, "score_of_the_acc": -1.1245, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_6_A_10739439", "code_snippet": "#include <iostream>\n#include <vector>\n#include <climits> \nusing namespace std;\nvoid CountingSort(vector<int>& A, vector<int>& B, int k) {\n vector<int> C(k + 1, 0);\n int n = A.size();\n for(int j = 0 ;j< n; j++){\n C[A[j]]++;\n }\n for(int i = 0 ;i<=k; i++){\n C[i] = C[i] + C[i-1];\n }\n for(int j = n-1;j>=0; j--){\n B[C[A[j]]-1] = A[j];\n C[A[j]]--;\n } \n}\nint main() {\n int N;\n cin >> N;\n vector<int> A(N), B(N);\n int max_val = 0;\n for (int i = 0; i < N; i++){\n cin >> A[i];\n if (A[i] > max_val) max_val = A[i];\n } \n CountingSort(A, B, max_val);\n for (int i = 0; i < N; i++) {\n cout << B[i];\n if (i != N - 1) cout << \" \";\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 18876, "score_of_the_acc": -0.9832, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_6_A_10737961", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int n;\n cin >> n;\n int ara[n+8];\n for(int i=0;i<n;i++)\n cin >> ara[i];\n sort(ara,ara+n);\n cout << ara[0];\n for(int i=1;i<n;i++)\n cout << \" \" << ara[i];\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 11160, "score_of_the_acc": -1.0913, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_6_A_10737960", "code_snippet": "#include<bits/stdc++.h>\n\nusing namespace std;\nint arr[2000000];\n\nint main()\n{\n int n,i;\n\n scanf(\"%d\",&n);\n\n for(i=0;i<n;i++)\n {\n scanf(\"%d\",&arr[i]);\n }\n\n sort(arr,arr+n);\n\n for(i=0;i<n-1;i++)\n {\n printf(\"%d \",arr[i]);\n }\n printf(\"%d\",arr[n-1]);\n printf(\"\\n\");\n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 11376, "score_of_the_acc": -0.4409, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_6_A_10737958", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint arr[10001];\nint main()\n{\n int cs=0;\n\n {\n int n;\n scanf(\"%d\",&n);\n\n\n memset(arr,0,sizeof(arr));\n\n for(int i=0;i<n;i++)\n {\n int a;\n scanf(\"%d\",&a);\n arr[a]++;\n\n }\n }\n\n int i=0;\n for( i=0;i<10001;i++)\n {\n if(arr[i]>0){\n\n printf(\"%d\",i);\n arr[i]--;\n\n break;\n }\n\n\n\n }\n for(int j=0;j<10001;j++)\n {\n if(arr[j]>0){\n for(int k=1;k<=arr[j];k++)\n printf(\" %d\",j);\n }\n\n\n\n }\n\n printf(\"\\n\");\n\n\n\n\n\n }", "accuracy": 1, "time_ms": 170, "memory_kb": 3612, "score_of_the_acc": -0.0098, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_6_A_10737956", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int n,i,j;\n cin>>n;\n int a[n+5];\n for(i=0;i<n;i++){\n cin>>a[i];\n }\n sort(a,a+n);\n for(i=0;i<n;i++){\n cout<<a[i];\n if(i<n-1) cout<<\" \";\n }\n cout<<\"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 11252, "score_of_the_acc": -1.0928, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_6_A_10737955", "code_snippet": "#include<cstdio>\n\nusing namespace std;\n\nint main()\n{\n int n,j;\n scanf(\"%d\",&n);\n int arr,i,chk[10007];\n for(i=0;i<10007;i++)\n chk[i]=0;\n for(i=0;i<n;i++)\n {\n scanf(\"%d\",&arr);\n chk[arr]++;\n }\n bool done = 0;\n for(i=0;i<10003;i++)\n {\n for(j=1;j<=chk[i];j++)\n {\n if(done) printf(\" \");\n done = 1;\n printf(\"%d\",i);\n }\n }\n printf(\"\\n\");\n return 0;\n\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 2996, "score_of_the_acc": -0.0385, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_6_A_10737952", "code_snippet": "#include<cstdio>\n\nusing namespace std;\n\nint main()\n{\n int n,j,mx=-1;\n scanf(\"%d\",&n);\n int arr,i,chk[10007];\n for(i=0;i<10007;i++)\n chk[i]=0;\n for(i=0;i<n;i++)\n {\n scanf(\"%d\",&arr);\n if(arr>mx)\n mx=arr;\n chk[arr]++;\n }\n for(i=0;i<10003;i++)\n {\n for(j=1;j<=chk[i];j++)\n {\n if(i==mx && j==chk[i])\n printf(\"%d\",i);\n else\n printf(\"%d \",i);\n }\n }\n printf(\"\\n\");\n return 0;\n\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 3016, "score_of_the_acc": -0.0388, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_6_A_10719861", "code_snippet": "#include <iostream> // 標準入出力のために必要\n#include <vector> // std::vector を使うために必要(動的配列)\n\n// k の最大値は A[i] の最大値 10,000 です\n// ただし、配列のインデックスとして0からkまで使うので、サイズは k+1 必要です\nconst int K_MAX = 10000;\n\nvoid CountingSort(std::vector<int>& A, std::vector<int>& B, int k, int n) {\n // カウンタ配列 C を初期化 (k+1 のサイズが必要)\n // 0 から k までの要素の出現数を記録するため\n std::vector<int> C(k + 1, 0);\n\n // C[i] に i の出現数を記録する\n // 配列 A のインデックスは 0 から n-1 なので、擬似コードの 1 から n を修正\n for (int j = 0; j < n; ++j) {\n C[A[j]]++;\n }\n\n // C[i] に i 以下の数の出現数を記録する(累積和)\n // これにより、B における各要素の最終位置が決定される\n for (int i = 1; i <= k; ++i) {\n C[i] = C[i] + C[i - 1];\n }\n\n // A[j] を正しい位置 B[C[A[j]]] に配置し、カウントを減らす\n // 安定性を保つため、A の末尾から処理していく\n // 擬似コードの n downto 1 に対応するため、インデックスは n-1 から 0 へ\n for (int j = n - 1; j >= 0; --j) {\n // C[A[j]] は、A[j] と同じ値を持つ要素が何個あり、その値がBのどこに配置されるかを示す\n // しかし、C[A[j]] は1ベースのインデックスで、vector は0ベースなので -1 する\n B[C[A[j]] - 1] = A[j];\n C[A[j]]--; // 同じ値を持つ次の要素のためにカウントを減らす\n }\n}\n\nint main() {\n // 高速な入出力を設定\n // これにより、大量のデータ入力でもタイムリミットに引っかかりにくくなる\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(NULL);\n\n int n;\n std::cin >> n; // 数列の長さを読み込む\n\n // 入力数列 A と出力数列 B を動的に確保\n // vector は動的なサイズ変更が可能で、メモリ管理を自動で行ってくれるため便利\n std::vector<int> A(n);\n std::vector<int> B(n);\n\n // 数列 A の要素を読み込む\n for (int i = 0; i < n; ++i) {\n std::cin >> A[i];\n }\n\n // CountingSort を呼び出してソートを実行\n // k_max は A[i] の最大値(今回の制約では10000)\n CountingSort(A, B, K_MAX, n);\n\n // ソートされた数列 B を出力\n for (int i = 0; i < n; ++i) {\n std::cout << B[i] << (i == n - 1 ? \"\" : \" \"); // 最後の要素の後にスペースは不要\n }\n std::cout << std::endl; // 改行\n\n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 18680, "score_of_the_acc": -0.2493, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_6_A_10718655", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nvoid CountingSort(int a[],int b[],int n,int k){\n int c[k+1];\n for(int i=0;i<=k;i++) c[i]=0;\n for(int j=1;j<=n;j++) c[a[j]]++;\n for(int i=1;i<=k;i++) c[i]=c[i]+c[i-1];\n for(int j=n;j>=1;j--){\n b[c[a[j]]]=a[j];\n c[a[j]]--;\n }\n}\nvoid solve(){\n int n;cin>>n;\n int a[n+1];\n int k=0;\n for(int i=1;i<=n;i++){\n cin>>a[i];\n k=max(k,a[i]);\n }\n int b[n+1];\n CountingSort(a,b,n,k);\n for(int i=1;i<=n;i++) cout<<b[i]<<\" \\n\"[i==n];\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 34612, "score_of_the_acc": -0.5026, "final_rank": 6 } ]
aoj_ALDS1_7_A_cpp
Rooted Trees A graph G = ( V , E ) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs). Fig. 1 A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node." Your task is to write a program which reports the following information for each node u of a given rooted tree T : node ID of u parent of u depth of u node type (root, internal node or leaf) a list of chidlren of u If the last edge on the path from the root r of a tree T to a node x is ( p , x ), then p is the parent of x , and x is a child of p . The root is the only node in T with no parent. A node with no children is an external node or leaf . A nonleaf node is an internal node The number of children of a node x in a rooted tree T is called the degree of x . The length of the path from the root r to a node x is the depth of x in T . Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n -1. Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input. Fig. 2 Input The first line of the input includes an integer n , the number of nodes of the tree. In the next n lines, the information of each node u is given in the following format: id k c 1 c 2 ... c k where id is the node ID of u , k is the degree of u , c 1 ... c k are node IDs of 1st, ... k th child of u . If the node does not have a child, the k is 0. Output Print the information of each node in the following format ordered by IDs: node id : parent = p , depth = d , type , [ c 1 ... c k ] p is ID of its parent. If the node does not have a parent, print -1 . d is depth of the node. type is a type of nodes represented by a string ( root , internal node or leaf ). If the root can be considered as a leaf or an internal node, print root . c 1 ... c k is the list of children as a ordered tree. Please follow the format presented in a sample output below. Constraints 1 ≤ n ≤ 100000 Sample Input 1 13 0 3 1 4 10 1 2 2 3 2 0 3 0 4 3 5 6 7 5 0 6 0 7 2 8 9 8 0 9 0 10 2 11 12 11 0 12 0 Sample Output 1 node 0: parent = -1, depth = 0, root, [1, 4, 10] node 1: parent = 0, depth = 1, internal node, [2, 3] node 2: parent = 1, depth = 2, leaf, [] node 3: parent = 1, depth = 2, leaf, [] node 4: parent = 0, depth = 1, internal node, [5, 6, 7] node 5: parent = 4, depth = 2, leaf, [] node 6: parent = 4, depth = 2, leaf, [] node 7: parent = 4, depth = 2, internal node, [8, 9] node 8: parent = 7, depth = 3, leaf, [] node 9: parent = 7, depth = 3, leaf, [] node 10: parent = 0, depth = 1, internal node, [11, 12] node 11: parent = 10, depth = 2, leaf, [] node 12: parent = 10, depth = 2, leaf, [] Sample Input 2 4 1 3 3 2 0 0 0 3 0 2 0 Sample Output 2 node 0: parent = 1, depth = 1, leaf, [] node 1: ...(truncated)
[ { "submission_id": "aoj_ALDS1_7_A_11041298", "code_snippet": "#include<iostream>\nusing namespace std;\nstatic const int MAX = 100005;\nstatic const int NIL = -1;\n\nstruct Node {int p, l, r;};\n\nNode T[MAX];\nint n, D[MAX];\n\nvoid print(int u){\n int i,c;\n cout << \"node \" << u << \": \";\n cout << \"parent = \" << T[u].p << \", \";\n cout << \"depth = \" << D[u] << \", \";\n\n if(T[u].p == NIL) cout << \"root, \";\n else if(T[u].l == NIL) cout << \"leaf, \";\n else cout << \"internal node, \";\n\n cout << \"[\";\n\n for(int i = 0, c = T[u].l; c!= NIL ;i++, c = T[c].r){\n if(i) cout << \", \";\n cout << c;\n }\n cout << \"]\" << endl;\n}\n\nvoid setDepth(int u, int p){\n D[u] = p;\n if(T[u].r != NIL) setDepth(T[u].r,p);\n if(T[u].l != NIL) setDepth(T[u].l, p + 1);\n}\n\nint main(){\n int i, j, d, v, c, l, r;\n cin >> n;\n for(int i = 0; i < n; i++){\n T[i].p = T[i].l = T[i].r = NIL;\n }\n\n for(int i = 0 ; i < n; i++){\n cin >> v >> d;\n for(j = 0; j < d; j++){\n cin >> c;\n if(j == 0) T[v].l = c;\n else T[l].r = c;\n l = c;\n T[c].p = v;\n }\n }\n\n for(i = 0;i < n; i++){\n if(T[i].p == NIL) r = i;\n }\n\n setDepth(r,0);\n\n for(i = 0; i < n; i++) print(i);\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 8120, "score_of_the_acc": -0.7402, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_7_A_11041286", "code_snippet": "#include<iostream>\nusing namespace std;\nstatic const int MAX = 100005;\nstatic const int NIL = -1;\n\nstruct Node {int p, l, r;};\n\nNode T[MAX];\nint n, D[MAX];\n\nvoid print(int u){\n int i,c;\n cout << \"node \" << u << \": \";\n cout << \"parent = \" << T[u].p << \", \";\n cout << \"depth = \" << D[u] << \", \";\n\n if(T[u].p == NIL) cout << \"root, \";\n else if(T[u].l == NIL) cout << \"leaf, \";\n else cout << \"internal node, \";\n\n cout << \"[\";\n\n for(int i = 0, c = T[u].l; c!= NIL ;i++, c = T[c].r){\n if(i) cout << \", \";\n cout << c;\n }\n cout << \"]\" << endl;\n}\n\nvoid setDepth(int u, int p){\n D[u] = p;\n if(T[u].r != NIL) setDepth(T[u].r,p);\n if(T[u].l != NIL) setDepth(T[u].l, p + 1);\n}\n\nint main(){\n int i, j, d, v, c, l, r;\n cin >> n;\n for(int i = 0; i < n; i++){\n T[i].p = T[i].l = T[i].r = NIL;\n }\n\n for(int i = 0 ; i < n; i++){\n cin >> v >> d;\n for(j = 0; j < d; j++){\n cin >> c;\n if(j == 0) T[v].l = c;\n else T[l].r = c;\n l = c;\n T[c].p = v;\n }\n }\n\n for(i = 0;i < n; i++){\n if(T[i].p == NIL) r = i;\n }\n\n setDepth(r,0);\n\n for(i = 0; i < n; i++) print(i);\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 7736, "score_of_the_acc": -0.6972, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_7_A_11014931", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct node\n{\n int id;\n int degree;\n node* parent;\n vector<node*> children;\n\n void adopt(int d, const vector<node*>& c)\n {\n degree += d;\n children = c;\n }\n node(int i)\n {\n id = i;\n parent = nullptr;\n }\n node()\n {\n\n }\n};\n\nstruct rooted_tree\n{\n vector<node> nodes;\n int node_count;\n\n void assign_node(int id, int d, const vector<int>& c_ids)\n {\n vector<node*> c_nodes;\n for(int c_id : c_ids)\n c_nodes.push_back(&nodes[c_id]);\n\n node& n = nodes[id];\n n.adopt(d, c_nodes);\n for(node* c_node : c_nodes)\n c_node->parent = &n;\n }\n\n int check_depth(int id, int count)\n {\n if(nodes[id].parent == nullptr)\n return count;\n else\n return check_depth(nodes[id].parent->id, count + 1);\n }\n\n void show_info()\n {\n for(node& n : nodes)\n {\n cout << \"node \" << n.id << \": \";\n\n cout << \"parent = \";\n if(n.parent == nullptr)\n {\n cout << \"-1\";\n }\n else\n {\n cout << n.parent->id;\n }\n cout << \", \";\n\n cout << \"depth = \" << check_depth(n.id, 0) << \", \";\n\n if(n.parent == nullptr)\n {\n cout << \"root\";\n }\n else if(n.children.size() == 0)\n {\n cout << \"leaf\";\n }\n else\n {\n cout << \"internal node\";\n }\n cout << \", \";\n\n cout << \"[\";\n for(int i = 0; i < (int)n.children.size(); i++)\n {\n cout << n.children[i]->id;\n if(i != (int)n.children.size()-1)\n cout << \", \";\n }\n cout << \"]\" << endl;\n }\n }\n rooted_tree(int n)\n {\n node_count = n;\n for(int i = 0; i < n; i++)\n nodes.push_back(node(i));\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n rooted_tree t = rooted_tree(n);\n\n for(int node = 0; node < n; node++)\n {\n int id, d;\n cin >> id >> d;\n vector<int> c_id(d);\n for(int i = 0; i < d; i++)\n cin >> c_id[i];\n \n t.assign_node(id, d, c_id);\n }\n\n t.show_info();\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 10028, "score_of_the_acc": -0.9542, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_7_A_10996069", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\n// 木の構造\nstruct tree {\n // ここのorderとは次数\n ll id=-1, order=-1, parent=-1, depth=-1;\n vector<ll> children;\n string statu;\n};\n\nll dep(vector<tree> &root_tree, ll &id, ll cnt){\n if (root_tree[id].parent == -1) return cnt;\n cnt++;\n return dep(root_tree, root_tree[id].parent, cnt);\n}\n\n// main\nvoid solve() {\n ll n;\n cin >> n;\n vector<tree> root_tree(n);\n nfor(i,0,n) {\n ll id, k, c;\n cin >> id >> k;\n root_tree[id].id = id;\n root_tree[id].order = k;\n nfor(i,0,k) {\n cin >> c;\n root_tree[id].children.push_back(c);\n root_tree[c].parent = id;\n }\n }\n // depth、状態を計算する\n // rootはparentが-1のとき\n // internarl nodeはparentが-1でなく,childrenが0でないとき\n // leafはchildrenが0のとき\n // 再帰関数で実現する\n nfor(i,0,n) {\n ll cnt = 0;\n ll d = dep(root_tree, i, cnt);\n root_tree[i].depth = d;\n }\n nfor(i,0,n) {\n if (root_tree[i].parent == -1) {\n root_tree[i].statu = \"root\";\n }\n else if (root_tree[i].parent != -1 and root_tree[i].children.size() != 0) {\n root_tree[i].statu = \"internal node\";\n }\n else {\n root_tree[i].statu = \"leaf\";\n }\n }\n // 結果を出力する\n nfor(i, 0, n) {\n cout << \"node \" << root_tree[i].id;\n cout << \": parent = \" << root_tree[i].parent;\n cout << \", depth = \" << root_tree[i].depth;\n cout << \", \" << root_tree[i].statu;\n cout << \", [\";\n nfor(j,0,root_tree[i].order) {\n cout << root_tree[i].children[j];\n if (j + 1 != root_tree[i].order) {\n cout << \", \";\n }\n }\n cout << \"]\" << endl;\n }\n\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 13408, "score_of_the_acc": -1.2, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_7_A_10993058", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nclass Node {\npublic:\n\tint value;\n\tNode* parent;\n\tvector<Node*> children;\n\n\tNode(int value) {\n\t\tthis->value = value;\n\t\tthis->parent = NULL;\n\t}\n};\n\nvoid computeDepth(Node* node, int depth, vector<int>& depths) {\n\tdepths[node->value] = depth;\n\tfor (Node* child : node->children) {\n\t\tcomputeDepth(child, depth + 1, depths);\n\t}\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tvector<Node*> nodes(n); // 建立的节点需要被保存\n\tfor (int i = 0; i < n; i++) {\n\t\tnodes[i] = new Node(i); // 先把数字变成待连接的节点\n\t}\n\t// 连接\n\tfor (int i = 0; i < n; i++) {\n\t\tint v, k;\n\t\tcin >> v >> k;\n\t\tfor (int j = 0; j < k; j++) {\n\t\t\tint c;\n\t\t\tcin >> c;\n\t\t\tnodes[v]->children.push_back(nodes[c]);\n\t\t\tnodes[c]->parent = nodes[v];\n\t\t}\n\t}\n\t// 找到根节点\n\tNode* root = NULL;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (nodes[i]->parent == NULL) {\n\t\t\troot = nodes[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\t// 计算深度\n\tvector<int> depths(n);\n\tcomputeDepth(root, 0, depths);\n\t// 输出结果\n\tfor (int i = 0; i < n; i++) {\n\t\tcout << \"node \" << i << \": \";\n\n\t\tcout << \"parent = \";\n\t\tif (nodes[i]->parent) {\n\t\t\tcout << nodes[i]->parent->value << \", \";\n\t\t}\n\t\telse {\n\t\t\tcout << \"-1, \";\n\t\t}\n\n\t\tcout << \"depth = \" << depths[i] << \", \";\n\n\t\tif (nodes[i]->value == root->value) {\n\t\t\tcout << \"root, \";\n\t\t}\n\t\telse if (nodes[i]->children.empty()) {\n\t\t\tcout << \"leaf, \";\n\t\t}\n\t\telse {\n\t\t\tcout << \"internal node, \";\n\t\t}\n\n\t\tcout << \"[\";\n\t\tfor (int j = 0; j < nodes[i]->children.size(); j++) {\n\t\t\tif (j)\n\t\t\t\tcout << \", \";\n\t\t\tcout << nodes[i]->children[j]->value;\n\t\t}\n\t\tcout << \"]\" << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 10304, "score_of_the_acc": -0.9852, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_7_A_10958239", "code_snippet": "#include <iostream>\n#include <vector>\n#include <optional>\nusing namespace std;\n\nstruct Node {\n optional<int> parent;\n optional<int> left; // first child\n optional<int> right; // next sibling\n};\n\nstruct Tree {\n vector<Node> nodes;\n vector<int> depth;\n\n explicit Tree(int n) : nodes(n), depth(n, 0) {}\n\n void add_children(int v, const vector<int>& children) {\n if (children.empty()) return;\n nodes[v].left = children.front();\n for (size_t i = 0; i < children.size(); ++i) {\n int c = children[i];\n nodes[c].parent = v;\n if (i + 1 < children.size()) nodes[c].right = children[i + 1];\n }\n }\n\n int find_root() const {\n for (size_t i = 0; i < nodes.size(); ++i)\n if (!nodes[i].parent) return static_cast<int>(i);\n return -1; // should not happen\n }\n\n void assign_depth(int u, int d) {\n depth[u] = d;\n if (nodes[u].right) assign_depth(*nodes[u].right, d);\n if (nodes[u].left) assign_depth(*nodes[u].left, d + 1);\n }\n\n void print(int u) const {\n cout << \"node \" << u << \": \"\n << \"parent = \" << (nodes[u].parent ? to_string(*nodes[u].parent) : string(\"-1\")) << \", \"\n << \"depth = \" << depth[u] << \", \";\n\n if (!nodes[u].parent) cout << \"root, \";\n else if (!nodes[u].left) cout << \"leaf, \";\n else cout << \"internal node, \";\n\n cout << \"[\";\n bool first = true;\n for (auto c = nodes[u].left; c; c = nodes[*c].right) {\n if (!first) cout << \", \";\n cout << *c;\n first = false;\n }\n cout << \"]\\n\";\n }\n};\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n if (!(cin >> n)) return 0;\n Tree tree(n);\n\n for (int i = 0; i < n; ++i) {\n int v, d;\n cin >> v >> d;\n vector<int> children(d);\n for (int j = 0; j < d; ++j) cin >> children[j];\n tree.add_children(v, children);\n }\n\n int root = tree.find_root();\n if (root == -1) return 1;\n\n tree.assign_depth(root, 0);\n\n for (int i = 0; i < n; ++i) tree.print(i);\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8864, "score_of_the_acc": -0.5237, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_7_A_10878704", "code_snippet": "#include <iostream>\n#include <list>\nusing namespace std;\nint main()\n{\n int n;\n cin >> n;\n\n int K[100000];\n list<int> C[100000];\n int P[100000];\n\n for(int id=0; id<n; id++){\n P[id] = -1;\n }\n for(int i=0; i<n; i++){\n int id, k;\n cin >> id >> k;\n K[id] = k;\n\n for(int j=0; j<k; j++){\n int c;\n cin >> c;\n\n C[id].push_back(c);\n P[c] = id;\n }\n }\n\n int D[100000];\n\n for(int id=0; id<n; id++){\n if(P[id]==-1){\n D[id] = 0;\n }\n else{\n D[id] = -1;\n }\n }\n\n for(int d=0; d<20; d++){\n for(int id=0; id<n; id++){\n if(D[id]!=d){\n continue;\n }\n for(list<int>::iterator it=C[id].begin(); it!=C[id].end(); it++){\n D[*it] = d+1;\n }\n }\n }\n for(int id=0; id<n; id++){\n cout << \"node \" << id << \": \";\n cout << \"parent = \" << P[id] << \", \";\n cout << \"depth = \" << D[id] << \", \";\n\n if(P[id]==-1){\n cout << \"root, \";\n }\n else if(K[id]>0){\n cout << \"internal node, \";\n }\n else{\n cout << \"leaf, \";\n }\n\n cout << \"[\";\n for(list<int>::iterator it=C[id].begin(); it!=C[id].end(); it++){\n if(it!=C[id].begin()){\n cout << \", \";\n }\n cout << *it;\n }\n cout << \"]\" << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 9952, "score_of_the_acc": -0.9457, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_7_A_10851375", "code_snippet": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n \nconst int MAX = 100000;\nint n, pa[MAX], ch[MAX], br[MAX];\n \nvoid solve(){\n for(int i=0;i<n;i++){\n cout << \"node \" << i << \": parent = \" << pa[i] << \", depth = \" << flush;\n \n int cnt = 0;\n for(int j=i; pa[j]!=-1; j=pa[j]) cnt++;\n cout << cnt << \", \" << flush;\n \n if(pa[i] == -1) cout << \"root, \" << flush;\n else if(ch[i] == -1) cout << \"leaf, \" << flush;\n else cout << \"internal node, \" << flush;\n \n cout << \"[\";\n for(int j=ch[i]; j!=-1; j=br[j]){\n if(j != ch[i]) cout << \", \";\n cout << j;\n }\n cout << \"]\" << endl;\n }\n}\n \nint main(){\n fill(pa,pa+MAX,-1);\n fill(ch,ch+MAX,-1);\n fill(br,br+MAX,-1);\n cin >> n;\n for(int i=0;i<n;i++){\n int x,prev,y,c;\n cin >> x >> c;\n for(int j=0;j<c;j++){\n cin >> y;\n pa[y] = x;\n if(j == 0) ch[x] = y;\n else br[prev] = y;\n prev = y;\n }\n }\n solve();\n}", "accuracy": 1, "time_ms": 330, "memory_kb": 4544, "score_of_the_acc": -1.0058, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_7_A_10847092", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < n; ++i)\n\nstruct Node {\n int parent;\n vector<int> children;\n};\n\nvector<Node> tree;\nvector<int> depth;\n\nvoid setDepth(int u, int d) {\n depth[u] = d;\n for(auto c : tree[u].children) setDepth(c, d+1);\n}\n\n\nint main() {\n int n;\n cin >> n;\n tree.resize(n);\n depth.resize(n);\n\n rep(i,n) tree[i].parent = -1;\n rep(i,n) {\n int id,k;\n cin >> id >> k;\n rep(j,k) {\n int c;\n cin >> c;\n tree[id].children.push_back(c);\n tree[c].parent = id;\n }\n }\n\n int root = -1;\n rep(i,n) if(tree[i].parent == -1) root = i;\n\n setDepth(root, 0);\n\n rep(i,n) {\n cout << \"node \" << i << \": \";\n cout << \"parent = \" << tree[i].parent << \", \";\n cout << \"depth = \" << depth[i] << \", \";\n\n if(tree[i].parent == -1) cout << \"root, \";\n else if(tree[i].children.empty()) cout << \"leaf, \";\n else cout << \"internal node, \";\n\n cout << \"[\";\n rep(j,(int)tree[i].children.size()) {\n if(j) cout << \", \";\n cout << tree[i].children[j];\n }\n cout << \"]\" << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 7096, "score_of_the_acc": -0.6254, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_7_A_10781753", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <iomanip>\n#include <map>\n#include <queue>\n#include <set>\n#include <bitset>\n#include <stack>\n#include <list>\n#include <unordered_set>\n#include <unordered_map>\n#define rep(i, a, b) for (int i = a; i < b; ++i)\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int mod = 1000000007;\n\nconst long long INF = 1LL << 60;\nconstexpr double pi = 3.141592653589793238462643383279502884L;\n\nstruct Edge {\n int to;\n long long w;\n Edge(int to, long long w) : to(to), w(w) {}\n};\n\nusing Graph = vector<vector<Edge>>;\nusing P = pair<int, int>;\nusing Pll = pair<long long, int>;\nusing ll = long long;\n\ntemplate<class T> bool chmin(T& a, T b) { if (a > b) { a = b; return true; } else return false; }\ntemplate<class T> bool chmax(T& a, T b) { if (a < b) { a = b; return true; } else return false; }\n\nstruct Node {\n int id;\n Node* parent;\n Node* first_child;\n Node* next_brother;\n\n Node() : id(-1), parent(nullptr), first_child(nullptr), next_brother(nullptr) {}\n};\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n\n int n; cin >> n;\n Node** nodes = new Node*[n];\n\n for (int i = 0; i < n; ++i) {\n nodes[i] = new Node;\n }\n\n for (int i = 0; i < n; ++i) {\n int id, k;\n cin >> id >> k;\n nodes[id]->id = id;\n int prev = -1;\n \n for (int j = 0; j < k; ++j) {\n int c; cin >> c;\n if (nodes[id]->first_child == nullptr) {\n nodes[id]->first_child = nodes[c];\n } else {\n if (prev != -1) {\n nodes[prev]->next_brother = nodes[c];\n }\n }\n nodes[c]->parent = nodes[id];\n prev = c;\n }\n }\n\n for (int i = 0; i < n; ++i) {\n int parent = nodes[i]->parent == nullptr ? -1 : nodes[i]->parent->id;\n int depth = 0;\n Node* cur = nodes[i];\n while (true) {\n cur = cur->parent;\n if (cur == nullptr) {\n break;\n }\n ++depth;\n }\n\n string type = \"\";\n if (parent == -1) {\n type = \"root\";\n } else if (nodes[i]->first_child == nullptr) {\n type = \"leaf\";\n } else {\n type = \"internal node\";\n }\n\n string children = \"[\";\n cur = nodes[i]->first_child;\n while (cur) {\n if (cur != nodes[i]->first_child) {\n children += \", \";\n }\n int child = cur->id;\n children += to_string(child);\n cur = cur->next_brother;\n }\n children += \"]\";\n\n cout << \"node \" << i << \": \" << flush;\n cout << \"parent = \" << parent << \", \" << flush;\n cout << \"depth = \" << depth << \", \" << flush;\n cout << type << \", \" << flush;\n cout << children << endl;\n }\n\n for (int i = 0; i < n; ++i) {\n delete nodes[i];\n }\n\n delete[] nodes;\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 9912, "score_of_the_acc": -1.1746, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_7_A_10767256", "code_snippet": "#include <iostream>\nusing namespace std;\n#define MAX 100005\n#define NIL -1\n\nstruct Node { int p, l, r; };\n\nNode T[MAX];\nint n, D[MAX];\n\nvoid print(int u) {\n int i, c;\n cout << \"node \" << u << \": \";\n cout << \"parent = \" << T[u].p << \", \";\n cout << \"depth = \" << D[u] << \", \";\n\n if (T[u].p == NIL) cout << \"root, \";\n else if (T[u].l == NIL) cout << \"leaf, \";\n else cout << \"internal node, \";\n\n cout << \"[\";\n\n for (int i=0, c = T[u].l; c != NIL ; i++, c = T[c].r) {\n if (i) cout << \", \";\n cout << c;\n }\n cout << \"]\" << endl;\n}\n\n// 再帰の深さを求める\nvoid rec(int u, int p) {\n D[u] = p;\n if (T[u].r != NIL) rec(T[u].r, p); // 右の兄弟にも同じ深さを設定\n if (T[u].l != NIL) rec(T[u].l, p+1); // 最も左の子に自分の深さ+1を設定\n}\n\nint main() {\n int i, j, d, v, c, l, r;\n cin >> n;\n for (i = 0; i<n; i++) T[i].p = T[i].l = T[i].r = NIL;\n\n for (i = 0; i<n; i++) {\n cin >> v >> d;\n for (j = 0; j<d; j++) {\n cin >> c;\n if (j==0) T[v].l = c;\n else T[l].r = c;\n l = c;\n T[c].p = v;\n }\n }\n for (int i = 0; i<n; i++) {\n if (T[i].p == NIL) r=i;\n }\n\n rec(r,0);\n\n for (i = 0; i<n; i++) print(i);\n\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 8024, "score_of_the_acc": -0.7295, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_7_A_10753189", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); i++)\n#define rep2(i, s, n) for (int i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<int> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<int> vec) {\n return *max_element(begin(vec), begin(vec));\n}\n\nvoid solve() {\n struct Node {\n int parent = -1;\n vector<int> child;\n int depth = 0;\n\n void add_child(int num) {\n child.push_back(num);\n }\n };\n\n ll n;\n cin >> n;\n vector<Node> tree(n);\n\n // 入力を受け取って、treeに格納する\n ll id, k, num;\n rep(i, n) {\n cin >> id >> k;\n rep(j, k) {\n cin >> num;\n tree[num].parent = id;\n tree[id].add_child(num);\n }\n }\n\n rep(i, n) {\n // 節点の深さを計算する\n ll d = 0;\n ll u = i;\n while (tree[u].parent != -1) {\n u = tree[u].parent;\n d++;\n }\n\n string type;\n if (tree[i].parent == -1) {\n type = \"root\";\n }\n else if (tree[i].child.size() == 0) {\n type = \"leaf\";\n }\n else {\n type = \"internal node\";\n }\n\n // 結果の出力\n cout << \"node \" << i << \": parent = \" << tree[i].parent << \", depth = \" << d << \", \" << type << \", \";\n cout << \"[\";\n rep(j, tree[i].child.size()) {\n if (j+1 == tree[i].child.size()) {\n cout << tree[i].child[j];\n }\n else {\n cout << tree[i].child[j] << \", \";\n }\n }\n cout << \"]\" << endl;\n }\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 8080, "score_of_the_acc": -0.6024, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_7_A_10739060", "code_snippet": "#define _USE_MATH_DEFINES\n#include<iostream>\n#include<string>\n#include<sstream>\n#include<vector>\n#include <algorithm>\n#include<cmath>\n#include <cassert>\n#include<bitset>\n#include<queue>\n#include<functional>\n#include<utility>\n#include<chrono>\n#include<random>\n#include <climits>\n#include<map>\n#include<set>\n#include<list>\n#include<stack>\n#include <iomanip>\n#include<stdio.h>\n#include<math.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define MAX 200000\n#define INFTY (1<<30)\ntypedef long long ll;\n\nstruct Node {\n\tint p, l, r;\n};\n\nNode T[MAX];\n\nint n, D[MAX];\n\nvoid depth(int u,int d) {\n\tD[u] = d;\n\tif (T[u].l != -1) {\n\t\tdepth(T[u].l, d + 1);\n\t}\n\n\tif (T[u].r != -1) {\n\t\tdepth(T[u].r, d);\n\t}\n}\n\nvoid print(int i) {\n\tcout << \"node \" << i << \": parent = \" << T[i].p << \", depth = \" << D[i] << \", \";\n\tif (T[i].p == -1) {\n\t\tcout << \"root, [\";\n\n\t}\n\telse if (T[i].l != -1) {\n\t\tcout << \"internal node, [\";\n\t}\n\telse {\n\t\tcout << \"leaf, [\";\n\t}\n\tint c;\n\tfor (int j = 0, c = T[i].l; c != -1; j++, c = T[c].r) {\n\t\tif (j)cout << \", \";\n\t\tcout << c;\n\t}\n\tcout << \"]\";\n}\n\nint main() {\n\tcin >> n;\n\tint num,size;\n\trep(i, n) {\n\t\tT[i].p = T[i].l = T[i].r = -1;\n\t}\n\trep(i, n) {\n\t\tcin >> num >> size;\n\t\tif (size == 0)continue;\n\t\tint sum, presum;\n\t\trep(j, size) {\n\t\t\tcin >> sum;\n\t\t\tT[sum].p = num;\n\t\t\tif (j == 0) {\n\t\t\t\tT[num].l = sum;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tT[presum].r = sum;\n\t\t\t}\n\t\t\tpresum = sum;\n\t\t}\n\t}\n\tint root;\n\trep(i, n) {\n\t\tif (T[i].p == -1)root = i;\n\t}\n\n\tdepth(root, 0);\n\n\trep(i, n) {\n\t\tprint(i);\n\t\tcout << endl;\n\t}\n\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 4740, "score_of_the_acc": -0.3611, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_7_A_10724077", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\n#define MAX 100000\n#define NIL -1\n\nstruct Node {\n int p, l, r;\n};\n\nint D[MAX];\nNode T[MAX];\n\nvoid depth(int u, int p) {\n D[u] = p;\n if (T[u].r != NIL) depth(T[u].r, p);\n if (T[u].l != NIL) depth(T[u].l, p+1);\n}\n\nvoid printChildren(int u) {\n int c = T[u].l;\n cout << \"[\";\n int i = 0;\n while (c != NIL) {\n if (i) cout << \", \";\n cout << c;\n c = T[c].r;\n i++;\n }\n cout << \"]\" << endl;\n}\n\nint main() {\n int n, id, k, c, old_c, root;\n root = NIL;\n cin >> n;\n for (int i = 0; i < n; i++) {\n T[i].l = T[i].r = T[i].p = NIL;\n }\n for (int i = 0; i < n; i++) {\n cin >> id >> k;\n for (int j = 0; j < k; j++) {\n cin >> c;\n if (j == 0) T[id].l = c;\n else T[old_c].r = c;\n old_c = c;\n T[c].p = id;\n }\n }\n\n for (int i = 0; i < n; i++) {\n if (T[i].p == NIL) root = i;\n }\n depth(root, 0);\n\n string type;\n for (int i = 0; i < n; i++) {\n if (T[i].p == NIL) type = \"root\";\n else if (T[i].l == NIL) type = \"leaf\";\n else type = \"internal node\";\n cout << \"node \" << i << \": parent = \" << T[i].p << \", depth = \" << D[i] << \", \" << type << \", \";\n printChildren(i);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 8024, "score_of_the_acc": -0.7295, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_7_A_10724055", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\n#define MAX 100000\n#define NIL -1\n\nstruct Node {\n int parent;\n int left;\n int right;\n};\n\nNode T[MAX];\nint D[MAX]; // depth\n\nvoid setDepth(int u, int d) {\n D[u] = d;\n if (T[u].left != NIL) setDepth(T[u].left, d + 1); // 子は深さ+1\n if (T[u].right != NIL) setDepth(T[u].right, d); // 兄弟は同じ深さ\n}\n\nvoid printChildren(int u) {\n int c = T[u].left;\n cout << \"[\";\n bool first = true;\n while (c != NIL) {\n if (!first) cout << \", \";\n cout << c;\n first = false;\n c = T[c].right;\n }\n cout << \"]\";\n}\n\nint main() {\n int n;\n cin >> n;\n\n // 初期化\n for (int i = 0; i < n; i++) {\n T[i].parent = NIL;\n T[i].left = NIL;\n T[i].right = NIL;\n }\n\n // 入力の読み込み\n for (int i = 0; i < n; i++) {\n int id, k, c, prev;\n cin >> id >> k;\n for (int j = 0; j < k; j++) {\n cin >> c;\n if (j == 0)\n T[id].left = c;\n else\n T[prev].right = c;\n prev = c;\n T[c].parent = id;\n }\n }\n\n // 根の探索\n int root = -1;\n for (int i = 0; i < n; i++) {\n if (T[i].parent == NIL) {\n root = i;\n break;\n }\n }\n\n // 深さの計算\n setDepth(root, 0);\n\n // 出力\n for (int i = 0; i < n; i++) {\n cout << \"node \" << i << \": parent = \" << T[i].parent << \", depth = \" << D[i] << \", \";\n\n if (T[i].parent == NIL)\n cout << \"root, \";\n else if (T[i].left == NIL)\n cout << \"leaf, \";\n else\n cout << \"internal node, \";\n\n printChildren(i);\n cout << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 4880, "score_of_the_acc": -0.3769, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_7_A_10719007", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nconst int N=1e5+5;\nvector<int>E[N];\nint n,pres[N],dep[N],cnts[N];\nvoid dfs(int u=0,int pre=-1,int d=0){\n pres[u]=pre;\n dep[u]=d;\n for(auto v:E[u]){\n dfs(v,u,d+1);\n }\n}\nvoid solve(){\n cin>>n;\n for(int i=0;i<n;i++) cnts[i]=0;\n for(int i=0;i<n;i++){\n int id;cin>>id;\n int k;cin>>k;\n for(int j=0;j<k;j++){\n int v;cin>>v;\n cnts[v]++;\n E[id].push_back(v);\n }\n }\n int root=-1;\n for(int i=0;i<n;i++) if(cnts[i]==0) root=i;\n dfs(root);\n for(int i=0;i<n;i++){\n cout<<\"node \"<<i<<\": parent = \"<<pres[i]<<\", depth = \"<<dep[i]<<\", \";\n if(i==root) cout<<\"root\";\n else if(E[i].empty()) cout<<\"leaf\";\n else cout<<\"internal node\";\n cout<<\", [\";\n bool first=true;\n for(auto v:E[i]){\n if(first) first=false;\n else cout<<\", \";\n cout<<v;\n }\n cout<<\"]\"<<endl;\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 9248, "score_of_the_acc": -0.5334, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_7_A_10712499", "code_snippet": "#define _USE_MATH_DEFINES\n#include<iostream>\n#include<string>\n#include<sstream>\n#include<vector>\n#include <algorithm>\n#include<cmath>\n#include <cassert>\n#include<bitset>\n#include<queue>\n#include<functional>\n#include<utility>\n#include<chrono>\n#include<random>\n#include <climits>\n#include<map>\n#include<set>\n#include<list>\n#include<stack>\n#include <iomanip>\n#include<stdio.h>\n#include<math.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define MAX 200000\n#define INFTY (1<<30)\n#define NIL -1\ntypedef long long ll;\n\nstruct Node {\n\tint parent, l, r;\n};\n\nNode T[MAX];\n\nint n, D[MAX];\n\nvoid rec(int u, int p) {\n\tD[u] = p;\n\tif (T[u].l != NIL)rec(T[u].l, p + 1);\n\tif (T[u].r != NIL)rec(T[u].r, p);\n}\n\nvoid print(int num) {\n\tcout << \"node \" << num << \": parent = \";\n\tif (T[num].parent == NIL) {\n\t\tcout << T[num].parent << \", depth = \" << D[num] << \", root, [\";\n\t}\n\telse {\n\t\tcout << T[num].parent << \", depth = \" << D[num] << \", \";\n\t\tif (T[num].l == NIL)cout << \"leaf, [\";\n\t\telse cout << \"internal node, [\";\n\t}\n\n\tint c = T[num].l;\n\tfor (int i = 0; c != NIL; i++, c = T[c].r) {\n\t\tif (i)cout << \", \";\n\t\tcout << c;\n\t}\n\tcout << \"]\" << endl;\n}\n\nint main() {\n\tcin >> n;\n\n\trep(i, n) {\n\t\tT[i].parent = T[i].l = T[i].r = NIL;\n\t}\n\tint node, size;\n\trep(i, n) {\n\t\tcin >> node >> size;\n\t\tif (size == 0)continue;\n\t\tint sum, presum;\n\t\trep(j, size) {\n\t\t\tcin >> sum;\n\t\t\tif (j == 0) {\n\t\t\t\tT[node].l = sum;\n\t\t\t\tpresum = sum;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tT[presum].r = sum;\n\t\t\t\tpresum = sum;\n\t\t\t}\n\n\t\t\tT[sum].parent = node;\n\t\t}\n\t}\n\tint root;\n\trep(i, n) {\n\t\tif (T[i].parent == NIL)root = i;\n\t}\n\n\trec(root, 0);\n\n\trep(i, n)print(i);\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 5008, "score_of_the_acc": -0.3579, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_7_A_10691877", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct node\n{\n int left = -1, parent = -1, right = -1;\n};\n\nint main()\n{\n int n;\n cin >> n;\n\n node tree[n];\n\n int k, id;\n\n for (int i = 0; i < n; i++)\n {\n cin >> id >> k;\n\n vector<int> c(k);\n for (auto &i : c) cin >> i;\n\n if (k > 0)\n tree[id].left = c[0];\n for (int j = 0; j < k; j++)\n {\n tree[c[j]].parent = id;\n if (j+1 < k)\n tree[c[j]].right = c[j+1];\n }\n }\n\n for (int i = 0; i < n; i++)\n {\n cout << \"node \" << i << \": \";\n cout << \"parent = \" << tree[i].parent << \", \";\n\n int depth = 0;\n for (int p = tree[i].parent; p != -1;)\n {\n depth++;\n p = tree[p].parent;\n }\n cout << \"depth = \" << depth << \", \";\n\n if (tree[i].parent == -1) cout << \"root, \";\n else if (tree[i].left == -1) cout << \"leaf, \";\n else cout << \"internal node, \";\n\n cout << \"[\";\n if (tree[i].left != -1)\n {\n int c = tree[i].left;\n cout << c;\n c = tree[c].right;\n while (c != -1)\n {\n cout << \", \" << c;\n c = tree[c].right;\n }\n }\n cout << \"]\" << endl;\n\n }\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 4492, "score_of_the_acc": -0.3333, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_7_A_10662260", "code_snippet": "#include<iostream>\n\nusing namespace std;\n\n#define N_MAX 100000 // ノード数の最大\n#define NIL -1\n\n// ノードの種類\n#define IS_ROOT 1\n#define IS_INTERNAL_NODE 2\n#define IS_LEAF 3\n\n\ntypedef struct {\n int parent; // 親ノード番号\n int children; // 子ノード\n int sibling; // 兄弟ノード\n} Node;\n\nNode nodes[N_MAX];\n\n\nint depth(int i) {\n // ノードiの深さを算出\n if(nodes[i].parent == NIL){\n return 0;\n }else{\n return 1 + depth(nodes[i].parent);\n }\n}\n\nint find_type(int i){\n // ノードiが\n // root, internal node, leafのどれに該当するか\n if(nodes[i].parent == NIL){\n return IS_ROOT;\n }else if(nodes[i].children == NIL) {\n return IS_LEAF;\n }else\n return IS_INTERNAL_NODE;\n}\n\nint main(){\n\n int n;\n scanf(\"%d\", &n);\n\n int id, k, child;\n\n for(int i=0;i<n;i++){\n nodes[i].parent = NIL;\n nodes[i].children = NIL;\n nodes[i].sibling = NIL;\n }\n\n for(int i=0;i<n;i++){\n scanf(\"%d %d\", &id, &k);\n // cout << \"ID=\" << id << \", degree=\" << k << endl;\n \n int current_node = id;\n for(int j=0; j<k; j++) {\n scanf(\"%d\", &child);\n // cout << \"child=\" << child << endl;\n // 小ノードの親\n nodes[child].parent = id;\n\n if(j == 0) // 最初に入力された子である場合\n nodes[current_node].children = child;\n else\n nodes[current_node].sibling = child;\n current_node = child;\n }\n }\n\n for(int i=0; i<n; i++) {\n cout << \"node \" << i << \": \";\n cout << \"parent = \" << nodes[i].parent << \", \";\n cout << \"depth = \" << depth(i) << \", \";\n switch (find_type(i)) { \n case IS_ROOT:\n cout << \"root\";\n break;\n case IS_INTERNAL_NODE:\n cout << \"internal node\";\n break;\n case IS_LEAF:\n cout << \"leaf\";\n break;\n default:\n break;\n }\n cout << \", [\";\n if(nodes[i].children != NIL){\n cout << nodes[i].children;\n int current_node = nodes[i].children;\n while(nodes[current_node].sibling != NIL){\n cout << \", \" << nodes[current_node].sibling;\n current_node = nodes[current_node].sibling;\n }\n }\n cout << \"]\";\n cout << endl;\n\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 4528, "score_of_the_acc": -0.2707, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_7_A_10659913", "code_snippet": "// 8.2 根付き木\n// 2025.06.28\n\n#include <iostream>\nusing namespace std;\nstatic const int MAX = 100005;\n\nstruct node{int parent, left_child, right_sibling;};\n\nnode tree[MAX]; // 根っこ付き木\nint depths[MAX]; // 深さリスト\n\n\n// 深さを計算する再帰関数 (引数: 節点番号, 深さ)\nvoid culcDepth(int id, int d){\n int child = tree[id].left_child, bro = tree[id].right_sibling;\n\n depths[id] = d; // 深さを記録\n if(child != -1) culcDepth(child, d+1); // 子供の深さは+1\n if(bro != -1) culcDepth(bro, d); // 兄弟の深さは同じ\n}\n\n// 兄弟を出力する関数\nvoid showBros(int id){\n cout << id;\n int bro = tree[id].right_sibling;\n if(tree[id].right_sibling != -1){\n cout << \", \";\n showBros(bro);\n }\n}\n\n// メイン関数\nint main() {\n // 初期化\n int n;\n cin >> n;\n for(int i=0; i<n; ++i) {\n tree[i].parent = -1; // .parent 初期化\n tree[i].left_child = -1; // .light_child 初期化\n tree[i].right_sibling = -1; // .right_sibling 初期化\n }\n\n // 入力\n for(int i=0, id, k; i<n; ++i){\n cin >> id >> k;\n for(int j=0, c, c_bro; j<k; ++j){ // 子供がいる場合\n cin >> c;\n tree[c].parent = id; // c の parent は id (全子供共通)\n if(j==0){ // c が長男の場合は\n tree[id].left_child = c; // id の left_child に長男を追加\n }else{ // c が次男以下の場合は\n tree[c_bro].right_sibling = c; // c_bro(兄貴) の right_sibling に自分を追加\n }\n c_bro = c; // c も兄貴になる\n }\n }\n\n // 深さを計算(根を探して再帰)\n for(int i=0; i<n; ++i){\n if(tree[i].parent == -1){\n culcDepth(i, 0);\n break;\n }\n }\n\n // 出力\n for(int i=0; i<n; ++i){\n cout << \"node \" << i << \": parent = \" << tree[i].parent << \", depth = \" << depths[i] << \", \";\n if(tree[i].parent == -1) {\n cout << \"root, [\";\n }else if(tree[i].left_child == -1){\n cout << \"leaf, [\";\n }else {\n cout << \"internal node, [\";\n }\n if(tree[i].left_child != -1) showBros(tree[i].left_child);\n cout << \"]\" << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5120, "score_of_the_acc": -0.2371, "final_rank": 1 } ]
aoj_ALDS1_8_A_cpp
Binary Search Tree I Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue. Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property: Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$. The following figure shows an example of the binary search tree. For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk. A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left , right , and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively. To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree. 1 insert(T, z) 2 y = NIL // parent of x 3 x = 'the root of T' 4 while x ≠ NIL 5 y = x // set the parent 6 if z.key < x.key 7 x = x.left // move to the left child 8 else 9 x = x.right // move to the right child 10 z.p = y 11 12 if y == NIL // T is empty 13 'the root of T' = z 14 else if z.key < y.key 15 y.left = z // z is the left child of y 16 else 17 y.right = z // z is the right child of y Write a program which performs the following operations to a binary search tree $T$. insert $k$: Insert a node containing $k$ as key into $T$. print : Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given. Output For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key . Constraints The number of operations $\leq 500,000$ ...(truncated)
[ { "submission_id": "aoj_ALDS1_8_A_11016963", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct binary_node\n{\n int id;\n binary_node* parent;\n binary_node* left;\n binary_node* right;\n\n int key;\n\n void set_left(binary_node& l)\n {\n left = &l;\n }\n void set_right(binary_node& r)\n {\n right = &r;\n }\n binary_node(int i, int k)\n {\n id = i;\n key = k;\n parent = nullptr;\n left = nullptr;\n right = nullptr;\n }\n binary_node() : binary_node(-1, -2147483648) {}\n};\n\nstruct binary_tree\n{\n vector<binary_node> nodes;\n int node_count;\n\n void insert(int k)\n {\n binary_node* z = &nodes[node_count];\n z->key = k;\n node_count++;\n\n binary_node* y = nullptr;\n binary_node* x = this->root();\n while(x != nullptr)\n {\n y = x;\n if(z->key < x->key)\n x = x->left;\n else\n x = x->right;\n }\n\n if(y != z)\n {\n z->parent = y;\n if(z->key < y->key)\n y->left = z;\n else\n y->right = z;\n }\n }\n\n binary_node* root()\n {\n for(int i = 0; i < node_count; i++)\n if(nodes[i].parent == nullptr)\n return &nodes[i];\n exit(-1);\n }\n\n void preorder_walk(binary_node* n)\n {\n cout << \" \" << n->key;\n if(n->left != nullptr)\n preorder_walk(n->left);\n if(n->right != nullptr)\n preorder_walk(n->right);\n }\n void preorder_walk()\n {\n preorder_walk(this->root());\n cout << endl;\n }\n void inorder_walk(binary_node* n)\n {\n if(n->left != nullptr)\n inorder_walk(n->left);\n cout << \" \" << n->key;\n if(n->right != nullptr)\n inorder_walk(n->right);\n }\n void inorder_walk()\n {\n inorder_walk(this->root());\n cout << endl;\n }\n\n binary_tree(int n)\n {\n node_count = 0;\n for(int i = 0; i < n; i++)\n nodes.push_back(binary_node(i,-2147483648));\n }\n binary_tree() : binary_tree(0) {};\n};\n\nint main()\n{\n int q;\n cin >> q;\n\n binary_tree t = binary_tree(q);\n\n for(int query = 0; query < q; query++)\n {\n string s;\n cin >> s;\n if(s == \"insert\")\n {\n int k;\n cin >> k;\n t.insert(k);\n }\n if(s == \"print\")\n {\n t.inorder_walk();\n t.preorder_walk();\n }\n }\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 24952, "score_of_the_acc": -1.6898, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_8_A_11008129", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\nstruct tree {\n // ここでは無駄なものを削除し、keyを追加した\n ll id = -1, parent=-1, key=-1, right=-1, left=-1;\n};\n\n// この関数ではvectorの最後の場所にparentとkeyとrightとleftを正しく設定する\nvoid insert(vector<tree> &binary_tree, ll root, ll target, ll key) {\n // 右側の木へ移動する\n if (binary_tree[root].key < key) {\n if (binary_tree[root].right == -1) {\n binary_tree[root].right = target;\n binary_tree[target].parent = root;\n return;\n }\n else {\n insert(binary_tree, binary_tree[root].right, target, key);\n }\n }\n // 左側の木へ移動する\n else if (binary_tree[root].key > key) {\n if (binary_tree[root].left == -1) {\n binary_tree[root].left = target;\n binary_tree[target].parent = root;\n }\n else {\n insert(binary_tree, binary_tree[root].left, target, key);\n }\n }\n}\n\n// 木の先行順巡回\nvoid preorder_tree_walk(vector<tree> &binary_tree, ll root) {\n cout << \" \" << binary_tree[root].key;\n if (binary_tree[root].left != -1) preorder_tree_walk(binary_tree, binary_tree[root].left);\n if (binary_tree[root].right != -1) preorder_tree_walk(binary_tree, binary_tree[root].right);\n return;\n}\n// 木の中間順巡回\nvoid inorder_tree_walk(vector<tree> &binary_tree, ll root) {\n if (binary_tree[root].left != -1) inorder_tree_walk(binary_tree, binary_tree[root].left);\n cout << \" \" << binary_tree[root].key;\n if (binary_tree[root].right != -1) inorder_tree_walk(binary_tree, binary_tree[root].right);\n return;\n}\n\n// main\nvoid solve() {\n ll m;\n cin >> m;\n ll used = -1, root = 0;\n vector<tree> binary_tree;\n while (m--) {\n string type;\n cin >> type;\n if (type == \"insert\") {\n ll k;\n cin >> k;\n tree temptree;\n binary_tree.push_back(temptree);\n ++used;\n binary_tree[used].id = used;\n binary_tree[used].key = k;\n if (used != 0) insert(binary_tree, root, used, k);\n }\n else if (type == \"print\") {\n inorder_tree_walk(binary_tree, root);\n cout << endl;\n preorder_tree_walk(binary_tree, root);\n cout << endl;\n }\n }\n\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 290, "memory_kb": 25568, "score_of_the_acc": -1.5015, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_8_A_10994035", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n int key;\n int left, right, parent;\n};\n\nconst int MAXN = 500000 + 5;\nNode tree[MAXN];\nint root = 0, tot = 0;\n\nvoid insert_key(int k) {\n int y = 0, x = root;\n int z = ++tot;\n tree[z].key = k;\n tree[z].left = tree[z].right = tree[z].parent = 0;\n\n while (x != 0) {\n y = x;\n if (k < tree[x].key)\n x = tree[x].left;\n else\n x = tree[x].right;\n }\n\n tree[z].parent = y;\n if (y == 0)\n root = z;\n else if (k < tree[y].key)\n tree[y].left = z;\n else\n tree[y].right = z;\n}\n\nvoid inorder(int u) {\n if (u == 0) return;\n inorder(tree[u].left);\n cout << \" \" << tree[u].key;\n inorder(tree[u].right);\n}\n\nvoid preorder(int u) {\n if (u == 0) return;\n cout << \" \" << tree[u].key;\n preorder(tree[u].left);\n preorder(tree[u].right);\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n, x;\n string op;\n cin >> n;\n while (n--) {\n cin >> op;\n if (op == \"insert\") {\n cin >> x;\n insert_key(x);\n } else {\n inorder(root);\n cout << \"\\n\";\n preorder(root);\n cout << \"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 11184, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_8_A_10994022", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node\n{\n int key;\n node *left, *right, *parent;\n};\nnode *root, *NIL;\nvoid insert(int k)\n{\n node *y = NIL;\n node *x = root;\n node *z;\n z=(node *)malloc(sizeof(node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n while (x != NIL)\n {\n y = x;\n if (z->key < x->key)\n {\n x = x->left;\n }\n else\n {\n x = x->right;\n }\n }\n z->parent = y;\n if (y == NIL)\n root = z;\n else\n {\n if (z->key < y->key)\n {\n y->left = z;\n }\n else\n {\n y->right = z;\n }\n }\n}\nvoid inorder(node *u)\n{\n if (u == NIL)\n return;\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\nvoid preoder(node *u)\n{\n if (u == NIL)\n return;\n cout << \" \" << u->key;\n preoder(u->left);\n preoder(u->right);\n}\nint main()\n{\n int n, i, x;\n string op;\n cin >> n;\n while (n--)\n {\n cin >> op;\n if (op == \"insert\")\n {\n cin >> x;\n insert(x);\n }\n else\n {\n inorder(root);\n cout << endl;\n preoder(root);\n cout << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 26788, "score_of_the_acc": -1.8969, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_8_A_10988457", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstdio>\n\nstruct Node {\n int key;\n Node *left, *right, *parent;\n};\n\nNode *root = nullptr;\nNode *NIL = nullptr;\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z = new Node{k, NIL, NIL, nullptr};\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key)\n x = x->left;\n else\n x = x->right;\n }\n z->parent = y;\n\n if (y == NIL)\n root = z;\n else if (z->key < y->key)\n y->left = z;\n else\n y->right = z;\n}\n\nvoid inorder(Node *u) {\n if (u == NIL) return;\n inorder(u->left);\n std::printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == NIL) return;\n std::printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int n, x;\n std::string com;\n\n NIL = nullptr;\n root = NIL;\n\n std::scanf(\"%d\", &n);\n for (int i = 0; i < n; ++i) {\n std::cin >> com;\n if (com == \"insert\") {\n std::scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n std::printf(\"\\n\");\n preorder(root);\n std::printf(\"\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 26980, "score_of_the_acc": -1.6818, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_8_A_10958552", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *parent, *left, *right;\n};\n\nNode* root = nullptr;\n\nvoid insert(Node* z) {\n Node* y = nullptr;\n Node* x = root;\n\n while (x != nullptr) {\n y = x;\n if (z->key < x->key) x = x->left;\n else x = x->right;\n }\n\n z->parent = y;\n\n if (y == nullptr) {\n root = z;\n } else if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n}\n\nvoid inorder(Node* u) {\n if (u == nullptr) return;\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\n\nvoid preorder(Node* u) {\n if (u == nullptr) return;\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int m;\n cin >> m;\n\n for (int i = 0; i < m; ++i) {\n string cmd;\n cin >> cmd;\n\n if (cmd == \"insert\") {\n int k;\n cin >> k;\n Node* z = new Node();\n z->key = k;\n z->left = z->right = z->parent = nullptr;\n insert(z);\n } \n else if (cmd == \"print\") {\n inorder(root);\n cout << \"\\n\";\n preorder(root);\n cout << \"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 26828, "score_of_the_acc": -1.3995, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_8_A_10947275", "code_snippet": "#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *parent, *left, *right;\n};\n\nNode *root;\n\nvoid insert (int k) {\n Node *x = root;\n Node *y = nullptr;\n Node *z;\n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = nullptr;\n z->right = nullptr;\n\n while ( x != nullptr ) {\n y = x;\n if ( z->key < x->key ) {\n x = x->left;\n }\n else {\n x = x->right;\n }\n }\n if ( y == nullptr ) {\n root = z;\n }\n else if ( z->key < y->key ) {\n y->left = z;\n }\n else {\n y->right = z;\n }\n}\n\nvoid inorder(Node *u) {\n if (u == nullptr) return;\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == nullptr) return;\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int m, k;\n cin >> m;\n string com;\n for (int i = 0; i < m; i++) {\n cin >> com;\n if ( com == \"insert\" ) {\n cin >> k;\n insert(k);\n }\n else if ( com == \"print\" ) {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 26876, "score_of_the_acc": -1.9025, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_8_A_10930153", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#define max 50000\ntypedef struct Node{\n int m;\n Node *p,*l,*r;\n}tree;\nint n;\ntree *root=NULL;\nvoid preorder(tree *a){\n if(a==NULL) return;\n printf(\" %d\",a->m);\n preorder(a->l);\n preorder(a->r);\n}\nvoid inorder(tree *a){\n if(a==NULL) return;\n inorder(a->l);\n printf(\" %d\",a->m);\n inorder(a->r);\n}\nvoid insert(int k){\n tree *b=NULL;\n tree *c=root;\n tree *w;\n w=(tree*)malloc(sizeof(tree));//分配了内存,结束后还存在\n w->m=k;\n w->l=NULL;\n w->r=NULL;\n while(c!=NULL){\n b=c;//设置父节点\n if(w->m<c->m){\n c=c->l;\n }else c=c->r;\n }\n w->p=b;\n if(b==NULL){\n root=w;\n }else if(b->m>w->m){\n b->l=w;\n }else if(b->m<w->m){\n b->r=w;\n }\n}\nint main(){\n scanf(\"%d\",&n);\n char q[20];\n int e;\n for(int i=0;i<n;i++){\n scanf(\"%s\",q);\n if(q[0]=='i'){\n scanf(\"%d\",&e);\n insert(e);\n }\n if(q[0]=='p'){\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 26416, "score_of_the_acc": -1.3734, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_8_A_10896829", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n#include <chrono>\n#include <complex>\n#include <cmath>\n#include <unistd.h>\n#define pc_u putchar\n#pragma GCC target (\"avx\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n#define rep(i,a,b) for(it i=(it)(a);i<(it)b;i++)\n#define rep2(i,a,b,c) for(it i=(it)(a);i<(it)b;i+=(it)c)\n#define repp(i,a,b) for(it i=(it)(a);i<=(it)b;i++)\n#define repp2(i,a,b,c) for(it i=(it)(a);i<=(it)b;i+=(it)c)\n#define irep(i,a,b) for(int i=(int)(a);i<(int)b;i++)\n#define irep2(i,a,b,c) for(int i=(int)(a);i<(int)b;i+=c)\n#define irepp(i,a,b) for(int i=(int)(a);i<=(int)b;i++)\n#define irepp2(i,a,b,c) for(int i=(int)(a);i<=(int)b;i+=c)\n#define nrep(i,a,b) for(it i=(it)(a)-1;i>=(it)b;i--)\n#define nrepp(i,a,b) for(it i=(it)(a);i>=(it)b;i--)\n#define inrep(i,a,b) for(int i=(int)(a)-1;i>=(int)b;i--)\n#define inrepp(i,a,b) for(int i=(int)(a);i>=(int)b;i--)\n#define inrep2(i,a,b,c) for(int i=(int)(a)-1;i>=(int)b;i-=c)\n#define inrepp2(i,a,b,c) for(int i=(int)(a);i>=(int)b;i-=c)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define Min(x) *min_element(all(x))\n#define Max(x) *max_element(all(x))\n#define popcount(x) __builtin_popcountll(x)\n#define moda 998244353LL\n#define modb 1000000007LL\n#define modc 968244353LL\n#define dai 2502502502502502502LL\n#define sho -dai\n#define aoi 1e18+1e6\n#define giri 1010000000\n#define en 3.14159265358979\n#define eps 1e-14\n#define fi first\n#define se second\n#define elif else if\ntemplate<typename T> using pq=priority_queue<T>;\ntemplate<typename T> using pqg=priority_queue<T,vector<T>,greater<T>>;\n#define uni(a) a.erase(unique(all(a)),a.end())\nusing it=long long;\nusing itn=int;\nusing un=unsigned long long;\nusing idb=double;\nusing db=long double;\nusing st=string;\nusing ch=char;\nusing bo=bool;\nusing P=pair<it,it>;\nusing ip=pair<int,int>;\nusing vi=vector<it>;\nusing ivi=vector<int>;\nusing ivd=vector<idb>;\nusing vd=vector<db>;\nusing vs=vector<st>;\nusing vc=vector<ch>;\nusing vb=vector<bo>;\nusing vp=vector<P>;\nusing ivp=vector<ip>;\nusing sp=set<P>;\nusing isp=set<ip>;\nusing ss=set<st>;\nusing sca=set<ch>;\nusing si=set<it>;\nusing isi=set<int>;\nusing svi=set<vi>;\nusing svb=set<vb>;\nusing vvi=vector<vi>;\nusing ivvi=vector<ivi>;\nusing ivvd=vector<ivd>;\nusing vvd=vector<vd>;\nusing vvs=vector<vs>;\nusing vvb=vector<vb>;\nusing vvc=vector<vc>;\nusing vvp=vector<vp>;\nusing ivvp=vector<ivp>;\nusing vsi=vector<si>;\nusing ivsi=vector<isi>;\nusing isvi=set<ivi>;\nusing vsc=vector<sca>;\nusing vsp=vector<sp>;\nusing ivsp=vector<isp>;\nusing vvsi=vector<vsi>;\nusing ivvsi=vector<ivsi>;\nusing vvsp=vector<vsp>;\nusing ivvsp=vector<ivsp>;\nusing svvb=set<vvb>;\nusing vvvi=vector<vvi>;\nusing ivvvi=vector<ivvi>;\nusing ivvvd=vector<ivvd>;\nusing vvvd=vector<vvd>;\nusing vvvb=vector<vvb>;\nusing ivvvp=vector<ivvp>;\nusing vvvp=vector<vvp>;\nusing vvvvi=vector<vvvi>;\nusing ivvvvi=vector<ivvvi>;\nusing vvvvd=vector<vvvd>;\nusing vvvvb=vector<vvvb>;\nusing ivvvvp=vector<ivvvp>;\nusing vvvvp=vector<vvvp>;\nusing ivvvvvi=vector<ivvvvi>;\nusing vvvvvi=vector<vvvvi>;\nusing ivvvvvvi=vector<ivvvvvi>;\nusing vvvvvvi=vector<vvvvvi>;\nusing ivvvvvvvi=vector<ivvvvvvi>;\nusing vvvvvvvi=vector<vvvvvvi>;\nusing vvvvvvvvi=vector<vvvvvvvi>;\nconst int dx[8]={0,1,0,-1,1,1,-1,-1};\nconst int dy[8]={1,0,-1,0,1,-1,1,-1};\nst abc=\"abcdefghijklmnopqrstuvwxyz\";\nst ABC=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nst num=\"0123456789\";\nst mb=\"xo\";\nst MB=\"XO\";\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\ntemplate<class T> using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\nnamespace {\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const pair<T, U> &p) {\n os << p.first << \" \" << p.second;\n return os;\n}\ntemplate <typename T, typename U>\nistream &operator>>(istream &is, pair<T, U> &p) {\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v) {\n int s = (int)v.size();\n for (int i = 0; i < s; i++) os << (i ? \" \" : \"\") << v[i];\n return os;\n}\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v) {\n for (auto &x : v) is >> x;\n return is;\n}\n\nistream &operator>>(istream &is, __int128_t &x) {\n string S;\n is >> S;\n x = 0;\n int flag = 0;\n for (auto &c : S) {\n if (c == '-') {\n flag = true;\n continue;\n }\n x *= 10;\n x += c - '0';\n }\n if (flag) x = -x;\n return is;\n}\n\nistream &operator>>(istream &is, __uint128_t &x) {\n string S;\n is >> S;\n x = 0;\n for (auto &c : S) {\n x *= 10;\n x += c - '0';\n }\n return is;\n}\n\nostream &operator<<(ostream &os, __int128_t x) {\n if (x == 0) return os << 0;\n if (x < 0) os << '-', x = -x;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\nostream &operator<<(ostream &os, __uint128_t x) {\n if (x == 0) return os << 0;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\n\nvoid input() {}\ntemplate <typename T, class... U>\nvoid input(T &t, U &...u) {\n cin >> t;\n input(u...);\n}\ntemplate <typename T, class... U>\nvoid input1(T &t, U &...u) {\n input(u...);\n}\nvoid print() { cout << \"\\n\"; }\ntemplate <typename T, class... U, char sep = ' '>\nvoid print(const T &t, const U &...u) {\n cout << t;\n if (sizeof...(u)) cout << sep;\n print(u...);\n}\ntemplate <typename T, class... U, char sep = ' '>\nvoid print1(const T &t, const U &...u) {\n print(u...);\n}\n\nstruct IoSetupNya {\n IoSetupNya() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n cerr << fixed << setprecision(7);\n }\n} iosetupnya;\n\n} //namespace Nyaan\n\ntemplate<typename T>\nT Sum(vector<T> &a){\n T s=0;\n for(auto i:a)s+=i;\n return s;\n}\n\ntemplate<typename T>\nT Sum(vector<T> &a,int l,int r){\n T s=0;\n irep(i,l,r)s+=a[i];\n return s;\n}\n\ntemplate <typename T>\nvoid dec(vector<T> &t){\n for(auto &i:t)i--;\n}\n\ntemplate <typename T>\nvoid inc(vector<T> &t,T k=1){\n for(auto &i:t)i+=k;\n}\n\ntemplate <typename T>\nvector<T> make_vec(int n,T t){\n vector<T> g(n);\n for(auto &i:g)i=t;\n return g;\n}\n\ntemplate <typename T>\nvector<T> subvec(vector<T> a,int f,int l){\n vector<T> g(l);\n irep(i,f,f+l)g[i-f]=a[i];\n return g;\n}\n\ntemplate<typename T>\nT gcda(T a,T b){\n if(!a||!b)return max(a,b);\n while(a%b&&b%a){\n if(a>b)a%=b;\n else b%=a;\n }\n return min(a,b);\n}\n\nit lcma(it a,it b){\n return a/gcda(a,b)*b;\n}\n\ndb distance(db a,db b,db c,db d){return sqrt((a-c)*(a-c)+(b-d)*(b-d));}\n\nbo outc(int h,int w,int x,int y){\n return (x<0||x>=h||y<0||y>=w);\n}\n\ntemplate<typename T>\nvector<vector<T>> nep(vector<T> a){\n vector<vector<T>> e;\n sort(all(a));\n do{\n e.emplace_back(a);\n }while(next_permutation(all(a)));\n return e;\n}\n\ntemplate<typename T>\nvoid chmin(T &a,T b){a=min(a,b);}\ntemplate<typename T>\nvoid chmax(T &a,T b){a=max(a,b);}\n\nvoid yn(bo a){print(a?string(\"Yes\"):string(\"No\"));}\nvoid YN(bo a){print(a?string(\"YES\"):string(\"NO\"));}\n\nstruct dsu1{\n ivi par,siz;\n dsu1(int n){\n init(n);\n }\n void init(int n){\n irep(i,0,n){\n par.emplace_back(i);\n }\n siz.resize(n,1);\n }\n int leader(int u){\n if(par[u]==u)return u;\n return par[u]=leader(par[u]);\n }\n void merge(int u,int v){\n int ru=leader(u),rv=leader(v);\n if(ru==rv)return;\n if(size(ru)<size(rv))swap(ru,rv);\n siz[ru]+=siz[rv];\n par[rv]=ru;\n }\n bool same(int u,int v){\n return leader(u)==leader(v);\n }\n int size(int u){\n return siz[leader(u)];\n }\n};\n\nstruct edge{\n int f;\n int t;\n it l;\n};\nvoid input(edge &a){input(a.f,a.t,a.l);}\nbo comppppp(edge &a,edge &b){return a.l<b.l;}\n\nit minspantree(vector<edge> &e,int n){\n /*\n 与えられた辺を持つグラフの最小全域木を求める\n 存在する場合はその答えを 存在しないならinf\n 計算量はO(MlogM+N)くらい\n */\n vector<edge> g=e;sort(all(g),comppppp);\n it ans=0;\n dsu1 uf(n);\n for(auto i:g){\n if(!uf.same(i.f,i.t)){\n uf.merge(i.f,i.t);\n ans+=i.l;\n }\n }\n if(uf.size(0)==n)return ans;\n return dai;\n}\n\n/*#include <atcoder/all>\nusing namespace atcoder;\nusing mints=modint998244353;\nusing mint=modint;\nusing minto=modint1000000007;\nusing vm=vector<mint>;\nusing vms=vector<mints>;\nusing vmo=vector<minto>;\nusing vvm=vector<vm>;\nusing vvms=vector<vms>;\nusing vvmo=vector<vmo>;\nusing vvvm=vector<vvm>;\nusing vvvms=vector<vvms>;\nusing vvvmo=vector<vvmo>;\nusing vvvvm=vector<vvvm>;\nusing vvvvms=vector<vvvms>;\nusing vvvvmo=vector<vvvmo>;\nusing vvvvvm=vector<vvvvm>;\nusing vvvvvms=vector<vvvvms>;\nusing vvvvvmo=vector<vvvvmo>;\nusing vvvvvvm=vector<vvvvvm>;\nusing vvvvvvms=vector<vvvvvms>;\nusing vvvvvvmo=vector<vvvvvmo>;\nusing vvvvvvvms=vector<vvvvvvms>;\nusing vvvvvvvmo=vector<vvvvvvmo>;*/\n\n/*総和をもとめるセグ木\nstruct nod{\n it val;\n nod(it v=0):val(v){}\n};\n\nnod op(nod a,nod b){return nod(a.val+b.val);}\nnod e(){return nod(0);}\n\nstruct act{\n it a;\n act(it e=0):a(e){}\n};\n\nnod mapping(act f,nod x){return nod(f.a+x.val);}\nact comp(act f,act g){return act(f.a+g.a);}\nact id(){return act(0);}*/\n//#define endl '\\n'\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n\ntemplate<typename T> struct binarytree{\n private:\n struct node {\n T v;\n node *l;\n node *r;\n node *p;\n // 初め、左右の子は nullptr となっている\n node(T v) : v(v), l(nullptr), r(nullptr), p(nullptr) {}\n };\n public:\n node *root=nullptr;\n void insert(T x){\n node *root_tmp=root;\n node *elem;\n elem=(node *)malloc(sizeof(node));\n elem->v=x;\n elem->l=nullptr;\n elem->r=nullptr;\n node *prev=nullptr;\n while(root_tmp!=nullptr){\n prev=root_tmp;\n if(x<root_tmp->v)root_tmp=root_tmp->l;\n else root_tmp=root_tmp->r;\n }\n elem->p=prev;\n if(elem->p==nullptr)root=elem;\n elif(elem->p->v>elem->v)elem->p->l=elem;\n else elem->p->r=elem;\n }\n void preorder(node *u){\n if(u==nullptr)return;\n cout<<' '<<(u->v);\n preorder(u->l);\n preorder(u->r);\n }\n void inorder(node *u){\n if(u==nullptr)return;\n inorder(u->l);\n cout<<' '<<(u->v);\n inorder(u->r);\n }\n};\n\nvoid solve(){\n int q;input(q);\n binarytree<int> e;\n while(q--){\n st s;input(s);\n if(s==\"insert\"){\n int x;input(x);\n e.insert(x);\n }\n else{\n e.inorder(e.root);cout<<endl;\n e.preorder(e.root);cout<<endl;\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int t=1;//input(t);\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 260, "memory_kb": 26828, "score_of_the_acc": -1.4449, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_8_A_10849685", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <cmath>\n#include <cstdlib>\nusing namespace std;\n\n\nstruct Node {\n int v;\n Node* l;\n Node* r;\n};\n\nNode* root = NULL;\n\nvoid insert(int v) {\n if (!root) {\n root = new Node;\n root -> v = v;\n root -> l = NULL;\n root -> r = NULL;\n return;\n }\n\n Node* par = NULL;\n Node* x = root;\n while (x) {\n par = x;\n if (v < x -> v) {\n x = x -> l;\n } else {\n x = x -> r;\n }\n }\n if (v < par->v) {\n par -> l = new Node;\n Node* p = par -> l;\n p -> v = v;\n p -> l = NULL;\n p -> r = NULL;\n } else {\n par -> r = new Node;\n Node* p = par -> r;\n p -> v = v;\n p -> l = NULL;\n p -> r = NULL;\n }\n}\n\nvoid preOrder(Node* root) {\n if (root == NULL) return ;\n printf(\" %d\", root -> v);\n preOrder(root -> l);\n preOrder(root -> r);\n}\n\nvoid inOrder(Node* root) {\n if (root == NULL) return ;\n inOrder(root -> l);\n printf(\" %d\", root -> v);\n inOrder(root -> r);\n}\n\n\nint main() {\n //freopen(\"in.txt\", \"r\", stdin);\n //freopen(\"out.txt\", \"w\", stdout);\n int n;\n int num;\n char s[10];\n scanf(\"%d\", &n);\n for (int i = 0; i < n; i++) {\n scanf(\"%s\", s);\n if (s[0] == 'i') {\n scanf(\"%d\", &num);\n insert(num);\n } else if (s[0] == 'p') {\n inOrder(root);\n printf(\"\\n\");\n preOrder(root);\n printf(\"\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 19196, "score_of_the_acc": -0.7345, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_8_A_10818356", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); i++)\n#define rep2(i, s, n) for (int i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<int> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<int> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\nstruct node {\n int key;\n node *right, *left, *parent;\n};\n\nnode *root, *NIL;\n\nvoid insert(int k) {\n node *y = NIL;\n node *x = root;\n node *z;\n\n z = (node *)malloc(sizeof(node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n z->parent = y;\n if (y == NIL) {\n root = z;\n } else {\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nvoid inorder(node *u) {\n if (u == NIL) {\n return;\n }\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\nvoid preorder(node *u) {\n if (u == NIL) {\n return;\n }\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\n\n\nvoid solve() {\n ll n;\n cin >> n;\n rep(i, n) {\n string cmd;\n cin >> cmd;\n if (cmd == \"insert\") {\n ll target;\n cin >> target;\n insert(target);\n }\n else if (cmd == \"print\") {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 26880, "score_of_the_acc": -1.6755, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_8_A_10785550", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\nstruct Node {\n long long key;\n Node *left, *right, *parent;\n Node(long long k) : key(k), left(nullptr), right(nullptr), parent(nullptr) {}\n};\n\nclass BST {\n Node* root;\n\n void insert(long long key) {\n Node* z = new Node(key);\n Node* y = nullptr; // Parent of x\n Node* x = root; // Start at root\n\n // Traverse to find the insertion point\n while (x != nullptr) {\n y = x; // Set parent\n if (z->key < x->key)\n x = x->left; // Move to left child\n else\n x = x->right; // Move to right child\n }\n\n z->parent = y; // Set z's parent\n\n if (y == nullptr) // Tree is empty\n root = z;\n else if (z->key < y->key)\n y->left = z; // z is left child\n else\n y->right = z; // z is right child\n }\n\n void inorder(Node* node) {\n if (node == nullptr) return;\n inorder(node->left);\n cout << \" \" << node->key;\n inorder(node->right);\n }\n\n void preorder(Node* node) {\n if (node == nullptr) return;\n cout << \" \" << node->key;\n preorder(node->left);\n preorder(node->right);\n }\n\npublic:\n BST() : root(nullptr) {}\n\n void insertKey(long long key) {\n insert(key);\n }\n\n void print() {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n};\n\nint main() {\n BST bst;\n int m;\n cin >> m;\n while (m--) {\n string op;\n cin >> op;\n if (op == \"insert\") {\n long long key;\n cin >> key;\n bst.insertKey(key);\n } else if (op == \"print\") {\n bst.print();\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 370, "memory_kb": 26652, "score_of_the_acc": -1.9338, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_8_A_10776634", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL;\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z;\n\n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n while (x != NIL) {\n y = x;\n if ( z->key < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n\n z->parent = y;\n if (y==NIL) {\n root = z;\n } else {\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nvoid inorder(Node *u) {\n if (u==NIL) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u==NIL) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main()\n{\n int n,i,x;\n string com;\n\n scanf(\"%d\", &n);\n\n for (i=0; i<n; i++) {\n cin >> com;\n if (com==\"insert\") {\n scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 26888, "score_of_the_acc": -1.676, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_8_A_10764520", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nstruct Node{\n int key;\n Node* p;\n Node* left;\n Node* right;\n Node(int k) : key(k), p(nullptr), left(nullptr), right(nullptr) {}\n};\n\n\nNode* insert(Node* &t, Node* z) {\n Node* y = nullptr;\n Node* x = t;\n while(x != nullptr){\n y = x;\n if(z->key < x->key){\n x = x->left;\n }else{\n x = x->right;\n }\n }\n z->p = y;\n if (y == nullptr) {\n t = z;\n } else if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n return t;\n}\n\n\nvoid printInorder(Node* t) {\n if (!t) return;\n printInorder(t->left);\n std::cout << \" \" << t->key;\n printInorder(t->right);\n}\n\nvoid printPreorder(Node* t) {\n if (!t) return;\n std::cout << \" \" << t->key;\n printPreorder(t->left);\n printPreorder(t->right);\n}\n\nint main() {\n int m, k;\n std::string operate;\n std::cin >> m;\n\n Node* root = nullptr;\n\n for (int i = 0; i < m; ++i) {\n std::cin >> operate;\n if (operate == \"insert\") {\n std::cin >> k;\n root = insert(root, new Node(k));\n } else if (operate == \"print\") {\n printInorder(root);\n\tstd::cout << std::endl;\n\tprintPreorder(root);\n\tstd::cout << std::endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 370, "memory_kb": 26496, "score_of_the_acc": -1.9239, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_8_A_10750042", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define loop(a,b) for (int a = 0;a < b;a++)\n#define rep(a,b,c) for(int a = b;a < c;a++)\n#define vec(a) vector<a>\n\nstruct Node{\n int key;\n Node *left,*right,*parent;\n Node(int key):key(key),left(nullptr),right(nullptr),parent(nullptr){};\n};\n\nclass BinarySearchTree{\n private:\n Node* root;\n Node* insert(Node* node,int key){\n Node* z = new Node(key);\n Node* y = nullptr;\n Node* x = root;\n while(x != nullptr){\n y = x;\n if(z->key < x->key) x = x->left;\n else x = x->right;\n }\n z->parent = y;\n if(y == nullptr) root = z;\n else if(z->key < y->key) y->left = z;\n else y->right = z;\n return z;\n }\n void inorder(Node* node){\n if(node == nullptr) return;\n inorder(node->left);\n cout <<\" \"<< node->key;\n inorder(node->right);\n }\n void preorder(Node* node){\n if(node == nullptr) return;\n cout << \" \"<< node->key;\n preorder(node->left);\n preorder(node->right);\n }\n \n Node* find(Node* node,int key){\n while(node != nullptr && node->key != key){\n if(key < node->key) node = node->left;\n else node = node->right;\n }\n return node;\n }\n Node* find_min(Node* node) {\n while (node->left != nullptr) {\n node = node->left;\n }\n return node;\n }\n \n void remove(Node* node,int key){\n Node* z = find(node,key);\n if(z == nullptr) return;\n \n \n if(z->left == nullptr && z->right == nullptr) {\n if(z->parent == nullptr) {\n root = nullptr; \n } else if(z->parent->left == z) {\n z->parent->left = nullptr;\n } else {\n z->parent->right = nullptr;\n }\n delete z;\n }\n else if(z->left == nullptr || z->right == nullptr) {\n Node* child = (z->left != nullptr) ? z->left : z->right;\n \n if(z->parent == nullptr) {\n root = child; \n } else if(z->parent->left == z) {\n z->parent->left = child;\n } else {\n z->parent->right = child;\n }\n \n if(child != nullptr) {\n child->parent = z->parent;\n }\n delete z;\n }\n \n else {\n \n Node* successor = find_min(z->right);\n \n \n z->key = successor->key;\n \n \n if(successor->parent->left == successor) {\n successor->parent->left = successor->right;\n } else {\n successor->parent->right = successor->right;\n }\n \n if(successor->right != nullptr) {\n successor->right->parent = successor->parent;\n }\n delete successor;\n }\n }\n\n public:\n BinarySearchTree():root(nullptr){};\n void print(){\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n void insert(int key){\n insert(root,key);\n }\n bool find(int key){\n Node* node = find(root,key);\n if(node != nullptr) return 1;\n else return 0;\n }\n void remove(int key){\n remove(root,key);\n }\n};\nint main()\n{\n int n;\n cin >> n;\n BinarySearchTree bst;\n loop(i,n){\n string command;\n int key;\n cin >> command;\n if(command == \"insert\"){\n cin >> key;\n bst.insert(key);\n } \n else if(command == \"find\") {\n cin >> key;\n cout << (bst.find(key) ? \"yes\" : \"no\") << endl;\n }\n else if(command == \"print\") {\n bst.print();\n }\n else if(command == \"delete\"){\n cin >> key;\n bst.remove(key);\n } \n }\n}", "accuracy": 1, "time_ms": 380, "memory_kb": 26764, "score_of_the_acc": -1.9863, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_8_A_10739227", "code_snippet": "// ALDS2_1_A\n#include <bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\n\nstruct Node {\n int key;\n Node *parent;\n Node *left, *right;\n Node(int k) : key(k), parent(nullptr), left(nullptr), right(nullptr) {}\n};\n\nvoid Insert(Node*& root, Node* newNode) {\n if(root == nullptr) {\n root = newNode;\n return;\n }\n Node* cur = root;\n while(true) {\n if(newNode->key < cur->key) {\n if(cur->left) cur = cur->left;\n else {\n cur->left = newNode;\n newNode->parent = cur;\n break;\n }\n }\n else {\n if(cur->right) cur = cur->right;\n else {\n cur->right = newNode;\n newNode->parent = cur;\n break;\n }\n }\n }\n}\n\nvoid rightRotate(Node*& root, Node* u) {\n Node* x = u->left;\n if(x == nullptr) return; // 回転できない\n Node* B = x->right;\n\n // xをuの親にする\n x->parent = u->parent;\n if(u->parent == nullptr) root = x;\n else if(u == u->parent->left) u->parent->left = x;\n else u->parent->right = x;\n\n // Bをuの左に接続\n x->left = B;\n if(B) B->parent = u;\n\n // uをxの右に接続\n x->right = u;\n u->parent = x;\n}\n\nvoid inOrder(Node* root) {\n if(root == nullptr) return;\n if(root->left != nullptr) inOrder(root->left);\n cout << \" \" << root->key;\n if(root->right != nullptr) inOrder(root->right);\n}\n\nvoid preOrder(Node* root) {\n if(root == nullptr) return;\n cout << \" \" << root->key;\n if(root->left != nullptr) preOrder(root->left);\n if(root->right != nullptr) preOrder(root->right);\n}\n\nint main() {\n int n;\n cin >> n;\n Node* root = nullptr;\n\n for(int i=0; i<n; ++i) {\n string com;\n cin >> com;\n if(com == \"insert\") {\n int key;\n cin >> key;\n Node* newNode = new Node(key);\n Insert(root, newNode);\n }\n else if(com == \"print\") {\n inOrder(root);\n cout << endl;\n preOrder(root);\n cout << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 380, "memory_kb": 26764, "score_of_the_acc": -1.9863, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_8_A_10719556", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nstruct node{\n int p,l,r,key;\n};\nconst int N=5e5+5;\nnode tree[N];\nint idx=0,root=-1;\nvoid insert(int z){\n int y=-1,x=root;\n while(x!=-1){\n y=x;\n if(tree[z].key<tree[x].key) x=tree[x].l;\n else x=tree[x].r;\n }\n tree[z].p=y;\n if(y==-1){\n root=z;\n }else if(tree[z].key<tree[y].key){\n tree[y].l=z;\n }else{\n tree[y].r=z;\n }\n}\nvoid dfs1(int u=0){\n if(u==-1) return;\n dfs1(tree[u].l);\n cout<<\" \"<<tree[u].key;\n dfs1(tree[u].r);\n}\nvoid dfs2(int u=0){\n if(u==-1) return;\n cout<<\" \"<<tree[u].key;\n dfs2(tree[u].l);\n dfs2(tree[u].r);\n}\nvoid solve(){\n int n;cin>>n;\n for(int i=0;i<n;i++){\n string s;cin>>s;\n if(s==\"insert\"){\n int k;cin>>k;\n int z=idx++;\n tree[z].key=k;\n tree[z].l=tree[z].r=-1;\n insert(z);\n }else{\n dfs1();\n cout<<endl;\n dfs2();\n cout<<endl;\n }\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 19088, "score_of_the_acc": -0.6822, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_8_A_10713850", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\nstruct node{\n int key;\n node *left,*right,*p;\n node(){}\n node(int key):key(key){left=right=p=NULL;};\n};\nnode *root;\nvoid insert(node z){\n node *y=NULL;\n node *x=root;\n while(x!=NULL){\n y=x;\n if(z.key<x->key) x=x->left;\n else x=x->right;\n }\n z.p=y;\n if(y==NULL) root=new node(z);\n else if(z.key<y->key) y->left=new node(z);\n else y->right=new node(z);\n}\nvoid inorderTreeWalk(node *v){\n if(v==NULL) return;\n inorderTreeWalk(v->left);\n cout<<\" \"<<v->key;\n inorderTreeWalk(v->right);\n}\nvoid preorderTreeWalk(node *v){\n if(v==NULL) return;\n cout<<\" \"<<v->key;\n preorderTreeWalk(v->left);\n preorderTreeWalk(v->right);\n}\nsigned main(){\n int n;\n cin>>n;\n root=NULL;\n for(int i=0;i<n;i++){\n string s;\n cin>>s;\n //cout<<(root==NULL?-1:root->key)<<endl;\n if(s==\"print\"){\n inorderTreeWalk(root);\n cout<<endl;\n preorderTreeWalk(root);\n cout<<endl;\n continue;\n }\n int x;\n cin>>x;\n insert(node(x));\n }\n return 0;\n}", "accuracy": 1, "time_ms": 370, "memory_kb": 26764, "score_of_the_acc": -1.9409, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_8_A_10711685", "code_snippet": "#include<cstdio>\n#include<cstdlib>\n#include<string>\n#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL;\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z;\n \n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n \n while ( x != NIL) {\n y = x;\n if (z->key < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n \n z->parent = y;\n if (y == NIL) {\n root = z;\n } else {\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nvoid inorder(Node *u) {\n if (u == NIL) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if ( u == NIL) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int n, i, x;\n string com;\n \n scanf(\"%d\", &n);\n \n for (i = 0; i < n; i++) {\n cin >> com;\n if (com == \"insert\") {\n scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 26884, "score_of_the_acc": -1.6757, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_8_A_10707550", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\nclass Node{\n public:\n Node* right;\n Node* left;\n Node* parent;\n int key;\n};\nclass Tree{\n private:\n Node* root;\n public:\n Tree(){\n root=0;\n }\n void insert(int key);\n void inorder(Node* u);\n void preorder(Node* u);\n void print();\n};\nvoid Tree::insert(int k){\n Node* z=new Node();\n z->right=0;\n z->left=0;\n z->parent=0;\n z->key=k;\n Node* y=0;\n Node* x=root;\n while(x!=0){\n y=x;\n if(z->key<x->key){\n x=x->left;\n }\n else{\n x=x->right;\n }\n }\n z->parent=y;\n if(y==0){\n root=z;\n }\n else if(z->key<y->key){\n y->left=z;\n }\n else{\n y->right=z;\n }\n}\nvoid Tree::inorder(Node* u){\n if(u==0){\n return;\n }\n inorder(u->left);\n cout<<' '<<u->key;\n inorder(u->right);\n}\nvoid Tree::preorder(Node* u){\n if(u==0){\n return;\n }\n cout<<' '<<u->key;\n preorder(u->left);\n preorder(u->right);\n}\nvoid Tree::print(){\n inorder(root);\n cout<<endl;\n preorder(root);\n cout<<endl;\n}\nint main(){\n int m;\n cin>>m;\n Tree T;\n for(int i=0;i<m;i++){\n string com;\n cin>>com;\n if(com==\"insert\"){\n int k;\n cin>>k;\n T.insert(k);\n }\n else if(com==\"print\"){\n T.print();\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 370, "memory_kb": 26780, "score_of_the_acc": -1.9419, "final_rank": 18 } ]
aoj_ALDS1_8_B_cpp
Binary Search Tree II Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. insert $k$: Insert a node containing $k$ as key into $T$. find $k$: Report whether $T$ has a node containing $k$. print : Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print " yes " if $T$ has a node containing $k$, " no " if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key . Constraints The number of operations $\leq 500,000$ The number of print operations $\leq 10$. $-2,000,000,000 \leq key \leq 2,000,000,000$ The height of the binary tree does not exceed 100 if you employ the above pseudo code. The keys in the binary search tree are all different. Sample Input 1 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Sample Output 1 yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.
[ { "submission_id": "aoj_ALDS1_8_B_11017045", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct binary_node\n{\n int id;\n binary_node* parent;\n binary_node* left;\n binary_node* right;\n\n int key;\n\n void set_left(binary_node& l)\n {\n left = &l;\n }\n void set_right(binary_node& r)\n {\n right = &r;\n }\n binary_node(int i, int k)\n {\n id = i;\n key = k;\n parent = nullptr;\n left = nullptr;\n right = nullptr;\n }\n binary_node() : binary_node(-1, -2147483648) {}\n};\n\nstruct binary_tree\n{\n vector<binary_node> nodes;\n int node_count;\n\n void insert(int k)\n {\n binary_node* z = &nodes[node_count];\n z->key = k;\n node_count++;\n\n binary_node* y = nullptr;\n binary_node* x = this->root();\n while(x != nullptr)\n {\n y = x;\n if(z->key < x->key)\n x = x->left;\n else\n x = x->right;\n }\n\n if(y != z)\n {\n z->parent = y;\n if(z->key < y->key)\n y->left = z;\n else\n y->right = z;\n }\n }\n\n bool find(int k)\n {\n if(node_count == 0)\n return false;\n else\n {\n binary_node* x = root();\n while(x != nullptr)\n {\n if(k == x->key)\n return true;\n\n if(k < x->key)\n x = x->left;\n else\n x = x->right;\n }\n return false;\n }\n }\n\n binary_node* root()\n {\n for(int i = 0; i < node_count; i++)\n if(nodes[i].parent == nullptr)\n return &nodes[i];\n exit(-1);\n }\n\n void preorder_walk(binary_node* n)\n {\n cout << \" \" << n->key;\n if(n->left != nullptr)\n preorder_walk(n->left);\n if(n->right != nullptr)\n preorder_walk(n->right);\n }\n void preorder_walk()\n {\n preorder_walk(this->root());\n cout << endl;\n }\n void inorder_walk(binary_node* n)\n {\n if(n->left != nullptr)\n inorder_walk(n->left);\n cout << \" \" << n->key;\n if(n->right != nullptr)\n inorder_walk(n->right);\n }\n void inorder_walk()\n {\n inorder_walk(this->root());\n cout << endl;\n }\n\n binary_tree(int n)\n {\n node_count = 0;\n for(int i = 0; i < n; i++)\n nodes.push_back(binary_node(i,-2147483648));\n }\n binary_tree() : binary_tree(0) {};\n};\n\nint main()\n{\n int q;\n cin >> q;\n\n binary_tree t = binary_tree(q);\n\n for(int query = 0; query < q; query++)\n {\n string s;\n cin >> s;\n if(s == \"insert\")\n {\n int k;\n cin >> k;\n t.insert(k);\n }\n if(s == \"find\")\n {\n int k;\n cin >> k;\n if(t.find(k))\n cout << \"yes\" << endl;\n else\n cout << \"no\" << endl;\n }\n if(s == \"print\")\n {\n t.inorder_walk();\n t.preorder_walk();\n }\n }\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 25464, "score_of_the_acc": -1.875, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_8_B_11017041", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct binary_node\n{\n int id;\n binary_node* parent;\n binary_node* left;\n binary_node* right;\n\n int key;\n\n void set_left(binary_node& l)\n {\n left = &l;\n }\n void set_right(binary_node& r)\n {\n right = &r;\n }\n binary_node(int i, int k)\n {\n id = i;\n key = k;\n parent = nullptr;\n left = nullptr;\n right = nullptr;\n }\n binary_node() : binary_node(-1, -2147483648) {}\n};\n\nstruct binary_tree\n{\n vector<binary_node> nodes;\n int node_count;\n\n void insert(int k)\n {\n binary_node* z = &nodes[node_count];\n z->key = k;\n node_count++;\n\n binary_node* y = nullptr;\n binary_node* x = this->root();\n while(x != nullptr)\n {\n y = x;\n if(z->key < x->key)\n x = x->left;\n else\n x = x->right;\n }\n\n if(y != z)\n {\n z->parent = y;\n if(z->key < y->key)\n y->left = z;\n else\n y->right = z;\n }\n }\n\n bool find(int k)\n {\n if(node_count == 0)\n return false;\n else\n {\n binary_node* y = nullptr;\n binary_node* x = root();\n while(x != nullptr)\n {\n y = x;\n if(k == y->key)\n return true;\n\n if(k < y->key)\n x = y->left;\n else\n x = y->right;\n }\n return false;\n }\n }\n\n binary_node* root()\n {\n for(int i = 0; i < node_count; i++)\n if(nodes[i].parent == nullptr)\n return &nodes[i];\n exit(-1);\n }\n\n void preorder_walk(binary_node* n)\n {\n cout << \" \" << n->key;\n if(n->left != nullptr)\n preorder_walk(n->left);\n if(n->right != nullptr)\n preorder_walk(n->right);\n }\n void preorder_walk()\n {\n preorder_walk(this->root());\n cout << endl;\n }\n void inorder_walk(binary_node* n)\n {\n if(n->left != nullptr)\n inorder_walk(n->left);\n cout << \" \" << n->key;\n if(n->right != nullptr)\n inorder_walk(n->right);\n }\n void inorder_walk()\n {\n inorder_walk(this->root());\n cout << endl;\n }\n\n binary_tree(int n)\n {\n node_count = 0;\n for(int i = 0; i < n; i++)\n nodes.push_back(binary_node(i,-2147483648));\n }\n binary_tree() : binary_tree(0) {};\n};\n\nint main()\n{\n int q;\n cin >> q;\n\n binary_tree t = binary_tree(q);\n\n for(int query = 0; query < q; query++)\n {\n string s;\n cin >> s;\n if(s == \"insert\")\n {\n int k;\n cin >> k;\n t.insert(k);\n }\n if(s == \"find\")\n {\n int k;\n cin >> k;\n if(t.find(k))\n cout << \"yes\" << endl;\n else\n cout << \"no\" << endl;\n }\n if(s == \"print\")\n {\n t.inorder_walk();\n t.preorder_walk();\n }\n }\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 24060, "score_of_the_acc": -1.7876, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_8_B_11013942", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\nstruct tree {\n // ここでは無駄なものを削除し、keyを追加した\n ll id = -1, parent=-1, key=-1, right=-1, left=-1;\n};\n\n// この関数ではvectorの最後の場所にparentとkeyとrightとleftを正しく設定する\nvoid insert(vector<tree> &binary_tree, ll root, ll target, ll key) {\n // 右側の木へ移動する\n if (binary_tree[root].key < key) {\n if (binary_tree[root].right == -1) {\n binary_tree[root].right = target;\n binary_tree[target].parent = root;\n return;\n }\n else {\n insert(binary_tree, binary_tree[root].right, target, key);\n }\n }\n // 左側の木へ移動する\n else if (binary_tree[root].key > key) {\n if (binary_tree[root].left == -1) {\n binary_tree[root].left = target;\n binary_tree[target].parent = root;\n }\n else {\n insert(binary_tree, binary_tree[root].left, target, key);\n }\n }\n}\n\n// この関数では引数の値をrootからたどって発見する\nvoid find(vector<tree> &binary_tree, ll root, ll target) {\n if (binary_tree[root].key == target) {\n cout << \"yes\" << endl;\n return;\n }\n if (binary_tree[root].key < target) {\n if (binary_tree[root].right == -1) {\n cout << \"no\" << endl;\n return;\n }\n else find(binary_tree, binary_tree[root].right, target);\n }\n else if (binary_tree[root].key > target) {\n if (binary_tree[root].left == -1) {\n cout << \"no\" << endl;\n return;\n }\n else find(binary_tree, binary_tree[root].left, target);\n }\n}\n\n// 木の先行順巡回\nvoid preorder_tree_walk(vector<tree> &binary_tree, ll root) {\n cout << \" \" << binary_tree[root].key;\n if (binary_tree[root].left != -1) preorder_tree_walk(binary_tree, binary_tree[root].left);\n if (binary_tree[root].right != -1) preorder_tree_walk(binary_tree, binary_tree[root].right);\n return;\n}\n// 木の中間順巡回\nvoid inorder_tree_walk(vector<tree> &binary_tree, ll root) {\n if (binary_tree[root].left != -1) inorder_tree_walk(binary_tree, binary_tree[root].left);\n cout << \" \" << binary_tree[root].key;\n if (binary_tree[root].right != -1) inorder_tree_walk(binary_tree, binary_tree[root].right);\n return;\n}\n\n// main\nvoid solve() {\n ll m;\n cin >> m;\n ll used = -1, root = 0;\n vector<tree> binary_tree;\n while (m--) {\n string type;\n cin >> type;\n if (type == \"insert\") {\n ll k;\n cin >> k;\n tree temptree;\n binary_tree.push_back(temptree);\n ++used;\n binary_tree[used].id = used;\n binary_tree[used].key = k;\n if (used != 0) insert(binary_tree, root, used, k);\n }\n else if (type == \"print\") {\n inorder_tree_walk(binary_tree, root);\n cout << endl;\n preorder_tree_walk(binary_tree, root);\n cout << endl;\n }\n /* ここから追加分 */\n else if (type == \"find\") {\n ll k;\n cin >> k;\n find(binary_tree, root, k);\n }\n }\n\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 24808, "score_of_the_acc": -1.4592, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_8_B_10996336", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n int key;\n int left, right, parent;\n};\n\nconst int MAXN = 500000 + 5;\nNode tree[MAXN];\nint root = 0, tot = 0;\n\nvoid insert_key(int k) {\n int y = 0, x = root;\n int z = ++tot;\n tree[z].key = k;\n tree[z].left = tree[z].right = tree[z].parent = 0;\n\n while (x != 0) {\n y = x;\n if (k < tree[x].key)\n x = tree[x].left;\n else\n x = tree[x].right;\n }\n\n tree[z].parent = y;\n if (y == 0)\n root = z;\n else if (k < tree[y].key)\n tree[y].left = z;\n else\n tree[y].right = z;\n}\n\nvoid inorder(int u) {\n if (u == 0) return;\n inorder(tree[u].left);\n cout << \" \" << tree[u].key;\n inorder(tree[u].right);\n}\nint find(int u,int k){\n while (u!=0&&k!=tree[u].key)\n {\n if(k<tree[u].key)u=tree[u].left;\n else u=tree[u].right;\n }\n return u;\n \n}\n\nvoid preorder(int u) {\n if (u == 0) return;\n cout << \" \" << tree[u].key;\n preorder(tree[u].left);\n preorder(tree[u].right);\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n, x;\n string op;\n cin >> n;\n while (n--) {\n cin >> op;\n if (op == \"insert\") {\n cin >> x;\n insert_key(x);\n } else if(op==\"find\"){\n int x;\n cin>>x;\n int u=find(root,x);\n if(u!=0)cout<<\"yes\"<<endl;\n else cout<<\"no\"<<endl;\n }\n else {\n inorder(root);\n cout << \"\\n\";\n preorder(root);\n cout << \"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 9392, "score_of_the_acc": -0.1667, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_8_B_10994938", "code_snippet": "#include <cstdio>\n#include <iostream>\n#include <string>\nusing namespace std;\n\nstruct Node {\n int key;\n Node* left;\n Node* right;\n Node* parent;\n};\n\nNode* root = nullptr;\nNode* NIL = nullptr;\n\nNode* find(Node* u, int k) {\n while (u != NIL && k != u->key) {\n u = (k < u->key) ? u->left : u->right;\n }\n return u;\n}\n\nvoid insert(int k) {\n Node* y = NIL;\n Node* x = root;\n Node* z = new Node{k, NIL, NIL, nullptr};\n\n while (x != NIL) {\n y = x;\n x = (z->key < x->key) ? x->left : x->right;\n }\n z->parent = y;\n\n if (y == NIL) {\n root = z;\n } else if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n}\n\nvoid inorder(Node* u) {\n if (u == NIL) return;\n inorder(u->left);\n std::printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node* u) {\n if (u == NIL) return;\n std::printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int n, x;\n string com;\n\n std::scanf(\"%d\", &n);\n\n for (int i = 0; i < n; ++i) {\n std::cin >> com;\n if (com == \"find\") {\n std::scanf(\"%d\", &x);\n Node* t = find(root, x);\n std::printf(t != NIL ? \"yes\\n\" : \"no\\n\");\n } else if (com == \"insert\") {\n std::scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n std::printf(\"\\n\");\n preorder(root);\n std::printf(\"\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 22228, "score_of_the_acc": -1.507, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_8_B_10994306", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nvector<int> preorder;\nvector<int> inorder;\nvector<int> postorder;\n\nclass Node {\npublic:\n\tint value;\n\tNode* left;\n\tNode* right;\n\n\tNode(int value) {\n\t\tthis->value = value;\n\t\tthis->left = NULL;\n\t\tthis->right = NULL;\n\t}\n};\n\nclass BST {\npublic:\n\tNode* root;\n\tBST() {\n\t\tthis->root = NULL;\n\t}\n\n\tvoid Insert(int num);\n\tbool Search(int num);\n};\n\nvoid BST::Insert(int num) {\n\tif (root == NULL) {\n\t\troot = new Node(num);\n\t\treturn;\n\t}\n\n\tNode* curr = root;\n\twhile (curr != NULL) {\n\t\tif (num < curr->value) {\n\t\t\tif (curr->left == NULL) {\n\t\t\t\tcurr->left = new Node(num);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcurr = curr->left; // 继续和左子树进行比较\n\t\t}\n\t\telse {\n\t\t\tif (curr->right == NULL) {\n\t\t\t\tcurr->right = new Node(num);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcurr = curr->right; // 继续和右子树进行比较\n\t\t}\n\t}\n}\n\nbool BST::Search(int num) {\n\tNode* curr = root;\n\twhile (curr != NULL) {\n\t\tif (num < curr->value) {\n\t\t\tcurr = curr->left;\n\t\t}\n\t\telse if (num > curr->value) {\n\t\t\tcurr = curr->right;\n\t\t}\n\t\telse {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n// 前序遍历\nvoid PreorderTraversal(Node* node) {\n\tif (node == NULL) {\n\t\treturn;\n\t}\n\tpreorder.push_back(node->value);\n\tPreorderTraversal(node->left);\n\tPreorderTraversal(node->right);\n}\n\n// 中序遍历\nvoid InorderTraversal(Node* node) {\n\tif (node == NULL) {\n\t\treturn;\n\t}\n\tInorderTraversal(node->left);\n\tinorder.push_back(node->value);\n\tInorderTraversal(node->right);\n}\n\n// 后序遍历\nvoid PostorderTraversal(Node* node) {\n\tif (node == NULL) {\n\t\treturn;\n\t}\n\tPostorderTraversal(node->left);\n\tPostorderTraversal(node->right);\n\tpostorder.push_back(node->value);\n}\n\nvoid Print(Node *node) {\n\tinorder.clear();\n\tpreorder.clear();\n\tpostorder.clear();\n\n\tInorderTraversal(node);\n\tfor (int i = 0; i < inorder.size(); i++) {\n cout << \" \";\n\t\tcout << inorder[i];\n\t}\n\tcout << endl;\n\n\tPreorderTraversal(node);\n\tfor (int i = 0; i < preorder.size(); i++) {\n\t\tcout << \" \";\n\t\tcout << preorder[i];\n\t}\n\tcout << endl;\n\n\t//PostorderTraversal(node);\n\t//for (int i = 0; i < postorder.size(); i++) {\n\t//\tif (i)\n\t//\t\tcout << \" \";\n\t//\tcout << postorder[i];\n\t//}\n\t//cout << endl;\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tBST* tree = new BST();\n\n\tfor (int i = 0; i < n; i++) {\n\t\tstring inst;\n\t\tcin >> inst;\n\t\tif(inst == \"insert\")\n\t\t{\n\t\t\tint num;\n\t\t\tcin >> num;\n\t\t\ttree->Insert(num);\n\t\t}\n\t\telse if (inst == \"find\")\n\t\t{\n\t\t\tint num;\n\t\t\tcin >> num;\n\t\t\tif (tree->Search(num))\n\t\t\t\tcout << \"yes\" << endl;\n\t\t\telse\n\t\t\t\tcout << \"no\" << endl;\n\t\t}\n\t\telse if (inst == \"print\")\n\t\t{\n\t\t\tPrint(tree->root);\n\t\t}\n\t}\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 20200, "score_of_the_acc": -1.5475, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_8_B_10947599", "code_snippet": "#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *parent, *left, *right;\n Node(int k) : key(k), parent(nullptr), left(nullptr), right(nullptr) {}\n};\n\nNode *root;\n\nvoid insert (int k) {\n Node *x = root;\n Node *y = nullptr;\n Node *z;\n z = new Node(k);\n\n while ( x != nullptr ) {\n y = x;\n if ( z->key < x->key ) {\n x = x->left;\n }\n else {\n x = x->right;\n }\n }\n if ( y == nullptr ) {\n root = z;\n }\n else if ( z->key < y->key ) {\n y->left = z;\n }\n else {\n y->right = z;\n }\n}\n\nvoid find(int k) {\n Node *x = root;\n int flag = 0;\n while ( x != nullptr ) {\n if ( k < x->key ) x = x->left;\n else if ( k > x->key ) x = x->right;\n else if ( k == x->key ) {\n flag += 1;\n break;\n }\n }\n if ( flag ) cout << \"yes\" << endl;\n else cout << \"no\" << endl;\n}\n\nvoid inorder(Node *u) {\n if (u == nullptr) return;\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == nullptr) return;\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int m, x;\n cin >> m;\n string com;\n for (int i = 0; i < m; i++) {\n cin >> com;\n if ( com == \"insert\" ) {\n cin >> x;\n insert(x);\n }\n else if ( com == \"print\" ) {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n else if ( com == \"find\" ) {\n cin >> x;\n find(x);\n }\n }\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 22196, "score_of_the_acc": -1.7967, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_8_B_10930278", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#define max 50000\ntypedef struct Node{\n int m;\n Node *p,*l,*r;\n}tree;\nint n;\ntree *root=NULL;\nvoid preorder(tree *a){\n if(a==NULL) return;\n printf(\" %d\",a->m);\n preorder(a->l);\n preorder(a->r);\n}\nvoid inorder(tree *a){\n if(a==NULL) return;\n inorder(a->l);\n printf(\" %d\",a->m);\n inorder(a->r);\n}\nvoid insert(int k){\n tree *b=NULL;\n tree *c=root;\n tree *w;\n w=(tree*)malloc(sizeof(tree));//分配了内存,结束后还存在\n w->m=k;\n w->l=NULL;\n w->r=NULL;\n while(c!=NULL){\n b=c;//设置父节点\n if(w->m<c->m){\n c=c->l;\n }else c=c->r;\n }\n w->p=b;\n if(b==NULL){\n root=w;\n }else if(b->m>w->m){\n b->l=w;\n }else if(b->m<w->m){\n b->r=w;\n }\n}\ntree* find(int a){\n tree*q=root;\n while(q!=NULL&&q->m!=a){\n if(q->m<a){\n q=q->r;\n }else q=q->l;\n }\n return q;\n}\nint main(){\n scanf(\"%d\",&n);\n char q[20];\n int e;\n for(int i=0;i<n;i++){\n scanf(\"%s\",q);\n if(q[0]=='i'){\n scanf(\"%d\",&e);\n insert(e);\n }\n if(q[0]=='p'){\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }\n if(q[0]=='f'){\n scanf(\"%d\",&e);\n if(find(e)!=NULL){\n printf(\"yes\\n\");\n }else printf(\"no\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 21720, "score_of_the_acc": -0.9337, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_8_B_10896848", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n#include <chrono>\n#include <complex>\n#include <cmath>\n#include <unistd.h>\n#define pc_u putchar\n#pragma GCC target (\"avx\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n#define rep(i,a,b) for(it i=(it)(a);i<(it)b;i++)\n#define rep2(i,a,b,c) for(it i=(it)(a);i<(it)b;i+=(it)c)\n#define repp(i,a,b) for(it i=(it)(a);i<=(it)b;i++)\n#define repp2(i,a,b,c) for(it i=(it)(a);i<=(it)b;i+=(it)c)\n#define irep(i,a,b) for(int i=(int)(a);i<(int)b;i++)\n#define irep2(i,a,b,c) for(int i=(int)(a);i<(int)b;i+=c)\n#define irepp(i,a,b) for(int i=(int)(a);i<=(int)b;i++)\n#define irepp2(i,a,b,c) for(int i=(int)(a);i<=(int)b;i+=c)\n#define nrep(i,a,b) for(it i=(it)(a)-1;i>=(it)b;i--)\n#define nrepp(i,a,b) for(it i=(it)(a);i>=(it)b;i--)\n#define inrep(i,a,b) for(int i=(int)(a)-1;i>=(int)b;i--)\n#define inrepp(i,a,b) for(int i=(int)(a);i>=(int)b;i--)\n#define inrep2(i,a,b,c) for(int i=(int)(a)-1;i>=(int)b;i-=c)\n#define inrepp2(i,a,b,c) for(int i=(int)(a);i>=(int)b;i-=c)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define Min(x) *min_element(all(x))\n#define Max(x) *max_element(all(x))\n#define popcount(x) __builtin_popcountll(x)\n#define moda 998244353LL\n#define modb 1000000007LL\n#define modc 968244353LL\n#define dai 2502502502502502502LL\n#define sho -dai\n#define aoi 1e18+1e6\n#define giri 1010000000\n#define en 3.14159265358979\n#define eps 1e-14\n#define fi first\n#define se second\n#define elif else if\ntemplate<typename T> using pq=priority_queue<T>;\ntemplate<typename T> using pqg=priority_queue<T,vector<T>,greater<T>>;\n#define uni(a) a.erase(unique(all(a)),a.end())\nusing it=long long;\nusing itn=int;\nusing un=unsigned long long;\nusing idb=double;\nusing db=long double;\nusing st=string;\nusing ch=char;\nusing bo=bool;\nusing P=pair<it,it>;\nusing ip=pair<int,int>;\nusing vi=vector<it>;\nusing ivi=vector<int>;\nusing ivd=vector<idb>;\nusing vd=vector<db>;\nusing vs=vector<st>;\nusing vc=vector<ch>;\nusing vb=vector<bo>;\nusing vp=vector<P>;\nusing ivp=vector<ip>;\nusing sp=set<P>;\nusing isp=set<ip>;\nusing ss=set<st>;\nusing sca=set<ch>;\nusing si=set<it>;\nusing isi=set<int>;\nusing svi=set<vi>;\nusing svb=set<vb>;\nusing vvi=vector<vi>;\nusing ivvi=vector<ivi>;\nusing ivvd=vector<ivd>;\nusing vvd=vector<vd>;\nusing vvs=vector<vs>;\nusing vvb=vector<vb>;\nusing vvc=vector<vc>;\nusing vvp=vector<vp>;\nusing ivvp=vector<ivp>;\nusing vsi=vector<si>;\nusing ivsi=vector<isi>;\nusing isvi=set<ivi>;\nusing vsc=vector<sca>;\nusing vsp=vector<sp>;\nusing ivsp=vector<isp>;\nusing vvsi=vector<vsi>;\nusing ivvsi=vector<ivsi>;\nusing vvsp=vector<vsp>;\nusing ivvsp=vector<ivsp>;\nusing svvb=set<vvb>;\nusing vvvi=vector<vvi>;\nusing ivvvi=vector<ivvi>;\nusing ivvvd=vector<ivvd>;\nusing vvvd=vector<vvd>;\nusing vvvb=vector<vvb>;\nusing ivvvp=vector<ivvp>;\nusing vvvp=vector<vvp>;\nusing vvvvi=vector<vvvi>;\nusing ivvvvi=vector<ivvvi>;\nusing vvvvd=vector<vvvd>;\nusing vvvvb=vector<vvvb>;\nusing ivvvvp=vector<ivvvp>;\nusing vvvvp=vector<vvvp>;\nusing ivvvvvi=vector<ivvvvi>;\nusing vvvvvi=vector<vvvvi>;\nusing ivvvvvvi=vector<ivvvvvi>;\nusing vvvvvvi=vector<vvvvvi>;\nusing ivvvvvvvi=vector<ivvvvvvi>;\nusing vvvvvvvi=vector<vvvvvvi>;\nusing vvvvvvvvi=vector<vvvvvvvi>;\nconst int dx[8]={0,1,0,-1,1,1,-1,-1};\nconst int dy[8]={1,0,-1,0,1,-1,1,-1};\nst abc=\"abcdefghijklmnopqrstuvwxyz\";\nst ABC=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nst num=\"0123456789\";\nst mb=\"xo\";\nst MB=\"XO\";\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\ntemplate<class T> using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\nnamespace {\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const pair<T, U> &p) {\n os << p.first << \" \" << p.second;\n return os;\n}\ntemplate <typename T, typename U>\nistream &operator>>(istream &is, pair<T, U> &p) {\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v) {\n int s = (int)v.size();\n for (int i = 0; i < s; i++) os << (i ? \" \" : \"\") << v[i];\n return os;\n}\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v) {\n for (auto &x : v) is >> x;\n return is;\n}\n\nistream &operator>>(istream &is, __int128_t &x) {\n string S;\n is >> S;\n x = 0;\n int flag = 0;\n for (auto &c : S) {\n if (c == '-') {\n flag = true;\n continue;\n }\n x *= 10;\n x += c - '0';\n }\n if (flag) x = -x;\n return is;\n}\n\nistream &operator>>(istream &is, __uint128_t &x) {\n string S;\n is >> S;\n x = 0;\n for (auto &c : S) {\n x *= 10;\n x += c - '0';\n }\n return is;\n}\n\nostream &operator<<(ostream &os, __int128_t x) {\n if (x == 0) return os << 0;\n if (x < 0) os << '-', x = -x;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\nostream &operator<<(ostream &os, __uint128_t x) {\n if (x == 0) return os << 0;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\n\nvoid input() {}\ntemplate <typename T, class... U>\nvoid input(T &t, U &...u) {\n cin >> t;\n input(u...);\n}\ntemplate <typename T, class... U>\nvoid input1(T &t, U &...u) {\n input(u...);\n}\nvoid print() { cout << \"\\n\"; }\ntemplate <typename T, class... U, char sep = ' '>\nvoid print(const T &t, const U &...u) {\n cout << t;\n if (sizeof...(u)) cout << sep;\n print(u...);\n}\ntemplate <typename T, class... U, char sep = ' '>\nvoid print1(const T &t, const U &...u) {\n print(u...);\n}\n\nstruct IoSetupNya {\n IoSetupNya() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n cerr << fixed << setprecision(7);\n }\n} iosetupnya;\n\n} //namespace Nyaan\n\ntemplate<typename T>\nT Sum(vector<T> &a){\n T s=0;\n for(auto i:a)s+=i;\n return s;\n}\n\ntemplate<typename T>\nT Sum(vector<T> &a,int l,int r){\n T s=0;\n irep(i,l,r)s+=a[i];\n return s;\n}\n\ntemplate <typename T>\nvoid dec(vector<T> &t){\n for(auto &i:t)i--;\n}\n\ntemplate <typename T>\nvoid inc(vector<T> &t,T k=1){\n for(auto &i:t)i+=k;\n}\n\ntemplate <typename T>\nvector<T> make_vec(int n,T t){\n vector<T> g(n);\n for(auto &i:g)i=t;\n return g;\n}\n\ntemplate <typename T>\nvector<T> subvec(vector<T> a,int f,int l){\n vector<T> g(l);\n irep(i,f,f+l)g[i-f]=a[i];\n return g;\n}\n\ntemplate<typename T>\nT gcda(T a,T b){\n if(!a||!b)return max(a,b);\n while(a%b&&b%a){\n if(a>b)a%=b;\n else b%=a;\n }\n return min(a,b);\n}\n\nit lcma(it a,it b){\n return a/gcda(a,b)*b;\n}\n\ndb distance(db a,db b,db c,db d){return sqrt((a-c)*(a-c)+(b-d)*(b-d));}\n\nbo outc(int h,int w,int x,int y){\n return (x<0||x>=h||y<0||y>=w);\n}\n\ntemplate<typename T>\nvector<vector<T>> nep(vector<T> a){\n vector<vector<T>> e;\n sort(all(a));\n do{\n e.emplace_back(a);\n }while(next_permutation(all(a)));\n return e;\n}\n\ntemplate<typename T>\nvoid chmin(T &a,T b){a=min(a,b);}\ntemplate<typename T>\nvoid chmax(T &a,T b){a=max(a,b);}\n\nvoid yn(bo a){print(a?string(\"Yes\"):string(\"No\"));}\nvoid YN(bo a){print(a?string(\"YES\"):string(\"NO\"));}\n\nstruct dsu1{\n ivi par,siz;\n dsu1(int n){\n init(n);\n }\n void init(int n){\n irep(i,0,n){\n par.emplace_back(i);\n }\n siz.resize(n,1);\n }\n int leader(int u){\n if(par[u]==u)return u;\n return par[u]=leader(par[u]);\n }\n void merge(int u,int v){\n int ru=leader(u),rv=leader(v);\n if(ru==rv)return;\n if(size(ru)<size(rv))swap(ru,rv);\n siz[ru]+=siz[rv];\n par[rv]=ru;\n }\n bool same(int u,int v){\n return leader(u)==leader(v);\n }\n int size(int u){\n return siz[leader(u)];\n }\n};\n\nstruct edge{\n int f;\n int t;\n it l;\n};\nvoid input(edge &a){input(a.f,a.t,a.l);}\nbo comppppp(edge &a,edge &b){return a.l<b.l;}\n\nit minspantree(vector<edge> &e,int n){\n /*\n 与えられた辺を持つグラフの最小全域木を求める\n 存在する場合はその答えを 存在しないならinf\n 計算量はO(MlogM+N)くらい\n */\n vector<edge> g=e;sort(all(g),comppppp);\n it ans=0;\n dsu1 uf(n);\n for(auto i:g){\n if(!uf.same(i.f,i.t)){\n uf.merge(i.f,i.t);\n ans+=i.l;\n }\n }\n if(uf.size(0)==n)return ans;\n return dai;\n}\n\n/*#include <atcoder/all>\nusing namespace atcoder;\nusing mints=modint998244353;\nusing mint=modint;\nusing minto=modint1000000007;\nusing vm=vector<mint>;\nusing vms=vector<mints>;\nusing vmo=vector<minto>;\nusing vvm=vector<vm>;\nusing vvms=vector<vms>;\nusing vvmo=vector<vmo>;\nusing vvvm=vector<vvm>;\nusing vvvms=vector<vvms>;\nusing vvvmo=vector<vvmo>;\nusing vvvvm=vector<vvvm>;\nusing vvvvms=vector<vvvms>;\nusing vvvvmo=vector<vvvmo>;\nusing vvvvvm=vector<vvvvm>;\nusing vvvvvms=vector<vvvvms>;\nusing vvvvvmo=vector<vvvvmo>;\nusing vvvvvvm=vector<vvvvvm>;\nusing vvvvvvms=vector<vvvvvms>;\nusing vvvvvvmo=vector<vvvvvmo>;\nusing vvvvvvvms=vector<vvvvvvms>;\nusing vvvvvvvmo=vector<vvvvvvmo>;*/\n\n/*総和をもとめるセグ木\nstruct nod{\n it val;\n nod(it v=0):val(v){}\n};\n\nnod op(nod a,nod b){return nod(a.val+b.val);}\nnod e(){return nod(0);}\n\nstruct act{\n it a;\n act(it e=0):a(e){}\n};\n\nnod mapping(act f,nod x){return nod(f.a+x.val);}\nact comp(act f,act g){return act(f.a+g.a);}\nact id(){return act(0);}*/\n//#define endl '\\n'\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n\ntemplate<typename T> struct binarytree{\n private:\n struct node {\n T v;\n node *l;\n node *r;\n node *p;\n // 初め、左右の子は nullptr となっている\n node(T v) : v(v), l(nullptr), r(nullptr), p(nullptr) {}\n };\n public:\n node *root=nullptr;\n void insert(T x){\n node *root_tmp=root;\n node *elem;\n elem=(node *)malloc(sizeof(node));\n elem->v=x;\n elem->l=nullptr;\n elem->r=nullptr;\n node *prev=nullptr;\n while(root_tmp!=nullptr){\n prev=root_tmp;\n if(x<root_tmp->v)root_tmp=root_tmp->l;\n else root_tmp=root_tmp->r;\n }\n elem->p=prev;\n if(elem->p==nullptr)root=elem;\n elif(elem->p->v>elem->v)elem->p->l=elem;\n else elem->p->r=elem;\n }\n bo find(T x,node *u){\n if(u==nullptr)return 0;\n if(x==u->v)return 1;\n if(x<u->v)return find(x,u->l);\n return find(x,u->r);\n }\n void preorder(node *u){\n if(u==nullptr)return;\n cout<<' '<<(u->v);\n preorder(u->l);\n preorder(u->r);\n }\n void inorder(node *u){\n if(u==nullptr)return;\n inorder(u->l);\n cout<<' '<<(u->v);\n inorder(u->r);\n }\n};\n\nvoid solve(){\n int q;input(q);\n binarytree<int> e;\n while(q--){\n st s;input(s);\n if(s==\"insert\"){\n int x;input(x);\n e.insert(x);\n }\n elif(s==\"find\"){\n int x;input(x);\n cout<<(e.find(x,e.root)?\"yes\":\"no\")<<endl;\n }\n else{\n e.inorder(e.root);cout<<endl;\n e.preorder(e.root);cout<<endl;\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int t=1;//input(t);\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 290, "memory_kb": 22212, "score_of_the_acc": -1.256, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_8_B_10858455", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <cmath>\n#include <cstdlib>\nusing namespace std;\n\n\nstruct Node {\n int v;\n Node* l;\n Node* r;\n};\n\nNode* root = NULL;\n\nbool find(int v) {\n Node* x = root;\n while (x && x->v != v) {\n if (v < x->v) {\n x = x -> l;\n } else if (v > x-> v) {\n x = x -> r;\n } \n }\n if (x && x->v == v) return true;\n return false;\n}\n\nvoid insert(int v) {\n if (!root) {\n root = new Node;\n root -> v = v;\n root -> l = NULL;\n root -> r = NULL;\n return;\n }\n\n Node* par = NULL;\n Node* x = root;\n while (x) {\n par = x;\n if (v < x -> v) {\n x = x -> l;\n } else {\n x = x -> r;\n }\n }\n if (v < par->v) {\n par -> l = new Node;\n Node* p = par -> l;\n p -> v = v;\n p -> l = NULL;\n p -> r = NULL;\n } else {\n par -> r = new Node;\n Node* p = par -> r;\n p -> v = v;\n p -> l = NULL;\n p -> r = NULL;\n }\n}\n\nvoid preOrder(Node* root) {\n if (root == NULL) return ;\n printf(\" %d\", root -> v);\n preOrder(root -> l);\n preOrder(root -> r);\n}\n\nvoid inOrder(Node* root) {\n if (root == NULL) return ;\n inOrder(root -> l);\n printf(\" %d\", root -> v);\n inOrder(root -> r);\n}\n\n\nint main() {\n //freopen(\"in.txt\", \"r\", stdin);\n //freopen(\"out.txt\", \"w\", stdout);\n int n;\n int num;\n char s[10];\n scanf(\"%d\", &n);\n for (int i = 0; i < n; i++) {\n scanf(\"%s\", s);\n if (s[0] == 'i') {\n scanf(\"%d\", &num);\n insert(num);\n } else if (s[0] == 'p') {\n inOrder(root);\n printf(\"\\n\");\n preOrder(root);\n printf(\"\\n\");\n } else if (s[0] == 'f') {\n scanf(\"%d\", &num);\n if (find(num)) printf(\"yes\\n\");\n else printf(\"no\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 15916, "score_of_the_acc": -0.4476, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_8_B_10818372", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); i++)\n#define rep2(i, s, n) for (int i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<int> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<int> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\nstruct node {\n int key;\n node *right, *left, *parent;\n};\n\nnode *root, *NIL;\n\nvoid insert(int k) {\n node *y = NIL;\n node *x = root;\n node *z;\n\n z = (node *)malloc(sizeof(node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n z->parent = y;\n if (y == NIL) {\n root = z;\n } else {\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nvoid find(int k) {\n node *x = root;\n while (x != NIL && k != x->key) {\n if (k < x->key) {\n x = x->left;\n }\n else {\n x = x->right;\n }\n }\n if (x == NIL) {\n cout << \"no\" << endl;\n }\n else cout << \"yes\" << endl;\n}\n\nvoid inorder(node *u) {\n if (u == NIL) {\n return;\n }\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\nvoid preorder(node *u) {\n if (u == NIL) {\n return;\n }\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nvoid solve() {\n ll n;\n cin >> n;\n rep(i, n) {\n string cmd;\n cin >> cmd;\n if (cmd == \"insert\") {\n ll target;\n cin >> target;\n insert(target);\n }\n else if (cmd == \"print\") {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n else if (cmd == \"find\") {\n ll target;\n cin >> target;\n find(target);\n }\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 22272, "score_of_the_acc": -1.3847, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_8_B_10776699", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <iostream>\nusing namespace std;\n\nstruct Node\n{\n int key;\n Node *parent, *left, *right;\n};\n\nNode *NIL, *root;\n\nvoid insert(int k)\n{\n Node *y = NIL;\n Node *x = root;\n Node *z = new Node;\n\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n while (x != NIL) {\n y = x;\n if (z->key < y->key) {\n x = y->left;\n } else {\n x = y->right;\n }\n }\n\n z->parent = y;\n\n if (y==NIL) {\n root = z;\n } else if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n}\n\nNode* find(Node *x, int k) {\n while (x != NIL && k != x->key) {\n if (k < x->key) x = x->left;\n else x = x->right;\n }\n return x;\n}\n\nvoid inorder(Node *u) {\n if (u==NIL) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u==NIL) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main()\n{\n int n,i,x;\n string com;\n\n scanf(\"%d\", &n);\n\n for (i=0; i<n; i++) {\n cin >> com;\n if (com==\"insert\") {\n scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n } else if (com == \"find\") {\n scanf(\"%d\", &x);\n Node* t = find(root,x);\n if (t!=NIL) printf(\"yes\\n\");\n else printf(\"no\\n\");\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 22216, "score_of_the_acc": -1.4646, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_8_B_10750039", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define loop(a,b) for (int a = 0;a < b;a++)\n#define rep(a,b,c) for(int a = b;a < c;a++)\n#define vec(a) vector<a>\n\nstruct Node{\n int key;\n Node *left,*right,*parent;\n Node(int key):key(key),left(nullptr),right(nullptr),parent(nullptr){};\n};\n\nclass BinarySearchTree{\n private:\n Node* root;\n Node* insert(Node* node,int key){\n Node* z = new Node(key);\n Node* y = nullptr;\n Node* x = root;\n while(x != nullptr){\n y = x;\n if(z->key < x->key) x = x->left;\n else x = x->right;\n }\n z->parent = y;\n if(y == nullptr) root = z;\n else if(z->key < y->key) y->left = z;\n else y->right = z;\n return z;\n }\n void inorder(Node* node){\n if(node == nullptr) return;\n inorder(node->left);\n cout <<\" \"<< node->key;\n inorder(node->right);\n }\n void preorder(Node* node){\n if(node == nullptr) return;\n cout << \" \"<< node->key;\n preorder(node->left);\n preorder(node->right);\n }\n \n Node* find(Node* node,int key){\n while(node != nullptr && node->key != key){\n if(key < node->key) node = node->left;\n else node = node->right;\n }\n return node;\n }\n Node* find_min(Node* node) {\n while (node->left != nullptr) {\n node = node->left;\n }\n return node;\n }\n \n void remove(Node* node,int key){\n Node* z = find(node,key);\n if(z == nullptr) return;\n \n \n if(z->left == nullptr && z->right == nullptr) {\n if(z->parent == nullptr) {\n root = nullptr; \n } else if(z->parent->left == z) {\n z->parent->left = nullptr;\n } else {\n z->parent->right = nullptr;\n }\n delete z;\n }\n else if(z->left == nullptr || z->right == nullptr) {\n Node* child = (z->left != nullptr) ? z->left : z->right;\n \n if(z->parent == nullptr) {\n root = child; \n } else if(z->parent->left == z) {\n z->parent->left = child;\n } else {\n z->parent->right = child;\n }\n \n if(child != nullptr) {\n child->parent = z->parent;\n }\n delete z;\n }\n \n else {\n \n Node* successor = find_min(z->right);\n \n \n z->key = successor->key;\n \n \n if(successor->parent->left == successor) {\n successor->parent->left = successor->right;\n } else {\n successor->parent->right = successor->right;\n }\n \n if(successor->right != nullptr) {\n successor->right->parent = successor->parent;\n }\n delete successor;\n }\n }\n\n public:\n BinarySearchTree():root(nullptr){};\n void print(){\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n void insert(int key){\n insert(root,key);\n }\n bool find(int key){\n Node* node = find(root,key);\n if(node != nullptr) return 1;\n else return 0;\n }\n void remove(int key){\n remove(root,key);\n }\n};\nint main()\n{\n int n;\n cin >> n;\n BinarySearchTree bst;\n loop(i,n){\n string command;\n int key;\n cin >> command;\n if(command == \"insert\"){\n cin >> key;\n bst.insert(key);\n } \n else if(command == \"find\") {\n cin >> key;\n cout << (bst.find(key) ? \"yes\" : \"no\") << endl;\n }\n else if(command == \"print\") {\n bst.print();\n }\n else if(command == \"delete\"){\n cin >> key;\n bst.remove(key);\n } \n }\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 21928, "score_of_the_acc": -1.6967, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_8_B_10734459", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\nclass Node{\npublic:\n Node* right;\n Node* left;\n Node* parent;\n int key;\n};\nclass Tree{\nprivate:\n Node* root;\npublic:\n Tree(){root = 0;}\n void insert(int k);\n void inorder(Node* u);\n void preorder(Node* u);\n void print();\n bool find(int x);\n};\n\n\nvoid Tree::insert(int k){\n Node* z = new Node();\n z->right = 0;\n z->left = 0;\n z->parent = 0;\n z->key = k;\n Node* y = 0;\n Node* x = root;\n while(x!=0){\n y = x;\n if(z->key < x->key){\n x = x->left;\n }\n else{\n x = x->right;\n }\n }\n z->parent = y;\n if(y==0){\n root = z;\n }\n else if(z->key < y->key){\n y->left = z;\n }\n else{\n y->right = z;\n }\n}\n\n\nvoid Tree::inorder(Node* u){\n if(u==0){\n return;\n }\n inorder(u->left);\n cout << ' ' << u->key;\n inorder(u->right);\n}\n\n\nvoid Tree::preorder(Node* u){\n if(u==0){\n return;\n }\n cout << ' ' << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\n\nvoid Tree::print(){\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n}\n\n\nbool Tree::find(int x){\n Node* a = root;\n while(a != 0){\n if(x < a->key){\n a = a->left;\n }\n else if(x > a->key){\n a = a->right;\n }\n else{\n return true;\n }\n }\n return false;\n} \n\n\nint main(){\n int m;\n cin >> m;\n Tree T;\n for(int i=0; i<m; i++){\n string com;\n cin >> com;\n if(com==\"insert\"){\n int k;\n cin >> k;\n T.insert(k);\n }\n else if(com == \"find\"){\n int k;\n cin >> k;\n if(T.find(k) == true)\n cout << \"yes\\n\";\n else cout << \"no\\n\";\n }\n else if(com==\"print\"){\n T.print();\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 21808, "score_of_the_acc": -1.7725, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_8_B_10734429", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\nclass node{\npublic:\n node* right;\n node* left;\n node* parent;\n int key;\n};\nclass tree{\nprivate:\n node* root;\npublic:\n tree(){root = 0;}\n void insert(int k);\n node* find(int k);\n void inorder(node* u);\n void preorder(node* u);\n void print();\n};\nvoid tree::insert(int k)\n{\n node* z = new node();\n z->right = 0;\n z->left = 0;\n z->parent = 0;\n z->key = k;\n node* y = 0; // xの親\n node* x = root; // 根\n while(x!=0){\n y = x; // 親を設定\n if(z->key < x->key){\n x = x->left; // 左の子へ移動\n }\n else{\n x= x->right; // 右の子へ移動\n }\n }\n z->parent = y;\n if(y==0){ // 木が空の場合\n root = z;\n }\n else if(z->key < y->key){\n y->left = z; // 左の子にする\n }\n else{\n y->right = z; // 右の子にする\n }\n}\nnode* tree::find(int k)\n{\n node* x = root; // 根\n while(x!=0){\n if(k == x->key){\n return x; // 見つかった\n }\n else if(k < x->key){\n x = x->left; // 左の子へ移動\n }\n else{\n x = x->right; // 右の子へ移動\n }\n }\nreturn 0; // 見つからなかった\n}\n// 中間順\nvoid tree::inorder(node* u)\n{\n if(u==0){\n return;\n }\n inorder(u->left);\n cout << ' ' << u->key;\n inorder(u->right);\n}\n// 先行順\nvoid tree::preorder(node* u)\n{\n if(u==0){\n return;\n }\n cout << ' ' << u->key;\n preorder(u->left);\n preorder(u->right);\n}\nvoid tree::print()\n{\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n}\nint main()\n{\n int m;\n cin >> m;\n tree T;\n for(int i=0; i<m; i++){\n string com;\n cin >> com;\n if(com==\"insert\"){\n int k;\n cin >> k;\n T.insert(k);\n }\n else if(com==\"find\"){\n int k;\n cin >> k;\n if(T.find(k)!=0){\n cout << \"yes\" << endl;\n }\n else{\n cout << \"no\" << endl;\n }\n }\n else if(com==\"print\"){\n T.print();\n }\n }\nreturn 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 22080, "score_of_the_acc": -1.7894, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_8_B_10734302", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\nclass node{\n public:\n node* right;\n node* left;\n node* parent;\n int key;\n};\nclass tree{\n private:\n node* root;\n public:\n tree(){root = 0;}\n void insert(int k);\n node* find(int k);\n void inorder(node* u);\n void preorder(node* u);\n void print();\n};\nvoid tree::insert(int k){\n node* z = new node();\n z->right = 0;\n z->left = 0;\n z->parent = 0;\n z->key = k;\n node* y = 0; // xの親\n node* x = root; // 根\n while(x!=0){\n y = x; // 親を設定\n if(z->key < x->key){\n x = x->left; // 左の子へ移動\n }\n else{\n x = x->right; // 右の子へ移動\n }\n }\n z->parent = y;\n if(y==0){ // 木が空の場合\n root = z;\n }\n else if(z->key < y->key){\n y->left = z; // 左の子にする\n }\n else{\n y->right = z; // 右の子にする\n }\n}\nnode* tree::find(int k){\n node* x = root; // 根\n while(x!=0){\n if(k == x->key){\n return x; // 見つかった\n }\n else if(k < x->key){\n x = x->left; // 左の子へ移動\n }\n else{\n x = x->right; // 右の子へ移動\n }\n }\n return 0; // 見つからなかった\n}\n// 中間順\nvoid tree::inorder(node* u){\n if(u==0){\n return;\n }\n inorder(u->left);\n cout << ' ' << u->key;\n inorder(u->right);\n}\n// 先行順\nvoid tree::preorder(node* u){\n if(u==0){\n return;\n }\n cout << ' ' << u->key;\n preorder(u->left);\n preorder(u->right);\n}\nvoid tree::print(){\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n}\nint main(){\n int m;\n cin >> m;\n tree T;\n for(int i=0; i<m; i++){\n string com;\n cin >> com;\n if(com==\"insert\"){\n int k;\n cin >> k;\n T.insert(k);\n }\n else if(com==\"find\"){\n int k;\n cin >> k;\n if(T.find(k)!=0){\n cout << \"yes\" << endl;\n }\n else{\n cout << \"no\" << endl;\n }\n }\n else if(com==\"print\"){\n T.print();\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 21956, "score_of_the_acc": -1.7401, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_8_B_10732667", "code_snippet": "// 2025/07/17 Tazoe\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\nclass node{\npublic:\n\tnode* right;\n\tnode* left;\n\tnode* parent;\n\tint key;\n};\n\nclass tree{\nprivate:\n\tnode* root;\npublic:\n\ttree(){root = 0;}\n\tvoid insert(int k);\n\tnode* find(int k);\n\tvoid inorder(node* u);\n\tvoid preorder(node* u);\n\tvoid print();\n};\n\nvoid tree::insert(int k)\n{\n\tnode* z = new node();\n\tz->right = 0;\n\tz->left = 0;\n\tz->parent = 0;\n\tz->key = k;\n\t\n\tnode* y = 0;\t\t// xの親\n\tnode* x = root;\t\t// 根\n\t\n\twhile(x!=0){\n\t\ty = x;\t\t\t\t// 親を設定\n\t\tif(z->key < x->key){\n\t\t\tx = x->left;\t\t// 左の子へ移動\n\t\t}\n\t\telse{\n\t\t\tx = x->right;\t\t// 右の子へ移動\n\t\t}\n\t}\n\t\n\tz->parent = y;\n\t\n\tif(y==0){\t\t\t// 木が空の場合\n\t\troot = z;\n\t}\n\telse if(z->key < y->key){\n\t\ty->left = z;\t\t\t// 左の子にする\n\t}\n\telse{\n\t\ty->right = z;\t\t\t// 右の子にする\n\t}\n}\n\nnode* tree::find(int k)\n{\n\tnode* x = root;\t\t// 根\n\t\n\twhile(x!=0){\n\t\tif(k == x->key){\n\t\t\treturn x;\t\t\t// 見つかった\n\t\t}\n\t\telse if(k < x->key){\n\t\t\tx = x->left;\t\t// 左の子へ移動\n\t\t}\n\t\telse{\n\t\t\tx = x->right;\t\t// 右の子へ移動\n\t\t}\n\t}\n\t\n\treturn 0;\t\t\t// 見つからなかった\n}\n\n// 中間順\nvoid tree::inorder(node* u)\n{\n\tif(u==0){\n\t\treturn;\n\t}\n\t\n\tinorder(u->left);\n\tcout << ' ' << u->key;\n\tinorder(u->right);\n}\n\n// 先行順\nvoid tree::preorder(node* u)\n{\n\tif(u==0){\n\t\treturn;\n\t}\n\t\n\tcout << ' ' << u->key;\n\tpreorder(u->left);\n\tpreorder(u->right);\n}\n\nvoid tree::print()\n{\n\tinorder(root);\n\tcout << endl;\n\tpreorder(root);\n\tcout << endl;\n}\n\n\nint main()\n{\n\tint m;\n\tcin >> m;\n\t\n\ttree T;\n\t\n\tfor(int i=0; i<m; i++){\n\t\tstring com;\n\t\tcin >> com;\n\t\t\n\t\tif(com==\"insert\"){\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\t\n\t\t\tT.insert(k);\n\t\t}\n\t\telse if(com==\"find\"){\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\t\n\t\t\tif(T.find(k)!=0){\n\t\t\t\tcout << \"yes\" << endl;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcout << \"no\" << endl;\n\t\t\t}\n\t\t}\n\t\telse if(com==\"print\"){\n\t\t\tT.print();\n\t\t}\n\t}\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 21952, "score_of_the_acc": -1.7398, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_8_B_10719566", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nstruct node{\n int p,l,r,key;\n};\nconst int N=5e5+5;\nnode tree[N];\nint idx=0,root=-1;\nvoid insert(int z){\n int y=-1,x=root;\n while(x!=-1){\n y=x;\n if(tree[z].key<tree[x].key) x=tree[x].l;\n else x=tree[x].r;\n }\n tree[z].p=y;\n if(y==-1){\n root=z;\n }else if(tree[z].key<tree[y].key){\n tree[y].l=z;\n }else{\n tree[y].r=z;\n }\n}\nvoid dfs1(int u=0){\n if(u==-1) return;\n dfs1(tree[u].l);\n cout<<\" \"<<tree[u].key;\n dfs1(tree[u].r);\n}\nvoid dfs2(int u=0){\n if(u==-1) return;\n cout<<\" \"<<tree[u].key;\n dfs2(tree[u].l);\n dfs2(tree[u].r);\n}\nbool find(int k,int u){\n if(u==-1) return false;\n if(k==tree[u].key) return true;\n else if(k<tree[u].key) return find(k,tree[u].l);\n else return find(k,tree[u].r);\n}\nvoid solve(){\n int n;cin>>n;\n for(int i=0;i<n;i++){\n string s;cin>>s;\n if(s==\"insert\"){\n int k;cin>>k;\n int z=idx++;\n tree[z].key=k;\n tree[z].l=tree[z].r=-1;\n insert(z);\n }else if(s==\"print\"){\n dfs1();\n cout<<endl;\n dfs2();\n cout<<endl;\n }else if(s==\"find\"){\n int k;cin>>k;\n if(find(k,root)) cout<<\"yes\"<<endl;\n else cout<<\"no\"<<endl;\n }\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 17476, "score_of_the_acc": -0.503, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_8_B_10713552", "code_snippet": "#include<stdio.h>\n#include<stdlib.h>\n#include<string>\n#include<iostream>\n\nusing namespace std;\n\n// Structure to represent a node in the binary search tree\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL; // Global pointers for the root of the tree and a sentinel NIL node\n\n// Function to find a node with a given key\nNode *find(Node *u, int k) {\n while (u != NIL && k != u->key) {\n if (k < u->key) {\n u = u->left;\n } else {\n u = u->right;\n }\n }\n return u;\n}\n\n// Function to insert a new key into the binary search tree\nvoid insert(int k) {\n Node *y = NIL; // y will be the parent of the new node z\n Node *x = root; // x traverses the tree to find the insertion point\n Node *z;\n\n // Allocate memory for the new node and initialize its fields\n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n // Traverse the tree to find the correct position for the new node\n while (x != NIL) {\n y = x; // Keep track of the current node's parent\n if (z->key < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n\n z->parent = y; // Set the parent of the new node\n\n // If the tree is empty, the new node becomes the root\n if (y == NIL) {\n root = z; // Correction: 'root z;' was a syntax error. Should be 'root = z;'\n } else {\n // Otherwise, attach the new node to its parent\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\n// Function for in-order tree traversal (left, root, right)\nvoid inorder(Node *u) {\n if (u == NIL) return; // Base case: if node is NIL, return\n inorder(u->left); // Recursively visit left subtree\n printf(\" %d\", u->key); // Print current node's key\n inorder(u->right); // Recursively visit right subtree\n}\n\n// Function for pre-order tree traversal (root, left, right)\nvoid preorder(Node *u) {\n if (u == NIL) return; // Base case: if node is NIL, return\n printf(\" %d\", u->key); // Print current node's key\n preorder(u->left); // Recursively visit left subtree\n preorder(u->right); // Recursively visit right subtree\n}\n\nint main() {\n int n, x; // n for number of commands, x for key value\n string com; // com for command string\n\n // Initialize NIL node. This is crucial for correctly handling tree boundaries.\n NIL = (Node *)malloc(sizeof(Node));\n NIL->left = NIL;\n NIL->right = NIL;\n NIL->parent = NIL;\n root = NIL; // Initialize root to NIL (empty tree)\n\n scanf(\"%d\", &n); // Read the number of commands\n\n for (int i = 0; i < n; i++) {\n cin >> com; // Read the command string\n if (com[0] == 'f') { // If command starts with 'f' (find)\n scanf(\"%d\", &x); // Read the key to find\n Node *t = find(root, x); // Call find function\n if (t != NIL) {\n printf(\"yes\\n\");\n } else {\n printf(\"no\\n\");\n }\n } else if (com == \"insert\") { // If command is \"insert\"\n scanf(\"%d\", &x); // Read the key to insert\n insert(x); // Call insert function\n } else if (com == \"print\") { // If command is \"print\"\n inorder(root); // Perform in-order traversal\n printf(\"\\n\");\n preorder(root); // Correction: 'preorder(\"root\");' was a type mismatch. Should be 'preorder(root);'\n printf(\"\\n\");\n }\n }\n\n // Free the NIL node when done. (Optional for competitive programming, good practice for full applications)\n free(NIL);\n\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 22200, "score_of_the_acc": -1.4636, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_8_B_10711731", "code_snippet": "#include<stdio.h>\n#include<stdlib.h>\n#include<string>\n#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL;\n\nNode * find(Node *u, int k) {\n while ( u != NIL && k != u->key) {\n if (k < u->key) u = u->left;\n else u = u->right;\n }\n \n return u;\n}\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z;\n \n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n \n while ( x != NIL) {\n y = x;\n if (z->key < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n \n z->parent = y;\n if (y == NIL) {\n root = z;\n } else {\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nvoid inorder(Node *u) {\n if (u == NIL) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if ( u == NIL) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int n, i, x;\n string com;\n \n scanf(\"%d\", &n);\n \n for (i = 0; i < n; i++) {\n cin >> com;\n if (com[0] == 'f') {\n scanf(\"%d\", &x);\n Node *t = find(root, x);\n if (t != NIL) printf(\"yes\\n\");\n else printf(\"no\\n\");\n } else if (com ==\"insert\") {\n scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 22284, "score_of_the_acc": -1.5105, "final_rank": 11 } ]
aoj_ALDS1_9_B_cpp
Maximum Heap A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself. Here is an example of a max-heap. Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code. $maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap. 1 maxHeapify(A, i) 2 l = left(i) 3 r = right(i) 4 // select the node which has the maximum value 5 if l ≤ H and A[l] > A[i] 6 largest = l 7 else 8 largest = i 9 if r ≤ H and A[r] > A[largest] 10 largest = r 11 12 if largest ≠ i // value of children is larger than that of i 13 swap A[i] and A[largest] 14 maxHeapify(A, largest) // call recursively The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner. 1 buildMaxHeap(A) 2 for i = H/2 downto 1 3 maxHeapify(A, i) Input In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$). Output Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value. Constraint $1 \leq H \leq 500,000$ $-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$ Sample Input 1 10 4 1 3 2 16 9 10 14 8 7 Sample Output 1 16 14 10 8 7 9 3 2 4 1 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.
[ { "submission_id": "aoj_ALDS1_9_B_11055699", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\n// 節点iを根とする部分木がmax-ヒープとなるようA[i]の値をmax-ヒープの葉へ向かって下降させる\nvoid maxHeapify(vector<ll> &A, ll i, ll h) {\n ll left = i * 2;\n ll right = i * 2 + 1;\n // 左の子, 右の子, 自分で値が最大なノードを選ぶ\n ll largest = i;\n if (left <= h and A[left] > A[largest]) {\n largest = left;\n }\n if (right <= h and A[right] > A[largest]) {\n largest = right;\n }\n // iの子の方が大きかったら\n if (largest != i) {\n swap(A[i], A[largest]);\n maxHeapify(A, largest, h);\n }\n}\n\n// ボトムアップにmaxHeapifyを適用することで配列Aをmax-ヒープに変換する\nvoid buildMaxHeap(vector<ll> &A, ll h) {\n for (int i = (h/2); i >= 1; i--) {\n maxHeapify(A, i, h);\n }\n}\n\n\n// main\nvoid solve() {\n ll h;\n cin >> h;\n vl A(h+1);\n rep(i,h) {\n cin >> A[i+1];\n }\n buildMaxHeap(A, h);\n rep(i,h) {\n cout << \" \" << A[i+1];\n }\n cout << endl;\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 7312, "score_of_the_acc": -1.5503, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_9_B_11041336", "code_snippet": "#include<iostream>\nusing namespace std;\nstatic const int MAX = 2000000;\n\nint H, A[MAX+1];\n\nvoid maxHeapify(int i){\n int l, r, largest;\n l = 2 * i;\n r = 2 * i + 1;\n\n if(l <= H && A[l] > A[i]) largest = l;\n else largest = i;\n if(r <= H && A[r] > A[largest]) largest = r;\n \n if(largest != i){\n swap(A[i],A[largest]);\n maxHeapify(largest);\n }\n}\n\nint main(){\n cin >> H;\n\n for(int i = 1; i <= H; i++) cin >> A[i];\n\n for(int i = H / 2; i >= 1; i--) maxHeapify(i);\n\n for(int i = 1; i <= H; i++){\n cout << \" \" << A[i];\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5276, "score_of_the_acc": -1.0671, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_9_B_11021962", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid swap(vector<int>& a, int x, int y)\n{\n int tmp = a[x];\n a[x] = a[y];\n a[y] = tmp;\n}\n\nvoid max_heapify(vector<int>& a, int h, int i)\n{\n int l_id = i*2;\n int r_id = i*2+1;\n\n int largest_id = i;\n if(l_id <= h && a[l_id] > a[largest_id])\n largest_id = l_id;\n if(r_id <= h && a[r_id] > a[largest_id])\n largest_id = r_id;\n\n if(largest_id != i)\n {\n swap(a, i, largest_id);\n max_heapify(a, h, largest_id);\n }\n}\n\nvoid build_max_heap(vector<int>& heap, int h)\n{\n for(int i = h/2; i >= 1; i--)\n max_heapify(heap, h, i);\n}\n\nint main()\n{\n int h;\n cin >> h;\n vector<int> heap(h+1);\n for(int i = 1; i <= h; i++)\n cin >> heap[i];\n\n build_max_heap(heap, h);\n for(int i = 1; i <= h; i++)\n cout << \" \" << heap[i];\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 4784, "score_of_the_acc": -1.0242, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_9_B_11017608", "code_snippet": "#include <iostream>\nusing namespace std;\n#define MAX 2000000\n\nint H, A[MAX+1];\n\nvoid maxHeapify(int i) {\n int l, r, largest;\n l = 2 * i;\n r = 2 * i + 1;\n\n if ( l <= H && A[l] > A[i] ) largest = l;\n else largest = i;\n if ( r <= H && A[r] > A[largest] ) largest = r;\n\n if ( largest != i ) {\n swap(A[i], A[largest]);\n maxHeapify(largest);\n }\n}\n\nint main(){\n cin >> H;\n\n for ( int i = 1; i <= H; i++ ) cin >> A[i];\n for ( int i = H / 2; i >= 1; i-- ) maxHeapify(i);\n for ( int i = 1; i <= H; i++ ) {\n cout << \" \" << A[i];\n }\n cout << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5144, "score_of_the_acc": -1.0173, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_9_B_10952175", "code_snippet": "#include<iostream>\nusing namespace std;\n#define MAX 500000\n\nint parent(int k) { return k / 2; }\nint left(int k) { return 2 * k; }\nint right(int k) { return 2 * k + 1; }\n\nvoid maxHeapify(int k, int B[], int h) {\n int largest = k;\n if ( left(k) <= h && B[k] < B[left(k)] ) largest = left(k);\n if ( right(k) <= h && B[largest] < B[right(k)] ) largest = right(k);\n if ( largest != k ) {\n int temp = B[k];\n B[k] = B[largest];\n B[largest] = temp;\n maxHeapify(largest, B, h);\n }\n}\n\nvoid buildMaxHeap(int B[], int h) {\n for (int i = h / 2; i > 0; i--) {\n maxHeapify(i, B, h);\n }\n}\n\nint main() {\n int H, i, A[MAX+1];\n cin >> H;\n for (i = 1; i <= H; i++) cin >> A[i];\n\n buildMaxHeap(A, H);\n for (i = 1; i <= H; i++) cout << \" \" << A[i];\n cout << endl;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5272, "score_of_the_acc": -1.0656, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_9_B_10934253", "code_snippet": "#include <stdio.h>\n#define max 500001\nint n;\nint a[max];\nvoid maxHeapify(int i)//从根节点到叶节点方向找a[i]的恰当位置\n{\n int l=2*i;\n int r=2*i+1;\n int largest;\n if(l<=n&&a[l]>a[i]){\n largest=l;\n }else largest=i;\n if(r<=n&&a[r]>a[largest]){\n largest=r;\n }\n if(largest!=i){\n int m=a[i];\n a[i]=a[largest];\n a[largest]=m;\n maxHeapify(largest);//largest值被换了,得算一下换完后这里的最大值\n }\n return;\n}\nvoid buildMaxHeap(void)//从最底部的根结点到根开始排位置\n{\n for(int j=n/2;j>0;j--){\n maxHeapify(j);\n }\n}\nint main()\n{\n scanf(\"%d\",&n);\n for(int i=1;i<=n;i++){\n scanf(\"%d\",&a[i]);\n }\n buildMaxHeap();\n for(int i=1;i<=n;i++){\n if(i!=1)printf(\" \");\n printf(\"%d\",a[i]);\n }\n printf(\"\\n\");\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4872, "score_of_the_acc": -0.2003, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_9_B_10879598", "code_snippet": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nint main()\n{\n std::vector<int> vi;\n int h;\n std::cin >> h;\n while (h--) {\n int n;\n std::cin >> n;\n vi.push_back(n);\n }\n std::make_heap(vi.begin(), vi.end());\n for (int i = 0; i < vi.size(); ++i) {\n if (i) std::cout << \" \";\n std::cout << vi[i];\n }\n std::cout << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5196, "score_of_the_acc": -1.0369, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_9_B_10848612", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <cmath>\n#include <cstdlib>\nusing namespace std;\n\n#define parent(x) ((x)>>(1))\n#define lc(x) ((x)<<(1))\n#define rc(x) ((x)<<(1)|1)\n\nconst int MAX = 500010;\nint heap[MAX];\nint H;\n\nvoid maxHeapify(int i) {\n int l = lc(i);\n int r = rc(i);\n int largest = i;\n if (l <= H && heap[l] > heap[i]) {\n largest = l;\n }\n if (r <= H && heap[r] > heap[largest]) {\n largest = r;\n }\n if (largest != i) {\n swap(heap[i], heap[largest]);\n maxHeapify(largest);\n }\n}\n\nint main() {\n //freopen(\"in.txt\", \"r\", stdin);\n //freopen(\"out.txt\", \"w\", stdout);\n scanf(\"%d\", &H);\n for (int i = 1; i <= H; i++) {\n scanf(\"%d\", &heap[i]);\n }\n for (int i = H / 2; i >= 1; i--) {\n maxHeapify(i);\n }\n for (int i = 1; i <= H; i++) {\n printf(\" %d\", heap[i]);\n }\n printf(\"\\n\");\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5444, "score_of_the_acc": -0.4163, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_9_B_10845716", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); i++)\n#define rep2(i, s, n) for (int i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<int> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<int> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\nint parent(int i) {\n return i / 2;\n}\nint left(int i) {\n return 2 * i;\n}\nint right(int i) {\n return 2 * i + 1;\n}\n\nvoid maxHeapify(vector<int> &A, int i, int h) {\n int l = left(i);\n int r = right(i);\n int largest;\n if (l <= h && A[l] > A[i]) {\n largest = l;\n }\n else {\n largest = i;\n }\n if (r <= h && A[r] > A[largest]) {\n largest = r;\n }\n if (largest != i) {\n swap(A[i], A[largest]);\n maxHeapify(A, largest, h);\n }\n}\n\nvoid buildMaxHeap(vector<int> &A, int h) {\n for (int i = h / 2; i > 0; --i) {\n maxHeapify(A,i,h);\n }\n}\n\nvoid solve() {\n int h;\n cin >> h;\n vector<int> A(h+1);\n for (int i = 1; i <= h; i++) {\n cin >> A[i];\n }\n buildMaxHeap(A, h);\n for (int i = 1; i<=h; i++) {\n cout << \" \" << A[i];\n }\n cout << endl;\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5248, "score_of_the_acc": -0.7708, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_9_B_10781586", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\n\nvoid maxHeapify(vector<int>& a, int i) {\n int h = a.size()-1;\n int l = 2*i;\n int r = 2*i+1;\n int largest;\n if (l <= h && a[l] > a[i]) largest = l;\n else largest = i;\n if (r <= h && a[r] > a[largest]) largest = r;\n\n if (largest != i) {\n swap(a[i], a[largest]);\n maxHeapify(a, largest);\n }\n}\n\nvoid buildMaxHeap(vector<int>& a) {\n int h = a.size()-1;\n for (int i=h/2; i>=1; i--) {\n maxHeapify(a, i);\n }\n}\n\nint main()\n{\n int h;\n cin >> h;\n vector<int> a(h+1);\n rep(i,h) cin >> a[i+1];\n buildMaxHeap(a);\n\n rep(i,h) cout << a[i+1] << \" \";\n cout << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 4720, "score_of_the_acc": -0.8571, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_9_B_10737008", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm> \nusing namespace std;\n\nvoid maxHeapify(vector<int>& a, int h, int i) {\n int l = i * 2;\n int r = i * 2 + 1;\n int largest;\n\n if (l <= h && a[i] < a[l]) {\n largest = l;\n } else {\n largest = i;\n }\n if (r <= h && a[largest] < a[r]) {\n largest = r;\n }\n if (largest != i) {\n swap(a[i], a[largest]);\n maxHeapify(a, h, largest);\n }\n}\n\nvoid buildMaxHeap(vector<int>& a, int h) {\n for (int i = h/2; i > 0; i --) {\n maxHeapify(a, h, i);\n }\n}\n\nint main(int argc, char const *argv[])\n{\n int h;\n cin >> h;\n vector<int> a(h);\n for (int i = 1; i <= h; i ++) {\n cin >> a[i];\n }\n\n buildMaxHeap(a, h);\n\n for (int i = 1; i <= h; i ++) {\n cout << \" \" << a[i];\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 4924, "score_of_the_acc": -0.9342, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_9_B_10723716", "code_snippet": "#include <stdio.h>\n#include <algorithm>\n\nusing namespace std;\n\nint H;\n\nvoid maxHeapify(long long array[],int i){\n\tint left = 2*i;\n\tint right = 2*i + 1;\n\tif(left > H) return;\n\tint largest = i;\n\tif(right <= H){\n\t\tif((array[right] > array[left]) && (array[right] > array[i])){\n\t\t\tlargest = right;\n\t\t}else if((array[left] > array[right]) && (array[left] > array[i])){\n\t\t\tlargest = left;\n\t\t}\n\t}else{\n\t\tif(array[i] < array[left]){\n\t\t\tlargest = left;\n\t\t}\n\t}\n\tif(largest != i){\n\t\tswap(array[i],array[largest]);\n\t\tmaxHeapify(array, largest);\n\t}\n}\n\nvoid buildMaxHeap(long long array[]){\n\tfor(int i = H/2; i >=1; i--) maxHeapify(array,i);\n}\n\nint main(){\n\tscanf(\"%d\",&H);\n\tlong long array[H+1];\n\n\tfor(int i = 1; i <= H; i++) scanf(\"%lld\",&array[i]);\n\n\tbuildMaxHeap(array);\n\n\tfor(int i = 1; i <= H; i++) printf(\" %lld\",array[i]);\n\tprintf(\"\\n\");\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 6628, "score_of_the_acc": -0.8634, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_9_B_10721329", "code_snippet": "#include <iostream>\nusing namespace std;\n#define MAX 500000\n\nint H, A[MAX + 1];\n\nvoid maxHeapify(int i) {\n int l, r, largest;\n l = 2 * i;\n r = 2 * i + 1;\n\n if (l <= H && A[l] > A[i])\n largest = l;\n else\n largest = i;\n if (r <= H && A[r] > A[largest]) largest = r;\n\n if (largest != i) {\n swap(A[i], A[largest]);\n maxHeapify(largest);\n }\n}\n\nint main() {\n cin >> H;\n\n for (int i = 1; i <= H; i++) cin >> A[i];\n\n for (int i = H / 2; i >= 1; i--) maxHeapify(i);\n\n for (int i = 1; i <= H; i++) {\n cout << \" \" << A[i];\n }\n cout << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5388, "score_of_the_acc": -1.1094, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_9_B_10719652", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nint H;\nvoid maxHeapify(int a[],int i){\n int l=i*2;\n int r=i*2+1;\n int p=i;\n if(l<=H&&a[l]>a[p]) p=l;\n if(r<=H&&a[r]>a[p]) p=r;\n if(p!=i){\n swap(a[p],a[i]);\n maxHeapify(a,p);\n }\n}\nvoid buildMaxHeap(int a[]){\n for(int i=H/2;i>=1;i--) maxHeapify(a,i);\n}\nvoid solve(){\n cin>>H;\n int a[H+1];\n for(int i=1;i<=H;i++) cin>>a[i];\n buildMaxHeap(a);\n for(int i=1;i<=H;i++) cout<<\" \"<<a[i];\n cout<<endl;\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 7368, "score_of_the_acc": -1, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_9_B_10714509", "code_snippet": "#include<iostream>\nusing namespace std;\n#define MAX 2000000\n\nint H, A[MAX + 1];\n\nvoid maxHeapify(int i) {\n int l, r, largest;\n l = 2 * i;\n r = 2 * i + 1;\n \n if ( l <= H && A[l] > A[i]) largest = l;\n else largest = i;\n if (r <= H && A[r] > A[largest]) largest = r;\n \n if (largest != i) {\n swap(A[i], A[largest]);\n maxHeapify(largest);\n }\n}\n\nint main() {\n cin >> H;\n \n for (int i = 1; i <= H; i++) cin >> A[i];\n \n for (int i = H / 2; i >= 1; i--) maxHeapify(i);\n \n for (int i = 1; i <= H; i++) {\n cout << \" \" << A[i];\n }\n \n cout << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5320, "score_of_the_acc": -1.0837, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_9_B_10711946", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n cin.tie(0);\n cin.sync_with_stdio(0);\n int H;\n cin >> H;\n vector<int> v;\n int now;\n for (int i = 0; i < H; ++i) {\n int now;\n cin >> now;\n v.push_back(now);\n }\n make_heap(v.begin(), v.end());\n for (auto i : v) cout << \" \" << i;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5088, "score_of_the_acc": -0.139, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_9_B_10711945", "code_snippet": "#include <iostream>\n\nusing namespace std;\n\nint num[500005];\nint H;\n\nvoid maxHeapify(int i){\n int l = i*2;\n int r = i*2 + 1;\n int largest;\n if(l <= H && (num[l] > num[i])){\n largest = l;\n }else{\n largest = i;\n }\n if(r <= H && (num[r] > num[largest])){\n largest = r;\n }\n if(largest != i){\n swap(num[largest], num[i]);\n maxHeapify(largest);\n }\n\n}\n\n\nvoid buildMaxHeap(){\n for(int i = H / 2; i >= 1; i--){\n maxHeapify(i);\n }\n}\n\nint main(){\n cin >> H;\n for (int i = 1; i <= H; i++){\n cin >> num[i];\n }\n buildMaxHeap();\n for (int i = 1; i <= H; i++){\n cout << ' ' << num[i];\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 5300, "score_of_the_acc": -1.219, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_9_B_10711944", "code_snippet": "#include <iostream>\n\nusing namespace std;\n\nint num[500005];\nint H;\n\nvoid maxHeapify(int i){\n int l = i*2;\n int r = i*2 + 1;\n int largest;\n if(l <= H && (num[l] > num[i])){\n largest = l;\n }else{\n largest = i;\n }\n if(r <= H && (num[r] > num[largest])){\n largest = r;\n }\n if(largest != i){\n swap(num[largest], num[i]);\n maxHeapify(largest);\n }\n\n}\n\n\nvoid buildMaxHeap(){\n for(int i = H / 2; i >= 1; i--){\n maxHeapify(i);\n }\n}\n\nint main(){\n cin >> H;\n for (int i = 1; i <= H; i++){\n cin >> num[i];\n }\n buildMaxHeap();\n for (int i = 1; i <= H; i++){\n cout << num[i] << ' ';\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5084, "score_of_the_acc": -0.9946, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_9_B_10711943", "code_snippet": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nint h[500001];\nint n;\n\n\n\nvoid maxHeapify(int i){\n int l = 2*i;\n int r = 2*i + 1;\n int largest;\n if(l <= n && h[l] > h[i])\n largest = l;\n else\n largest = i;\n if(r <= n && h[r] > h[largest])\n largest = r;\n if(largest != i){\n swap(h[i], h[largest]);\n maxHeapify(largest);\n }\n}\n\nint main()\n{\n cin>>n;\n for(int i = 1; i <= n; ++i){\n int num;\n cin>>num;\n h[i] = num;\n }\n\n for (int i = n/2; i >= 1; --i)\n maxHeapify(i);\n\n for(int i = 1; i <= n; ++i){\n cout<<' '<<h[i];\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5124, "score_of_the_acc": -1.0097, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_9_B_10711942", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\t\n\tvector<int> v;\n\tfor(int i = 0; i < n; i++) {\n\t\tint x;\n\t\tcin >> x;\n\t\t\n\t\tv.push_back(x);\n\t}\n\t\n\tmake_heap(v.begin(), v.end());\n\t\n\tfor(int i = 0; i < n - 1; i++) {\n\t\tcout << v[i] << \" \";\n\t}\n\tcout << v.back() << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5076, "score_of_the_acc": -0.9916, "final_rank": 8 } ]
aoj_ALDS1_8_C_cpp
Binary Search Tree III Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. insert $k$: Insert a node containing $k$ as key into $T$. find $k$: Report whether $T$ has a node containing $k$. delete $k$: Delete a node containing $k$. print : Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print " yes " if $T$ has a node containing $k$, " no " if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Constraints The number of operations $\leq 500,000$ The number of print operations $\leq 10$. $-2,000,000,000 \leq key \leq 2,000,000,000$ The height of the binary tree does not exceed 100 if you employ the above pseudo code. The keys in the binary search tree are all different. Sample Input 1 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Sample Output 1 yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.
[ { "submission_id": "aoj_ALDS1_8_C_11025601", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); i++)\n#define rep2(i, s, n) for (int i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<int> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<int> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<int> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\nstruct node {\n int key;\n node *right, *left, *parent;\n};\n\nnode *root, *NIL;\n\nvoid insert(int k) {\n node *y = NIL;\n node *x = root;\n node *z;\n\n z = (node *)malloc(sizeof(node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n z->parent = y;\n if (y == NIL) {\n root = z;\n } else {\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nnode* getMinimum(node *x) {\n while (x->left != NIL) {\n x = x->left;\n }\n return x;\n}\n\nnode* getSuccessor(node *x) {\n if (x->right != NIL) {\n return getMinimum(x->right);\n }\n node *y = x->parent;\n while (y != NIL && x == y->parent) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid tree_delete(node *z) {\n node *y;\n node *x;\n if (z->left == NIL || z->right == NIL) {\n y = z;\n }\n else {\n y = getSuccessor(z);\n }\n\n if (y->left != NIL) {\n x = y->left;\n }\n else {\n x = y->right;\n }\n if (x != NIL) {\n x->parent = y->parent;\n }\n if (y->parent == NIL) {\n root = x;\n }\n else {\n if (y == y->parent->left) {\n y->parent->left = x;\n }\n else {\n y->parent->right = x;\n }\n }\n if (y != z) {\n z->key = y->key;\n }\n free(y);\n}\n\nnode* find(int k) {\n node *x = root;\n while (x != NIL && k != x->key) {\n if (k < x->key) {\n x = x->left;\n }\n else {\n x = x->right;\n }\n }\n return x;\n}\n\nvoid inorder(node *u) {\n if (u == NIL) {\n return;\n }\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\nvoid preorder(node *u) {\n if (u == NIL) {\n return;\n }\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nvoid solve() {\n ll n;\n cin >> n;\n rep(i, n) {\n string cmd;\n cin >> cmd;\n if (cmd == \"insert\") {\n ll target;\n cin >> target;\n insert(target);\n }\n else if (cmd == \"print\") {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n else if (cmd == \"find\") {\n ll target;\n cin >> target;\n node* t = find(target);\n if (t != NIL) {\n cout << \"yes\" << endl;\n }\n else cout << \"no\" << endl;\n }\n else if (cmd == \"delete\") {\n ll target;\n cin >> target;\n tree_delete(find(target));\n }\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 22272, "score_of_the_acc": -1.0865, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_8_C_11017211", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct binary_node\n{\n int id;\n binary_node* parent;\n binary_node* left;\n binary_node* right;\n bool disposed;\n\n int key;\n\n void set_left(binary_node& l)\n {\n left = &l;\n }\n void set_right(binary_node& r)\n {\n right = &r;\n }\n binary_node(int i, int k)\n {\n id = i;\n key = k;\n parent = nullptr;\n left = nullptr;\n right = nullptr;\n disposed = false;\n }\n binary_node() : binary_node(-1, -2147483648) {}\n};\n\nstruct binary_tree\n{\n vector<binary_node> nodes;\n binary_node* root;\n int node_count;\n\n void insert(int k)\n {\n binary_node* z = &nodes[node_count];\n z->key = k;\n node_count++;\n\n binary_node* y = nullptr;\n binary_node* x = this->root;\n while(x != nullptr)\n {\n y = x;\n if(z->key < x->key)\n x = x->left;\n else\n x = x->right;\n }\n\n if(y == nullptr)\n {\n root = z;\n }\n else\n {\n z->parent = y;\n if(z->key < y->key)\n y->left = z;\n else\n y->right = z;\n }\n }\n\n bool find(int k)\n {\n if(node_count == 0)\n return false;\n else\n {\n binary_node* x = root;\n while(x != nullptr)\n {\n if(k == x->key && !x->disposed)\n return true;\n\n if(k < x->key)\n x = x->left;\n else\n x = x->right;\n }\n return false;\n }\n }\n \n void del(binary_node* z)\n {\n z->disposed = true;\n if(z->left == nullptr && z->right == nullptr)\n {\n if(z->key < z->parent->key)\n z->parent->left = nullptr;\n else\n z->parent->right = nullptr;\n }\n else if(z->left != nullptr && z->right == nullptr)\n {\n if(z->key < z->parent->key)\n {\n z->parent->left = z->left;\n z->left->parent = z->parent;\n }\n else\n {\n z->parent->right = z->left;\n z->left->parent = z->parent;\n }\n }\n else if(z->left == nullptr && z->right != nullptr)\n {\n if(z->key < z->parent->key)\n {\n z->parent->left = z->right;\n z->right->parent = z->parent;\n }\n else\n {\n z->parent->right = z->right;\n z->right->parent = z->parent;\n }\n }\n else\n {\n z->disposed = false;\n // successor(右部分木の最小ノード)を探す\n binary_node* y = z->right;\n while (y->left != nullptr)\n y = y->left;\n\n z->key = y->key; // 値をコピー\n del(y); // successorを削除\n }\n }\n void del(int k)\n {\n //キーの位置の節点を探す\n if(node_count == 0)\n return;\n else\n {\n binary_node* x = root;\n while(true)\n {\n if(x == nullptr)\n return;\n\n if(k == x->key)\n {\n del(x);\n return; \n }\n\n if(k < x->key)\n x = x->left;\n else\n x = x->right;\n }\n }\n }\n\n void preorder_walk(binary_node* n)\n {\n if(n->disposed == false)\n cout << \" \" << n->key;\n if(n->left != nullptr)\n preorder_walk(n->left);\n if(n->right != nullptr)\n preorder_walk(n->right);\n }\n void preorder_walk()\n {\n preorder_walk(root);\n cout << endl;\n }\n void inorder_walk(binary_node* n)\n {\n if(n->left != nullptr)\n inorder_walk(n->left);\n if(n->disposed == false)\n cout << \" \" << n->key;\n if(n->right != nullptr)\n inorder_walk(n->right);\n }\n void inorder_walk()\n {\n inorder_walk(root);\n cout << endl;\n }\n\n binary_tree(int n)\n {\n node_count = 0;\n root = nullptr;\n for(int i = 0; i < n; i++)\n nodes.push_back(binary_node(i,-2147483648));\n }\n binary_tree() : binary_tree(0) {};\n};\n\nint main()\n{\n int q;\n cin >> q;\n\n binary_tree t = binary_tree(q);\n\n for(int query = 0; query < q; query++)\n {\n string s;\n cin >> s;\n if(s == \"insert\")\n {\n int k;\n cin >> k;\n t.insert(k);\n }\n if(s == \"find\")\n {\n int k;\n cin >> k;\n if(t.find(k))\n cout << \"yes\" << endl;\n else\n cout << \"no\" << endl;\n }\n if(s == \"delete\")\n {\n int k;\n cin >> k;\n t.del(k);\n }\n if(s == \"print\")\n {\n t.inorder_walk();\n t.preorder_walk();\n }\n }\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 23940, "score_of_the_acc": -1.5495, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_8_C_11006195", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstdio>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL;\n\nNode* treeMinimum(Node *x) {\n while (x->left != NIL) x = x->left;\n return x;\n}\n\nNode* find(Node *u, int k) {\n while (u != NIL && k != u->key) {\n if (k < u->key) u = u->left;\n else u = u->right;\n }\n return u;\n}\n\nNode* treeSuccessor(Node *x) {\n if (x->right != NIL) return treeMinimum(x->right);\n Node *y = x->parent;\n while (y != NIL && x == y->right) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid treeDelete(Node *z) {\n Node *y = (z->left == NIL || z->right == NIL) ? z : treeSuccessor(z);\n Node *x = (y->left != NIL) ? y->left : y->right;\n\n if (x != NIL) x->parent = y->parent;\n\n if (y->parent == NIL) {\n root = x;\n } else if (y == y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n\n if (y != z) z->key = y->key;\n\n delete y;\n}\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z = new Node{k, NIL, NIL, nullptr};\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key) x = x->left;\n else x = x->right;\n }\n\n z->parent = y;\n if (y == NIL) root = z;\n else if (z->key < y->key) y->left = z;\n else y->right = z;\n}\n\nvoid inorder(Node *u) {\n if (u == NIL) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == NIL) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int n, x;\n string com;\n\n // --- 番兵ノードを初期化 ---\n NIL = new Node{0, nullptr, nullptr, nullptr};\n NIL->left = NIL->right = NIL->parent = NIL;\n root = NIL;\n\n scanf(\"%d\", &n);\n\n for (int i = 0; i < n; i++) {\n cin >> com;\n if (com[0] == 'f') {\n scanf(\"%d\", &x);\n Node *t = find(root, x);\n printf(t != NIL ? \"yes\\n\" : \"no\\n\");\n } else if (com == \"insert\") {\n scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n } else if (com == \"delete\") {\n scanf(\"%d\", &x);\n Node *t = find(root, x);\n if (t != NIL) treeDelete(t);\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 22220, "score_of_the_acc": -1.2008, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_8_C_10994386", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nvector<int> preorder;\nvector<int> inorder;\nvector<int> postorder;\n\nclass Node {\npublic:\n\tint value;\n\tNode* left;\n\tNode* right;\n\n\tNode(int value) {\n\t\tthis->value = value;\n\t\tthis->left = NULL;\n\t\tthis->right = NULL;\n\t}\n};\n\nclass BST {\npublic:\n\tNode* root;\n\tBST() {\n\t\tthis->root = NULL;\n\t}\n\n\tvoid Insert(int num);\n\tbool Find(int num);\n\tNode* Search(int num);\n\tvoid Delete(int num);\n\nprivate:\n\tNode* deleteNode(Node* node, int num); // 内部辅助函数\n};\n\nvoid BST::Insert(int num) {\n\tif (root == NULL) {\n\t\troot = new Node(num);\n\t\treturn;\n\t}\n\n\tNode* curr = root;\n\twhile (curr != NULL) {\n\t\tif (num < curr->value) {\n\t\t\tif (curr->left == NULL) {\n\t\t\t\tcurr->left = new Node(num);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcurr = curr->left; // 继续和左子树进行比较\n\t\t}\n\t\telse {\n\t\t\tif (curr->right == NULL) {\n\t\t\t\tcurr->right = new Node(num);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcurr = curr->right; // 继续和右子树进行比较\n\t\t}\n\t}\n}\n\nbool BST::Find(int num) {\n\tNode* curr = root;\n\twhile (curr != NULL) {\n\t\tif (num < curr->value) {\n\t\t\tcurr = curr->left;\n\t\t}\n\t\telse if (num > curr->value) {\n\t\t\tcurr = curr->right;\n\t\t}\n\t\telse {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nNode* BST::Search(int num) {\n\tNode* curr = root;\n\twhile (curr != NULL) {\n\t\tif (num < curr->value) {\n\t\t\tcurr = curr->left;\n\t\t}\n\t\telse if (num > curr->value) {\n\t\t\tcurr = curr->right;\n\t\t}\n\t\telse {\n\t\t\treturn curr;\n\t\t}\n\t}\n\treturn NULL;\n}\n\nNode* BST::deleteNode(Node* root, int num) {\n\tif (root == NULL) \n\t\treturn NULL;\n\n\tif (num < root->value) { // 在左子树中找\n\t\troot->left = deleteNode(root->left, num);\n\t}\n\telse if (num > root->value) { // 在右子树中找\n\t\troot->right = deleteNode(root->right, num);\n\t}\n\telse { // 此时的root就是要删除的节点\n\n\t\t// ① 没有左子树\n\t\tif (root->left == NULL) {\n\t\t\tNode* rightChild = root->right;\n\t\t\tdelete root;\n\t\t\treturn rightChild;\n\t\t}\n\n\t\t// ② 没有右子树\n\t\telse if (root->right == NULL) {\n\t\t\tNode* leftChild = root->left;\n\t\t\tdelete root;\n\t\t\treturn leftChild;\n\t\t}\n\n\t\t// ③ 左右子树都有\n\t\telse {\n\t\t\t// 找右子树中的最小节点(即中序后继)\n\t\t\tNode* successor = root->right;\n\t\t\twhile (successor->left != NULL) {\n\t\t\t\tsuccessor = successor->left;\n\t\t\t}\n\t\t\t// 用后继的值替换当前节点\n\t\t\troot->value = successor->value;\n\t\t\t// 删除右子树中的那个后继节点\n\t\t\troot->right = deleteNode(root->right, successor->value);\n\t\t}\n\t}\n\treturn root;\n}\n\n\nvoid BST::Delete(int num) {\n\troot = deleteNode(root, num);\n}\n\n// 前序遍历\nvoid PreorderTraversal(Node* node) {\n\tif (node == NULL) {\n\t\treturn;\n\t}\n\tpreorder.push_back(node->value);\n\tPreorderTraversal(node->left);\n\tPreorderTraversal(node->right);\n}\n\n// 中序遍历\nvoid InorderTraversal(Node* node) {\n\tif (node == NULL) {\n\t\treturn;\n\t}\n\tInorderTraversal(node->left);\n\tinorder.push_back(node->value);\n\tInorderTraversal(node->right);\n}\n\n// 后序遍历\nvoid PostorderTraversal(Node* node) {\n\tif (node == NULL) {\n\t\treturn;\n\t}\n\tPostorderTraversal(node->left);\n\tPostorderTraversal(node->right);\n\tpostorder.push_back(node->value);\n}\n\nvoid Print(Node *node) {\n\tinorder.clear();\n\tpreorder.clear();\n\tpostorder.clear();\n\n\tInorderTraversal(node);\n\tfor (int i = 0; i < inorder.size(); i++) {\n\t\t\n\t\t\tcout << \" \";\n\t\tcout << inorder[i];\n\t}\n\tcout << endl;\n\n\tPreorderTraversal(node);\n\tfor (int i = 0; i < preorder.size(); i++) {\n\t\t\n\t\t\tcout << \" \";\n\t\tcout << preorder[i];\n\t}\n\tcout << endl;\n\n\t//PostorderTraversal(node);\n\t//for (int i = 0; i < postorder.size(); i++) {\n\t//\tif (i)\n\t//\t\tcout << \" \";\n\t//\tcout << postorder[i];\n\t//}\n\t//cout << endl;\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tBST* tree = new BST();\n\n\tfor (int i = 0; i < n; i++) {\n\t\tstring inst;\n\t\tcin >> inst;\n\t\tif(inst == \"insert\")\n\t\t{\n\t\t\tint num;\n\t\t\tcin >> num;\n\t\t\ttree->Insert(num);\n\t\t}\n\t\telse if (inst == \"find\")\n\t\t{\n\t\t\tint num;\n\t\t\tcin >> num;\n\t\t\tif (tree->Find(num))\n\t\t\t\tcout << \"yes\" << endl;\n\t\t\telse\n\t\t\t\tcout << \"no\" << endl;\n\t\t}\n\t\telse if (inst == \"delete\") {\n\t\t\tint num;\n\t\t\tcin >> num;\n\t\t\ttree->Delete(num);\n\t\t}\n\t\telse if (inst == \"print\")\n\t\t{\n\t\t\tPrint(tree->root);\n\t\t}\n\t}\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 20156, "score_of_the_acc": -1.1744, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_8_C_10948368", "code_snippet": "#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *parent, *left, *right;\n Node(int k) : key(k), parent(nullptr), left(nullptr), right(nullptr) {}\n};\n\nNode *root;\n\nvoid insert (int k) {\n Node *x = root;\n Node *y = nullptr;\n Node *z;\n z = new Node(k);\n\n while ( x != nullptr ) {\n y = x;\n if ( z->key < x->key ) x = x->left;\n else x = x->right;\n }\n z->parent = y;\n if ( y == nullptr ) root = z;\n else if ( z->key < y->key ) y->left = z;\n else y->right = z;\n}\n\nNode * find(int k) {\n Node *x = root;\n while ( x != nullptr && k != x->key ) {\n if (k < x->key) x = x->left;\n else x = x->right;\n }\n return x;\n}\n\nNode * getMinimum(Node *u) {\n Node *v = nullptr;\n while( u != nullptr ) {\n v = u;\n u = u->left;\n }\n return v;\n}\n\nNode * getSuccessor(Node *u) {\n return getMinimum(u->right);\n}\n\nvoid treeDelete( int k ) {\n Node *z = find(k);\n Node *y, *x = nullptr;\n if ( z->left == nullptr || z->right == nullptr ) y = z;\n else y = getSuccessor(z);\n\n if ( y->left != nullptr ) x = y->left;\n else if (y->right != nullptr ) x = y->right;\n\n if ( x!= nullptr ) x->parent = y->parent;\n if ( y->parent != nullptr ) {\n if ( y == y->parent->left ) y->parent->left = x;\n else if ( y == y->parent->right ) y->parent->right = x;\n z->key = y->key;\n }\n}\n\nvoid inorder(Node *u) {\n if (u == nullptr) return;\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == nullptr) return;\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int m, x;\n cin >> m;\n string com;\n for (int i = 0; i < m; i++) {\n cin >> com;\n if ( com == \"insert\" ) {\n cin >> x;\n insert(x);\n }\n else if ( com == \"print\" ) {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n else if ( com == \"find\" ) {\n cin >> x;\n if ( find(x) != nullptr ) cout << \"yes\" << endl;\n else cout << \"no\" << endl;\n }\n else if ( com == \"delete\" ) {\n cin >> x;\n treeDelete(x);\n }\n }\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 22092, "score_of_the_acc": -1.4668, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_8_C_10931902", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#define max 50000\ntypedef struct Node{\n int m;\n Node *p,*l,*r;\n}tree;\nint n;\ntree *root=NULL;\nvoid preorder(tree *a){\n if(a==NULL) return;\n printf(\" %d\",a->m);\n preorder(a->l);\n preorder(a->r);\n}\nvoid inorder(tree *a){\n if(a==NULL) return;\n inorder(a->l);\n printf(\" %d\",a->m);\n inorder(a->r);\n}\nvoid insert(int k){\n tree *b=NULL;\n tree *c=root;\n tree *w;\n w=(tree*)malloc(sizeof(tree));//分配了内存,结束后还存在\n w->m=k;\n w->l=NULL;\n w->r=NULL;\n while(c!=NULL){\n b=c;//设置父节点\n if(w->m<c->m){\n c=c->l;\n }else c=c->r;\n }\n w->p=b;\n if(b==NULL){\n root=w;\n }else if(b->m>w->m){\n b->l=w;\n }else if(b->m<w->m){\n b->r=w;\n }\n}\ntree* find(int a){\n tree*q=root;\n while(q!=NULL&&q->m!=a){\n if(q->m<a){\n q=q->r;\n }else q=q->l;\n }\n return q;\n}\n/*void deletenode(int a){//删除操作\n tree* t=find(a);\n if(t->l==NULL&&t->r==NULL){\n if(t->p->l=t){\n tree *x=t->p;\n x->l=NULL;\n free(find(a));\n }else if(t->p->r=t){\n tree *x=t->p;\n x->r=NULL;\n free(find(a));\n }\n }else if(t->l!=NULL&t->r==NULL){\n if(t->p->l=t){\n tree *x=t->p;\n tree *y=t->l;\n x->l=y;\n y->p=x;\n free(find(a));\n }else if(t->p->r=t){\n tree *x=t->p;\n tree *y=t->l;\n x->r=y;\n y->p=x;\n free(find(a));\n }\n }else if(t->r!=NULL&t->l==NULL){\n if(t->p->l=t){\n tree *x=t->p;\n tree *y=t->r;\n x->l=y;\n y->p=x;\n free(find(a));\n }else if(t->p->r=t){\n tree *x=t->p;\n tree *y=t->r;\n x->r=y;\n y->p=x;\n free(find(a));\n }\n }else{\n\n }\n} 有点复杂,学习下讲解的做法*/\ntree* getMinimum(tree* a){//找到键值最小点\n while(a->l!=NULL){\n a=a->l;\n }\n return a;\n}\ntree* getSuccessor(tree* a){//寻找下一个结点,但我们是在有两个结点调用,所以只会走第一个框\n if(a->r!=NULL){\n tree *v=getMinimum(a->r);\n return v;\n }\n tree* v=a->p;\n while(v!=NULL&&a==v->r){\n a=v;\n v=v->p;\n }\n return v;\n}\nvoid deletenode(int a){\n tree* h=find(a);\n tree* y;\n if(h->l==NULL||h->r==NULL){//用y表示要删除的结点\n y=h;\n }else y=getSuccessor(h);\n //用x表示要删除的结点结点的子结点\n tree* x;\n if(y->l!=NULL){//三种情况都可\n x=y->l;\n }else x=y->r;\n //设置x的父结点\n if(x!=NULL){\n x->p=y->p;\n }\n if(y->p==NULL) {root=x;\n }else if(y->p->l==y){\n y->p->l=x;\n }else y->p->r=x;\n if(h!=y){\n h->m=y->m;\n }\n free(y);\n return;\n}\nint main(){\n scanf(\"%d\",&n);\n char q[20];\n int e;\n for(int i=0;i<n;i++){\n scanf(\"%s\",q);\n if(q[0]=='i'){\n scanf(\"%d\",&e);\n insert(e);\n }else\n if(q[0]=='p'){\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }else\n if(q[0]=='f'){\n scanf(\"%d\",&e);\n if(find(e)!=NULL){\n printf(\"yes\\n\");\n }else printf(\"no\\n\");\n }else\n if(q[0]=='d'){\n scanf(\"%d\",&e);\n deletenode(e);\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 21696, "score_of_the_acc": -0.6234, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_8_C_10806594", "code_snippet": "#include <iostream>\n#include <string.h>\n#include<vector>\nusing namespace std;\n\nstruct Node {\n int data; // ノードが保持するデータ\n Node *right, *left, *parent; \n\n};\n\nNode *root=NULL, *NIL=NULL;\n\nvoid insert(int k) {\n Node *y = NIL; // 親\n Node *x = root; // 子\n Node *z;\n z = (Node *)malloc(sizeof(Node));\n z->data = k;\n z->left = NIL;\n z->right = NIL;\n\n while (x != NIL) { // 葉のとこまでいくようにする\n y = x;\n if (z->data < x->data) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n z->parent = y;\n if (y == NIL) {\n root = z;\n } else if (z->data < y->data) {\n y->left = z;\n } else {\n y->right = z;\n }\n}\n\nint countNodes(Node *p) {\n if (p == NULL) {\n return 0;\n } else {\n return 1 + countNodes(p->left) + countNodes(p->right);\n }\n}\nvoid inorder(Node *p, vector<int>& result) {\n if(p != NULL) {\n inorder(p->left, result); // 左ノードへ移動\n result.push_back(p->data);\n inorder(p->right, result); // 右ノードへ移動\n }\n}\n\nvoid preorder(Node *p, vector<int>& result) {\n if(p != NULL) {\n result.push_back(p->data);\n preorder(p->left, result); // 左ノードへ移動\n preorder(p->right, result); // 右ノードへ移動\n }\n}\n\nvoid printVector(const vector<int>& arr) {\n for (size_t i = 0; i < arr.size(); i ++) {\n cout << \" \";\n cout << arr[i];\n if (i < arr.size() - 1) {\n\n }\n }\n cout << endl;\n} \n\nbool find(Node* root, int k) {\n while (root != NULL) {\n if (k == root->data) {\n return true;\n } else if (k < root->data) {\n root = root->left;\n } else {\n root = root->right;\n }\n }\n return false;\n}\n\nvoid deleteNode(int k) {\n Node *z = root; // 削除するNode\n Node *p = NIL; // zの親\n\n while (z != NIL && z->data != k) {\n p = z;\n if (k < z->data) {\n z = z->left;\n } else {\n z = z->right;\n }\n }\n if (z == NIL) {\n return;\n }\n\n Node *target_node;\n Node *target_parent;\n\n if (z->left != NIL && z->right != NIL) {\n Node *y = z->right;\n Node *y_parent = z; \n while (y->left != NIL) {\n y_parent = y;\n y = y->left;\n }\n z->data = y->data;\n\n target_node = y;\n target_parent = y_parent;\n } else {\n target_node = z;\n target_parent = p;\n }\n\n if (target_node->left == NIL && target_node->right ==NIL) { // zが子を持たない場合\n if (target_parent == NIL) {\n root = NIL;\n } else if (target_node == target_parent->left) {\n target_parent->left = NIL;\n } else if (target_node == target_parent->right) {\n target_parent->right = NIL;\n }\n free(target_node);\n } else if (target_node->left == NIL || target_node->right == NIL) { // zがちょうど1つの子を持つ場合\n Node *child_of_target = NIL; // z の唯一の子\n if (target_node->left != NIL) {\n child_of_target = target_node->left;\n } else {\n child_of_target = target_node->right;\n }\n\n if (target_parent == NIL) { // zがルートノードの時\n root = child_of_target;\n child_of_target->parent = NIL;\n } else if (target_node == target_parent->left) {\n target_parent->left = child_of_target;\n child_of_target->parent = target_parent;\n } else {\n target_parent->right = child_of_target;\n child_of_target->parent = target_parent;\n }\n free(target_node);\n } \n}\n\n\n\n\n\nint main(int argc, char const *argv[])\n{\n int n, k;\n string s;\n bool is_find;\n cin >> n;\n for (int i = 0; i < n; i ++) {\n cin >> s;\n if (s == \"insert\") {\n cin >> k;\n insert(k);\n } else if (s == \"find\") {\n cin >> k;\n is_find = find(root, k);\n if (is_find == true) {\n cout << \"yes\" << endl;\n } else {\n cout << \"no\" << endl;\n }\n } else if (s == \"delete\") {\n cin >> k;\n deleteNode(k);\n } else if (s == \"print\") {\n vector<int> inorder_result;\n vector<int> preorder_result;\n inorder(root, inorder_result);\n preorder(root, preorder_result);\n printVector(inorder_result);\n printVector(preorder_result);\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 26588, "score_of_the_acc": -1.92, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_8_C_10780318", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *parent, *left, *right;\n};\n\nNode *NIL, *root;\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z = new Node;\n\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n while (x != NIL) {\n y = x;\n if (z->key < y->key) {\n x = y->left;\n } else {\n x = y->right;\n }\n }\n\n z->parent = y;\n\n if (y==NIL) {\n root = z;\n } else if (z->key < y->key) {\n y->left = z;\n } else {\n y-> right = z;\n }\n}\n\nNode* find(Node* x, int k) {\n while (x != NIL && k != x->key) {\n if (k < x->key) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n return x;\n}\n\nNode* treeMinimum(Node *x) {\n while (x->left != NIL) {\n x = x->left;\n }\n return x;\n}\n\n// Inorderで次に得られるノードを見る\nNode* treeSuccessor(Node *x) {\n if (x->right != NIL) return treeMinimum(x->right);\n Node *y = x->parent;\n while (y != NIL && x == y->right) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid treeDelete(Node *z) {\n Node *y;\n Node *x;\n\n // 削除するノードを決める\n if (z->left == NIL || z->right == NIL) y = z;\n else y = treeSuccessor(z);\n\n // yの子xを決める\n if (y->left != NIL) {\n x = y->left;\n } else {\n x = y->right;\n }\n\n if (x != NIL) {\n x->parent = y->parent;\n }\n\n // yの親から見たxはどういう値か\n if (y->parent == NIL) {\n root = x;\n } else {\n if (y == y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n }\n\n // case3の場合の処理\n if (y != z) {\n z->key = y->key;\n }\n\n free(y); // メモリの解放\n}\n\nvoid inorder(Node *u) {\n if (u==NIL) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u==NIL) return ;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main()\n{\n int n,i,x;\n string com;\n\n scanf(\"%d\", &n);\n\n for (i=0; i<n; i++) {\n cin >> com;\n if (com[0] == 'f') {\n scanf(\"%d\", &x);\n Node *t = find(root,x);\n if (t != NIL) printf(\"yes\\n\");\n else printf(\"no\\n\");\n } else if (com == \"insert\") {\n scanf(\"%d\", &x);\n insert(x);\n } else if (com == \"print\") {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n } else if (com == \"delete\") {\n scanf(\"%d\", &x);\n treeDelete(find(root,x));\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 22200, "score_of_the_acc": -1.1986, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_8_C_10750035", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define loop(a,b) for (int a = 0;a < b;a++)\n#define rep(a,b,c) for(int a = b;a < c;a++)\n#define vec(a) vector<a>\n\nstruct Node{\n int key;\n Node *left,*right,*parent;\n Node(int key):key(key),left(nullptr),right(nullptr),parent(nullptr){};\n};\n\nclass BinarySearchTree{\n private:\n Node* root;\n Node* insert(Node* node,int key){\n Node* z = new Node(key);\n Node* y = nullptr;\n Node* x = root;\n while(x != nullptr){\n y = x;\n if(z->key < x->key) x = x->left;\n else x = x->right;\n }\n z->parent = y;\n if(y == nullptr) root = z;\n else if(z->key < y->key) y->left = z;\n else y->right = z;\n return z;\n }\n void inorder(Node* node){\n if(node == nullptr) return;\n inorder(node->left);\n cout <<\" \"<< node->key;\n inorder(node->right);\n }\n void preorder(Node* node){\n if(node == nullptr) return;\n cout << \" \"<< node->key;\n preorder(node->left);\n preorder(node->right);\n }\n \n Node* find(Node* node,int key){\n while(node != nullptr && node->key != key){\n if(key < node->key) node = node->left;\n else node = node->right;\n }\n return node;\n }\n Node* find_min(Node* node) {\n while (node->left != nullptr) {\n node = node->left;\n }\n return node;\n }\n \n void remove(Node* node,int key){\n Node* z = find(node,key);\n if(z == nullptr) return;\n \n \n if(z->left == nullptr && z->right == nullptr) {\n if(z->parent == nullptr) {\n root = nullptr; \n } else if(z->parent->left == z) {\n z->parent->left = nullptr;\n } else {\n z->parent->right = nullptr;\n }\n delete z;\n }\n else if(z->left == nullptr || z->right == nullptr) {\n Node* child = (z->left != nullptr) ? z->left : z->right;\n \n if(z->parent == nullptr) {\n root = child; \n } else if(z->parent->left == z) {\n z->parent->left = child;\n } else {\n z->parent->right = child;\n }\n \n if(child != nullptr) {\n child->parent = z->parent;\n }\n delete z;\n }\n \n else {\n \n Node* successor = find_min(z->right);\n \n \n z->key = successor->key;\n \n \n if(successor->parent->left == successor) {\n successor->parent->left = successor->right;\n } else {\n successor->parent->right = successor->right;\n }\n \n if(successor->right != nullptr) {\n successor->right->parent = successor->parent;\n }\n delete successor;\n }\n }\n\n public:\n BinarySearchTree():root(nullptr){};\n void print(){\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n void insert(int key){\n insert(root,key);\n }\n bool find(int key){\n Node* node = find(root,key);\n if(node != nullptr) return 1;\n else return 0;\n }\n void remove(int key){\n remove(root,key);\n }\n};\nint main()\n{\n int n;\n cin >> n;\n BinarySearchTree bst;\n loop(i,n){\n string command;\n int key;\n cin >> command;\n if(command == \"insert\"){\n cin >> key;\n bst.insert(key);\n } \n else if(command == \"find\") {\n cin >> key;\n cout << (bst.find(key) ? \"yes\" : \"no\") << endl;\n }\n else if(command == \"print\") {\n bst.print();\n }\n else if(command == \"delete\"){\n cin >> key;\n bst.remove(key);\n } \n }\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 22028, "score_of_the_acc": -1.4598, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_8_C_10734325", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\nclass node{\n public:\n node* right;\n node* left;\n node* parent;\n int key;\n};\nclass tree{\n private:\n node* root;\n public:\n tree(){root = 0;}\n void insert(int k);\n node* find(int k);\n void deleteb(int k);\n void inorder(node* u);\n void preorder(node* u);\n void print();\n};\nvoid tree::insert(int k){\n node* z = new node();\n z->right = 0;\n z->left = 0;\n z->parent = 0;\n z->key = k;\n node* y = 0; // xの親\n node* x = root; // 根\n while(x!=0){\n y = x; // 親を設定\n if(z->key < x->key){\n x = x->left; // 左の子へ移動\n }\n else{\n x = x->right; // 右の子へ移動\n }\n }\n z->parent = y;\n if(y==0){ // 木が空の場合\n root = z;\n }\n else if(z->key < y->key){\n y->left = z; // 左の子にする\n }\n else{\n y->right = z; // 右の子にする\n }\n}\nnode* tree::find(int k){\n node* x = root; // 根\n while(x!=0){\n if(k == x->key){\n return x; // 見つかった\n }\n else if(k < x->key){\n x = x->left; // 左の子へ移動\n }\n else{\n x = x->right; // 右の子へ移動\n }\n }\n return 0; // 見つからなかった\n}\nvoid tree::deleteb(int k){\n node* y = 0; // xの親\n node* x = root; // 根\n while(k != x->key){\n y = x; // 親を設定\n if(k < x->key){\n x = x->left; // 左の子へ移動\n }\n else{\n x = x->right; // 右の子へ移動\n }\n }\n if(x->left == 0 && x->right == 0){ // 0個の子\n if(y==0){\n root = 0;\n }\n else if(y->left == x){\n y->left = 0;\n }\n else{\n y->right = 0;\n }\n }\n else if(x->left == 0){ // 1個の子(右の子)\n if(y==0){\n root = x->right;\n x->right->parent = 0;\n }\n else if(y->left == x){\n y->left = x->right;\n x->right->parent = y;\n }\n else{\n y->right = x->right;\n x->right->parent = y;\n }\n }\n else if(x->right == 0){ // 1個の子(左の子)\n if(y==0){\n root = x->left;\n x->left->parent = 0;\n }\n else if(y->left == x){\n y->left = x->left;\n x->left->parent = y;\n }\n else{\n y->right = x->left;\n x->left->parent = y;\n }\n }\n else{ // 2個の子\n node* yt = x; // xtの親\n node* xt = x->right;\n while(xt->left != 0){ // 探索(つぎに大きい要素)\n yt = xt;\n xt = xt->left;\n }\n x->key = xt->key; // 頂点xに割り当て\n if(yt==x){ // xtの親がxのまま\n if(xt->right == 0){\n x->right = 0;\n }\n else{\n x->right = xt->right;\n xt->right->parent = x;\n }\n }\n else{\n if(xt->right == 0){\n yt->left = 0;\n }\n else{\n yt->left = xt->right;\n xt->right->parent = yt;\n }\n }\n x = xt;\n }\n delete x; // メモリの解放\n}\n// 中間順\nvoid tree::inorder(node* u){\n if(u==0){\n return;\n }\n inorder(u->left);\n cout << ' ' << u->key;\n inorder(u->right);\n}\n// 先行順\nvoid tree::preorder(node* u){\n if(u==0){\n return;\n }\n cout << ' ' << u->key;\n preorder(u->left);\n preorder(u->right);\n}\nvoid tree::print(){\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n}\nint main(){\n int m;\n cin >> m;\n tree T;\n for(int i=0; i<m; i++){\n string com;\n cin >> com;\n if(com==\"insert\"){\n int k;\n cin >> k;\n T.insert(k);\n }\n else if(com==\"find\"){\n int k;\n cin >> k;\n if(T.find(k)!=0){\n cout << \"yes\" << endl;\n }\n else{\n cout << \"no\" << endl;\n }\n }\n else if(com==\"delete\"){\n int k;\n cin >> k;\n T.deleteb(k);\n }\n else if(com==\"print\"){\n T.print();\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 22196, "score_of_the_acc": -1.4782, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_8_C_10732694", "code_snippet": "// 2025/07/17 Tazoe\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\nclass node{\npublic:\n\tnode* right;\n\tnode* left;\n\tnode* parent;\n\tint key;\n};\n\nclass tree{\nprivate:\n\tnode* root;\npublic:\n\ttree(){root = 0;}\n\tvoid insert(int k);\n\tnode* find(int k);\n\tvoid deleteb(int k);\n\tvoid inorder(node* u);\n\tvoid preorder(node* u);\n\tvoid print();\n};\n\nvoid tree::insert(int k)\n{\n\tnode* z = new node();\n\tz->right = 0;\n\tz->left = 0;\n\tz->parent = 0;\n\tz->key = k;\n\t\n\tnode* y = 0;\t\t// xの親\n\tnode* x = root;\t\t// 根\n\t\n\twhile(x!=0){\n\t\ty = x;\t\t\t\t// 親を設定\n\t\tif(z->key < x->key){\n\t\t\tx = x->left;\t\t// 左の子へ移動\n\t\t}\n\t\telse{\n\t\t\tx = x->right;\t\t// 右の子へ移動\n\t\t}\n\t}\n\t\n\tz->parent = y;\n\t\n\tif(y==0){\t\t\t// 木が空の場合\n\t\troot = z;\n\t}\n\telse if(z->key < y->key){\n\t\ty->left = z;\t\t\t// 左の子にする\n\t}\n\telse{\n\t\ty->right = z;\t\t\t// 右の子にする\n\t}\n}\n\nnode* tree::find(int k)\n{\n\tnode* x = root;\t\t// 根\n\t\n\twhile(x!=0){\n\t\tif(k == x->key){\n\t\t\treturn x;\t\t\t// 見つかった\n\t\t}\n\t\telse if(k < x->key){\n\t\t\tx = x->left;\t\t// 左の子へ移動\n\t\t}\n\t\telse{\n\t\t\tx = x->right;\t\t// 右の子へ移動\n\t\t}\n\t}\n\t\n\treturn 0;\t\t\t// 見つからなかった\n}\n\nvoid tree::deleteb(int k)\n{\n\tnode* y = 0;\t\t// xの親\n\tnode* x = root;\t\t// 根\n\t\n\twhile(k != x->key){\n\t\ty = x;\t\t\t\t// 親を設定\n\t\tif(k < x->key){\n\t\t\tx = x->left;\t\t// 左の子へ移動\n\t\t}\n\t\telse{\n\t\t\tx = x->right;\t\t// 右の子へ移動\n\t\t}\n\t}\n\t\n\tif(x->left == 0 && x->right == 0){\t// 0個の子\n\t\tif(y==0){\n\t\t\troot = 0;\n\t\t}\n\t\telse if(y->left == x){\n\t\t\ty->left = 0;\n\t\t}\n\t\telse{\n\t\t\ty->right = 0;\n\t\t}\n\t}\n\telse if(x->left == 0){\t\t\t\t// 1個の子(右の子)\n\t\tif(y==0){\n\t\t\troot = x->right;\n\t\t\tx->right->parent = 0;\n\t\t}\n\t\telse if(y->left == x){\n\t\t\ty->left = x->right;\n\t\t\tx->right->parent = y;\n\t\t}\n\t\telse{\n\t\t\ty->right = x->right;\n\t\t\tx->right->parent = y;\n\t\t}\n\t}\n\telse if(x->right == 0){\t\t\t\t// 1個の子(左の子)\n\t\tif(y==0){\n\t\t\troot = x->left;\n\t\t\tx->left->parent = 0;\n\t\t}\n\t\telse if(y->left == x){\n\t\t\ty->left = x->left;\n\t\t\tx->left->parent = y;\n\t\t}\n\t\telse{\n\t\t\ty->right = x->left;\n\t\t\tx->left->parent = y;\n\t\t}\n\t}\n\telse{\t\t\t\t\t\t\t\t// 2個の子\n\t\tnode* yt = x;\t\t\t\t\t// xtの親\n\t\tnode* xt = x->right;\n\t\twhile(xt->left != 0){\t\t\t// 探索(つぎに大きい要素)\n\t\t\tyt = xt;\n\t\t\txt = xt->left;\n\t\t}\n\t\tx->key = xt->key;\t\t\t\t// 頂点xに割り当て\n\t\tif(yt==x){\t\t\t\t\t\t// xtの親がxのまま\n\t\t\tif(xt->right == 0){\n\t\t\t\tx->right = 0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tx->right = xt->right;\n\t\t\t\txt->right->parent = x;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif(xt->right == 0){\n\t\t\t\tyt->left = 0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tyt->left = xt->right;\n\t\t\t\txt->right->parent = yt;\n\t\t\t}\n\t\t}\n\t\t\n\t\tx = xt;\n\t}\n\t\n\tdelete x;\t\t\t// メモリの解放\n}\n\n// 中間順\nvoid tree::inorder(node* u)\n{\n\tif(u==0){\n\t\treturn;\n\t}\n\t\n\tinorder(u->left);\n\tcout << ' ' << u->key;\n\tinorder(u->right);\n}\n\n// 先行順\nvoid tree::preorder(node* u)\n{\n\tif(u==0){\n\t\treturn;\n\t}\n\t\n\tcout << ' ' << u->key;\n\tpreorder(u->left);\n\tpreorder(u->right);\n}\n\nvoid tree::print()\n{\n\tinorder(root);\n\tcout << endl;\n\tpreorder(root);\n\tcout << endl;\n}\n\n\nint main()\n{\n\tint m;\n\tcin >> m;\n\t\n\ttree T;\n\t\n\tfor(int i=0; i<m; i++){\n\t\tstring com;\n\t\tcin >> com;\n\t\t\n\t\tif(com==\"insert\"){\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\t\n\t\t\tT.insert(k);\n\t\t}\n\t\telse if(com==\"find\"){\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\t\n\t\t\tif(T.find(k)!=0){\n\t\t\t\tcout << \"yes\" << endl;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcout << \"no\" << endl;\n\t\t\t}\n\t\t}\n\t\telse if(com==\"delete\"){\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\t\n\t\t\tT.deleteb(k);\n\t\t}\n\t\telse if(com==\"print\"){\n\t\t\tT.print();\n\t\t}\n\t}\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 22192, "score_of_the_acc": -1.4778, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_8_C_10719601", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nstruct node{\n int p,l,r,key;\n};\nconst int N=5e5+5;\nnode tree[N];\nint idx=0,root=-1;\nvoid insert(int z){\n int y=-1,x=root;\n while(x!=-1){\n y=x;\n if(tree[z].key<tree[x].key) x=tree[x].l;\n else x=tree[x].r;\n }\n tree[z].p=y;\n if(y==-1){\n root=z;\n }else if(tree[z].key<tree[y].key){\n tree[y].l=z;\n }else{\n tree[y].r=z;\n }\n}\nvoid dfs1(int u){\n if(u==-1) return;\n dfs1(tree[u].l);\n cout<<\" \"<<tree[u].key;\n dfs1(tree[u].r);\n}\nvoid dfs2(int u){\n if(u==-1) return;\n cout<<\" \"<<tree[u].key;\n dfs2(tree[u].l);\n dfs2(tree[u].r);\n}\nbool find(int k,int u){\n if(u==-1) return false;\n if(k==tree[u].key) return true;\n else if(k<tree[u].key) return find(k,tree[u].l);\n else return find(k,tree[u].r);\n}\nvoid Delete(int k,int u){\n if(u==-1) return;\n if(tree[u].key==k){\n int pre=tree[u].p;\n int ls=tree[u].l,rs=tree[u].r;\n if(pre==-1){\n if(ls==-1&&rs==-1){\n root=-1;\n }else if(ls!=-1&&rs!=-1){\n int v=rs;\n while(tree[v].l!=-1) v=tree[v].l;\n tree[u].key=tree[v].key;\n int p1=tree[v].p;\n if(tree[p1].l==v) tree[p1].l=-1;\n else tree[p1].r=-1;\n }else if(ls!=-1){\n root=ls;\n }else{\n root=rs;\n }\n }else{\n if(ls==-1&&rs==-1){\n if(tree[pre].l==u) tree[pre].l=-1;\n else tree[pre].r=-1;\n }else if(ls!=-1&&rs!=-1){\n int v=rs;\n while(tree[v].l!=-1) v=tree[v].l;\n tree[u].key=tree[v].key;\n int p1=tree[v].p;\n if(tree[p1].l==v) tree[p1].l=-1;\n else tree[p1].r=-1;\n }else if(ls!=-1){\n tree[ls].p=tree[u].p;\n if(tree[pre].l==u) tree[pre].l=ls;\n else tree[pre].r=ls;\n }else{\n tree[rs].p=tree[u].p;\n if(tree[pre].l==u) tree[pre].l=rs;\n else tree[pre].r=rs;\n }\n }\n }\n else if(k<tree[u].key) Delete(k,tree[u].l);\n else Delete(k,tree[u].r);\n}\nvoid solve(){\n int n;cin>>n;\n for(int i=0;i<n;i++){\n string s;cin>>s;\n if(s==\"insert\"){\n int k;cin>>k;\n int z=idx++;\n tree[z].key=k;\n tree[z].l=tree[z].r=-1;\n insert(z);\n }else if(s==\"print\"){\n dfs1(root);\n cout<<endl;\n dfs2(root);\n cout<<endl;\n }else if(s==\"find\"){\n int k;cin>>k;\n if(find(k,root)) cout<<\"yes\"<<endl;\n else cout<<\"no\"<<endl;\n }else if(s==\"delete\"){\n int k;cin>>k;\n Delete(k,root);\n }\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 17472, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_8_C_10715006", "code_snippet": "#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL;\n\nNode * treeMinimum(Node *x) {\n while(x->left != NIL) {\n x = x->left;\n }\n return x;\n}\n\nNode * find(Node *u, int k) {\n while(u !=NIL && k != u->key) {\n if(k < u->key) {\n u = u->left;\n } else {\n u = u->right;\n }\n }\n return u;\n}\n\nNode * treeSuccessor(Node *x) {\n if(x->right != NIL) {\n return treeMinimum(x->right);\n }\n Node *y = x->parent;\n while(y != NIL && x == y->right) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid treeDelete(Node *z) {\n Node *x, *y;\n if(z->left == NIL || z->right == NIL) {\n y = z;\n } else {\n y = treeSuccessor(z);\n }\n if(y->left != NIL) {\n x = y->left;\n } else {\n x = y->right;\n }\n if(x != NIL) {\n x->parent = y->parent;\n }\n if(y->parent == NIL) {\n root = x;\n } else {\n if(y == y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n }\n\n if(y != z) {\n z->key = y->key;\n }\n free(y);\n}\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z;\n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n while(x != NIL){\n y = x;\n if(z->key < x->key){\n x = x->left;\n }else{\n x = x->right;\n }\n }\n z->parent = y;\n if(y == NIL){\n root = z;\n }else{\n if(z->key < y->key){\n y->left = z;\n }else{\n y->right = z;\n }\n }\n}\n\nvoid inorder(Node *u) {\n if(u == NIL) {\n return;\n }\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == NIL) {\n return;\n }\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int m;\n string command;\n int key;\n cin >> m;\n for(int i=0; i<m; i++){\n cin >> command;\n if(command == \"insert\"){\n cin >> key;\n insert(key);\n }else if(command == \"find\"){\n cin >> key;\n if(find(root, key) != NIL){\n cout << \"yes\\n\";\n }else{\n cout << \"no\\n\";\n }\n }else if(command == \"delete\"){\n cin >> key;\n treeDelete(find(root, key));\n }else if(command == \"print\"){\n inorder(root);\n cout << \"\\n\";\n preorder(root);\n cout << \"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 22104, "score_of_the_acc": -1.4281, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_8_C_10714999", "code_snippet": "#include <iostream>\n#include <string>\n#include <sstream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *left, *right, *parent;\n};\n\nNode *root, *NIL;\n\nNode *treeMinimum(Node *x) {\n while (x->left != NIL) x = x->left;\n return x;\n}\n\nNode *find(Node *u, int k) {\n while (u != NIL && k != u->key) {\n if (k < u->key) u = u->left;\n else u = u->right;\n }\n return u;\n}\n\nNode *treeSuccessor(Node *x) {\n if (x->right != NIL) return treeMinimum(x->right);\n Node *y = x->parent;\n while (y != NIL && x == y->right) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid treeDelete(Node *z) {\n Node *y, *x;\n\n if (z->left == NIL || z->right == NIL) {\n y = z;\n } else {\n y = treeSuccessor(z);\n }\n\n if (y->left != NIL) x = y->left;\n else x = y->right;\n\n if (x != NIL) x->parent = y->parent;\n\n if (y->parent == NIL) {\n root = x;\n } else if (y == y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n\n if (y != z) {\n z->key = y->key;\n }\n\n free(y);\n}\n\nvoid insert(int k) {\n Node *z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = z->right = z->parent = NIL;\n\n Node *y = NIL;\n Node *x = root;\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key) x = x->left;\n else x = x->right;\n }\n\n z->parent = y;\n if (y == NIL) root = z;\n else if (z->key < y->key) y->left = z;\n else y->right = z;\n}\n\nvoid inorder(Node *u) {\n if (u == NIL) return;\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == NIL) return;\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\nvoid print() {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n NIL = (Node *)malloc(sizeof(Node));\n NIL->left = NIL->right = NIL->parent = NIL;\n root = NIL;\n\n string line;\n while (getline(cin, line)) {\n if (line.empty()) continue;\n\n stringstream ss(line);\n string cmd;\n int k;\n ss >> cmd;\n\n if (cmd == \"insert\") {\n ss >> k;\n insert(k);\n } else if (cmd == \"find\") {\n ss >> k;\n Node *res = find(root, k);\n cout << (res != NIL ? \"yes\" : \"no\") << endl;\n } else if (cmd == \"delete\") {\n ss >> k;\n Node *z = find(root, k);\n if (z != NIL) treeDelete(z);\n } else if (cmd == \"print\") {\n print();\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 430, "memory_kb": 21908, "score_of_the_acc": -1.4866, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_8_C_10714997", "code_snippet": "#include <iostream>\n#include <string>\n#include <sstream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *left, *right, *parent;\n};\n\n// グローバル変数\nNode *root, *NIL;\n\n// 最小ノード\nNode *treeMinimum(Node *x) {\n while (x->left != NIL) x = x->left;\n return x;\n}\n\n// 探索\nNode *find(Node *u, int k) {\n while (u != NIL && k != u->key) {\n if (k < u->key) u = u->left;\n else u = u->right;\n }\n return u;\n}\n\n// 次節点\nNode *treeSuccessor(Node *x) {\n if (x->right != NIL) return treeMinimum(x->right);\n Node *y = x->parent;\n while (y != NIL && x == y->right) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\n// 削除\nvoid treeDelete(Node *z) {\n Node *y, *x;\n\n if (z->left == NIL || z->right == NIL) {\n y = z;\n } else {\n y = treeSuccessor(z);\n }\n\n if (y->left != NIL) x = y->left;\n else x = y->right;\n\n if (x != NIL) x->parent = y->parent;\n\n if (y->parent == NIL) {\n root = x;\n } else if (y == y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n\n if (y != z) {\n z->key = y->key;\n }\n\n free(y);\n}\n\n// 挿入\nvoid insert(int k) {\n Node *z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = z->right = z->parent = NIL;\n\n Node *y = NIL;\n Node *x = root;\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key) x = x->left;\n else x = x->right;\n }\n\n z->parent = y;\n if (y == NIL) root = z;\n else if (z->key < y->key) y->left = z;\n else y->right = z;\n}\n\n// inorder\nvoid inorder(Node *u) {\n if (u == NIL) return;\n inorder(u->left);\n cout << \" \" << u->key;\n inorder(u->right);\n}\n\n// preorder\nvoid preorder(Node *u) {\n if (u == NIL) return;\n cout << \" \" << u->key;\n preorder(u->left);\n preorder(u->right);\n}\n\n// 出力\nvoid print() {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n}\n\n// メイン処理\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n // NIL 初期化\n NIL = (Node *)malloc(sizeof(Node));\n NIL->left = NIL->right = NIL->parent = NIL;\n root = NIL;\n\n string line;\n while (getline(cin, line)) {\n if (line.empty()) continue;\n\n stringstream ss(line);\n string cmd;\n int k;\n ss >> cmd;\n\n if (cmd == \"insert\") {\n ss >> k;\n insert(k);\n } else if (cmd == \"find\") {\n ss >> k;\n Node *res = find(root, k);\n cout << (res != NIL ? \"yes\" : \"no\") << endl;\n } else if (cmd == \"delete\") {\n ss >> k;\n Node *z = find(root, k);\n if (z != NIL) treeDelete(z);\n } else if (cmd == \"print\") {\n print();\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 430, "memory_kb": 21900, "score_of_the_acc": -1.4857, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_8_C_10714977", "code_snippet": "#include<stdio.h>\n#include<stdlib.h>\n#include<string>\n#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL;\n\nNode * treeMinimum(Node *x) {\n while( x->left != NIL ) x = x->left;\n return x;\n}\n\nNode * find(Node *u, int k) {\n while( u != NIL && k != u->key ) {\n if ( k < u-> key ) u = u->left;\n else u = u->right;\n }\n return u;\n}\n\nNode * treeSuccessor(Node *x) {\n if ( x->right != NIL ) return treeMinimum(x->right);\n Node *y = x->parent;\n while(y!= NIL && x == y->right) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid treeDelete(Node *z) {\n Node *y;\n Node *x;\n if (z->left == NIL || z->right == NIL) y=z;\n else y = treeSuccessor(z);\n if (y->left != NIL) {\n x = y->left;\n } else {\n x = y->right;\n }\n if (x != NIL) {\n x->parent = y->parent;\n }\n if (x != NIL) {\n x->parent = y->parent;\n }\n if (y->parent == NIL) {\n root = x;\n } else {\n if (y==y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n }\n if (y!=z) {\n z->key = y->key;\n }\n free(y);\n}\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z;\n\n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n\n while ( x != NIL) {\n y = x;\n if ( z->key < x->key ) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n z->parent = y;\n if ( y==NIL) {\n root = z;\n } else {\n if (z->key < y->key) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nvoid inorder(Node *u) {\n if ( u == NIL ) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\nvoid preorder(Node *u) {\n if ( u == NIL ) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int n, i, x;\n string com;\n\n scanf(\"%d\", &n);\n\n for ( i = 0; i<n; i++ ) {\n cin >> com;\n if ( com[0] == 'f' ) {\n scanf(\"%d\", &x);\n Node *t = find(root, x);\n if ( t != NIL ) printf(\"yes\\n\");\n else printf(\"no\\n\");\n } else if ( com == \"insert\" ) {\n scanf(\"%d\", &x);\n insert(x);\n } else if ( com == \"print\" ) {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n } else if ( com == \"delete\" ) {\n scanf(\"%d\", &x);\n treeDelete(find(root, x));\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 21996, "score_of_the_acc": -1.1763, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_8_C_10714021", "code_snippet": "#include<stdio.h>\n#include<stdlib.h>\n\nstruct node{\nstruct node *right;\nstruct node *left;\nstruct node *parent;\nint key;\n};\ntypedef struct node *Node;\n#define NIL NULL\n\nNode root;\n\nNode treeMinimum(Node x){\nwhile(x->left != NIL)x=x->left;\nreturn x;\n}\n\nNode treeSearch(Node u, int k){\nwhile(u!=NIL){\nif(u->key==k)break;\nif(k<u->key){\nu=u->left;\n}else{\nu=u->right;\n}\n}\nreturn u;\n}\n\nNode treeSuccessor(Node x){\nif(x->right!=NIL){\nreturn treeMinimum(x->right);\n}\nNode y=x->parent;\nwhile(y!=NIL && x==y->right){\nx=y;\ny=y->parent;\n}\nreturn y;\n}\n\nvoid treeDelete(Node z){\n\nNode y; // node to be deleted\nNode x; // child of y\nif(z==NIL)return;\nif(z->left==NIL || z->right==NIL){\ny=z;\n}else{\ny=treeSuccessor(z);\n}\nif(y->left!=NIL){\nx=y->left;\n}else{\nx=y->right;\n}\nif(x!=NIL){\nx->parent=y->parent;\n}\nif(y->parent==NIL){\nroot=x;\n}else{\nif(y==y->parent->left){\ny->parent->left=x;\n}else{\ny->parent->right=x;\n}\n}\nif(y!=z) z->key=y->key;\n}\n\nvoid insert(int k){\nNode y = NIL;\nNode x = root;\nNode z;\n\nz = (struct node*)malloc(sizeof(struct node));\nz->key = k;\nz->left = NIL;\nz->right = NIL;\nwhile(x!=NIL){\ny=x;\nif(z->key < x->key){\nx=x->left;\n}else{\nx=x->right;\n}\n}\nz->parent=y;\nif(y==NIL){\nroot=z;\n}else{\nif(z->key < y->key){\ny->left=z;\n }else{\n\ty->right=z;\n}\n\n\n}\n}\n\nvoid inorder(Node u){\nif(u==NIL)return;\ninorder(u->left);\nprintf(\" %d\",u->key);\ninorder(u->right);\n}\nvoid preorder(Node u){\nif(u==NIL)return;\nprintf(\" %d\",u->key);\npreorder(u->left);\npreorder(u->right);\n}\n\nint main(){\nint n, i, x;\nchar com[20];\nscanf(\"%d\", &n);\n\nfor ( i = 0; i < n; i++ ){\nscanf(\"%s\", com);\nif ( com[0] == 'f' ){\nscanf(\"%d\", &x);\nNode t = treeSearch(root, x);\nif ( t != NIL ) printf(\"yes\\n\");\nelse printf(\"no\\n\");\n} else if ( com[0] == 'i' ){\nscanf(\"%d\", &x);\ninsert(x);\n} else if ( com[0] == 'p' ){\ninorder(root);\nprintf(\"\\n\");\npreorder(root);\nprintf(\"\\n\");\n} else if ( com[0] == 'd' ){\nscanf(\"%d\", &x);\ntreeDelete(treeSearch(root, x));\n}\n}\n\nreturn 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 21636, "score_of_the_acc": -0.6568, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_8_C_10713997", "code_snippet": "#include <stdio.h>\n#include <iostream>\n\nusing namespace std;\n\n#define BUF_SIZE 22\n\nstruct Node{\n\tNode(){\n\t\tleft_child = right_child = parent = 0;\n\t\tdata = 0;\n\t}\n\tNode *left_child,*right_child,*parent;\n\tlong long data;\n};\n\nclass Tree{\npublic:\n\tTree(){\n\t\troot = new Node();\n\t\tnum_of_node = 0;\n\t}\n\tvoid insert(long long insert_data){\n\t\tif(num_of_node == 0){\n\t\t\troot->data = insert_data;\n\t\t\tnum_of_node++;\n\t\t}else{\n\t\t\tNode* tmp = root;\n\t\t\twhile(true){\n\t\t\t\tif(tmp->data < insert_data){\n\t\t\t\t\tif(tmp->right_child == 0){\n\t\t\t\t\t\ttmp->right_child = new Node();\n\t\t\t\t\t\ttmp->right_child->data = insert_data;\n\t\t\t\t\t\ttmp->right_child->parent = tmp;\n\t\t\t\t\t\tnum_of_node++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttmp = tmp->right_child;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif(tmp->left_child == 0){\n\t\t\t\t\t\ttmp->left_child = new Node();\n\t\t\t\t\t\ttmp->left_child->data = insert_data;\n\t\t\t\t\t\ttmp->left_child->parent = tmp;\n\t\t\t\t\t\tnum_of_node++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttmp = tmp->left_child;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbool find(long long data){\n\t\tif(num_of_node == 0){\n\t\t\treturn false;\n\t\t}else{\n\t\t\tNode* tmp = root;\n\t\t\twhile(true){\n\t\t\t\tif(tmp->data < data){\n\t\t\t\t\tif(tmp->right_child == 0){\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttmp = tmp->right_child;\n\t\t\t\t\t}\n\t\t\t\t}else if(tmp->data > data){\n\t\t\t\t\tif(tmp->left_child == 0){\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttmp = tmp->left_child;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid deleteNode(long long delete_data){\n\t\tif(num_of_node == 0){\n\t\t\treturn;\n\t\t}else{\n\t\t\tdoDELETE(root,delete_data);\n\t\t}\n\t}\n\n\tvoid print(){\n\t\tinORDER(root);\n\t\tprintf(\"\\n\");\n\t\tpreORDER(root);\n\t\tprintf(\"\\n\");\n\t}\n\nprivate:\n\tNode* root;\n\tint num_of_node;\n\nprivate:\n\n\tNode* findNextNode(Node* node){\n\t\tNode* tmp = node;\n\t\twhile(tmp->left_child != 0) tmp = tmp->left_child;\n\t\treturn tmp;\n\t}\n\n\tvoid doDELETE(Node* node,long long delete_data){\n\n\t\tNode* tmp = node;\n\t\twhile(true){\n\t\t\tif(tmp->data < delete_data){\n\t\t\t\tif(tmp->right_child == 0){\n\t\t\t\t\t//Do nothing\n\t\t\t\t\tbreak;\n\t\t\t\t}else{\n\t\t\t\t\ttmp = tmp->right_child;\n\t\t\t\t}\n\t\t\t}else if(tmp->data > delete_data){\n\t\t\t\tif(tmp->left_child == 0){\n\t\t\t\t\t//Do nothing\n\t\t\t\t\tbreak;\n\t\t\t\t}else{\n\t\t\t\t\ttmp = tmp->left_child;\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tif(tmp->left_child == 0 && tmp->right_child == 0){\n\t\t\t\t\tif(tmp->parent->data < tmp->data){\n\t\t\t\t\t\ttmp->parent->right_child = 0;\n\t\t\t\t\t}else if(tmp->parent->data > tmp->data){\n\t\t\t\t\t\ttmp->parent->left_child = 0;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttmp->parent->right_child = 0;\n\t\t\t\t\t}\n\t\t\t\t\tdelete tmp;\n\t\t\t\t\tnum_of_node--;\n\t\t\t\t\tbreak;\n\t\t\t\t}else if(tmp->left_child == 0 && tmp->right_child != 0){\n\n\t\t\t\t\tif(tmp->parent->data < tmp->data){\n\t\t\t\t\t\ttmp->parent->right_child = tmp->right_child;\n\t\t\t\t\t}else if(tmp->parent->data > tmp->data){\n\t\t\t\t\t\ttmp->parent->left_child = tmp->right_child;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttmp->parent->right_child = 0;\n\t\t\t\t\t}\n\t\t\t\t\ttmp->right_child->parent = tmp->parent;\n\t\t\t\t\tdelete tmp;\n\t\t\t\t\tnum_of_node--;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}else if(tmp->left_child != 0 && tmp->right_child == 0){\n\n\t\t\t\t\tif(tmp->parent->data < tmp->data){\n\t\t\t\t\t\ttmp->parent->right_child = tmp->left_child;\n\t\t\t\t\t}else if(tmp->parent->data > tmp->data){\n\t\t\t\t\t\ttmp->parent->left_child = tmp->left_child;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttmp->parent->right_child = 0;\n\t\t\t\t\t}\n\t\t\t\t\ttmp->left_child->parent = tmp->parent;\n\t\t\t\t\tdelete tmp;\n\t\t\t\t\tnum_of_node--;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}else{\n\t\t\t\t\tNode* next_node = findNextNode(tmp->right_child);\n\t\t\t\t\ttmp->data = next_node->data;\n\t\t\t\t\tdoDELETE(tmp->right_child,next_node->data);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid preORDER(Node* node){\n\t\tprintf(\" %lld\",node->data);\n\t\tif(node->left_child != 0) preORDER(node->left_child);\n\t\tif(node->right_child != 0) preORDER(node->right_child);\n\t}\n\n\tvoid inORDER(Node* node){\n\t\tif(node->left_child != 0) inORDER(node->left_child);\n\t\tprintf(\" %lld\",node->data);\n\t\tif(node->right_child != 0) inORDER(node->right_child);\n\t}\n};\n\n\nint main(){\n\tint m;\n\tlong long insert_data,search_data,delete_data;\n\tlong long minusFLG;\n\tchar buf[BUF_SIZE];\n\tTree tree;\n\n\tscanf(\"%d\",&m);\n\tgetchar();\n\n\tfor(int i = 0; i < m; i++){\n\t\tminusFLG = 1;\n\t\tfgets(buf,BUF_SIZE,stdin);\n\t\tif(buf[0] == 'i'){\n\t\t\tinsert_data = 0;\n\t\t\tfor(int k = 0; buf[k] != '\\0';k++){\n\t\t\t\tif(buf[k] == '-') minusFLG = -1;\n\t\t\t\tif(buf[k] >= '0' && buf[k] <= '9'){\n\t\t\t\t\tinsert_data = 10*insert_data + (buf[k] - '0');\n\t\t\t\t}\n\t\t\t}\n\t\t\ttree.insert(minusFLG*insert_data);\n\t\t}else if(buf[0] == 'p'){\n\t\t\ttree.print();\n\t\t}else if(buf[0] == 'f'){\n\t\t\tsearch_data = 0;\n\t\t\tfor(int k = 0; buf[k] != '\\0';k++){\n\t\t\t\tif(buf[k] == '-') minusFLG = -1;\n\t\t\t\tif(buf[k] >= '0' && buf[k] <= '9'){\n\t\t\t\t\tsearch_data = 10*search_data + (buf[k] - '0');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(tree.find(minusFLG*search_data)){\n\t\t\t\tprintf(\"yes\\n\");\n\t\t\t}else{\n\t\t\t\tprintf(\"no\\n\");\n\t\t\t}\n\t\t}else{\n\t\t\tdelete_data = 0;\n\t\t\tfor(int k = 0; buf[k] != '\\0';k++){\n\t\t\t\tif(buf[k] == '-') minusFLG = -1;\n\t\t\t\tif(buf[k] >= '0' && buf[k] <= '9'){\n\t\t\t\t\tdelete_data = 10*delete_data + (buf[k] - '0');\n\t\t\t\t}\n\t\t\t}\n\t\t\ttree.deleteNode(minusFLG*delete_data);\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 22284, "score_of_the_acc": -0.6079, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_8_C_10713193", "code_snippet": "#include<stdio.h>\n#include<stdlib.h>\n#include<string>\n#include<iostream>\nusing namespace std;\n\nstruct Node {\n int key;\n Node *right, *left, *parent;\n};\n\nNode *root, *NIL;\n\nNode * treeMinimum(Node *x) {\n while( x->left != NIL ) x = x->left;\n return x;\n}\n\nNode * find(Node *u, int k) {\n while( u != NIL && k != u->key ) {\n if ( k < u->key ) u = u->left;\n else u = u->right;\n }\n return u;\n}\n\nNode * treeSuccessor(Node *x) {\n if ( x->right != NIL ) return treeMinimum(x->right);\n Node *y = x->parent;\n while( y != NIL && x == y->right ) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid treeDelete(Node *z) {\n Node *y;\n Node *x;\n if ( z->left == NIL || z->right == NIL ) y = z;\n else y = treeSuccessor(z);\n if ( y->left != NIL ) {\n x = y->left;\n } else {\n x = y->right;\n }\n if ( x != NIL ) {\n x->parent = y->parent;\n }\n if ( y->parent == NIL ) {\n root = x;\n } else {\n if ( y == y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n }\n if ( y != z ) {\n z->key = y->key;\n }\n free(y);\n}\n\nvoid insert(int k) {\n Node *y = NIL;\n Node *x = root;\n Node *z;\n z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n while( x != NIL ) {\n y = x;\n if ( z->key < x->key ) {\n x = x->left;\n } else {\n x = x->right;\n }\n }\n z->parent = y;\n if ( y == NIL ) {\n root = z;\n } else {\n if ( z->key < y->key ) {\n y->left = z;\n } else {\n y->right = z;\n }\n }\n}\n\nvoid inorder(Node *u) {\n if ( u == NIL ) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if ( u == NIL ) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int n, i, x;\n string com;\n scanf(\"%d\", &n);\n for ( i = 0; i < n; i++ ) {\n cin >> com;\n if ( com[0] == 'f' ) {\n scanf(\"%d\", &x);\n Node *t = find(root, x);\n if ( t != NIL ) printf(\"yes\\n\");\n else printf(\"no\\n\");\n } else if ( com == \"insert\" ) {\n scanf(\"%d\", &x);\n insert(x);\n } else if ( com == \"print\" ) {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n } else if ( com == \"delete\") {\n scanf(\"%d\", &x);\n treeDelete(find(root, x));\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 22284, "score_of_the_acc": -1.2079, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_8_C_10713102", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\nstruct Node {\n Node *parent, *left, *right;\n int key;\n};\n\nNode *NIL, *root;\n\nNode* treeMinimum(Node *x) {\n while (x->left != NIL) x = x->left;\n return x;\n}\n\nNode* find(Node *u, int k) {\n while (u != NIL && k != u->key) {\n if (k < u->key) u = u->left;\n else u = u->right;\n }\n return u;\n}\n\nNode* treeSuccessor(Node *x) {\n if (x->right != NIL) return treeMinimum(x->right);\n Node *y = x->parent;\n while (y != NIL && x == y->right) {\n x = y;\n y = y->parent;\n }\n return y;\n}\n\nvoid treeDelete(Node *z) {\n Node *y, *x;\n if (z->left == NIL || z->right == NIL) {\n y = z;\n } else {\n y = treeSuccessor(z);\n }\n\n if (y->left != NIL) x = y->left;\n else x = y->right;\n\n if (x != NIL) x->parent = y->parent;\n\n if (y->parent == NIL) {\n root = x;\n } else if (y == y->parent->left) {\n y->parent->left = x;\n } else {\n y->parent->right = x;\n }\n\n if (y != z) {\n z->key = y->key;\n }\n\n free(y);\n}\n\nvoid insert(int k) {\n Node *z = (Node *)malloc(sizeof(Node));\n z->key = k;\n z->left = NIL;\n z->right = NIL;\n z->parent = NIL;\n\n Node *y = NIL;\n Node *x = root;\n\n while (x != NIL) {\n y = x;\n if (z->key < x->key) x = x->left;\n else x = x->right;\n }\n\n z->parent = y;\n if (y == NIL) root = z;\n else if (z->key < y->key) y->left = z;\n else y->right = z;\n}\n\nvoid inorder(Node *u) {\n if (u == NIL) return;\n inorder(u->left);\n printf(\" %d\", u->key);\n inorder(u->right);\n}\n\nvoid preorder(Node *u) {\n if (u == NIL) return;\n printf(\" %d\", u->key);\n preorder(u->left);\n preorder(u->right);\n}\n\nint main() {\n int m, x;\n char com[20];\n\n NIL = (Node *)malloc(sizeof(Node));\n NIL->left = NIL->right = NIL->parent = NIL;\n root = NIL;\n\n scanf(\"%d\", &m);\n for (int i = 0; i < m; i++) {\n scanf(\"%s\", com);\n if (strcmp(com, \"insert\") == 0) {\n scanf(\"%d\", &x);\n insert(x);\n } else if (strcmp(com, \"find\") == 0) {\n scanf(\"%d\", &x);\n Node *t = find(root, x);\n printf(t != NIL ? \"yes\\n\" : \"no\\n\");\n } else if (strcmp(com, \"delete\") == 0) {\n scanf(\"%d\", &x);\n Node *t = find(root, x);\n if (t != NIL) treeDelete(t);\n } else if (strcmp(com, \"print\") == 0) {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 240, "memory_kb": 21732, "score_of_the_acc": -0.7073, "final_rank": 5 } ]
aoj_ALDS1_8_D_cpp
Treap A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree The following figure shows processes of the rotate operations after the insert operation to maintain the properties. The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be move ...(truncated)
[ { "submission_id": "aoj_ALDS1_8_D_10850490", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nstruct point{\n\tint a,b;\n\tpoint *l,*r,*pa;\n\tpoint(){l=r=pa=NULL;}\n\tpoint(int aa,int bb):a(aa),b(bb){l=r=pa=NULL;};\n};\npoint *root;\npoint *rightRotate(point *t){\n\tpoint *s=t->l;\n\tt->l=s->r;\n\ts->r=t;\n\treturn s;\n}\npoint *leftRotate(point *t){\n\tpoint *s=t->r;\n\tt->r=s->l;\n\ts->l=t;\n\treturn s;\n}\npoint* insert(point *p,int a,int b){\n\tif(p==NULL)return new point(a,b);\n\tif(a==p->a)return p;\n\tif(a<p->a){\n\t\tp->l=insert(p->l,a,b);\n\t\tif(p->b<p->l->b)\n\t\t\tp=rightRotate(p);\n\t}else{\n\t\tp->r=insert(p->r,a,b);\n\t\tif(p->b<p->r->b)\n\t\t\tp=leftRotate(p);\n\t}return p;\n}\npoint *_del(point *p, int a);\npoint *del(point *p,int a){\n\tif(p==NULL)return NULL;\n\tif(a<p->a)p->l=del(p->l,a);\n\telse if(a>p->a)p->r=del(p->r,a);\n\telse return _del(p,a);\n\treturn p;\n}\npoint *_del(point *p, int a){\n\tif(p->l==NULL&&p->r==NULL)return NULL;\n\telse if(p->l==NULL)p=leftRotate(p);\n\telse if(p->r==NULL)p=rightRotate(p);\n\telse{\n\t\tif(p->l->b>p->r->b)p=rightRotate(p);\n\t\telse p=leftRotate(p);\n\t}return del(p,a);\n}\nbool find(int a){\n\tpoint *p=root;\n\twhile(p){\n\t\tif(a==p->a)return 1;\n\t\tif(a>p->a)p=p->r;\n\t\telse p=p->l;\n\t}\n\treturn 0;\n}\nvoid dfs1(point *p){\n\tif(!p)return;\n\tdfs1(p->l);\n\tprintf(\" %d\",p->a);\n\tdfs1(p->r);\n}\nvoid dfs2(point *p){\n\tif(!p)return;\n\tprintf(\" %d\",p->a);\n\tdfs2(p->l);\n\tdfs2(p->r);\n}\nint main(){\n\tios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\tint T;cin>>T;\n\tint ta,tb;\n\tstring s;\n\twhile(cin>>s){\n\t\tif(s==\"insert\"){\n\t\t\tcin>>ta>>tb;\n//\t\t\tif(!root)root=new point(ta,tb);\n//\t\t\telse \n\t\t\troot=insert(root,ta,tb);\n\t\t}else if(s==\"find\"){\n\t\t\tcin>>ta;\n\t\t\tif(find(ta))printf(\"yes\\n\");\n\t\t\telse printf(\"no\\n\");\n\t\t}else if(s==\"print\"){\n\t\t\tdfs1(root);\n\t\t\tprintf(\"\\n\");\n\t\t\tdfs2(root);\n\t\t\tprintf(\"\\n\");\n\t\t}else if(s==\"delete\"){\n\t\t\tcin>>ta;\n\t\t\troot=del(root,ta);\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 12868, "score_of_the_acc": -0.7363, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_8_D_10750031", "code_snippet": "#include <bits/stdc++.h>\n#define endl '\\n'\n#define rep(i, n) for(int i = 0; i < n; ++i)\nusing namespace std;\n\nstruct Node {\n int key, priority;\n Node *left, *right;\n Node(int k, int p) : key(k), priority(p), left(nullptr), right(nullptr) {}\n};\n\nclass Treap {\n public:\n Node* root;\n Treap() : root(nullptr) {}\n\n Node* rightRotate(Node* root) {\n Node* newRoot = root->left;\n root->left = newRoot->right;\n newRoot->right = root;\n return newRoot;\n }\n\n Node* leftRotate(Node* root) {\n Node* newRoot = root->right;\n root->right = newRoot->left;\n newRoot->left = root;\n return newRoot;\n }\n\n Node* insert(Node* root, int key, int priority) {\n if(root == nullptr) return new Node(key, priority);\n\n if(key == root->key) return root;\n\n if(key < root->key) {\n root->left = insert(root->left, key, priority);\n if(root->priority < root->left->priority) root = rightRotate(root);\n } \n else {\n root->right = insert(root->right, key, priority);\n if(root->priority < root->right->priority) root = leftRotate(root);\n }\n\n return root;\n }\n\n Node* _deleteNode(Node* root, int key) {\n if(root->left == nullptr && root->right == nullptr) {\n delete root;\n return nullptr;\n }\n else if(root->left == nullptr) {\n root = leftRotate(root);\n }\n else if(root->right == nullptr) {\n root = rightRotate(root);\n }\n else {\n if(root->left->priority > root->right->priority) {\n root = rightRotate(root);\n }\n else {\n root = leftRotate(root);\n }\n }\n return deleteNode(root, key);\n }\n\n Node* deleteNode(Node* root, int key) {\n if(root == nullptr) return nullptr;\n\n if(key < root->key) {\n root->left = deleteNode(root->left, key);\n }\n else if(key > root->key) {\n root->right = deleteNode(root->right, key);\n }\n else {\n return _deleteNode(root, key);\n }\n return root;\n }\n\n bool find(Node* root, int key) {\n if(root == nullptr) return false;\n if(key == root->key) return true;\n if(key < root->key) return find(root->left, key);\n else return find(root->right, key);\n }\n\n void inOrder(Node* root) {\n if(root == nullptr) return;\n if(root->left != nullptr) inOrder(root->left);\n cout << \" \" << root->key;\n if(root->right != nullptr) inOrder(root->right);\n }\n\n void preOrder(Node* root) {\n if(root == nullptr) return;\n cout << \" \" << root->key;\n if(root->left != nullptr) preOrder(root->left);\n if(root->right != nullptr) preOrder(root->right);\n }\n};\n\nint main() {\n int m;\n cin >> m;\n Treap treap;\n\n rep(i, m) {\n string com;\n cin >> com;\n if(com == \"insert\") {\n int k, p;\n cin >> k >> p;\n treap.root = treap.insert(treap.root, k, p);\n }\n else if(com == \"find\") {\n int k;\n cin >> k;\n cout << (treap.find(treap.root, k) ? \"yes\" : \"no\") << endl;\n }\n else if(com == \"delete\") {\n int k;\n cin >> k;\n treap.root = treap.deleteNode(treap.root, k);\n }\n else if(com == \"print\") {\n treap.inOrder(treap.root);\n cout << endl;\n treap.preOrder(treap.root);\n cout << endl;\n }\n } \n return 0;\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 9748, "score_of_the_acc": -1.2336, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_8_D_10737598", "code_snippet": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct Node {\n int key;\n int priority;\n struct Node *left, *right;\n} Node;\n\nNode *root;\n\nNode* createNode(int key, int priority) {\n Node* newNode = (Node*)malloc(sizeof(Node));\n newNode->key = key;\n newNode->priority = priority;\n newNode->left = newNode->right = NULL;\n return newNode;\n}\n\nNode* rightRotate(Node *t) {\n Node *s = t->left;\n t->left = s->right;\n s->right = t;\n return s;\n}\n\nNode* leftRotate(Node *t) {\n Node *s = t->right;\n t->right = s->left;\n s->left = t;\n return s;\n}\n\nNode* insert(Node *t, int key, int priority) {\n if (t == NULL) return createNode(key, priority);\n if (key == t->key) return t;\n\n if (key < t->key) {\n t->left = insert(t->left, key, priority);\n if (t->priority < t->left->priority)\n t = rightRotate(t);\n } else {\n t->right = insert(t->right, key, priority);\n if (t->priority < t->right->priority)\n t = leftRotate(t);\n }\n return t;\n}\n\nNode* deleteNode(Node *t, int key) {\n if (t == NULL) return NULL;\n \n if (key < t->key) {\n t->left = deleteNode(t->left, key);\n } else if (key > t->key) {\n t->right = deleteNode(t->right, key);\n } else { // 削除対象のノードを発見\n if (t->left == NULL && t->right == NULL) {\n free(t);\n return NULL;\n } else if (t->left == NULL) {\n t = leftRotate(t);\n } else if (t->right == NULL) {\n t = rightRotate(t);\n } else {\n if (t->left->priority > t->right->priority) {\n t = rightRotate(t);\n } else {\n t = leftRotate(t);\n }\n }\n // 回転後、削除対象が下に移動したので、そこから再度deleteを呼び出す\n return deleteNode(t, key);\n }\n return t;\n}\n\nint find(Node *t, int key) {\n while (t != NULL) {\n if (key == t->key) return 1;\n if (key < t->key) t = t->left;\n else t = t->right;\n }\n return 0;\n}\n\nvoid inorder(Node *t) {\n if (t == NULL) return;\n inorder(t->left);\n printf(\" %d\", t->key);\n inorder(t->right);\n}\n\nvoid preorder(Node *t) {\n if (t == NULL) return;\n printf(\" %d\", t->key);\n preorder(t->left);\n preorder(t->right);\n}\n\nint main() {\n int m, k, p;\n char command[10];\n root = NULL;\n\n scanf(\"%d\", &m);\n for (int i = 0; i < m; i++) {\n scanf(\"%s\", command);\n if (strcmp(command, \"insert\") == 0) {\n scanf(\"%d %d\", &k, &p);\n root = insert(root, k, p);\n } else if (strcmp(command, \"find\") == 0) {\n scanf(\"%d\", &k);\n if (find(root, k)) {\n printf(\"yes\\n\");\n } else {\n printf(\"no\\n\");\n }\n } else if (strcmp(command, \"delete\") == 0) {\n scanf(\"%d\", &k);\n root = deleteNode(root, k);\n } else if (strcmp(command, \"print\") == 0) {\n inorder(root);\n printf(\"\\n\");\n preorder(root);\n printf(\"\\n\");\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 9056, "score_of_the_acc": -0.3443, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_8_D_10737584", "code_snippet": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n\n// ノード構造体の定義\nstruct Node {\n int key; // キー\n int priority; // 優先度\n Node* left; // 左子\n Node* right; // 右子\n Node(int k, int p) : key(k), priority(p), left(nullptr), right(nullptr) {}\n};\n\n// 右回転\nNode* rightRotate(Node* t) {\n Node* s = t->left;\n t->left = s->right;\n s->right = t;\n return s;\n}\n\n// 左回転\nNode* leftRotate(Node* t) {\n Node* s = t->right;\n t->right = s->left;\n s->left = t;\n return s;\n}\n\n// 挿入操作\nNode* insert(Node* t, int key, int priority) {\n if (!t) return new Node(key, priority); // 新しいノードを挿入\n\n if (key < t->key) {\n t->left = insert(t->left, key, priority);\n if (t->left->priority > t->priority) {\n t = rightRotate(t); // ヒープ条件を満たすまで右回転\n }\n } else {\n t->right = insert(t->right, key, priority);\n if (t->right->priority > t->priority) {\n t = leftRotate(t); // ヒープ条件を満たすまで左回転\n }\n }\n return t;\n}\n\n// 削除操作\nNode* deleteNode(Node* t, int key) {\n if (!t) return nullptr; // ノードがない場合\n\n if (key < t->key) {\n t->left = deleteNode(t->left, key);\n } else if (key > t->key) {\n t->right = deleteNode(t->right, key);\n } else {\n // 削除対象のノードを発見\n if (!t->left || !t->right) {\n Node* tmp = t->left ? t->left : t->right;\n delete t;\n return tmp;\n } else if (t->left->priority > t->right->priority) {\n t = rightRotate(t);\n t->right = deleteNode(t->right, key);\n } else {\n t = leftRotate(t);\n t->left = deleteNode(t->left, key);\n }\n }\n return t;\n}\n\n// 探索操作\nbool find(Node* t, int key) {\n if (!t) return false;\n if (key == t->key) return true;\n if (key < t->key) return find(t->left, key);\n return find(t->right, key);\n}\n\n// 中間順巡回 (inorder)\nvoid inorder(Node* t) {\n if (!t) return;\n inorder(t->left);\n cout << \" \" << t->key ;\n inorder(t->right);\n}\n// 先行順巡回 (preorder)\nvoid preorder(Node* t) {\n if (!t) return;\n cout << \" \" << t->key ;\n preorder(t->left);\n preorder(t->right);\n}\n\nint main() {\n int m;\n cin >> m; // 操作数を入力\n Node* treap = nullptr; // 空のTreapを初期化\n\n while (m--) {\n string command;\n cin >> command; // コマンドを入力\n\n if (command == \"insert\") {\n int key, priority;\n cin >> key >> priority;\n treap = insert(treap, key, priority); // 挿入\n } else if (command == \"find\") {\n int key;\n cin >> key;\n cout << (find(treap, key) ? \"yes\" : \"no\") << endl; // 探索\n } else if (command == \"delete\") {\n int key;\n cin >> key;\n treap = deleteNode(treap, key); // 削除\n } else if (command == \"print\") {\n inorder(treap); // 中間順巡回\n cout << endl;\n preorder(treap); // 先行順巡回\n cout << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 9596, "score_of_the_acc": -1.0362, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_8_D_10737565", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\nstruct Treap {\n int key, priority;\n Treap *left, *right;\n Treap(int k, int p) : key(k), priority(p), left(nullptr), right(nullptr) {}\n};\n\nTreap* root = nullptr;\n\nTreap* rightRotate(Treap* t) {\n Treap* s = t->left;\n t->left = s->right;\n s->right = t;\n return s;\n}\n\nTreap* leftRotate(Treap* t) {\n Treap* s = t->right;\n t->right = s->left;\n s->left = t;\n return s;\n}\n\n\nTreap* insert(Treap* t, int key, int priority) {\n if (!t) return new Treap(key, priority);\n if (key == t->key) return t;\n\n if (key < t->key) {\n t->left = insert(t->left, key, priority);\n if (t->left->priority > t->priority)\n t = rightRotate(t);\n } else {\n t->right = insert(t->right, key, priority);\n if (t->right->priority > t->priority)\n t = leftRotate(t);\n }\n return t;\n}\n\nbool find(Treap* t, int key) {\n if (!t) return false;\n if (key == t->key) return true;\n if (key < t->key) return find(t->left, key);\n return find(t->right, key);\n}\n\nTreap* deleteTreap(Treap* t, int key) {\n if (!t) return nullptr;\n if (key < t->key) {\n t->left = deleteTreap(t->left, key);\n } else if (key > t->key) {\n t->right = deleteTreap(t->right, key);\n } else {\n if (!t->left && !t->right) {\n delete t;\n return nullptr;\n } else if (!t->left) {\n t = leftRotate(t);\n t->left = deleteTreap(t->left, key);\n } else if (!t->right) {\n t = rightRotate(t);\n t->right = deleteTreap(t->right, key);\n } else {\n if (t->left->priority > t->right->priority) {\n t = rightRotate(t);\n t->right = deleteTreap(t->right, key);\n } else {\n t = leftRotate(t);\n t->left = deleteTreap(t->left, key);\n }\n }\n }\n return t;\n}\nvoid inorder(Treap* t) {\n if (!t) return;\n inorder(t->left);\n cout << \" \" << t->key;\n inorder(t->right);\n}\n\nvoid preorder(Treap* t) {\n if (!t) return;\n cout << \" \" << t->key;\n preorder(t->left);\n preorder(t->right);\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int m;\n cin >> m;\n string cmd;\n int k, p;\n\n for (int i = 0; i < m; ++i) {\n cin >> cmd;\n if (cmd == \"insert\") {\n cin >> k >> p;\n root = insert(root, k, p);\n } else if (cmd == \"find\") {\n cin >> k;\n cout << (find(root, k) ? \"yes\" : \"no\") << '\\n';\n } else if (cmd == \"delete\") {\n cin >> k;\n root = deleteTreap(root, k);\n } else if (cmd == \"print\") {\n inorder(root); cout << endl;\n preorder(root); cout << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 9648, "score_of_the_acc": -0.3143, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_8_D_10712889", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=2e5+5;\nint cnt,rt,n,m;\nchar op[10];\nstruct node{int ls,rs,val=0,rnd=0,siz=0;}tr[N];\nvoid newnode(int &x,int val,int rnd){tr[x=++cnt]={0,0,val,rnd,1},(!rt?rt=x:0);}\nvoid push_up(int x){tr[x].siz=x?tr[tr[x].ls].siz+tr[tr[x].rs].siz+1:0;}\nvoid split(int x,int val,int &u,int &v){\n if(!x) return u=v=0,void();\n if(tr[x].val<=val) u=x,split(tr[x].rs,val,tr[u].rs,v),push_up(x);\n else v=x,split(tr[x].ls,val,u,tr[v].ls),push_up(v);\n}\nint merge(int x,int y){\n if(!x||!y) return x|y;\n if(tr[x].rnd>tr[y].rnd) return tr[x].rs=merge(tr[x].rs,y),push_up(x),x;\n else return tr[y].ls=merge(x,tr[y].ls),push_up(y),y;\n}\nvoid insert(int val,int rnd){\n int x,y,z;\n split(rt,val,x,y),newnode(z,val,rnd),rt=merge(merge(x,z),y);\n}\nvoid del(int val){\n int x,y,z;\n split(rt,val,x,z),split(x,val-1,x,y),\n y=merge(tr[y].ls,tr[y].rs),rt=merge(merge(x,y),z);\n}\nint get_rank(int val){\n int x,y,ans;\n split(rt,val-1,x,y),ans=tr[x].siz+1,rt=merge(x,y);\n return ans;\n}\nint get_val(int x,int k){\n int lsiz=tr[tr[x].ls].siz;\n return k==lsiz+1?tr[x].val:(k<=lsiz?get_val(tr[x].ls,k):get_val(tr[x].rs,k-(lsiz+1)));\n}\nint get_pre(int val){\n int x,y,ans;\n split(rt,val-1,x,y),ans=get_val(x,tr[x].siz),rt=merge(x,y);\n return ans;\n}\nint get_nxt(int val){\n int x,y,ans;\n split(rt,val,x,y),ans=get_val(y,1),rt=merge(x,y);\n return ans;\n}\nvoid Preorder(int x){\n if(tr[x].val!=1e9&&tr[x].val!=-1e9) printf(\" %d\",tr[x].val);\n if(tr[x].ls) Preorder(tr[x].ls);\n if(tr[x].rs) Preorder(tr[x].rs);\n}\nvoid Mid_order(int x){\n if(tr[x].ls) Mid_order(tr[x].ls);\n if(tr[x].val!=1e9&&tr[x].val!=-1e9) printf(\" %d\",tr[x].val);\n if(tr[x].rs) Mid_order(tr[x].rs);\n}\nint main(){\n scanf(\"%d\",&m),insert(1e9,0),insert(-1e9,0);\n for(int k,p,i=1;i<=m;i++){\n scanf(\" %s\",op+1);\n if(op[1]=='i') scanf(\"%d%d\",&k,&p),insert(k,p);\n if(op[1]=='f')\n scanf(\"%d\",&k),\n printf(\"%s\\n\",get_pre(k+1)==k?\"yes\":\"no\");\n if(op[1]=='d') scanf(\"%d\",&k),del(k);\n if(op[1]=='p')\n Mid_order(rt),printf(\"\\n\"),Preorder(rt),printf(\"\\n\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 7476, "score_of_the_acc": -0.3636, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_8_D_10712870", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=2e5+5;\nint cnt,rt;\nint n,m;\nchar op[10];\nstruct node{int ls,rs,val=0,rnd=0,siz=0;}tr[N];\nvoid newnode(int &x,int val,int rnd){tr[x=++cnt]={0,0,val,rnd,1},(!rt?rt=x:0);}\nvoid push_up(int x){tr[x].siz=x?tr[tr[x].ls].siz+tr[tr[x].rs].siz+1:0;}\nvoid split(int x,int val,int &u,int &v){\n if(!x) return u=v=0,void();\n if(tr[x].val<=val) u=x,split(tr[x].rs,val,tr[u].rs,v),push_up(x);\n else v=x,split(tr[x].ls,val,u,tr[v].ls),push_up(v);\n}\nint merge(int x,int y){\n if(!x||!y) return x|y;\n if(tr[x].rnd>tr[y].rnd) return tr[x].rs=merge(tr[x].rs,y),push_up(x),x;\n else return tr[y].ls=merge(x,tr[y].ls),push_up(y),y;\n}\nvoid insert(int val,int rnd){\n int x,y,z;\n split(rt,val,x,y),newnode(z,val,rnd),rt=merge(merge(x,z),y);\n}\nvoid del(int val){\n int x,y,z;\n split(rt,val,x,z),split(x,val-1,x,y),\n y=merge(tr[y].ls,tr[y].rs),rt=merge(merge(x,y),z);\n}\nint get_rank(int val){\n int x,y,ans;\n split(rt,val-1,x,y),ans=tr[x].siz+1,rt=merge(x,y);\n return ans;\n}\nint get_val(int x,int k){\n int lsiz=tr[tr[x].ls].siz;\n return k==lsiz+1?tr[x].val:(k<=lsiz?get_val(tr[x].ls,k):get_val(tr[x].rs,k-(lsiz+1)));\n}\nint get_pre(int val){\n int x,y,ans;\n split(rt,val-1,x,y),ans=get_val(x,tr[x].siz),rt=merge(x,y);\n return ans;\n}\nint get_nxt(int val){\n int x,y,ans;\n split(rt,val,x,y),ans=get_val(y,1),rt=merge(x,y);\n return ans;\n}\nvoid Preorder(int x){\n printf(\" %d\",tr[x].val);\n if(tr[x].ls) Preorder(tr[x].ls);\n if(tr[x].rs) Preorder(tr[x].rs);\n}\nvoid Mid_order(int x){\n if(tr[x].ls) Mid_order(tr[x].ls);\n printf(\" %d\",tr[x].val);\n if(tr[x].rs) Mid_order(tr[x].rs);\n}\nint main(){\n scanf(\"%d\",&m);\n for(int k,p,i=1;i<=m;i++){\n scanf(\" %s\",op+1);\n if(op[1]=='i') scanf(\"%d%d\",&k,&p),insert(k,p);\n if(op[1]=='f')\n scanf(\"%d\",&k),\n printf(\"%s\\n\",get_val(rt,get_rank(k))==k?\"yes\":\"no\");\n if(op[1]=='d') scanf(\"%d\",&k),del(k);\n if(op[1]=='p')\n Mid_order(rt),printf(\"\\n\"),Preorder(rt),printf(\"\\n\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 7476, "score_of_the_acc": -0.3636, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_8_D_10668623", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\nconst int INF = (1 << 30);\n\nstruct Node\n{\n int key, priority;\n Node *left;\n Node *right;\n Node(int _k, int _p) : key(_k), priority(_p), left(nullptr), right(nullptr) {}\n};\n\nstruct treap\n{\n int siz;\n Node *n;\n const int MAXI;\n treap(int _size, int _max) : siz(_size), MAXI(_max), n(nullptr) {};\n\n Node *rightRotate(Node *t)\n {\n Node *s = t->left;\n t->left = s->right;\n s->right = t;\n return s;\n }\n\n Node *leftRotate(Node *t)\n {\n Node *s = t->right;\n t->right = s->left;\n s->left = t;\n return s;\n }\n\n Node *insert(Node *t, int key, int priority)\n {\n if (t == nullptr)\n {\n return new Node(key, priority);\n }\n if (key == t->key)\n {\n return t;\n }\n if (key < t->key)\n {\n t->left = insert(t->left, key, priority);\n if (t->priority < t->left->priority)\n {\n t = rightRotate(t);\n }\n }\n else\n {\n t->right = insert(t->right, key, priority);\n if (t->priority < t->right->priority)\n {\n t = leftRotate(t);\n }\n }\n return t;\n }\n Node *_delete(Node *t, int key)\n {\n if (t == nullptr)\n {\n return t;\n }\n if (key < t->key)\n {\n t->left = _delete(t->left, key);\n }\n else if (key > t->key)\n {\n t->right = _delete(t->right, key);\n }\n else\n {\n return _delete_(t, key);\n }\n return t;\n }\n Node *_delete_(Node *t, int key)\n {\n if (t->left == nullptr and t->right == nullptr)\n {\n return nullptr;\n }\n else if (t->left == nullptr)\n {\n t = leftRotate(t);\n }\n else if (t->right == nullptr)\n {\n t = rightRotate(t);\n }\n else\n {\n if (t->left->priority > t->right->priority)\n {\n t = rightRotate(t);\n }\n else\n {\n t = leftRotate(t);\n }\n }\n return _delete(t, key);\n }\n bool find(int key, Node *t)\n {\n if (t == nullptr)\n {\n return false;\n }\n else if (key == t->key)\n {\n return true;\n }\n else if (key < t->key)\n {\n return find(key, t->left);\n }\n else\n {\n return find(key, t->right);\n }\n }\n void order(Node *t, bool inorder = true)\n {\n if (t == nullptr)\n {\n return;\n }\n if (!inorder)\n {\n cout << \" \" << t->key;\n }\n order(t->left, inorder);\n if (inorder)\n {\n cout << \" \" << t->key;\n }\n order(t->right, inorder);\n }\n void print()\n {\n order(n);\n cout << endl;\n order(n, false);\n cout << endl;\n\n }\n};\n\nsigned main()\n{\n int m;\n cin >> m;\n treap t(200005, 2000000000);\n for (int i = 0; i < m; i++)\n {\n string s;\n cin >> s;\n if (s == \"insert\")\n {\n int k, p;\n cin >> k >> p;\n t.n = t.insert(t.n, k, p);\n }\n else if (s == \"find\")\n {\n int k;\n cin >> k;\n if (t.find(k, t.n)) {\n cout << \"yes\" << endl;\n }\n else {\n cout << \"no\" << endl;\n }\n }\n else if (s == \"delete\")\n {\n int k;\n cin >> k;\n t.n = t._delete(t.n, k);\n }\n else\n {\n t.print();\n }\n }\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 12760, "score_of_the_acc": -1.3616, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_8_D_10668160", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nstruct Node{\n int key;\n int pri;\n Node* left;\n Node* right;\n Node(int k, int p) : key(k), pri(p), left(nullptr), right(nullptr) {}\n};\n\nNode* rightRotate(Node* &t){\n Node* s = t->left;\n t->left = s->right;\n s->right = t;\n return s;\n}\n\nNode* leftRotate(Node* &t){\n Node* s = t->right;\n t->right = s->left;\n s->left = t;\n return s;\n}\n\nNode* insert(Node* &t, int key, int pri) {\n if (t == nullptr) {\n t = new Node(key, pri);\n } else if (key < t->key) {\n insert(t->left, key, pri);\n if (t->left->pri > t->pri) t = rightRotate(t);\n } else {\n insert(t->right, key, pri);\n if (t->right->pri > t->pri) t = leftRotate(t);\n }\n return t;\n}\n\n\nNode* erase(Node* t, int key){\n if (t == nullptr) return NULL;\n if(key == t->key){\n if(t->left == NULL && t->right == NULL){\n return NULL;\n }else if(t->left == NULL){\n t = leftRotate(t);\n }else if(t->right == NULL){\n t = rightRotate(t);\n }else{\n if(t->left->pri > t->right->pri){\n\tt = rightRotate(t);\n }else{\n\tt = leftRotate(t);\n }\n }\n return erase(t, key);\n }\n if(key < t->key){\n t->left = erase(t->left, key);\n }else{\n t->right = erase(t->right, key);\n }\n return t;\n}\n\n\nbool find(Node* t, int key) {\n if (t == nullptr) return false;\n if (key == t->key) return true;\n if (key < t->key) return find(t->left, key);\n return find(t->right, key);\n}\n\n\nvoid printInorder(Node* t) {\n if (!t) return;\n printInorder(t->left);\n std::cout << \" \" << t->key;\n printInorder(t->right);\n}\n\nvoid printPreorder(Node* t) {\n if (!t) return;\n std::cout << \" \" << t->key;\n printPreorder(t->left);\n printPreorder(t->right);\n}\n\nint main() {\n int m, k, p;\n std::string operate;\n std::cin >> m;\n\n Node* root = nullptr;\n std::srand(std::time(nullptr));\n\n for (int i = 0; i < m; ++i) {\n std::cin >> operate;\n if (operate == \"insert\") {\n std::cin >> k >> p;\n root = insert(root, k, p);\n } else if (operate == \"find\") {\n std::cin >> k;\n std::cout << (find(root, k) ? \"yes\" : \"no\") << std::endl;\n } else if (operate == \"delete\") {\n std::cin >> k;\n root = erase(root, k);\n } else if (operate == \"print\") {\n printInorder(root);\n\tstd::cout << std::endl;\n\tprintPreorder(root);\n\tstd::cout << std::endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 9596, "score_of_the_acc": -1.0362, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_8_D_10668098", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nstruct Node{\n int key;\n int pri;\n Node* left;\n Node* right;\n Node(int k, int p) : key(k), pri(p), left(nullptr), right(nullptr) {}\n};\n\nNode* rightRotate(Node* &t){\n Node* s = t->left;\n t->left = s->right;\n s->right = t;\n return s;\n}\n\nNode* leftRotate(Node* &t){\n Node* s = t->right;\n t->right = s->left;\n s->left = t;\n return s;\n}\n\nNode* insert(Node* &t, int key, int pri) {\n if (t == nullptr) {\n t = new Node(key, pri);\n } else if (key < t->key) {\n insert(t->left, key, pri);\n if (t->left->pri > t->pri) t = rightRotate(t);\n } else {\n insert(t->right, key, pri);\n if (t->right->pri > t->pri) t = leftRotate(t);\n }\n return t;\n}\n\nvoid erase(Node* &t, int key) {\n if (t == nullptr) return;\n if (key < t->key) {\n erase(t->left, key);\n } else if (key > t->key) {\n erase(t->right, key);\n } else {\n if (!t->left && !t->right) {\n delete t;\n t = nullptr;\n } else if (!t->left) {\n t = leftRotate(t);\n erase(t->left, key);\n } else if (!t->right) {\n t = rightRotate(t);\n erase(t->right, key);\n } else {\n if (t->left->pri > t->right->pri) {\n\tt = rightRotate(t);\n\terase(t->right, key);\n } else {\n\tt = leftRotate(t);\n\terase(t->left, key);\n }\n }\n }\n}\n\nbool find(Node* t, int key) {\n if (t == nullptr) return false;\n if (key == t->key) return true;\n if (key < t->key) return find(t->left, key);\n return find(t->right, key);\n}\n\n\nvoid printInorder(Node* t) {\n if (!t) return;\n printInorder(t->left);\n std::cout << \" \" << t->key;\n printInorder(t->right);\n}\n\nvoid printPreorder(Node* t) {\n if (!t) return;\n std::cout << \" \" << t->key;\n printPreorder(t->left);\n printPreorder(t->right);\n}\n\nint main() {\n int m, k, p;\n std::string operate;\n std::cin >> m;\n \n Node* root = nullptr;\n std::srand(std::time(nullptr));\n \n for (int i = 0; i < m; ++i) {\n std::cin >> operate;\n if (operate == \"insert\") {\n std::cin >> k >> p;\n root = insert(root, k, p);\n } else if (operate == \"find\") {\n std::cin >> k;\n std::cout << (find(root, k) ? \"yes\" : \"no\") << std::endl;\n } else if (operate == \"delete\") {\n std::cin >> k;\n erase(root, k);\n } else if (operate == \"print\") {\n printInorder(root);\n\tstd::cout << std::endl;\n\tprintPreorder(root);\n\tstd::cout << std::endl;\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 9608, "score_of_the_acc": -1.0374, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_8_D_10667204", "code_snippet": "#include <iostream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <numeric>\n#include <tuple>\n#include <ranges>\nnamespace ranges = std::ranges;\nnamespace views = std::views;\n// #include \"Src/Number/IntegerDivision.hpp\"\n// #include \"Src/Utility/BinarySearch.hpp\"\n// #include \"Src/Sequence/CompressedSequence.hpp\"\n// #include \"Src/Sequence/RunLengthEncoding.hpp\"\n// #include \"Src/Algebra/Group/AdditiveGroup.hpp\"\n// #include \"Src/DataStructure/FenwickTree/FenwickTree.hpp\"\n// #include \"Src/DataStructure/SegmentTree/SegmentTree.hpp\"\n// #include \"Src/DataStructure/DisjointSetUnion/DisjointSetUnion.hpp\"\n// using namespace zawa;\n// #include \"atcoder/modint\"\n// using mint = atcoder::modint998244353;\n\nstruct Node {\n int val = -1, pri = -1, par = -1, lch = -1, rch = -1;\n};\nstd::vector<Node> BST;\nint& val(int n) {\n return BST.at(n).val;\n}\nint& par(int n) {\n return BST.at(n).par;\n}\nint& pri(int n) {\n return BST.at(n).pri;\n}\nint& lch(int n) {\n return BST.at(n).lch;\n}\nint& rch(int n) {\n return BST.at(n).rch;\n}\n\nint right_rotate(int t) {\n int s = lch(t);\n lch(t) = rch(s);\n rch(s) = t;\n return s;\n}\n\nint left_rotate(int t) {\n int s = rch(t);\n rch(t) = lch(s);\n lch(s) = t;\n return s;\n}\n\nint make_node(int va = -1, int pr = -1, int p = -1) {\n int res = std::ssize(BST);\n BST.push_back({va, pr, p, -1, -1});\n return res;\n}\n\nint root = -1;\n\nvoid insert(int va, int pr) {\n auto internal_insert = [&](auto rec, int t, int par) -> int {\n if (t == -1) return make_node(va, pr, par);\n if (val(t) == va) return t;\n if (va < val(t)) {\n lch(t) = rec(rec, lch(t), t);\n if (pri(t) < pri(lch(t))) {\n t = right_rotate(t);\n }\n }\n else {\n rch(t) = rec(rec, rch(t), t);\n if (pri(t) < pri(rch(t))) {\n t = left_rotate(t);\n }\n }\n return t;\n };\n root = internal_insert(internal_insert, root, -1);\n}\n\nint find(int v) {\n int node = root;\n while (node != -1) {\n if (v < val(node)) node = lch(node);\n else if (v == val(node)) return node;\n else node = rch(node);\n }\n return node;\n}\n\nbool contains(int v) {\n return find(v) != -1;\n}\n\nint erase(int, int);\nint erase_(int, int);\n\nint erase(int t, int va) {\n // std::cout << t << ' ' << val(t) << ' ' << va << std::endl;\n if (t == -1) return -1;\n if (va < val(t)) lch(t) = erase(lch(t), va);\n else if (va > val(t)) rch(t) = erase(rch(t), va);\n else return erase_(t, va);\n return t;\n}\n\nint erase_(int t, int va) {\n if (lch(t) == -1 and rch(t) == -1) return -1;\n else if (lch(t) == -1) t = left_rotate(t);\n else if (rch(t) == -1) t = right_rotate(t);\n else {\n if (pri(lch(t)) > pri(rch(t))) {\n t = right_rotate(t);\n }\n else {\n t = left_rotate(t);\n }\n }\n return erase(t, va);\n}\n\nvoid inorder_tree_walk(int n) {\n if (n == -1) return;\n std::cout << ' ' << val(n);\n inorder_tree_walk(lch(n));\n inorder_tree_walk(rch(n));\n}\n\nvoid preorder_tree_walk(int n) {\n if (n == -1) return;\n preorder_tree_walk(lch(n));\n std::cout << ' ' << val(n);\n preorder_tree_walk(rch(n));\n}\n\nint main() {\n std::cin.tie(nullptr);\n std::cout.tie(nullptr);\n std::ios::sync_with_stdio(false);\n int Q;\n std::cin >> Q;\n while (Q--) {\n std::string s;\n std::cin >> s;\n if (s[0] == 'i') {\n int v, p;\n std::cin >> v >> p;\n // std::cout << \"insert \" << v << ' ' << p << std::endl;\n insert(v, p);\n }\n else if (s[0] == 'p') {\n preorder_tree_walk(root);\n std::cout << '\\n';\n inorder_tree_walk(root);\n std::cout << '\\n';\n // std::cout.flush();\n }\n else if (s[0] == 'f') {\n int v;\n std::cin >> v;\n std::cout << (contains(v) ? \"yes\\n\" : \"no\\n\");\n // std::cout.flush();\n }\n else if (s[0] == 'd') {\n int v;\n std::cin >> v;\n // std::cout << \"delete \" << v << std::endl;\n root = erase(root, v);\n std::cout.flush();\n }\n else assert(false);\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 9708, "score_of_the_acc": -0.2295, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_8_D_10666291", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define loop(a,b) for (int a = 0;a < b;a++)\n#define rep(a,b,c) for(int a = b;a < c;a++)\n#define vec(a) vector<a>\n//SEGSIVの原因がつかめなかったので、AIに修正してもらったコードを再実装しています。修正箇所をコメントで記載しています。\n\n// === 修正箇所1: Node構造体の定義は同じ ===\nstruct Node{\n int key,priority;\n Node *left,*right;\n Node(int key,int priority = rand()%1000000):key(key),priority(priority),left(nullptr),right(nullptr){};\n \n};\n\nclass Treap {\nprivate:\n Node* root;\n \n // === 修正箇所2: 回転操作は同じ ===\n Node* rightRotate(Node* y) {\n Node* x = y->left;\n y->left = x->right;\n x->right = y;\n return x;\n }\n \n Node* leftRotate(Node* x) {\n Node* y = x->right;\n x->right = y->left;\n y->left = x;\n return y;\n }\n\n // === 修正箇所3: insert操作は同じ ===\n Node* insert(Node* t, int key,int pri) {\n if (t == nullptr) return new Node(key,pri);\n \n if (key <= t->key) {\n t->left = insert(t->left, key,pri);\n if (t->left->priority > t->priority)\n t = rightRotate(t);\n } else {\n t->right = insert(t->right, key,pri);\n if (t->right->priority > t->priority)\n t = leftRotate(t);\n }\n return t;\n }\n \n // === 修正箇所4: remove操作 - 元のコードにコメントを追加 ===\n Node* remove(Node* t, int key) {\n if (!t) return nullptr;\n \n if (key < t->key) {\n t->left = remove(t->left, key);\n } else if (key > t->key) {\n t->right = remove(t->right, key);\n } else {\n // キーが見つかった場合の削除処理\n \n // 葉ノードの場合\n if (!t->left && !t->right) {\n delete t;\n return nullptr;\n }\n // 左子のみ存在する場合\n else if (!t->right) {\n Node* temp = t->left;\n delete t;\n return temp;\n }\n // 右子のみ存在する場合\n else if (!t->left) {\n Node* temp = t->right;\n delete t;\n return temp;\n }\n // 両方の子が存在する場合\n else {\n if (t->left->priority > t->right->priority) {\n t = rightRotate(t);\n t->right = remove(t->right, key);\n } else {\n t = leftRotate(t);\n t->left = remove(t->left, key);\n }\n }\n }\n return t;\n }\n \n // === 修正箇所5: search操作は同じ ===\n bool search(Node* t, int key) {\n if (!t) return false;\n if (t->key == key) return true;\n if (key < t->key) return search(t->left, key);\n return search(t->right, key);\n }\n \n // === 修正箇所6: inorder操作 - 元のコードにコメントを追加 ===\n void inorder(Node* t) {\n if (t) { // 引数tをチェック\n inorder(t->left);\n cout << \" \" << t->key;\n inorder(t->right);\n }\n }\n \n // === 修正箇所7: preorder操作 - 元のコードにコメントを追加 === \n void preorder(Node* t) {\n if (t) { // 引数tをチェック\n cout << \" \" << t->key;\n preorder(t->left);\n preorder(t->right);\n }\n }\n \npublic:\n Treap() : root(nullptr) {}\n \n void insert(int key,int pri) { root = insert(root, key,pri); }\n void remove(int key) { root = remove(root, key); }\n bool search(int key) { return search(root, key); }\n void print() {\n inorder(root);\n cout << endl;\n preorder(root);\n cout << endl;\n }\n};\n\n\nint main(){\n int m;\n cin >> m;\n Treap treap;\n loop(i,m){\n string com;\n cin >> com;\n if(com == \"insert\") {\n int key, pri;\n cin >> key >> pri;\n treap.insert(key,pri);\n }\n else if(com == \"find\") {\n int key;\n cin >> key;\n bool result = treap.search(key);\n cout << (result ? \"yes\" : \"no\") << endl;\n }\n else if(com == \"delete\") {\n int key;\n cin >> key;\n treap.remove(key);\n }\n else if(com == \"print\") {\n treap.print();\n }\n }\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 9628, "score_of_the_acc": -1.0395, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_8_D_10660247", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/beta/ice/?problemId=ALDS1_8_D\n#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; (i) < (n); ++(i))\n\ntypedef struct Node\n{\n int key;\n int priority;\n Node *left;\n Node *right;\n\n Node(int k, int pri)\n {\n key = k;\n priority = pri;\n left = NULL;\n right = NULL;\n }\n};\n\nNode *t = NULL;\n\nNode *erase(Node *, int);\nNode *_delete(Node *, int);\n\nNode *rightRotate(Node *t)\n{\n Node *s = t->left;\n t->left = s->right;\n s->right = t;\n return s;\n}\n\nNode *leftRotate(Node *t)\n{\n Node *s = t->right;\n t->right = s->left;\n s->left = t;\n return s;\n}\n\nNode *insert(Node *t, int key, int priority)\n{\n if (t == NULL)\n {\n return new Node(key, priority);\n }\n if (key == t->key)\n {\n return t;\n }\n\n if (key < t->key)\n {\n t->left = insert(t->left, key, priority);\n\n if (t->priority < t->left->priority)\n {\n t = rightRotate(t);\n }\n }\n else\n {\n t->right = insert(t->right, key, priority);\n if (t->priority < t->right->priority)\n {\n t = leftRotate(t);\n }\n }\n return t;\n}\n\nNode *erase(Node *t, int k)\n{\n if (t == NULL)\n {\n return NULL;\n }\n\n if (k < t->key)\n {\n t->left = erase(t->left, k);\n }\n else if (k > t->key)\n {\n t->right = erase(t->right, k);\n }\n else\n {\n return _delete(t, k);\n }\n return t;\n // if (k == t->key)\n // {\n // if (t->left == NULL && t->right == NULL)\n // {\n // return NULL;\n // }\n // else if (t->left == NULL)\n // {\n // t = leftRotate(t);\n // }\n // else if (t->right == NULL)\n // {\n // t = rightRotate(t);\n // }\n // else\n // {\n // if (t->left->priority > t->right->priority)\n // {\n // t = rightRotate(t);\n // }\n // else\n // {\n // t = leftRotate(t);\n // }\n // return erase(t, k);\n // }\n // }\n // if (k < t->key)\n // {\n // t->left = erase(t->left, k);\n // }\n // else\n // {\n // t->right = erase(t->right, k);\n // }\n // return t;\n}\n\nNode *_delete(Node *t, int k)\n{\n if (t->left == NULL && t->right == NULL)\n {\n return NULL;\n }\n else if (t->left == NULL)\n {\n t = leftRotate(t);\n }\n else if (t->right == NULL)\n {\n t = rightRotate(t);\n }\n else\n {\n if ((t->left->priority) > (t->right->priority))\n {\n t = rightRotate(t);\n }\n else\n {\n t = leftRotate(t);\n }\n }\n return erase(t, k);\n}\n\nNode *find(Node *x, int key)\n{\n while (x != NULL && key != x->key)\n {\n if (key < x->key)\n {\n x = x->left;\n }\n else\n {\n x = x->right;\n }\n }\n return x;\n}\n\nvoid inorder(Node *x)\n{\n if (x == NULL)\n {\n return;\n }\n inorder(x->left);\n cout << \" \" << x->key;\n inorder(x->right);\n}\n\nvoid preorder(Node *x)\n{\n if (x == NULL)\n {\n return;\n }\n cout << \" \" << x->key;\n preorder(x->left);\n preorder(x->right);\n}\n\nint main()\n{\n int order_num;\n\n cin >> order_num;\n\n rep(i, order_num)\n {\n string order;\n int k, p;\n cin >> order;\n if (order == \"insert\")\n {\n cin >> k >> p;\n t = insert(t, k, p);\n }\n else if (order == \"delete\")\n {\n cin >> k;\n t = erase(t, k);\n }\n else if (order == \"find\")\n {\n cin >> k;\n Node *result = find(t, k);\n if (result != NULL)\n {\n cout << \"yes\" << endl;\n }\n else\n {\n cout << \"no\" << endl;\n }\n }\n else if (order == \"print\")\n {\n inorder(t);\n cout << endl;\n preorder(t);\n\n cout << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 9692, "score_of_the_acc": -1.0461, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_8_D_10641877", "code_snippet": "// ALDS1_8_D\n#include <bits/stdc++.h>\n#define endl '\\n'\n#define ll long long\nusing namespace std;\n\nstruct Node {\n int key, priority;\n Node *left, *right;\n Node(int k, int p) : key(k), priority(p), left(nullptr), right(nullptr) {}\n};\n\nNode* deleteNode(Node* root, int key);\nNode* _deleteNode(Node* root, int key);\n\n\nNode* rightRotate(Node* root) {\n Node* newRoot = root->left;\n root->left = newRoot->right;\n newRoot->right = root;\n return newRoot;\n}\n\nNode* leftRotate(Node* root) {\n Node* newRoot = root->right;\n root->right = newRoot->left;\n newRoot->left = root;\n return newRoot;\n}\n\nNode* insert(Node* root, int key, int priority) {\n if(root == nullptr) return new Node(key, priority);\n\n if(key == root->key) return root;\n\n if(key < root->key) {\n root->left = insert(root->left, key, priority);\n if(root->priority < root->left->priority) root = rightRotate(root);\n } \n else {\n root->right = insert(root->right, key, priority);\n if(root->priority < root->right->priority) root = leftRotate(root);\n }\n\n return root;\n}\n\nNode* deleteNode(Node* root, int key) {\n if(root == nullptr) return nullptr;\n // 削除対象を検索\n if(key < root->key) {\n root->left = deleteNode(root->left, key);\n }\n else if(key > root->key) {\n root->right = deleteNode(root->right, key);\n }\n else {\n return _deleteNode(root, key);\n }\n return root;\n}\n\nNode* _deleteNode(Node* root, int key) {\n if(root->left == nullptr && root->right == nullptr) {\n return nullptr;\n }\n else if(root->left == nullptr) {\n root = leftRotate(root);\n } \n else if(root->right == nullptr) {\n root = rightRotate(root);\n }\n else {\n if(root->left->priority > root->right->priority) {\n root = rightRotate(root);\n }\n else {\n root = leftRotate(root);\n }\n }\n return deleteNode(root, key);\n}\n\nbool find(Node* root, int key) {\n if(root == nullptr) return false;\n if(key == root->key) return true;\n if(key < root->key) return find(root->left, key);\n return find(root->right, key);\n}\n\nvoid inOrder(Node* root) {\n if(root == nullptr) return;\n if(root->left != nullptr) inOrder(root->left);\n cout << \" \" << root->key;\n if(root->right != nullptr) inOrder(root->right);\n}\n\nvoid preOrder(Node* root) {\n if(root == nullptr) return;\n cout << \" \" << root->key;\n if(root->left != nullptr) preOrder(root->left);\n if(root->right != nullptr) preOrder(root->right);\n}\n\n\nint main() {\n int m;\n cin >> m;\n\n Node* root = nullptr;\n for(int i=0; i<m; ++i) {\n string com;\n cin >> com;\n if(com == \"insert\") {\n int k, p;\n cin >> k >> p;\n root = insert(root, k, p);\n }\n else if(com == \"find\") {\n int k;\n cin >> k;\n if(find(root, k)) {\n cout << \"yes\" << endl;\n } \n else {\n cout << \"no\" << endl;\n }\n\n }\n else if(com == \"delete\") {\n int k;\n cin >> k;\n root = deleteNode(root, k);\n }\n else if(com == \"print\") {\n inOrder(root);\n cout << endl;\n preOrder(root);\n cout << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 9696, "score_of_the_acc": -1.0465, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_8_D_10632495", "code_snippet": "//Treap\n#include<iostream>\n#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\nusing namespace std;\n\n//NodePointerの定義\ntypedef struct node * NodePointer;\n\n//node型構造体の定義\nstruct node{\n int k;\n int pri;\n NodePointer p,l,r;\n};\n\n//外部変数で定義する二分探索木の根\nNodePointer root;\n\n\n//各関数のプロトタイプ宣言\nNodePointer insert(NodePointer,int,int);\nNodePointer ddelete(NodePointer,int);\nNodePointer cdelete(NodePointer,int);\nNodePointer find(NodePointer,int);\nNodePointer right(NodePointer);\nNodePointer left(NodePointer);\nvoid in(NodePointer);\nvoid pre(NodePointer);\n\nint main(){\n int i,j,pri,n,m;\n NodePointer t;\n char com[8];\n\n cin >> m;\n\n for(i=0;i<m;i++){\n cin >> com;\n if(strcmp(\"insert\", com)==0){\n cin >> n >> pri;\n t = insert(root,n,pri);\n }else if(strcmp(\"find\", com)==0){\n cin >> n;\n if(find(root,n)!=NULL){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }else if(strcmp(\"print\", com)==0){\n in(root);\n cout << endl;\n pre(root);\n cout << endl;\n }else if(strcmp(\"delete\", com)==0){\n cin >> n;\n t = ddelete(root,n);\n }\n\n\n }\n\n return 0;\n}\n\nNodePointer insert(NodePointer t,int k,int pri){\n NodePointer z,x;\n if(t == NULL){\n x = root;\n z = (NodePointer)malloc(sizeof(struct node));\n z->k = k;\n z->pri = pri;\n z->l = NULL;\n z->r = NULL;\n \n while(x!=NULL){\n t = x;\n if(z->k < x->k){\n\tx = x->l;\n }else{\n\tx = x->r;\n }\n }\n z->p = t;\n \n if(t==NULL){\n root = z;\n }else if(z->k < t->k){\n t->l = z;\n }else{\n t->r = z;\n }\n return z;\n }\n\n if(k==t->k)return t;\n\n if(k < t->k){\n t->l = insert(t->l, k, pri);\n if(t->pri < t->l->pri)t = right(t);\n }else{\n t->r = insert(t->r, k, pri);\n if(t->pri < t->r->pri)t = left(t);\n }\n\n return t;\n}\n\nNodePointer right(NodePointer t){\n NodePointer s;\n s = t->l;\n if(t==root)root = s;\n t->l = s->r;\n s->r = t;\n return s;\n}\n\nNodePointer left(NodePointer t){\n NodePointer s;\n s = t->r;\n if(t==root)root = s;\n t->r = s->l;\n s->l = t;\n return s;\n}\n\nNodePointer ddelete(NodePointer t,int ky){\n NodePointer x,y;\n if(t==NULL)return NULL;\n \n if(ky < t->k)t->l = ddelete(t->l,ky);\n else if(ky > t->k)t->r = ddelete(t->r,ky);\n else return cdelete(t,ky);\n \n return t;\n}\n\nNodePointer cdelete(NodePointer t,int k){\n if(t->l == NULL && t->r == NULL){\n return NULL;\n }else if(t->l == NULL){\n t = left(t);\n }else if(t->r == NULL){\n t = right(t);\n }else{\n if(t->l->pri > t->r->pri){\n t = right(t);\n }else{\n t = left(t);\n }\n }\n \n return ddelete(t,k);\n}\n\nNodePointer find(NodePointer x,int k){\n while(x!=NULL && k!=x->k){\n if(k < x->k)x = x->l;\n else x = x->r;\n }\n return x;\n}\n\nvoid in(NodePointer u){\n if(u==NULL)return;\n\n in(u->l);\n cout << \" \" << u->k;\n in(u->r);\n}\n\nvoid pre(NodePointer u){\n if(u==NULL)return;\n\n cout << \" \" << u->k;\n pre(u->l);\n pre(u->r);\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 12736, "score_of_the_acc": -1.45, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_8_D_10621098", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (n); ++i)\nusing ll = long long;\n\nstruct Node {\n int key;\n int priority;\n Node *left, *right;\n Node(int key, int priority)\n : key(key), priority(priority), left(nullptr), right(nullptr) {}\n};\n\nNode* rightRotate(Node*& t) {\n Node* s = t->left;\n t->left = s->right;\n s->right = t;\n return s; // root of the subtree\n}\nNode* leftRotate(Node*& t) {\n Node* s = t->right;\n t->right = s->left;\n s->left = t;\n return s; // root of the subtree\n}\nNode* insert(Node*& t, int key, int priority) { // 再帰的に探索\n if (t == nullptr)\n return new Node(key,\n priority); // 葉に到達したら新しい節点を生成して返す\n if (key == t->key) return t; // 重複したkeyは無視\n if (key < t->key) { // 左の子へ移動\n t->left = insert(t->left, key, priority); // ポインタ更新\n if (t->priority < t->left->priority) t = rightRotate(t);\n } else { // 右の子へ移動\n t->right = insert(t->right, key, priority); // ポインタ更新\n if (t->priority < t->right->priority) t = leftRotate(t);\n }\n return t;\n}\nNode* _deleten(Node*& t, int key);\nNode* deleten(Node*& t, int key) {\n if (t == nullptr) return nullptr;\n if (key < t->key) // 削除対象を検索\n t->left = deleten(t->left, key);\n else if (key > t->key)\n t->right = deleten(t->right, key);\n else\n return _deleten(t, key);\n return t;\n}\nNode* _deleten(Node*& t, int key) { // 削除対象の節点の場合\n if ((t->left == nullptr) && (t->right == nullptr)) {\n delete t;\n return nullptr;\n } else if (t->left == nullptr) // 右の子のみ持つ場合左回転\n t = leftRotate(t);\n else if (t->right == nullptr) // 左の子のみ持つ場合左回転\n t = rightRotate(t);\n else { // 左右両方の子を持つ場合\n if (t->left->priority > t->right->priority) // 高優先度を上へ\n t = rightRotate(t);\n else\n t = leftRotate(t);\n }\n return deleten(t, key);\n}\n\nbool find(Node*& t, int key) {\n if (t == nullptr) return false;\n bool ret = false;\n if (t->key > key)\n ret = find(t->left, key);\n else if (t->key < key)\n ret = find(t->right, key);\n else\n ret = true;\n return ret;\n}\n\nvector<int> ino, preo;\nvoid dfs(Node* t) {\n if (t == nullptr) return;\n preo.push_back(t->key);\n dfs(t->left);\n ino.push_back(t->key);\n dfs(t->right);\n}\nvoid print(Node* t) {\n ino.clear();\n preo.clear();\n dfs(t);\n int n = ino.size();\n rep(i, n) cout << \" \" << ino[i];\n cout << endl;\n rep(i, n) cout << \" \" << preo[i];\n cout << endl;\n}\n\nNode* root;\nvoid solve() {\n string s;\n cin >> s;\n if (s == \"insert\") {\n int k, p;\n cin >> k >> p;\n root = insert(root, k, p);\n } else if (s == \"find\") {\n int k;\n cin >> k;\n if (find(root, k))\n cout << \"yes\" << endl;\n else\n cout << \"no\" << endl;\n } else if (s == \"delete\") {\n int k;\n cin >> k;\n deleten(root, k);\n } else {\n print(root);\n }\n}\nint main() {\n int m;\n cin >> m;\n root = nullptr;\n rep(im, m) solve();\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 11132, "score_of_the_acc": -1.1942, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_8_D_10481491", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define all(x) (x).begin(), (x).end()\nusing ll = long long;\n\nstruct Node {\n ll value;\n ll priority;\n Node *left = nullptr;\n Node *right = nullptr;\n Node *parent = nullptr;\n};\n\nclass Treap {\n private:\n Node *root = nullptr;\n\n void destroy(Node *node) {\n if (!node) return;\n destroy(node->left);\n destroy(node->right);\n delete node;\n }\n\n public:\n Treap() {}\n\n ~Treap() { destroy(root); }\n\n // nodeの左子をnodeの親にする回転\n Node *right_rotate(Node *node) {\n Node *node2 = node->left;\n node2->parent = node->parent;\n if (node2->parent && node2->parent->left == node) {\n node2->parent->left = node2;\n }\n if (node2->parent && node2->parent->right == node) {\n node2->parent->right = node2;\n }\n node->left = node2->right;\n if (node2->right) node2->right->parent = node;\n node2->right = node;\n node->parent = node2;\n if (!node2->parent) {\n root = node2;\n }\n return node2;\n }\n // nodeの右子をnodeの親にする回転\n Node *left_rotate(Node *node) {\n Node *node2 = node->right;\n node2->parent = node->parent;\n if (node2->parent && node2->parent->left == node) {\n node2->parent->left = node2;\n }\n if (node2->parent && node2->parent->right == node) {\n node2->parent->right = node2;\n }\n node->right = node2->left;\n if (node2->left) node2->left->parent = node;\n node2->left = node;\n node->parent = node2;\n if (!node2->parent) {\n root = node2;\n }\n return node2;\n }\n\n void insert(const ll value, ll priority = -1) {\n auto f = [&](auto rec, Node *&node, Node *p) -> Node * {\n if (!node) {\n node = new Node();\n node->value = value;\n node->priority = priority;\n node->parent = p;\n return node;\n } else if (value < node->value) {\n node->left = rec(rec, node->left, node);\n node->left->parent = node;\n // 子の方が優先度が高い場合、回転して上に上げる\n if (node->priority < node->left->priority) {\n node = right_rotate(node);\n }\n return node;\n } else {\n node->right = rec(rec, node->right, node);\n node->right->parent = node;\n if (node->priority < node->right->priority) {\n node = left_rotate(node);\n }\n return node;\n }\n };\n f(f, root, nullptr);\n }\n\n Node *find(const ll value, Node *subtree_root = nullptr) {\n auto f = [](auto rec, Node *&node, ll v) -> Node * {\n if (!node) return nullptr;\n if (node->value == v) return node;\n if (node->value > v) {\n return rec(rec, node->left, v);\n } else {\n return rec(rec, node->right, v);\n }\n };\n return f(f, subtree_root ? subtree_root : root, value);\n }\n\n void erase(const ll value) {\n Node *delete_node = find(value);\n // 木にvalueが存在しなかった\n if (!delete_node) return;\n\n // 葉まで移動させてから削除する\n auto f = [&](auto rec, Node *node) -> void {\n // debug_node(node);\n // 両方の子がない場合\n if (!node->left && !node->right) {\n // これを削除する\n if (node->parent && node == node->parent->left)\n node->parent->left = nullptr;\n if (node->parent && node == node->parent->right)\n node->parent->right = nullptr;\n } else if (!node->left) {\n // 右の子を上に持ち上げる(=左回転)\n left_rotate(node);\n rec(rec, node);\n } else if (!node->right) {\n right_rotate(node);\n rec(rec, node);\n } else {\n // 両方の子を持つ場合、優先度が高い方を持ち上げる\n if (node->left->priority > node->right->priority) {\n right_rotate(node);\n rec(rec, node);\n } else {\n left_rotate(node);\n rec(rec, node);\n }\n }\n };\n f(f, delete_node);\n delete delete_node;\n }\n\n // 指定したnodeを根とする部分木の最も小さい値を返す。デフォルトは木全体\n Node *tree_minimum(Node *root_node = nullptr) {\n auto f = [&](auto rec, Node *&node) -> Node * {\n return node->left ? rec(rec, node->left) : node;\n };\n return f(f, root_node ? root_node : root);\n }\n Node *tree_maximum(Node *root_node = nullptr) {\n auto f = [&](auto rec, Node *&node) -> Node * {\n return node->right ? rec(rec, node->right) : node;\n };\n return f(f, root_node ? root_node : root);\n }\n\n Node *tree_successor(Node *node) {\n assert(node);\n // 右の子がいるならその中で一番小さい値\n if (node->right) return tree_minimum(node->right);\n // 祖先のうち右上方向に登る最初のもの\n Node *ret = node;\n while (ret->parent) {\n if (ret->parent->left == ret) {\n // 初めて右上に登ったらそれがsuccessor\n ret = ret->parent;\n break;\n } else {\n // 左上に登っている間は登り続ける\n ret = ret->parent;\n }\n }\n return ret;\n }\n Node *tree_predecessor(Node *node) {\n assert(node);\n // 左の子がいるならその中で一番大きい値\n if (node->left) return tree_maximum(node->left);\n // 祖先のうち左上方向に登る最初のもの\n Node *ret = node;\n while (ret->parent) {\n if (ret->parent->right == ret) {\n // 初めて左上に登ったらそれがsuccessor\n ret = ret->parent;\n break;\n } else {\n // 右上に登っている間は登り続ける\n ret = ret->parent;\n }\n }\n return ret;\n }\n\n vector<ll> inorder_tree_walk() {\n vector<ll> ret;\n auto dfs = [&](auto rec, Node *&node) -> void {\n if (!node) return;\n rec(rec, node->left);\n ret.push_back(node->value);\n rec(rec, node->right);\n };\n dfs(dfs, root);\n return ret;\n }\n\n vector<ll> preorder_tree_walk() {\n vector<ll> ret;\n auto dfs = [&](auto rec, Node *&node) -> void {\n if (!node) return;\n ret.push_back(node->value);\n rec(rec, node->left);\n rec(rec, node->right);\n };\n dfs(dfs, root);\n return ret;\n }\n\n void print() {\n auto res = inorder_tree_walk();\n for (auto v : res) cout << \" \" << v;\n cout << endl;\n res = preorder_tree_walk();\n for (auto v : res) cout << \" \" << v;\n cout << endl;\n }\n\n // 可視化用(https://binomialsheep.github.io/sheep-visualize-graph-beta/)\n void print_edges() {\n cerr << \"print_edge\" << endl;\n vector<pair<int, int>> edges;\n auto dfs = [&](auto rec, Node *&node) -> void {\n if (!node) return;\n debug_node(node);\n if (node->parent) edges.emplace_back(node->parent->value, node->value);\n rec(rec, node->left);\n rec(rec, node->right);\n };\n dfs(dfs, root);\n int n = 0;\n for (auto [v, u] : edges) {\n n = max(n, v);\n n = max(n, u);\n }\n int m = (int)edges.size();\n // ラベルは圧縮しない\n cout << n << \" \" << m << endl;\n for (auto [v, u] : edges) {\n cout << v << \" \" << u << endl;\n }\n }\n // デバッグ用\n\n void debug_node(Node *node) {\n ll value = node->value;\n ll left = node->left ? node->left->value : -1;\n ll right = node->right ? node->right->value : -1;\n ll parent = node->parent ? node->parent->value : -1;\n cerr << \"v,l,r.p: \" << value << \", \" << left << \", \" << right << \", \"\n << parent << endl;\n }\n\n void assert_valid_tree() {\n auto dfs = [&](auto rec, Node *&node) -> void {\n if (!node) return;\n if (node->left) {\n assert(node == node->left->parent);\n assert(node->value >= node->left->value);\n }\n if (node->right) {\n assert(node == node->right->parent);\n assert(node->value <= node->right->value);\n }\n rec(rec, node->left);\n rec(rec, node->right);\n };\n dfs(dfs, root);\n }\n};\n\nvoid test() {\n {\n // minimum, maximu, successor, predecessorのテスト\n Treap tree;\n tree.insert(2);\n tree.insert(1);\n tree.insert(5);\n tree.insert(4);\n tree.insert(3);\n tree.insert(6);\n\n Node *node = tree.tree_minimum();\n for (int i = 1; i <= 6; i++) {\n if (node->value != i) {\n cerr << i << \" \" << node->value << endl;\n assert(false);\n }\n node = tree.tree_successor(node);\n }\n node = tree.tree_maximum();\n for (int i = 6; i >= 1; i--) {\n if (node->value != i) {\n cerr << i << \" \" << node->value << endl;\n assert(false);\n }\n node = tree.tree_predecessor(node);\n }\n }\n}\n\nint main() {\n test();\n Treap tree;\n\n int N;\n cin >> N;\n rep(i, N) {\n string command;\n cin >> command;\n if (command == \"insert\") {\n int v, p;\n cin >> v >> p;\n tree.insert(v, p);\n } else if (command == \"find\") {\n int v;\n cin >> v;\n cout << (tree.find(v) ? \"yes\" : \"no\") << endl;\n } else if (command == \"delete\") {\n int v;\n cin >> v;\n tree.erase(v);\n // tree.print_edges();\n } else if (command == \"print\") {\n tree.print();\n // tree.print_edges();\n } else if (command == \"minmax\") {\n Node *min = tree.tree_minimum();\n Node *max = tree.tree_maximum();\n cout << min->value << \" \" << max->value << endl;\n } else {\n assert(false);\n }\n }\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 17200, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_8_D_10471386", "code_snippet": "#include <bits/stdc++.h>\n#include <iomanip>\n\nstruct Treap {\n int value = 0;\n int priority = 0;\n Treap* left = nullptr;\n Treap* right = nullptr;\n Treap(int value, int priority, Treap* left = nullptr, Treap* right = nullptr) {\n this->value = value;\n this->priority = priority;\n this->left = left;\n this->right = right;\n }\n};\n\nTreap* right_rotate(Treap* now) {\n Treap* new_root = now->left;\n now->left = new_root->right;\n new_root->right = now;\n return new_root;\n}\n\nTreap* left_rotate(Treap* now) {\n Treap* new_root = now->right;\n now->right = new_root->left;\n new_root->left = now;\n return new_root;\n}\nTreap* insert(Treap* now, int x, int p) {\n if (now == nullptr) {\n return new Treap(x, p);\n }\n if (x < now->value) {\n now->left = insert(now->left, x, p);\n if (now->left->priority > now->priority) {\n now = right_rotate(now);\n }\n } else {\n now->right = insert(now->right, x, p);\n if (now->right->priority > now->priority) {\n now = left_rotate(now);\n }\n }\n return now;\n}\n\nbool find(Treap* now, int x) {\n if (now == nullptr) {\n return false;\n }\n if (x == now->value) {\n return true;\n } else if (x < now->value) {\n return find(now->left, x);\n } else { // x > now->value\n return find(now->right, x);\n }\n}\n\nTreap* remove(Treap* now, int x);\n\nTreap* _remove(Treap* now, int x) {\n if (now->left == nullptr && now->right == nullptr) {\n delete now;\n return nullptr;\n } else if (now->right == nullptr) { // has left subtree\n now = right_rotate(now);\n } else if (now->left == nullptr) { // has right subtree\n now = left_rotate(now);\n } else { // has left and right subtree\n if (now->left->priority > now->right->priority) {\n now = right_rotate(now);\n } else {\n now = left_rotate(now);\n }\n }\n Treap* ret = remove(now, x);\n return ret;\n// return remove(now, x);\n}\n\nTreap* remove(Treap* now, int x) {\n if (now == nullptr) {\n return nullptr;\n }\n if (x == now->value) {\n Treap* ret = _remove(now, x);\n return ret;\n// return _remove(now, x);\n } else if (x < now->value) {\n now->left = remove(now->left, x);\n } else { // x > now->value\n now->right = remove(now->right, x);\n }\n return now;\n}\n\nvoid inorder(Treap* now) {\n if (now == nullptr) {\n return;\n }\n inorder(now->left);\n std::cout << \" \" << now->value;\n inorder(now->right);\n}\n\nvoid preorder(Treap* now) {\n if (now == nullptr) {\n return;\n }\n std::cout << \" \" << now->value;\n preorder(now->left);\n preorder(now->right);\n}\n\nvoid print(Treap* root) {\n inorder(root);\n std::cout << std::endl;\n preorder(root);\n std::cout << std::endl;\n}\n\nvoid my_release(Treap* now) {\n if (now == nullptr) {\n return;\n }\n my_release(now->left);\n my_release(now->right);\n delete now;\n}\n\nint main() {\n int n;\n std::cin >> n;\n\n std::string command;\n int x, p;\n Treap* root = nullptr;\n for (int i = 0; i < n; i++) {\n std::cin >> command;\n if (command == \"insert\") {\n std::cin >> x >> p;\n root = insert(root, x, p);\n } else if (command == \"find\") {\n std::cin >> x;\n std::cout << (find(root, x) ? \"yes\" : \"no\") << std::endl;\n } else if (command == \"delete\") {\n std::cin >> x;\n root = remove(root, x);\n } else if (command == \"print\") {\n print(root);\n }\n }\n\n my_release(root);\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 9692, "score_of_the_acc": -1.137, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_8_D_10394321", "code_snippet": "#include <iostream>\n\nclass Treap {\n class Node_t {\n public:\n int key;\n int pri;\n Node_t* left;\n Node_t* right;\n };\n\n Node_t* arr;\n Node_t* root = NULL;\n int idx = 0;\n int pri_max = -2000000001;\n\npublic:\n Treap(int n) {\n arr = new Node_t[n];\n }\n\n ~Treap() {\n delete[] arr;\n }\n\n Node_t* get_root() {\n return root;\n }\n\n void set_root(Node_t* t) {\n root = t;\n }\n\n Node_t* insert(Node_t* t, int in_key, int in_pri) {\n if (t == NULL) {\n arr[idx].key = in_key;\n arr[idx].pri = in_pri;\n arr[idx].left = NULL;\n arr[idx].right = NULL;\n t = &arr[idx];\n if (in_pri > pri_max) {\n pri_max = in_pri;\n root = &arr[idx];\n }\n ++idx;\n return t;\n }\n\n if (in_key == t->key)\n return t;\n\n if (in_key < t->key) {\n t->left = insert(t->left, in_key, in_pri);\n if (t->pri < t->left->pri)\n t = rightRotate(t);\n }\n else {\n t->right = insert(t->right, in_key, in_pri);\n if (t->pri < t->right->pri)\n t = leftRotate(t);\n }\n \n return t;\n }\n\n Node_t* rightRotate(Node_t* t) {\n Node_t* s = t->left;\n t->left = s->right;\n s->right = t;\n\n return s;\n }\n\n Node_t* leftRotate(Node_t* t) {\n Node_t* s = t->right;\n t->right = s->left;\n s->left = t;\n\n return s;\n }\n\n Node_t* deleteNode(Node_t* t, int in_key) {\n if (t == NULL)\n return NULL;\n else if (in_key < t->key)\n t->left = deleteNode(t->left, in_key);\n else if (in_key > t->key)\n t->right = deleteNode(t->right, in_key);\n else\n return _deleteNode(t, in_key);\n\n return t;\n }\n\n Node_t* _deleteNode(Node_t* t, int in_key) {\n if (t->left == NULL && t->right == NULL)\n return NULL;\n else if (t->left == NULL)\n t = leftRotate(t);\n else if (t->right == NULL)\n t = rightRotate(t);\n else\n if (t->left->pri > t->right->pri)\n t = rightRotate(t);\n else\n t = leftRotate(t);\n \n return deleteNode(t, in_key);\n }\n \n bool find(int in_key) {\n bool flg = false;\n Node_t* temp = root;\n\n while (!flg && temp != NULL)\n if (in_key == temp->key)\n flg = true;\n else if (in_key < temp->key)\n temp = temp->left;\n else\n temp = temp->right;\n\n return flg;\n }\n\n void inorder_tree_walk(Node_t* in_parent) {\n if (in_parent != NULL) {\n inorder_tree_walk(in_parent->left);\n std::cout << \" \" << in_parent->key;\n inorder_tree_walk(in_parent->right);\n }\n }\n\n void preorder_tree_walk(Node_t* in_parent) {\n if (in_parent != NULL) {\n std::cout << \" \" << in_parent->key;\n preorder_tree_walk(in_parent->left);\n preorder_tree_walk(in_parent->right);\n }\n }\n\n};\n\nint main()\n{\n int n;\n std::string cmd;\n int in_key, in_pri;\n \n std::cin >> n;\n Treap tr = Treap(n);\n \n for (int i = 0; i < n; i++) {\n std::cin >> cmd;\n if (cmd == \"insert\") {\n std::cin >> in_key >> in_pri;\n tr.insert(tr.get_root(), in_key, in_pri);\n }\n else if (cmd == \"delete\") {\n std::cin >> in_key;\n tr.set_root(tr.deleteNode(tr.get_root(), in_key));\n }\n else if (cmd == \"find\") {\n std::cin >> in_key;\n if (tr.find(in_key))\n std::cout << \"yes\" << std::endl;\n else\n std::cout << \"no\" << std::endl;\n }\n else if (cmd == \"print\") {\n tr.inorder_tree_walk(tr.get_root());\n std::cout << std::endl;\n tr.preorder_tree_walk(tr.get_root());\n std::cout << std::endl;\n }\n }\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 7776, "score_of_the_acc": -0.7581, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_8_D_10383163", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n\tint key;\n\tint priority;\n\tNode* left;\n\tNode* right;\n\tNode(int k, int p) : key(k), priority(p), left(nullptr), right(nullptr) {}\n};\n\nNode* rightRotate(Node* t) {\n\tNode* s = t->left;\n\tt->left = s->right;\n\ts->right = t;\n\treturn s;\n}\n\nNode* leftRotate(Node* t) {\n\tNode* s = t->right;\n\tt->right = s->left;\n\ts->left = t;\n\treturn s;\n}\n\nNode* insert(Node* t, int key, int priority) {\n\tif (t == nullptr) {\n\t\treturn new Node(key, priority);\n\t}\n\tif (key == t->key) {\n\t\treturn t;\n\t}\n\tif (key < t->key) {\n\t\tt->left = insert(t->left, key, priority);\n\t\tif (t->priority < t->left->priority) {\n\t\t\tt = rightRotate(t);\n\t\t}\n\t} else {\n\t\tt->right = insert(t->right, key, priority);\n\t\tif (t->priority < t->right->priority) {\n\t\t\tt = leftRotate(t);\n\t\t}\n\t}\n\treturn t;\n}\n\nNode* deleteNode(Node* t, int key) {\n\tif (t == nullptr) {\n\t\treturn nullptr;\n\t}\n\tif (key < t->key) {\n\t\tt->left = deleteNode(t->left, key);\n\t} else if (key > t->key) {\n\t\tt->right = deleteNode(t->right, key);\n\t} else {\n\t\tif (t->left == nullptr && t->right == nullptr) {\n\t\t\tdelete t;\n\t\t\treturn nullptr;\n\t\t}\n\t\tif (t->left == nullptr) {\n\t\t\tNode* temp = t->right;\n\t\t\tdelete t;\n\t\t\tt = temp;\n\t\t} else if (t->right == nullptr) {\n\t\t\tNode* temp = t->left;\n\t\t\tdelete t;\n\t\t\tt = temp;\n\t\t} else {\n\t\t\tif (t->left->priority > t->right->priority) {\n\t\t\t\tt = rightRotate(t);\n\t\t\t\tt->right = deleteNode(t->right, key);\n\t\t\t} else {\n\t\t\t\tt = leftRotate(t);\n\t\t\t\tt->left = deleteNode(t->left, key);\n\t\t\t}\n\t\t}\n\t}\n\treturn t;\n}\n\nbool find(Node* t, int key) {\n\tif (t == nullptr) return false;\n\tif (key == t->key) return true;\n\tif (key < t->key) return find(t->left, key);\n\telse return find(t->right, key);\n}\n\nvoid inorder(Node* t) {\n\tif (t == nullptr) return;\n\tinorder(t->left);\n\tcout << \" \" << t->key;\n\tinorder(t->right);\n}\n\nvoid preorder(Node* t) {\n\tif (t == nullptr) return;\n\tcout << \" \" << t->key;\n\tpreorder(t->left);\n\tpreorder(t->right);\n}\n\nint main() {\n\tint m; cin >> m;\n\tNode* root = nullptr;\n\twhile (m--) {\n\t\tstring op;\n\t\tcin >> op;\n\t\tif (op == \"insert\") {\n\t\t\tint k, p;\n\t\t\tcin >> k >> p;\n\t\t\troot = insert(root, k, p);\n\t\t} else if (op == \"find\") {\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\tif (find(root, k)) cout << \"yes\" << endl;\n\t\t\telse cout << \"no\" << endl;\n\t\t} else if (op == \"delete\") {\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\troot = deleteNode(root, k);\n\t\t} else {\n\t\t\tinorder(root);\n\t\t\tcout << \"\\n\";\n\t\t\tpreorder(root);\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 9692, "score_of_the_acc": -1.0461, "final_rank": 12 } ]
aoj_ALDS1_9_D_cpp
Heap Sort There are a number of sorting algorithms which have different characteristics as follows. Algorithm Time Complexity (Worst) Time Complexity (Average) Stability Memory Efficiency Method Features Insertion Sort ALDS1_1_A O($N^2$) O($N^2$) 〇 〇 Insertion Can be fast for an almost sorted array Bubble Sort ALDS1_2_A O($N^2$) O($N^2$) 〇 〇 Swap Selection Sort ALDS1_2_B O($N^2$) O($N^2$) × 〇 Swap Shell Sort ALDS1_2_D O($N^2$) O($N log N$) × 〇 Insertion Merge Sort ALDS1_5_A O($N log N$) O($N log N$) 〇 × Divide and Conqure Fast and stable. It needs an external memory other than the input array. Counting Sort ALDS1_6_A O($N + K$) O($N + K$) 〇 × Bucket Fast and stable. There is a limit to the value of array elements. Quick Sort ALDS1_6_B O($N^2$) O($N log N$) × △ Divide and Conqure Fast and almost-in-place if it takes a measure for the corner cases. Naive implementation can be slow for the corner cases. Heap Sort ALDS1_9_D (This problem) O($N log N$) O($N log N$) × 〇 Heap structure Fast and in-place. It is unstable and performs random access for non-continuous elements frequently. The Heap Sort algorithms is one of fast algorithms which is based on the heap data structure. The algorithms can be implemented as follows. 1 maxHeapify(A, i) 2 l = left(i) 3 r = right(i) 4 // select the node which has the maximum value 5 if l ≤ heapSize and A[l] > A[i] 6 largest = l 7 else 8 largest = i 9 if r ≤ heapSize and A[r] > A[largest] 10 largest = r 11 12 if largest ≠ i  13 swap A[i] and A[largest] 14 maxHeapify(A, largest) 15 16 heapSort(A): 17 // buildMaxHeap 18 for i = N/2 downto 1: 19 maxHeapify(A, i) 20 // sort 21 heapSize ← N 22 while heapSize ≥ 2: 23 swap(A[1], A[heapSize]) 24 heapSize-- 25 maxHeapify(A, 1) On the other hand, the heap sort algorithm exchanges non-continuous elements through random accesses frequently. Your task is to find a permutation of a given sequence $A$ with $N$ elements, such that it is a max-heap and when converting it to a sorted sequence, the total number of swaps in maxHeapify of line 25 in the pseudo code is maximal possible. Input In the first line, an integer $N$ is given. In the next line, $A_i$ ($i=0,1,...,N−1$) are given separated by a single space character. Output Print $N$ integers of the permutation of $A$ separated by a single space character in a line. This problem has multiple solutions and the judge will be performed by a special validator. Constraints $1 \leq N \leq 200000$ $0 \leq$ each element of $A$ $\leq 1000000000$ The elements of $A$ are all different Sample Input and Output Sample Input 1 8 1 2 3 5 9 12 15 23 Sample Output 1 23 9 15 2 5 3 12 1
[ { "submission_id": "aoj_ALDS1_9_D_10848487", "code_snippet": "#include <stdio.h>\n#include <stdlib.h>\n#define gc() getchar()\n#define pc(c) putchar(c)\n#define p(i) i/2\n\nvoid out(int a){\n char i = 0, str[10];\n do str[i++] = (a%10)|0x30, a /= 10; while(a > 0);\n while(i--) pc(str[i]);\n}\n\nint in(){\n int ret = 0, ch;\n while((ch = gc()) > ' ') ret = ret*10+(ch&0xf);\n return ret;\n}\n\nint cmp(const void* a, const void* b){\n return *(int*)a-*(int*)b;\n}\n\nint i, j, temp, n, A[200001];\n\nint main(){\n n = in();\n for(i = 0; i < n; i++) A[i] = in();\n qsort(A, n, 4, cmp);\n A[n] = A[0];\n for(i = 1; i < n; i++){\n j = i;\n while(p(j) > 0 && A[j] > A[p(j)]){\n temp = A[j], A[j] = A[p(j)], A[p(j)] = temp;\n j = p(j);\n }\n }\n for(int i = 1; i < n; i++) out(A[i]), pc(' ');\n out(A[n]), pc('\\n');\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 4016, "score_of_the_acc": -0.2615, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_9_D_10737602", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint H;\n\n\n\nvoid arrange(vector<int>& A)\n{\n int i;\n int b = 0;\n int node = 1;\n int nextnode;\n\n for (i = H; i > 1; i /= 2) {\n b++;\n }\n while (b > 0) {\n if (H & (1 << b - 1)) {\n nextnode = 2*node+1;\n } else {\n nextnode = 2*node;\n }\n swap(A[node], A[nextnode]);\n node = nextnode;\n b--;\n }\n}\n\nint main()\n{\n int i, n;\n cin >> H;\n n = H;\n vector<int> V(n);\n for (i = 0; i < n; i++) {\n cin >> V[i];\n }\n sort(V.begin(), V.end());\n\n vector<int> order(H+1);\n for (i = 1; i <= H; i++) {\n order[i] = i;\n }\n while (H > 1) {\n swap(order[1], order[H--]);\n arrange(order);\n }\n\n vector<int> A(n+1);\n for (i = 1; i <= n; i++) {\n A[order[i]] = V[i-1];\n }\n for (int i = 1; i <= n; i++) {\n if (i > 1) cout << \" \";\n cout << A[i];\n }\n cout << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 5304, "score_of_the_acc": -1.0732, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_9_D_10566439", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid heapify(vector<int> &a, int i, int N) {\n int l = 2*i+1, r = 2*i+2;\n if (r < N) {\n if (l < N && a[l] < a[r]) l = r;\n }\n\n if (l < N && a[i] < a[l]) {\n swap(a[i], a[l]);\n heapify(a, l, N);\n }\n}\n\nvoid unheapify(vector<int> &a, int i, int N) {\n swap(a[0], a[i]);\n\n while (i) {\n int p = (i-1)/2;\n swap(a[i], a[p]);\n i = p;\n }\n}\n\nvoid heapSort(vector<int> &a, int N) {\n // 最大ヒープ\n for (int i = N/2-1; i >= 0; --i) {\n heapify(a, i, N);\n }\n\n for (int i = N-1; i >= 0; --i) {\n swap(a[0], a[i]);\n heapify(a, 0, i);\n }\n\n for (int i = 1; i < N-1; ++i) {\n unheapify(a, i, N);\n }\n swap(a[0], a[N-1]);\n\n}\n\nint main() {\n int N; cin >> N;\n vector<int> a(N);\n for (int i = 0; i < N; ++i) cin >> a[i];\n heapSort(a, N);\n\n for (int i = 0; i < N; ++i) {\n if (i == 0) cout << a[i];\n else cout << \" \" << a[i];\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4096, "score_of_the_acc": -0.6142, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_9_D_10472506", "code_snippet": "#include <bits/stdc++.h>\n#include <iomanip>\n\n// input must be sorted\nvoid build_my_heap(std::vector<int>& vec) {\n for (int i = 1; i < vec.size(); i++) {\n int now = i;\n std::swap(vec[now], vec[0]);\n int parent = (now - 1) / 2;\n while (vec[parent] < vec[now]) {\n std::swap(vec[parent], vec[now]);\n now = parent;\n parent = (now - 1) / 2;\n }\n if (i != vec.size() - 1) {\n now = i;\n parent = (now - 1) / 2;\n while (vec[parent] > vec[now]) {\n std::swap(vec[parent], vec[now]);\n now = parent;\n parent = (now - 1) / 2;\n if (now == 0) {\n break;\n }\n }\n }\n }\n}\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<int> vec(n);\n for (int i = 0; i < n; i++) std::cin >> vec[i];\n std::sort(vec.begin(), vec.end());\n build_my_heap(vec);\n for (int i = 0; i < vec.size(); i++) {\n if (i != 0) {\n std::cout << \" \";\n }\n std::cout << vec[i];\n }\n std::cout << std::endl;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3780, "score_of_the_acc": -0.7044, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_9_D_10401420", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_N = 200000;\nint heap[MAX_N+1];\n\nvoid solve(int N) {\n\tsort(heap + 1, heap + N + 1);\n\tfor (int n = 1; n <= N; ++n) {\n\t\tint i = n - 1, par = i / 2;\n\t\twhile(par >= 1) {\n\t\t\tswap(heap[i], heap[par]);\n\t\t\ti = par, par = i/2;\n\t\t}\n\t\tswap(heap[1], heap[n]);\n\t}\n}\n\nint main() {\n\tint N;\n\tcin >> N;\n\tfor (int i = 1; i <= N; ++i)\n\t\tcin >> heap[i];\n\t\n\tsolve(N);\n\t\n\tfor (int i = 1; i <= N; ++i) {\n\t\tcout << heap[i];\n\t\tif (i != N) cout << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4124, "score_of_the_acc": -0.7877, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_9_D_10310104", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint up(int i){\n return i / 2;\n}\n\nvoid buildMaxHeapAsInverseOfHeapSort(int A[], int N){\n sort(A+1, A+N+1, less<int>());\n for(int i = 2; i < N; i++){\n swap(A[1], A[i]);\n int j = i;\n while(j > 1){\n swap(A[j], A[up(j)]);\n j = up(j);\n }\n }\n swap(A[1], A[N]);\n}\n\nint main(){\n int N;\n cin >> N;\n int A[N + 1];\n for(int i = 1; i <= N; i++){\n cin >> A[i];\n }\n buildMaxHeapAsInverseOfHeapSort(A, N);\n for(int i = 1; i <= N; i++){\n cout << A[i];\n if(i <= N - 1){\n cout << \" \";\n }else{\n cout << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3916, "score_of_the_acc": -0.7373, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_9_D_10310097", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint up(int i){\n return i / 2;\n}\n\nvoid buildMaxHeap2(int A[], int N){\n sort(A+1, A+N+1, less<int>());\n for(int i = 2; i < N; i++){\n swap(A[1], A[i]);\n int j = i;\n while(j > 1){\n swap(A[j], A[up(j)]);\n j = up(j);\n }\n }\n swap(A[1], A[N]);\n}\n\nint main(){\n int N;\n cin >> N;\n int A[N + 1];\n for(int i = 1; i <= N; i++){\n cin >> A[i];\n }\n buildMaxHeap2(A, N);\n for(int i = 1; i <= N; i++){\n cout << A[i];\n if(i <= N - 1){\n cout << \" \";\n }else{\n cout << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4124, "score_of_the_acc": -0.7877, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_9_D_10287614", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid maxheapify(int *a,int i,int n)\n{\n int left=i*2;\n int right=i*2+1;\n int largest;\n if(left<=n&&a[left]>a[i])\n {\n largest=left;\n }\n else largest=i;\n if(right<=n&&a[right]>a[largest])\n {\n largest=right;\n }\n if(largest!=i)\n {\n swap(a[largest],a[i]);\n maxheapify(a,largest,n);\n }\n}\n\nvoid buildmaxheap(int *a,int n)\n{\n for(int i=n/2;i>0;i--)\n {\n maxheapify(a,i,n);\n }\n}\n\nvoid heapsort(int *a,int n)\n{\n for(int i=n;i>1;i--)\n {\n swap(a[1],a[i]);\n maxheapify(a,1,i-1);\n }\n}\n\nvoid update(int *a,int i)\n{\n if(i>1)\n {\n if(a[i/2]>a[i])\n {\n swap(a[i/2],a[i]);\n update(a,i/2);\n }\n }\n}\n\nint main()\n{\n int n;cin>>n;\n int a[n+1];\n for(int i=1;i<=n;i++)\n {\n cin>>a[i];\n }\n\n buildmaxheap(a,n);\n heapsort(a,n);\n\n for(int i=2;i<=n;i++)\n {\n update(a,i-1);\n swap(a[1],a[i]);\n }\n\n for(int i=1;i<=n;i++)\n {\n if(i!=1) cout<<\" \";\n cout<<a[i];\n }\n cout<<endl;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3912, "score_of_the_acc": -0.903, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_9_D_10205858", "code_snippet": "#include <algorithm>\n#include <cstddef>\n#include <iostream>\n#include <utility>\n#include <vector>\n#include <ranges>\n#include <cstdint>\n\n// C++23では高速な入出力のため、std::ios_base::sync_with_stdio(false)や\n// std::cin.tie(nullptr) を利用して、標準I/Oとの同期を解除します。\n\n// 簡易な出力関数:余計なオーバーヘッドを避けるため、array_wrapper を排除し、\n// 直接ループで出力します。\ntemplate <typename Container>\nvoid print_container(const Container& c, std::string_view sep = \" \") {\n if (c.empty()) return;\n auto it = std::cbegin(c);\n std::cout << *it;\n for (++it; it != std::cend(c); ++it) {\n std::cout << sep << *it;\n }\n std::cout << \"\\n\";\n}\n\n// ヒープソートのworst-caseを作る関数。\n// ※各swap操作はmaxHeapifyの25行目(疑似コード中の再帰呼び出し直前のswap)に対応しており\n// これが最大回数になるように構成しています。\ntemplate <typename T>\n[[gnu::always_inline]] inline void make_worst_case_heap(std::vector<T>& vec) {\n const auto n = vec.size();\n if (n <= 1) [[unlikely]] return;\n // ループ中、vec[0](ヒープの根)と各要素とをswapし、その後上方向にバブルアップさせる\n for (std::size_t i = 1; i + 1 < n; ++i) {\n std::swap(vec[0], vec[i]);\n std::size_t c = i;\n while (c > 0) {\n const std::size_t p = (c - 1) / 2;\n std::swap(vec[p], vec[c]);\n c = p;\n }\n }\n std::swap(vec[0], vec.back());\n}\n\nint main() {\n // I/O最適化:C++標準I/OとC標準I/Oの同期を解除し、tieも解除する\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n\n std::size_t N;\n std::cin >> N;\n std::vector<std::uint_fast32_t> vec;\n vec.resize(N);\n for (auto &x : vec) {\n std::cin >> x;\n }\n // まずソート(O(N log N))し、最小値から最大値へ並ぶようにする\n std::ranges::sort(vec);\n // ヒープソートで最大ヒープ条件を満たしつつ、maxHeapifyのswap回数が最大となる順列に変換\n make_worst_case_heap(vec);\n // 出力:余計なオーバーヘッドを避けるため、シンプルなループで出力\n print_container(vec);\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4992, "score_of_the_acc": -0.3311, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_9_D_10194780", "code_snippet": "#include<iostream>\n#include<vector>\n#include<climits>\n#include<algorithm>\nusing namespace std;\n\nint main(){\n int n,j,k;\n cin >> n;\n int X[300000];\n for(int i=0;i<n;i++){\n cin >> X[i];\n }\n sort(X,X+n);\n for(int i=0;i<n-1;i++) {\n j=i;\n while(j>0){\n k=(j-1)/2;\n swap(X[k],X[j]);\n j=k;\n }\n swap(X[0],X[i+1]);\n }\n for(int i=0;i<n;i++){\n if(i!=0)cout<<\" \";\n cout<<X[i];\n }\n cout << endl;\n\n \n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4228, "score_of_the_acc": -0.8128, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_9_D_10176895", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int N; cin >> N;\n vector<int> A(N);\n for(int i = 0; i < N; i++) cin >> A[i];\n\n // 1. 配列を昇順にソート(最小→最大の順)\n sort(A.begin(), A.end());\n\n // 2. (i=0 .. N-2) 各要素を「根までバブルアップ」する\n for(int i = 0; i < N - 1; i++){\n int v = i;\n // 親のインデックスは (v - 1) / 2\n // ここでは「親が0番目以外なら swap する」という条件でループ\n while((v - 1) / 2){\n swap(A[v], A[(v - 1) / 2]);\n v = (v - 1) / 2;\n }\n }\n\n // 3. ルート(0番目)と末尾(N-1番目)を最後に1回交換\n swap(A[0], A[N - 1]);\n\n // 4. 出力\n for(int i = 0; i < N; i++){\n cout << A[i] << (i == N - 1 ? '\\n' : ' ');\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3760, "score_of_the_acc": -0.6996, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_9_D_10176868", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int N; cin>>N;\n vector<int> A(N);\n for(int i=0;i<N;i++)cin>>A[i];\n sort(A.begin(),A.end());\n for(int i=0;i<N-1;i++){\n int v=i;\n while((v-1)/2){\n swap(A[v],A[(v-1)/2]);\n v=(v-1)/2;\n }\n }\n swap(A[0],A[N-1]);\n for(int i=0;i<N;i++)cout<<A[i]<<\" \\n\"[i==N-1];\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3896, "score_of_the_acc": -0.7325, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_9_D_10104933", "code_snippet": "#include<iostream>\n#include<utility>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n\nint main(){\n cin.tie(nullptr)->ios::sync_with_stdio(false);\n int n;\n cin>>n;\n vector<int> A(n);\n for(auto &e:A) cin>>e;\n sort(A.begin(),A.end());\n for(int i=0;i<n-1;i++){\n int val=i;\n while((val-1)/2){\n int nev=(val-1)/2;\n swap(A[val],A[nev]);\n val=nev;\n }\n }\n swap(A.front(),A.back());\n for(int i=0;i<n;i++) cout<<A[i]<<\" \\n\"[i+1==n];\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3692, "score_of_the_acc": -0.1831, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_9_D_10036526", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Heap {\n int heap_size, N;\n vector<int> A;\n Heap(int N) : heap_size(N), N(N), A(N + 1) {}\n int parent(int i) { return floor(i / 2); }\n int left(int i) { return i * 2; }\n int right(int i) { return left(i) + 1; }\n void maxHeapify(int i) {\n int l = left(i), r = right(i), largest;\n largest = l <= heap_size && A[l] > A[i] ? l : i;\n largest = r <= heap_size && A[r] > A[largest] ? r : largest;\n if (largest != i) {\n swap(A[i], A[largest]);\n maxHeapify(largest);\n }\n }\n void minHeapify(int i) {\n int p = parent(i);\n if (p > 0) {\n swap(A[i], A[p]);\n minHeapify(p);\n }\n }\n void buildMaxHeap() {\n for (int i = N / 2; 0 < i; i--) {\n maxHeapify(i);\n }\n }\n void heapSort() {\n buildMaxHeap();\n while (heap_size >= 2) {\n swap(A[1], A[heap_size]);\n heap_size--;\n maxHeapify(1);\n }\n }\n void reverseHeapSort() {\n heap_size = 1;\n while (heap_size < N) {\n minHeapify(heap_size);\n heap_size++;\n swap(A[1], A[heap_size]);\n }\n }\n};\n\nint main() {\n int H;\n cin >> H;\n Heap heap(H);\n for (int i = 1; i <= H; i++) {\n cin >> heap.A[i];\n }\n heap.heapSort();\n heap.reverseHeapSort();\n for (int i = 1; i <= H; i++) {\n cout << heap.A[i] << (i == H ? '\\n' : ' ');\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3864, "score_of_the_acc": -0.7247, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_9_D_9906029", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n\nvoid swap(int& a, int& b) {\n int temp = a;\n a = b;\n b = temp;\n}\n\n// 0\n// 1 2\n// 3 4 5 6\n// 7...\n// のイメージで\nsize_t get_parent_idx(size_t current_idx) {\n return (current_idx + 1) / 2 - 1;\n}\n\nsize_t get_left_idx(size_t current_idx) {\n return 2 * (current_idx + 1) - 1;\n}\n\nsize_t get_right_idx(size_t current_idx) {\n return 2 * (current_idx + 1) -1 + 1;\n}\n\n// 常にroot_idxの要素がヒープの最後の要素(heap_end_idx位置)になるように要素を入れ替える関数\nvoid fake_max_heapify(vector<int>& heap, size_t heap_end_idx) {\n // 末尾から入れ替えられる要素をたどって記録\n vector<int> indexes_on_route;\n size_t current_idx = heap_end_idx;\n indexes_on_route.push_back(heap_end_idx);\n // 末尾の要素から親をたどる\n while (current_idx != 0) {\n auto parent = get_parent_idx(current_idx);\n indexes_on_route.push_back(parent);\n current_idx = parent;\n }\n\n // root_idxが末尾と入れ替わるようになってほしいので、列挙した親と順に入れ替わる動きをシミュレーションする\n // そのような操作になる場合を探したいだけなので、root_idxと親要素との入れ替えが常に最大ヒープ条件を\n // 満たしていることにする\n for (auto i = 0; i < indexes_on_route.size() - 1; i++) {\n ::swap(heap[indexes_on_route[indexes_on_route.size()-1-(i+1)]], heap[indexes_on_route[indexes_on_route.size()-1-i]]);\n }\n}\n\nint main() {\n int n;\n vector<long long int> values;\n vector<int> indexes;\n\n cin >> n;\n for (auto i = 0; i < n; i++) {\n long long int a;\n cin >> a;\n values.push_back(a);\n indexes.push_back(i);\n }\n\n sort(values.begin(), values.end());\n\n // ヒープの最後の要素が最小の値である場合をシミュレーションして\n // ヒープから抽出される要素の添え字を出てくる順に並べる\n int heap_size = n;\n while (heap_size > 0) {\n // 既にヒープ条件を満たすので最初の要素をpopし、末尾と入れ替える\n ::swap(indexes[0], indexes[heap_size-1]);\n heap_size--;\n\n // 今根にいる要素がmax_heapifyで末尾に移動することをシミュレーションする\n if (heap_size > 1) {\n fake_max_heapify(indexes, heap_size - 1);\n }\n }\n\n // indexesで並んでいる順に要素がpopされている\n // -> valuesをindexesにある添え字の順番に並べ替えれば、valuesの値を持つヒープであって、\n // シミュレーションした操作が行われるものの例を構築できる\n long long int res[n];\n for (auto i = 0; i < indexes.size(); i++) {\n res[indexes[i]] = values[i];\n }\n for (auto i = 0; i < n; i++) {\n cout << res[i];\n if (i < n - 1) {\n cout << \" \";\n }\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 7756, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_9_D_9856198", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nvoid min_heapify( vector<ll> &v, int id ){\n\n while( true ){\n int parent = ( id - 1 ) / 2;\n if( parent < 0 ) break;\n if( v[parent] > v[id] ){\n SWAP( v[parent], v[id] );\n }\n else\n break;\n id = parent;\n }\n\n}\n\nint main(){\n\n int n;\n ll key;\n vector<ll> res;\n\n cin >> n;\n for( int i = 0 ; i < n ; i++ ){\n cin >> key;\n res.push_back( key );\n }\n sort( res.begin(), res.end() );\n for( int i = 1 ; i < n - 1 ; i++ ){\n SWAP( res[0], res[i] );\n min_heapify( res, i );\n }\n SWAP( res[0], res[n-1] );\n\n print( res );\n\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 6000, "score_of_the_acc": -1.2417, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_9_D_9856167", "code_snippet": "// Heap Sort\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid unsift(std::vector<int> *A, int i, int bound);\nvoid reverseSorting(std::vector<int> *A);\n\nint main()\n{\n int N;\n std::cin >> N;\n std::vector<int> A(N + 1, 0);\n for (size_t i = 0; i < N; i++)\n {\n int a;\n std::cin >> a;\n A[i + 1] = a;\n }\n\n reverseSorting(&A);\n\n for (size_t i = 0; i < N; i++)\n {\n if (i != 0)\n std::cout << \" \";\n std::cout << A[i + 1];\n }\n std::cout << std::endl;\n return 0;\n}\n\n// 今回の用途ではboundは1で固定なので引数としては本当は無用\nvoid unsift(std::vector<int> *A, int i, int bound)\n{\n int parent = i / 2;\n if (parent >= bound)\n {\n // std::cout << \" swap: \" << (*A)[i] << \"<->\" << (*A)[parent] << std::endl;\n // 無条件で交換していく\n std::swap((*A)[i], (*A)[parent]);\n unsift(A, parent, bound);\n }\n}\n\nvoid reverseSorting(std::vector<int> *A)\n{\n std::sort(A->begin() + 1, A->end());\n int N = A->size() - 1;\n\n // iをヒープ領域の終端とする\n for (size_t i = 1; i < N; i++)\n {\n // 常にヒープの最後尾が最小値\n // ヒープ範囲内の最小値を先頭へアンシフトする\n unsift(A, i, 1);\n // 先頭に来た最小値とヒープの最後尾の1つ後ろを交換\n std::swap((*A)[1], (*A)[i + 1]);\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3860, "score_of_the_acc": -0.7238, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_9_D_9752934", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <string>\n#include <string.h>\n\nusing namespace std;\n\n\nvoid maxHeapify(vector<int> &A, int i, int size) {\n int largestIndex = i;\n\n int leftChildIndex = 2 * i + 1;\n int rightChildIndex = 2 * i + 2;\n if (size > leftChildIndex && A[leftChildIndex] > A[largestIndex]) largestIndex = leftChildIndex;;\n if (size > rightChildIndex && A[rightChildIndex] > A[largestIndex]) largestIndex = rightChildIndex;\n \n if (largestIndex != i) {\n swap(A[i], A[largestIndex]);\n maxHeapify(A, largestIndex, size);\n }\n}\n\nvoid heapSort(vector<int> &A) {\n int size = A.size();\n for (int i = (A.size() - 1) / 2; i >= 0; i--) {\n maxHeapify(A, i, size);\n }\n while (true) {\n swap(A[0], A[size - 1]);\n size--;\n if (size < 2) break;\n maxHeapify(A, 0, size);\n }\n\n}\n\nint main() {\n int n;\n vector<int> A;\n \n cin >> n;\n for (int i = 0; i < n; i++) {\n int a;\n cin >> a;\n A.push_back(a);\n }\n\n //heapSort(A);\n sort(A.begin(), A.end());\n\n \n for (int i = 1; i < n-1; i++) {\n swap(A[0], A[i]);\n\n int index = i;\n while (index > 0) {\n swap(A[index], A[(index-1) / 2]);\n index = (index-1) / 2;\n }\n }\n swap(A[0], A.back());\n\n for (int i = 0; i < n; i++) {\n cout << A[i];\n if (i < n - 1) {\n cout << \" \";\n }\n else {\n cout << endl;\n }\n }\n \n\n\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4084, "score_of_the_acc": -0.778, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_9_D_9744951", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#ifdef LOCAL\n #include \"settings/debug.cpp\"\n#else\n #define Debug(...) void(0)\n#endif\n#define rep(i, n) for (int i = 0; i < (n); ++i)\nusing ll = long long;\nusing ull = unsigned long long;\n\nint main() {\n int n;\n cin >> n;\n vector<int> a(n + 1, -1e9);\n rep(i, n) cin >> a[i + 1];\n sort(a.begin(), a.end());\n\n for (int i = 1; i < n; ++i) {\n for (int j = i; j > 1; j /= 2) swap(a[j], a[j / 2]);\n swap(a[i + 1], a[1]);\n }\n\n rep(i, n) cout << a[i + 1] << \" \\n\"[i == n - 1];\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3736, "score_of_the_acc": -0.6938, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_9_D_9675033", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\nvoid maxheap_swap(vector<int> &v,int p)\n{\n int cur=p;\n int parent=p/2;\n while(parent>1)\n {\n swap(v[cur],v[parent]);\n cur=parent;\n parent=cur/2;\n }\n \n}\nint main() \n{\n vector<int>b;\n int h;\n scanf(\"%d\",&h);\n b.resize(h+1);\n for(int i=1;i<=h;i++)scanf(\"%d\",&b[i]);\n\n sort(b.begin()+1,b.end());\n \n for(int i=1;i<h;i++)maxheap_swap(b,i);\n swap(b[1],b[h]);\n \n for(int i=1;i<h;i++)printf(\"%d \",b[i]);\n printf(\"%d\\n\",b[h]);\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3624, "score_of_the_acc": -0.1667, "final_rank": 1 } ]
aoj_ALDS1_12_A_cpp
Minimum Spanning Tree For a given weighted graph $G = (V, E)$, find the minimum spanning tree (MST) of $G$ and print total weight of edges belong to the MST. Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, a $n \times n$ adjacency matrix $A$ which represents $G$ is given. $a_{ij}$ denotes the weight of edge connecting vertex $i$ and vertex $j$. If there is no edge between $i$ and $j$, $a_{ij}$ is given by -1. Output Print the total weight of the minimum spanning tree of $G$. Constraints $1 \leq n \leq 100$ $0 \leq a_{ij} \leq 2,000$ (if $a_{ij} \neq -1$) $a_{ij} = a_{ji}$ $G$ is a connected graph Sample Input 1 5 -1 2 3 1 -1 2 -1 -1 4 -1 3 -1 -1 1 1 1 4 1 -1 3 -1 -1 1 3 -1 Sample Output 1 5 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.
[ { "submission_id": "aoj_ALDS1_12_A_10644587", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nmap<int, vector<int>> vertex;\nmap<int, vector<int>> edge;\nint sum = 0;\n\nstruct UnionFind {\n vector<int> parent, rank;\n\n UnionFind(int n) {\n parent.resize(n + 1);\n rank.resize(n + 1, 0);\n for (int i = 0; i <= n; i++) parent[i] = i;\n }\n\n int find(int x) {\n if (parent[x] != x) parent[x] = find(parent[x]);\n return parent[x];\n }\n\n bool unite(int x, int y) {\n int rx = find(x);\n int ry = find(y);\n if (rx == ry) return false;\n if (rank[rx] < rank[ry]) {\n parent[rx] = ry;\n } else {\n parent[ry] = rx;\n if (rank[rx] == rank[ry]) rank[rx]++;\n }\n return true;\n }\n};\n\nvoid explore(int weight, int N, UnionFind &uf) {\n bool updated = false;\n\n for (int i = 1; i <= N; i++) {\n int counter = 0;\n for (int w : edge[i]) {\n if (w == weight) {\n int u = i;\n int v = vertex[i][counter];\n\n if (uf.unite(u, v)) {\n sum += weight;\n // cout << u << \" - \" << v << \" : \" << weight << endl;\n updated = true;\n }\n }\n counter++;\n }\n }\n\n if (updated) explore(weight + 1, N, uf); // まだ更新があれば次へ\n else if (weight <= 10000) explore(weight + 1, N, uf); // 一応探索を続ける\n}\n\nint main() {\n int N;\n cin >> N;\n\n vector<vector<int>> matrix(N, vector<int>(N));\n for (int i = 0; i < N; i++)\n for (int j = 0; j < N; j++)\n cin >> matrix[i][j];\n\n // vertex と edge の構築(上三角のみ)\n for (int i = 0; i < N - 1; i++) {\n for (int j = i + 1; j < N; j++) {\n if (matrix[i][j] != -1) {\n vertex[i + 1].push_back(j + 1);\n edge[i + 1].push_back(matrix[i][j]);\n }\n }\n }\n\n UnionFind uf(N);\n explore(1, N, uf);\n cout << sum << endl;\n\n return 0;\n}", "accuracy": 0.8333333333333334, "time_ms": 20, "memory_kb": 5660, "score_of_the_acc": -2, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_12_A_10345519", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Route\n{\n int start = -1;\n int end = -1;\n int cost = -1;\n\n Route(int s, int e, int c)\n {\n start = s;\n end = e;\n cost = c;\n }\n\n bool operator<(const Route &another) const\n {\n return cost < another.cost;\n }\n\n bool operator==(const Route &another) const\n {\n return (start == another.start && end == another.end) || (start == another.end && end == another.start);\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n vector<Route> routes;\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n int num;\n cin >> num;\n if (num != -1)\n {\n Route r(i, j, num);\n if (!count(routes.begin(), routes.end(), r))\n {\n routes.push_back(r);\n }\n }\n }\n }\n // コストでソート\n sort(routes.begin(), routes.end());\n\n int costSum = 0;\n vector<int> routeGroup(n, -1);\n int groupNum = 0;\n for (Route route : routes)\n {\n // 両方グループ化されていないなら、グループに設定\n if (routeGroup[route.start] == -1 && routeGroup[route.end] == -1)\n {\n routeGroup[route.start] = groupNum;\n routeGroup[route.end] = groupNum;\n groupNum++;\n costSum += route.cost;\n }\n // 同じグループならスキップ\n else if (routeGroup[route.start] == routeGroup[route.end])\n {\n continue;\n }\n else\n {\n // 片方だけグループ化されていない場合は、もう片方のグループに追加\n if (routeGroup[route.start] == -1)\n {\n routeGroup[route.start] = routeGroup[route.end];\n }\n else if (routeGroup[route.end] == -1)\n {\n routeGroup[route.end] = routeGroup[route.start];\n }\n // 別々のグループの場合は、start のグループの番号に変更\n else\n {\n int targetNumber = routeGroup[route.end];\n // end と同じグループだったものも start のグループ番号に変更\n for (int &number : routeGroup)\n {\n if (number == targetNumber)\n {\n number = routeGroup[route.start];\n }\n }\n }\n costSum += route.cost;\n }\n }\n cout << costSum << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3440, "score_of_the_acc": -0.0297, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_12_A_10345504", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Route\n{\n int start = -1;\n int end = -1;\n int cost = -1;\n\n Route(int s, int e, int c)\n {\n start = s;\n end = e;\n cost = c;\n }\n\n bool operator<(const Route &another) const\n {\n return cost < another.cost;\n }\n\n bool operator==(const Route &another) const\n {\n return (start == another.start && end == another.end) || (start == another.end && end == another.start);\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n vector<Route> routes;\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n int num;\n cin >> num;\n if (num != -1)\n {\n Route r(i, j, num);\n if (!count(routes.begin(), routes.end(), r))\n {\n routes.push_back(r);\n }\n }\n }\n }\n // コストでソート\n sort(routes.begin(), routes.end());\n\n int costSum = 0;\n vector<int> routeGroup(n, -1);\n int groupNum = 0;\n for (Route route : routes)\n {\n if (routeGroup[route.start] == -1 && routeGroup[route.end] == -1)\n {\n routeGroup[route.start] = groupNum;\n routeGroup[route.end] = groupNum;\n groupNum++;\n costSum += route.cost;\n }\n else if (routeGroup[route.start] == routeGroup[route.end])\n {\n continue;\n }\n else\n {\n if (routeGroup[route.start] == -1)\n {\n routeGroup[route.start] = routeGroup[route.end];\n }\n else if (routeGroup[route.end] == -1)\n {\n routeGroup[route.end] = routeGroup[route.start];\n }\n else\n {\n int targetNumber = routeGroup[route.end];\n for (int &number : routeGroup)\n {\n if (number == targetNumber)\n {\n number = routeGroup[route.start];\n }\n }\n }\n costSum += route.cost;\n }\n }\n cout << costSum << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3436, "score_of_the_acc": -0.028, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_12_A_10345466", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Route\n{\n int start = -1;\n int end = -1;\n int cost = -1;\n\n Route(int s, int e, int c)\n {\n start = s;\n end = e;\n cost = c;\n }\n\n bool operator<(const Route &another) const\n {\n return cost < another.cost;\n }\n\n bool operator==(const Route &another) const\n {\n return (start == another.start && end == another.end) || (start == another.end && end == another.start);\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n vector<Route> routes;\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n int num;\n cin >> num;\n if (num != -1)\n {\n Route r(i, j, num);\n if (!count(routes.begin(), routes.end(), r))\n {\n routes.push_back(r);\n }\n }\n }\n }\n sort(routes.begin(), routes.end());\n vector<vector<bool>> routeMap(n);\n for (int i = 0; i < n; i++)\n {\n routeMap[i].resize(n);\n }\n int costSum = 0;\n for (Route r : routes)\n {\n if (routeMap[r.start][r.end])\n continue;\n routeMap[r.start][r.end] = true;\n routeMap[r.end][r.start] = true;\n for (int i = 0; i < n; i++)\n {\n if (routeMap[i][r.start])\n {\n for (int j = 0; j < n; j++)\n {\n if (routeMap[r.end][j])\n {\n routeMap[i][j] = true;\n routeMap[j][i] = true;\n }\n }\n routeMap[i][r.end] = true;\n routeMap[r.end][i] = true;\n }\n if (routeMap[i][r.end])\n {\n if (routeMap[i][r.end])\n {\n for (int j = 0; j < n; j++)\n {\n if (routeMap[r.start][j])\n {\n routeMap[i][j] = true;\n routeMap[j][i] = true;\n }\n }\n }\n routeMap[i][r.start] = true;\n routeMap[r.start][i] = true;\n }\n }\n costSum += r.cost;\n }\n\n cout << costSum << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3440, "score_of_the_acc": -0.0297, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_12_A_10343643", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct route\n{\n int start = -1;\n int end = -1;\n int cost = -1;\n\n route(int s, int e, int c) {\n start = s;\n end = e;\n cost = c;\n }\n\n bool operator<(const route& another) const {\n return cost < another.cost;\n }\n\n bool operator==(const route& another) const {\n return (start == another.start && end == another.end)\n || (start == another.end && end == another.start);\n }\n};\n\n/*\n 道を昇順で登録\n ab(1) cd(2) ac(3) ... など\n サイクルになる場合は除外\n ab cd ac bd(×)\n*/\n\nint main()\n{\n int n;\n cin >> n;\n vector<route> routes;\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++) {\n int num;\n cin >> num;\n if (num != -1) {\n route r(i, j, num);\n if (!count(routes.begin(), routes.end(), r)) {\n routes.push_back(r);\n }\n }\n }\n }\n sort(routes.begin(), routes.end());\n vector<vector<bool>> routeMap(n);\n for (int i=0;i<n;i++) {\n routeMap[i].resize(n);\n }\n int costSum = 0;\n // ループチェック\n // \n for (route r: routes) {\n if (routeMap[r.start][r.end])\n continue;\n routeMap[r.start][r.end] = true;\n routeMap[r.end][r.start] = true;\n for (int i=0;i<n;i++){\n if (routeMap[i][r.start]) {\n for (int j = 0; j < n; j++) {\n if (routeMap[r.end][j]) {\n routeMap[i][j] = true;\n routeMap[j][i] = true;\n }\n }\n routeMap[i][r.end] = true;\n routeMap[r.end][i] = true;\n }\n if (routeMap[i][r.end]) {\n if (routeMap[i][r.end]) {\n for (int j = 0; j < n; j++) {\n if (routeMap[r.start][j]) {\n routeMap[i][j] = true;\n routeMap[j][i] = true;\n }\n }\n }\n routeMap[i][r.start] = true;\n routeMap[r.start][i] = true;\n }\n }\n costSum += r.cost;\n }\n\n cout << costSum << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3372, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_12_A_10256523", "code_snippet": "#include <iostream>\nusing namespace std;\n\nconst int MAX_N = 100;\nint p[MAX_N];\nint r[MAX_N];\n\nvoid init(int n)\n{\n for(int i=0; i<n; i++){\n p[i] = i;\n r[i] = 0;\n }\n}\n\nint find(int x)\n{\n if(p[x]==x){\n return x;\n }\n else{\n p[x] = find(p[x]);\n return p[x];\n }\n}\n\nvoid unite(int x, int y)\n{\n x = find(x);\n y = find(y);\n\n if(x==y){\n return;\n }\n if(r[x]<r[y]){\n p[x] = y;\n }\n else{\n p[y] = x;\n if(r[x]==r[y]){\n r[x]++;\n }\n }\n}\n\nbool same(int x, int y)\n{\n return (find(x)==find(y));\n}\n\nstruct edge{\n int u, v, w;\n};\n\nconst int MAX_E = 5000;\n\nstruct edge E[MAX_E];\n\nint kruskal(int m, int n)\n{\n for(int i=0; i<m-1; i++){\n for(int j=i+1; j<m; j++){\n if(E[i].w>E[j].w){\n swap(E[i], E[j]);\n }\n }\n }\n\n init(n);\n\n int sum = 0;\n\n for(int i=0; i<m; i++){\n if(!same(E[i].u, E[i].v)){\n unite(E[i].u, E[i].v);\n sum += E[i].w;\n }\n }\n return sum;\n}\n\nint main()\n{\nint n;\ncin >> n;\n\nint G[100][100];\n\nfor(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n cin >> G[i][j];\n }\n}\n\nint m = 0;\n\nfor(int i=0; i<n; i++){\n for(int j=i+1; j<n; j++){\n if(G[i][j]!=-1){\n E[m].u = i;\n E[m].v = j;\n E[m].w = G[i][j];\n m++;\n }\n }\n}\n\ncout << kruskal(m, n) << endl;\n\nreturn 0;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3384, "score_of_the_acc": -0.0052, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_12_A_10156727", "code_snippet": "// 2025/01/29 Tazoe\n#include <iostream>\nusing namespace std;\nconst int MAX_N = 100; // 最大要素数\nint p[MAX_N]; // 親\nint r[MAX_N]; // 木の深さ\n// n要素で初期化\nvoid init(int n)\n{\nfor(int i=0; i<n; i++){\np[i] = i; // 根のときには親の代りに集合名(根)\nr[i] = 0;\n}\n}\n// 集合名(根)を求める\nint find(int x)\n{\nif(p[x]==x){ // 根だったら\nreturn x;\n}\nelse{\np[x] = find(p[x]); // 路の圧縮\nreturn p[x];\n}\n}\n// xとyの属する集合を併合\nvoid unite(int x, int y)\n{\nx = find(x); // 集合名(根)\ny = find(y);\nif(x==y){\nreturn;\n}\nif(r[x]<r[y]){\np[x] = y;\n}\nelse{\np[y] = x;\nif(r[x]==r[y]){\nr[x]++;\n}\n}\n}\n// xとyが同じ集合に属するか否か\nbool same(int x, int y)\n\n{\nreturn (find(x)==find(y));\n}\nstruct edge{\nint u, v, w;\n};\nconst int MAX_E = 5000;\nstruct edge E[MAX_E];\nint kruskal(int m, int n) // nは頂点数,mは辺数\n{\n// 辺の配列Eを重みwでソートする\nfor(int i=0; i<m-1; i++){\nfor(int j=i+1; j<m; j++){\nif(E[i].w>E[j].w){\nswap(E[i], E[j]);\n}\n}\n}\ninit(n); // union-findのデータ構造の初期化\nint sum = 0; // 辺の重みの総和\nfor(int i=0; i<m; i++){\nif(!same(E[i].u, E[i].v)){\nunite(E[i].u, E[i].v);\nsum += E[i].w;\n}\n}\nreturn sum;\n}\nint main()\n{\nint n; // 頂点数\ncin >> n;\nint G[100][100];\nfor(int i=0; i<n; i++){\nfor(int j=0; j<n; j++){\ncin >> G[i][j];\n}\n}\nint m = 0; // 辺数\nfor(int i=0; i<n; i++){\nfor(int j=i+1; j<n; j++){\n\nif(G[i][j]!=-1){\nE[m].u = i;\nE[m].v = j;\nE[m].w = G[i][j];\nm++;\n}\n}\n}\ncout << kruskal(m, n) << endl;\nreturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3376, "score_of_the_acc": -0.0017, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_12_A_10154427", "code_snippet": "// 2025/01/29 Tazoe\n\n#include <iostream>\nusing namespace std;\n\nconst int MAX_N = 100;\t// 最大要素数\n\nint p[MAX_N];\t\t\t// 親\nint r[MAX_N];\t\t\t// 木の深さ\n\n\n// n要素で初期化\nvoid init(int n)\n{\n\tfor(int i=0; i<n; i++){\n\t\tp[i] = i;\t\t\t\t// 根のときには親の代りに集合名(根)\n\t\tr[i] = 0;\n\t}\n}\n\n// 集合名(根)を求める\nint find(int x)\n{\n\tif(p[x]==x){\t\t\t// 根だったら\n\t\treturn x;\n\t}\n\telse{\n\t\tp[x] = find(p[x]);\t\t// 路の圧縮\n\t\treturn p[x];\n\t}\n}\n\n// xとyの属する集合を併合\nvoid unite(int x, int y)\n{\n\tx = find(x);\t\t\t// 集合名(根)\n\ty = find(y);\n\tif(x==y){\n\t\treturn;\n\t}\n\t\n\tif(r[x]<r[y]){\n\t\tp[x] = y;\n\t}\n\telse{\n\t\tp[y] = x;\n\t\tif(r[x]==r[y]){\n\t\t\tr[x]++;\n\t\t}\n\t}\n}\n\n// xとyが同じ集合に属するか否か\nbool same(int x, int y)\n{\n\treturn (find(x)==find(y));\n}\n\n\nstruct edge{\n\tint u, v, w;\n};\n\nconst int MAX_E = 5000;\n\nstruct edge E[MAX_E];\n\n\nint kruskal(int m, int n)\t// nは頂点数,mは辺数\n{\n\t// 辺の配列Eを重みwでソートする\n\tfor(int i=0; i<m-1; i++){\n\t\tfor(int j=i+1; j<m; j++){\n\t\t\tif(E[i].w>E[j].w){\n\t\t\t\tswap(E[i], E[j]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tinit(n);\t\t\t\t// union-findのデータ構造の初期化\n\tint sum = 0;\t\t\t// 辺の重みの総和\n\t\n\tfor(int i=0; i<m; i++){\n\t\tif(!same(E[i].u, E[i].v)){\n\t\t\tunite(E[i].u, E[i].v);\n\t\t\tsum += E[i].w;\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\n\nint main()\n{\n\tint n;\t\t\t\t\t\t\t// 頂点数\n\tcin >> n;\n\t\n\tint G[100][100];\n\tfor(int i=0; i<n; i++){\n\t\tfor(int j=0; j<n; j++){\n\t\t\tcin >> G[i][j];\n\t\t}\n\t}\n\t\n\tint m = 0;\t\t\t\t\t\t// 辺数\n\tfor(int i=0; i<n; i++){\n\t\tfor(int j=i+1; j<n; j++){\n\t\t\tif(G[i][j]!=-1){\n\t\t\t\tE[m].u = i;\n\t\t\t\tE[m].v = j;\n\t\t\t\tE[m].w = G[i][j];\n\t\t\t\tm++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << kruskal(m, n) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3484, "score_of_the_acc": -0.049, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_12_A_10154421", "code_snippet": "// 2025/01/29 Tazoe\n\n#include <iostream>\nusing namespace std;\n\nconst int MAX_N = 100;\t// 最大要素数\n\nint p[MAX_N];\t\t\t// 親\nint r[MAX_N];\t\t\t// 木の深さ\n\n\n// n要素で初期化\nvoid init(int n)\n{\n\tfor(int i=0; i<n; i++){\n\t\tp[i] = i;\t\t\t\t// 根のときには親の代りに集合名(根)\n\t\tr[i] = 0;\n\t}\n}\n\n// 集合名(根)を求める\nint find(int x)\n{\n\tif(p[x]==x){\t\t\t// 根だったら\n\t\treturn x;\n\t}\n\telse{\n\t\tp[x] = find(p[x]);\t\t// 路の圧縮\n\t\treturn p[x];\n\t}\n}\n\n// xとyの属する集合を併合\nvoid unite(int x, int y)\n{\n\tx = find(x);\t\t\t// 集合名(根)\n\ty = find(y);\n\tif(x==y){\n\t\treturn;\n\t}\n\t\n\tif(r[x]<r[y]){\n\t\tp[x] = y;\n\t}\n\telse{\n\t\tp[y] = x;\n\t\tif(r[x]==r[y]){\n\t\t\tr[x]++;\n\t\t}\n\t}\n}\n\n// xとyが同じ集合に属するか否か\nbool same(int x, int y)\n{\n\treturn (find(x)==find(y));\n}\n\n\nstruct edge{\n\tint u, v, w;\n};\n\nconst int MAX_E = 10000;\n\nstruct edge E[MAX_E];\n\n\nint kruskal(int m, int n)\t// nは頂点数,mは辺数\n{\n\t// 辺の配列Eを重みwでソートする\n\tfor(int i=0; i<m-1; i++){\n\t\tfor(int j=i+1; j<m; j++){\n\t\t\tif(E[i].w>E[j].w){\n\t\t\t\tswap(E[i], E[j]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tinit(n);\t\t\t\t// union-findのデータ構造の初期化\n\tint sum = 0;\t\t\t// 辺の重みの総和\n\t\n\tfor(int i=0; i<m; i++){\n\t\tif(!same(E[i].u, E[i].v)){\n\t\t\tunite(E[i].u, E[i].v);\n\t\t\tsum += E[i].w;\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\n\nint main()\n{\n\tint n;\t\t\t\t\t\t\t// 頂点数\n\tcin >> n;\n\t\n\tint G[100][100];\n\tfor(int i=0; i<n; i++){\n\t\tfor(int j=0; j<n; j++){\n\t\t\tcin >> G[i][j];\n\t\t}\n\t}\n\t\n\tint m = 0;\t\t\t\t\t\t// 辺数\n\tfor(int i=0; i<n; i++){\n\t\tfor(int j=i+1; j<n; j++){\n\t\t\tif(G[i][j]!=-1){\n\t\t\t\tE[m].u = i;\n\t\t\t\tE[m].v = j;\n\t\t\t\tE[m].w = G[i][j];\n\t\t\t\tm++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << kruskal(m, n) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3444, "score_of_the_acc": -0.0315, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_12_A_10154415", "code_snippet": "// 2025/01/29 Tazoe\n\n#include <iostream>\nusing namespace std;\n\nconst int MAX_N = 100;\t// 最大要素数\n\nint p[MAX_N];\t\t\t// 親\nint r[MAX_N];\t\t\t// 木の深さ\n\n\n// n要素で初期化\nvoid init(int n)\n{\n\tfor(int i=0; i<n; i++){\n\t\tp[i] = i;\t\t\t\t// 根のときには親の代りに集合名(根)\n\t\tr[i] = 0;\n\t}\n}\n\n// 集合名(根)を求める\nint find(int x)\n{\n\tif(p[x]==x){\t\t\t// 根だったら\n\t\treturn x;\n\t}\n\telse{\n\t\tp[x] = find(p[x]);\t\t// 路の圧縮\n\t\treturn p[x];\n\t}\n}\n\n// xとyの属する集合を併合\nvoid unite(int x, int y)\n{\n\tx = find(x);\t\t\t// 集合名(根)\n\ty = find(y);\n\tif(x==y){\n\t\treturn;\n\t}\n\t\n\tif(r[x]<r[y]){\n\t\tp[x] = y;\n\t}\n\telse{\n\t\tp[y] = x;\n\t\tif(r[x]==r[y]){\n\t\t\tr[x]++;\n\t\t}\n\t}\n}\n\n// xとyが同じ集合に属するか否か\nbool same(int x, int y)\n{\n\treturn (find(x)==find(y));\n}\n\n\nstruct edge{\n\tint u, v, w;\n};\n\nconst int MAX_E = 10000;\n\nstruct edge E[MAX_E];\n\n\nint kruskal(int m, int n)\t// nは頂点数,mは辺数\n{\n\t// 辺の配列Eを重みwでソートする\n\tfor(int i=0; i<m-1; i++){\n\t\tfor(int j=i+1; j<m; j++){\n\t\t\tif(E[i].w>E[j].w){\n\t\t\t\tswap(E[i], E[j]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tinit(n);\t\t\t\t// union-findのデータ構造の初期化\n\tint sum = 0;\t\t\t// 辺の重みの総和\n\t\n\tfor(int i=0; i<m; i++){\n\t\tif(!same(E[i].u, E[i].v)){\n\t\t\tunite(E[i].u, E[i].v);\n\t\t\tsum += E[i].w;\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\t\n\tint G[100][100];\n\tfor(int i=0; i<n; i++){\n\t\tfor(int j=0; j<n; j++){\n\t\t\tcin >> G[i][j];\n\t\t}\n\t}\n\t\n\tint m = 0;\n\tfor(int i=0; i<n; i++){\n\t\tfor(int j=i+1; j<n; j++){\n\t\t\tif(G[i][j]!=-1){\n\t\t\t\tE[m].u = i;\n\t\t\t\tE[m].v = j;\n\t\t\t\tE[m].w = G[i][j];\n\t\t\t\tm++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << kruskal(m, n) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3512, "score_of_the_acc": -0.0612, "final_rank": 9 } ]
aoj_ALDS1_10_D_cpp
Optimal Binary Search Tree Optimal Binary Search Tree is a binary search tree constructed from $n$ keys and $n+1$ dummy keys so as to minimize the expected value of cost for a search operation. We are given a sequence $K = {k_1, k_2, ..., k_n}$ of $n$ distinct keys in sorted order $(k_1 < k_2 < ... < k_n)$, and we wish to construct a binary search tree. For each key $k_i$, we have a probability $p_i$ that a search will be for $k_i$. Some searches may be for values not in $K$, and so we also have $n+1$ dummy keys $d_0, d_1, d_2, ..., d_n$ representing values not in $K$. The dummy keys $d_i (0 \le i \le n)$ are defined as follows: if $i=0$, then $d_i$ represents all values less than $k_1$ if $i=n$, then $d_i$ represents all values greater than $k_n$ if $1 \le i \le n-1$, then $d_i$ represents all values between $k_i$ and $k_{i+1}$ For each dummy key $d_i$, we have a probability $q_i$ that a search will correspond to $d_i$. For $p_i (1 \le i \le n)$ and $q_i (0 \le i \le n)$, we have \[ \sum_{i=1}^n p_i + \sum_{i=0}^n q_i = 1 \] Then the expected cost of a search in a binary search tree $T$ is \[ E_T = \sum_{i=1}^n (depth_T(k_i) + 1) \cdot p_i + \sum_{i=0}^n (depth_T(d_i) + 1) \cdot q_i \] where $depth_T(v)$ is the depth of node $v$ in $T$. For a given set of probabilities, our goal is to construct a binary search tree whose expected search cost is smallest. We call such a tree an optimal binary search tree . Each key $k_i$ is an internal node and each dummy key $d_i$ is a leaf. For example, the following figure shows the optimal binary search tree obtained from Sample Input 1. Task Write a program which calculates the expected value of a search operation on the optimal binary search tree obtained by given $p_i$ that a search will be for $k_i$ and $q_i$ that a search will correspond to $d_i$. Input $n$ $p_1$ $p_2$ ... $p_n$ $q_0$ $q_1$ $q_2$ ... $q_n$ In the first line, an integer $n$ which represents the number of keys is given. In the second line, $p_i (1 \le i \le n)$ are given in real numbers with four decimal places. In the third line, $q_i (0 \le i \le n)$ are given in real numbers with four decimal places. Output Print the expected value for a search operation on the optimal binary search tree in a line. The output must not contain an error greater than $10^{−4}$. Constraints $1 \le n \le 500$ $0 \lt p_i, q_i \lt 1$ $\displaystyle \sum_{i=1}^n p_i + \sum_{i=0}^n q_i = 1$ Sample Input 1 5 0.1500 0.1000 0.0500 0.1000 0.2000 0.0500 0.1000 0.0500 0.0500 0.0500 0.1000 Sample Output 1 2.75000000 Sample Input 2 7 0.0400 0.0600 0.0800 0.0200 0.1000 0.1200 0.1400 0.0600 0.0600 0.0600 0.0600 0.0500 0.0500 0.0500 0.0500 Sample Output 2 3.12000000
[ { "submission_id": "aoj_ALDS1_10_D_11017187", "code_snippet": "//\n// Created by Manas Choudhary on 04-11-2025 05:05 PM\n//\n#include <algorithm>\n#include <iostream>\n#include <chrono>\n#include <vector>\n#include <cmath>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#define ll long double\n#define ld long double\n#define umap unordered_map\n#define vec(type) vector<type>\n#define pb push_back\n#define all(v) v.begin(), v.end()\n#define sz(v) (int)(v).size()\n#define vecout(v) for (auto &x : v) cout << x << ' '; cout << '\\n';\n#define fastio() ios::sync_with_stdio(false); cin.tie(nullptr);\n#define yes cout << \"YES\\n\"\n#define no cout << \"NO\\n\"\n\nusing namespace std;\nusing namespace chrono;\n\nconst int INF = 1e9;\nconst long long LINF = 1e18;\nconst int MOD = 1e9 + 7;\nconst double pi = acos(-1);\n\n\n\n#include <iomanip> // Make sure to add this header\n\nint solve() {\n long long n;\n cin >> n;\n vec(ld) k(n+1,0);\n vec(ld) d(n+1,0);\n\n // 1. INPUT (Assuming this is fixed now)\n for (int i = 1; i <= n; i++) {\n cin >> k[i];\n }\n for (int i = 0; i <= n; i++) {\n cin >> d[i];\n }\n\n // 2. PREFIX SUMS (This part is correct)\n vec(ld) pk(n+1,0);\n for (int i = 1; i <= n; i++) {\n pk[i] = pk[i-1] + k[i];\n }\n vec(ld) pd(n+2,0);\n for (int i = 0; i < n + 1; i++) {\n pd[i+1] = pd[i] + d[i];\n }\n auto getsumk = [& pk](int i,int j)->ld{\n if (i > j) return 0; // Handle empty range\n return pk[j]-pk[i-1];\n };\n auto getsumd = [& pd](int i , int j)->ld {\n if (i > j) return 0; // Handle empty range\n return pd[j+1]-pd[i];\n };\n\n // 3. DP TABLE (FIX A: Make size n+2 by n+2)\n // We need to access dp[1][0] through dp[n+1][n]\n vec(vec(ld)) dp(n+2, vector<ld>(n+2, 0));\n\n // 4. BASE CASES (FIX B: Initialize empty trees)\n // dp[i][i-1] = cost of dummy key d[i-1]\n for (int i = 1; i <= n + 1; i++) {\n // getsumd(i-1, i-1) = pd[i] - pd[i-1] = d[i-1]\n dp[i][i-1] = getsumd(i-1, i-1);\n }\n\n // 5. MAIN DP LOOP\n for (int l = 1; l <= n; l++) {\n for (int i = 1; i <= n - l + 1; i++) {\n int j = i + l - 1;\n\n // This is the cost w(i,j)\n ld w_ij = getsumk(i, j) + getsumd(i - 1, j);\n\n // Start with a very high cost\n dp[i][j] = 1e18; // Use LINF or 1e18\n\n // k is the root\n for (int k = i; k <= j; k++) {\n\n // FIX C: No more ternary. Use the base cases.\n ld left = dp[i][k-1]; // Cost of left tree (uses dp[i][i-1] when k=i)\n ld right = dp[k+1][j]; // Cost of right tree (uses dp[j+1][j] when k=j)\n\n // The recurrence:\n // dp[i][j] = min(dp[i][j], left + right);\n // We add w_ij ONCE, after the loop\n dp[i][j] = min(dp[i][j], left + right);\n }\n\n // FIX D: Add the w(i,j) cost *after* finding the min\n dp[i][j] += w_ij;\n }\n }\n\n // 6. OUTPUT (FIX E: Add precision)\n cout << fixed << setprecision(12) << dp[1][n] << endl ;\n\n return 0;\n}\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n auto start = high_resolution_clock::now();\n\n\n int t=1;\n while (t--) {\n solve();\n }\n\n \n auto end = high_resolution_clock::now();\n auto duration = duration_cast<microseconds>(end - start);\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 7128, "score_of_the_acc": -0.5082, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_10_D_11017185", "code_snippet": "//\n// Created by Manas Choudhary on 04-11-2025 05:05 PM\n//\n#include <algorithm>\n#include <iostream>\n#include <chrono>\n#include <vector>\n#include <cmath>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#define ll long double\n#define ld long double\n#define umap unordered_map\n#define vec(type) vector<type>\n#define pb push_back\n#define all(v) v.begin(), v.end()\n#define sz(v) (int)(v).size()\n#define vecout(v) for (auto &x : v) cout << x << ' '; cout << '\\n';\n#define fastio() ios::sync_with_stdio(false); cin.tie(nullptr);\n#define yes cout << \"YES\\n\"\n#define no cout << \"NO\\n\"\n\nusing namespace std;\nusing namespace chrono;\n\nconst int INF = 1e9;\nconst long long LINF = 1e18;\nconst int MOD = 1e9 + 7;\nconst double pi = acos(-1);\n\n\n\n#include <iomanip> // Make sure to add this header\n\nint solve() {\n long long n;\n cin >> n;\n vec(ld) k(n+1,0);\n vec(ld) d(n+1,0);\n\n // 1. INPUT (Assuming this is fixed now)\n for (int i = 1; i <= n; i++) {\n cin >> k[i];\n }\n for (int i = 0; i <= n; i++) {\n cin >> d[i];\n }\n\n // 2. PREFIX SUMS (This part is correct)\n vec(ld) pk(n+1,0);\n for (int i = 1; i <= n; i++) {\n pk[i] = pk[i-1] + k[i];\n }\n vec(ld) pd(n+2,0);\n for (int i = 0; i < n + 1; i++) {\n pd[i+1] = pd[i] + d[i];\n }\n auto getsumk = [& pk](int i,int j)->ld{\n if (i > j) return 0; // Handle empty range\n return pk[j]-pk[i-1];\n };\n auto getsumd = [& pd](int i , int j)->ld {\n if (i > j) return 0; // Handle empty range\n return pd[j+1]-pd[i];\n };\n\n // 3. DP TABLE (FIX A: Make size n+2 by n+2)\n // We need to access dp[1][0] through dp[n+1][n]\n vec(vec(ld)) dp(n+2, vector<ld>(n+2, 0));\n\n // 4. BASE CASES (FIX B: Initialize empty trees)\n // dp[i][i-1] = cost of dummy key d[i-1]\n for (int i = 1; i <= n + 1; i++) {\n // getsumd(i-1, i-1) = pd[i] - pd[i-1] = d[i-1]\n dp[i][i-1] = getsumd(i-1, i-1);\n }\n\n // 5. MAIN DP LOOP\n for (int l = 1; l <= n; l++) {\n for (int i = 1; i <= n - l + 1; i++) {\n int j = i + l - 1;\n\n // This is the cost w(i,j)\n ld w_ij = getsumk(i, j) + getsumd(i - 1, j);\n\n // Start with a very high cost\n dp[i][j] = 1e18; // Use LINF or 1e18\n\n // k is the root\n for (int k = i; k <= j; k++) {\n\n // FIX C: No more ternary. Use the base cases.\n ld left = dp[i][k-1]; // Cost of left tree (uses dp[i][i-1] when k=i)\n ld right = dp[k+1][j]; // Cost of right tree (uses dp[j+1][j] when k=j)\n\n // The recurrence:\n // dp[i][j] = min(dp[i][j], left + right);\n // We add w_ij ONCE, after the loop\n dp[i][j] = min(dp[i][j], left + right);\n }\n\n // FIX D: Add the w(i,j) cost *after* finding the min\n dp[i][j] += w_ij;\n }\n }\n\n // 6. OUTPUT (FIX E: Add precision)\n cout << fixed << setprecision(12) << dp[1][n] ;\n\n return 0;\n}\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n auto start = high_resolution_clock::now();\n\n\n int t=1;\n while (t--) {\n solve();\n }\n\n \n auto end = high_resolution_clock::now();\n auto duration = duration_cast<microseconds>(end - start);\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 7068, "score_of_the_acc": -0.5041, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_10_D_10851079", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <algorithm>\nusing namespace std;\n#define MAXN 1000\nint n;\ndouble p[MAXN + 5], q[MAXN + 5];\ndouble dp[MAXN + 5][MAXN + 5];\ndouble w[MAXN + 5][MAXN + 5];\nint seg[MAXN + 5][MAXN + 5];\ndouble calc(int l, int r, int d) {\n if (l == r + 1)\n return q[r] * d;\n return calc(l, seg[l][r] - 1, d + 1) + calc(seg[l][r] + 1, r, d + 1) + p[seg[l][r]] * d;\n}\nint main() {\n scanf(\"%d\", &n);\n for (int i = 1; i <= n; ++i)\n scanf(\"%lf\", &p[i]);\n for (int i = 0; i <= n; ++i)\n scanf(\"%lf\", &q[i]);\n for (int i = 0; i <= n + 1; ++i)\n for (int j = 0; j <= n + 1; ++j)\n dp[i][j] = 1e20;\n memset(w, 0, sizeof w);\n for (int i = 1; i <= n; ++i)\n w[i][i - 1] = q[i - 1];\n for (int i = 0; i <= n; ++i)\n dp[i][i - 1] = dp[i + 1][i] = 0;\n for (int len = 1; len <= n; ++len)\n for (int l = 1; l + len - 1 <= n; ++l) {\n int r = l + len - 1;\n w[l][r] = w[l][r - 1] + p[r] + q[r];\n for (int k = l; k <= r; ++k) {\n auto val = dp[l][k - 1] + dp[k + 1][r] + w[l][r];\n if (val < dp[l][r]) {\n dp[l][r] = val;\n seg[l][r] = k;\n }\n }\n }\n printf(\"%.6lf\", calc(1, n, 1));\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 19304, "score_of_the_acc": -1, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_10_D_10737653", "code_snippet": "#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <limits>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n vector<double> p(n), q(n+1);\n for (int i = 0; i < n; i++) cin >> p[i];\n for (int i = 0; i <= n; i++) cin >> q[i];\n\n vector<vector<double>> e(n+2, vector<double>(n+2, 0));\n vector<vector<double>> w(n+2, vector<double>(n+2, 0));\n for (int i = 0; i <= n; ++i) {\n e[i][i] = q[i];\n w[i][i] = q[i];\n }\n for (int l = 1; l <= n; ++l) {\n for (int i = 0; i <= n-l; ++i) {\n int j = i+l;\n e[i][j] = numeric_limits<double>::infinity();\n w[i][j] = w[i][j-1]+p[j-1]+q[j];\n for (int r = i; r < j; ++r) {\n double t = e[i][r]+e[r+1][j]+w[i][j];\n if (t < e[i][j]) {\n e[i][j] = t;\n }\n }\n }\n }\n\n cout << fixed << setprecision(8) << e[0][n] << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7484, "score_of_the_acc": -0.3101, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_10_D_10697763", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nusing ull=unsigned long long;\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n#define loop(n) for (int tjh = 0; tjh < (int)(n); ++tjh)\nconstexpr double INF=1e100;\nsigned main() {\n cin.tie(0)->sync_with_stdio(0);\n cout<<fixed<<setprecision(16);\n int n;cin>>n;vector<double>a(2*n+1);\n rep(i,n)cin>>a[i*2+1];\n rep(i,n+1)cin>>a[i*2];\n vector<double>a0(2*n+2);\n partial_sum(a.begin(), a.end(),a0.begin()+1);\n vector dp(n+1,vector<double>(n+1));\n rep(i,n+1)dp[i][i]=a[i*2];\n for (int l=1;l<=n;++l) {\n rep(i,n-l+1) {\n const int j{i+l};\n dp[i][j]=INF;\n for (int k=i;k<j;++k) {\n double te1{dp[i][k]+dp[k+1][j]};\n if (te1<dp[i][j])dp[i][j]=te1;\n }\n dp[i][j]+=a0[j*2+1]-a0[i*2];\n }\n }\n cout<<dp[0][n]<<'\\n';\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5632, "score_of_the_acc": -0.0735, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_10_D_10382118", "code_snippet": "#include <stdio.h>\n\n#define MAX 500 // 最大のキーの個数\n#define INF 1e6 // 非常に大きな値\n\ndouble e[MAX + 1][MAX + 1]; // 部分木の期待コスト\ndouble w[MAX + 1][MAX + 1]; // 部分木の確率の合計\ndouble root[MAX + 1][MAX + 1]; // 部分木の根ノード\n\ndouble minCost(int n, double p[], double q[]) {\n // 配列初期化\n for (int i = 0; i <= n; i++) {\n for (int j = 0; j <= n; j++) {\n e[i][j] = 0.0;\n w[i][j] = 0.0;\n }\n }\n\n // 初期化\n for (int i = 0; i <= n; i++) {\n e[i][i] = q[i];\n w[i][i] = q[i];\n }\n\n // 動的計画法によるコスト計算\n for (int l = 1; l <= n; l++) { // 部分木の長さ\n for (int i = 0; i <= n - l; i++) {\n int j = i + l;\n e[i][j] = INF;\n w[i][j] = w[i][j - 1] + p[j - 1] + q[j];\n\n // 最小コストを計算\n for (int r = i + 1; r <= j; r++) {\n double cost = e[i][r - 1] + e[r][j] + w[i][j];\n if (cost < e[i][j]) {\n e[i][j] = cost;\n root[i][j] = r;\n }\n }\n }\n }\n\n return e[0][n];\n}\n\nint main() {\n int n;\n double p[MAX], q[MAX];\n\n // 入力\n scanf(\"%d\", &n);\n if (n > MAX || n <= 0) {\n printf(\"Error: Invalid number of keys.\\n\");\n return 1;\n }\n\n for (int i = 0; i < n; i++) {\n scanf(\"%lf\", &p[i]);\n }\n for (int i = 0; i <= n; i++) {\n scanf(\"%lf\", &q[i]);\n }\n\n // 最適探索コストの計算\n double result = minCost(n, p, q);\n\n // 出力\n printf(\"%.8lf\\n\", result);\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8812, "score_of_the_acc": -0.289, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_10_D_10320319", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <string>\n#include <string.h>\n#include <set>\n#include <map>\n//#include <atcoder/all>\n\nusing namespace std;\n//using namespace atcoder;\n\n\nstatic const int MAX = 550;\n\n\nfloat P[MAX], Q[MAX];\nfloat minCostArray[MAX][MAX];\nfloat SumArray_P[MAX], SumArray_Q[MAX];\n\nfloat SumOfProp(int x, int y) {\n\tif (x == 1) {\n\t\treturn SumArray_P[y] + SumArray_Q[y];\n\t}\n\telse {\n\t\treturn (SumArray_P[y] - SumArray_P[x - 1]) + (SumArray_Q[y] - SumArray_Q[x - 2]);\n\t}\n}\n\nfloat CalcCost(int i, int j){\n\n\tif (minCostArray[i][j] != -1) {\n\t\treturn minCostArray[i][j];\n\t}\n\n\n\tfloat minC = 1000000000;\n\tif (i - 1 == j ) {\n\t\tminC = Q[i - 1];\n\t}\n\telse {\n\t\tfor (int r = i; r <= j; r++) {\n\t\t\tminC = min(minC, CalcCost(i, r - 1) + CalcCost(r + 1, j) + SumOfProp(i, j));\n\t\t}\n\t}\n\n\tminCostArray[i][j] = minC;\n\treturn minC;\n\n}\n\n\nint main() {\n\n\tfor (int i = 0; i < MAX; i++) {\n\t\tfor(int j = 0; j < MAX; j++) {\n\t\t\tminCostArray[i][j] = -1;\n\t\t}\n\t}\n\n\tint n;\n\tcin >> n;\n\n\tSumArray_P[0] = SumArray_Q[0] = 0;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> P[i];\n\t\tSumArray_P[i] = SumArray_P[i - 1] + P[i];\n\t}\n\tfor (int i = 0; i <= n; i++) {\n\t\tcin >> Q[i];\n\t\tif (i == 0) SumArray_Q[i] = Q[i];\n\t\telse SumArray_Q[i] = SumArray_Q[i - 1] + Q[i];\n\t}\n\n\tcout << CalcCost(1, n) << endl;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4788, "score_of_the_acc": -0.4607, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_10_D_10320315", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <string>\n#include <string.h>\n#include <set>\n#include <map>\n//#include <atcoder/all>\n\nusing namespace std;\n//using namespace atcoder;\n\n\nstatic const int MAX = 501;\n\n\nfloat P[MAX], Q[MAX];\nfloat minCostArray[MAX][MAX];\nfloat SumArray_P[MAX], SumArray_Q[MAX];\n\nfloat SumOfProp(int x, int y) {\n\tif (x == 1) {\n\t\treturn SumArray_P[y] + SumArray_Q[y];\n\t}\n\telse {\n\t\treturn (SumArray_P[y] - SumArray_P[x - 1]) + (SumArray_Q[y] - SumArray_Q[x - 2]);\n\t}\n}\n\nfloat CalcCost(int i, int j){\n\n\tif (minCostArray[i][j] != -1) {\n\t\treturn minCostArray[i][j];\n\t}\n\n\n\tfloat minC = 100000000;\n\tif (i - 1 == j ) {\n\t\tminC = Q[i - 1];\n\t}\n\telse {\n\t\tfor (int r = i; r <= j; r++) {\n\t\t\tminC = min(minC, CalcCost(i, r - 1) + CalcCost(r + 1, j) + SumOfProp(i, j));\n\t\t}\n\t}\n\n\tminCostArray[i][j] = minC;\n\treturn minC;\n\n}\n\n\nint main() {\n\n\tfor (int i = 0; i < MAX; i++) {\n\t\tfor(int j = 0; j < MAX; j++) {\n\t\t\tminCostArray[i][j] = -1;\n\t\t}\n\t}\n\n\tint n;\n\tcin >> n;\n\n\tSumArray_P[0] = SumArray_Q[0] = 0;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> P[i];\n\t\tSumArray_P[i] = SumArray_P[i - 1] + P[i];\n\t}\n\tfor (int i = 0; i <= n; i++) {\n\t\tcin >> Q[i];\n\t\tif (i == 0) SumArray_Q[i] = Q[i];\n\t\telse SumArray_Q[i] = SumArray_Q[i - 1] + Q[i];\n\t}\n\n\tcout << CalcCost(1, n) << endl;\n}", "accuracy": 0.9333333333333333, "time_ms": 60, "memory_kb": 4548, "score_of_the_acc": -0.4444, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_10_D_10265771", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n#include <algorithm>\n#include <limits>\nusing namespace std;\n\n// 各範囲のキーのコストの合計を求める\nvector<vector<double>> setKeySumCost(const vector<double> &array_k, const vector<double> &array_d)\n{\n int n = array_d.size();\n vector<vector<double>> keySumCost(n);\n for (int i = 0; i < n; i++)\n {\n keySumCost[i].resize(n);\n keySumCost[i][i] = array_d[i];\n for (int j = i + 1; j < n; j++)\n {\n keySumCost[i][j] = keySumCost[i][j - 1] + array_k[j - 1] + array_d[j];\n }\n }\n return keySumCost;\n}\n\n// 最小のコストを求める\ndouble getMinCost(const vector<vector<double>> &keySumCost)\n{\n int n = keySumCost.size();\n vector<vector<double>> optCost(n);\n\n // ダミーキー単体のコストを設定\n for (int i = 0; i < n; i++)\n {\n optCost[i].resize(n);\n optCost[i][i] = keySumCost[i][i];\n }\n\n // 範囲の長さを指定\n // 最初は短い範囲から、最後は全体の範囲で最小のコストを求める\n for (int len = 1; len < n; len++)\n {\n // 起点を設定する\n // 最初は k1~k2, k2~k3\n for (int begin = 0; begin < n - len; begin++)\n {\n // 範囲内でどのキーを中央にすると最小のコストになるか求める\n double minSum = std::numeric_limits<double>::infinity();\n for (int r = begin + 1; r <= begin + len; r++)\n {\n double tmpSum = optCost[begin][r - 1] + optCost[r][begin + len];\n // double left = optCost[begin][r - 1];\n // double right = optCost[r][begin + len];\n if (tmpSum < minSum)\n {\n minSum = tmpSum;\n }\n }\n optCost[begin][begin + len] = keySumCost[begin][begin + len] + minSum;\n }\n }\n\n return optCost[0][n - 1];\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<double> array_k;\n vector<double> array_d;\n for (int i = 0; i < n; i++)\n {\n double num;\n cin >> num;\n array_k.push_back(num);\n }\n for (int i = 0; i < n + 1; i++)\n {\n double num;\n cin >> num;\n array_d.push_back(num);\n }\n vector<vector<double>> keySumCost = setKeySumCost(array_k, array_d);\n double minCost = getMinCost(keySumCost);\n cout << fixed << setprecision(12) << minCost << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7100, "score_of_the_acc": -0.1729, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_10_D_10265758", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n#include <algorithm>\n#include <limits>\nusing namespace std;\n\n// 各範囲のキーのコストの合計を求める\nvector<vector<double>> setKeySumCost(const vector<double> &array_k, const vector<double> &array_d)\n{\n int n = array_k.size() + 1;\n vector<vector<double>> keySumCost(n);\n for (int i = 0; i < n; i++)\n {\n keySumCost[i].resize(n);\n keySumCost[i][i] = array_d[i];\n for (int j = i + 1; j < n; j++)\n {\n keySumCost[i][j] = keySumCost[i][j - 1] + array_k[j - 1] + array_d[j];\n }\n }\n return keySumCost;\n}\n\n// 最小のコストを求める\ndouble getMinCost(const vector<vector<double>> &keySumCost)\n{\n int n = keySumCost.size();\n vector<vector<double>> optCost(n);\n\n // ダミーキー単体のコストを設定\n for (int i = 0; i < n; i++)\n {\n optCost[i].resize(n);\n optCost[i][i] = keySumCost[i][i];\n }\n // 内部節点の下にダミーキーしかない時のコストを求める\n // for (int i = 0; i < n - 1; i++)\n // {\n // optCost[i][i + 1] = keySumCost[i][i + 1] + optCost[i][i] + optCost[i + 1][i + 1];\n // }\n\n // 範囲の長さを指定\n // 最初は短い範囲から、最後は全体の範囲で最小のコストを求める\n for (int len = 1; len < n; len++)\n {\n // 起点を設定する\n // 最初は k1~k2, k2~k3\n for (int begin = 0; begin < n - len; begin++)\n {\n // 範囲内でどのキーを中央にすると最小のコストになるか求める\n double minSum = std::numeric_limits<double>::infinity();\n for (int r = begin + 1; r <= begin + len; r++)\n {\n double tmpSum = optCost[begin][r - 1] + optCost[r][begin + len];\n // double left = optCost[begin][r - 1];\n // double right = optCost[r][begin + len];\n if (tmpSum < minSum)\n {\n minSum = tmpSum;\n }\n }\n optCost[begin][begin + len] = keySumCost[begin][begin + len] + minSum;\n }\n }\n\n return optCost[0][n - 1];\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<double> array_k;\n vector<double> array_d;\n for (int i = 0; i < n; i++)\n {\n double num;\n cin >> num;\n array_k.push_back(num);\n }\n for (int i = 0; i < n + 1; i++)\n {\n double num;\n cin >> num;\n array_d.push_back(num);\n }\n vector<vector<double>> keySumCost = setKeySumCost(array_k, array_d);\n double minCost = getMinCost(keySumCost);\n cout << fixed << setprecision(12) << minCost << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7056, "score_of_the_acc": -0.17, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_10_D_10265754", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n#include <algorithm>\n#include <limits>\nusing namespace std;\n\n// 各範囲のキーのコストの合計を求める\nvector<vector<double>> setKeySumCost(const vector<double> &array_k, const vector<double> &array_d)\n{\n int n = array_k.size() + 1;\n vector<vector<double>> keySumCost(n);\n for (int i = 0; i < n; i++)\n {\n keySumCost[i].resize(n);\n keySumCost[i][i] = array_d[i];\n for (int j = i + 1; j < n; j++)\n {\n keySumCost[i][j] = keySumCost[i][j - 1] + array_k[j - 1] + array_d[j];\n }\n }\n return keySumCost;\n}\n\n// 最小のコストを求める\ndouble getMinCost(const vector<vector<double>> &keySumCost)\n{\n int n = keySumCost.size();\n vector<vector<double>> optCost(n);\n\n // ダミーキー単体のコストを設定\n for (int i = 0; i < n; i++)\n {\n optCost[i].resize(n);\n optCost[i][i] = keySumCost[i][i];\n }\n // 内部節点の下にダミーキーしかない時のコストを求める\n for (int i = 0; i < n - 1; i++)\n {\n optCost[i][i + 1] = keySumCost[i][i + 1] + optCost[i][i] + optCost[i + 1][i + 1];\n }\n\n // 範囲の長さを指定\n // 最初は短い範囲から、最後は全体の範囲で最小のコストを求める\n for (int len = 2; len < n; len++)\n {\n // 起点を設定する\n // 最初は k1~k2, k2~k3\n for (int begin = 0; begin < n - len; begin++)\n {\n // 範囲内でどのキーを中央にすると最小のコストになるか求める\n double minSum = std::numeric_limits<double>::infinity();\n for (int r = begin + 1; r <= begin + len; r++)\n {\n double tmpSum = optCost[begin][r - 1] + optCost[r][begin + len];\n // double left = optCost[begin][r - 1];\n // double right = optCost[r][begin + len];\n if (tmpSum < minSum)\n {\n minSum = tmpSum;\n }\n }\n optCost[begin][begin + len] = keySumCost[begin][begin + len] + minSum;\n }\n }\n\n return optCost[0][n - 1];\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<double> array_k;\n vector<double> array_d;\n for (int i = 0; i < n; i++)\n {\n double num;\n cin >> num;\n array_k.push_back(num);\n }\n for (int i = 0; i < n + 1; i++)\n {\n double num;\n cin >> num;\n array_d.push_back(num);\n }\n vector<vector<double>> keySumCost = setKeySumCost(array_k, array_d);\n double minCost = getMinCost(keySumCost);\n cout << fixed << setprecision(12) << minCost << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7056, "score_of_the_acc": -0.17, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_10_D_10265726", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n#include <algorithm>\nusing namespace std;\n\n// 各範囲のキーのコストの合計を求める\nvector<vector<double>> setKeySumCost(const vector<double> &array_k, const vector<double> &array_d)\n{\n int n = array_k.size() + 1;\n vector<vector<double>> keySumCost(n);\n for (int i = 0; i < n; i++)\n {\n keySumCost[i].resize(n);\n keySumCost[i][i] = array_d[i];\n for (int j = i + 1; j < n; j++)\n {\n keySumCost[i][j] = keySumCost[i][j - 1] + array_k[j - 1] + array_d[j];\n }\n }\n return keySumCost;\n}\n\n// 最小のコストを求める\ndouble getMinCost(const vector<vector<double>> &keySumCost)\n{\n int n = keySumCost.size();\n vector<vector<double>> optCost(n);\n\n // ダミーキー単体のコストを設定\n for (int i = 0; i < n; i++)\n {\n optCost[i].resize(n);\n optCost[i][i] = keySumCost[i][i];\n }\n // 内部節点の下にダミーキーしかない時のコストを求める\n for (int i = 0; i < n - 1; i++)\n {\n optCost[i][i + 1] = keySumCost[i][i + 1] + optCost[i][i] + optCost[i + 1][i + 1];\n }\n\n // 範囲の長さを指定\n // 最初は短い範囲から、最後は全体の範囲で最小のコストを求める\n for (int len = 2; len < n; len++)\n {\n // 起点を設定する\n // 最初は k1~k2, k2~k3\n for (int begin = 0; begin < n - len; begin++)\n {\n // 範囲内でどのキーを中央にすると最小のコストになるか求める\n vector<double> sums;\n for (int r = begin + 1; r <= begin + len; r++)\n {\n double left = optCost[begin][r - 1];\n double right = optCost[r][begin + len];\n sums.push_back(left + right);\n }\n vector<double>::iterator iter = min_element(sums.begin(), sums.end());\n size_t index = distance(sums.begin(), iter);\n optCost[begin][begin + len] = keySumCost[begin][begin + len] + sums[index];\n }\n }\n\n return optCost[0][n - 1];\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<double> array_k;\n vector<double> array_d;\n for (int i = 0; i < n; i++)\n {\n double num;\n cin >> num;\n array_k.push_back(num);\n }\n for (int i = 0; i < n + 1; i++)\n {\n double num;\n cin >> num;\n array_d.push_back(num);\n }\n vector<vector<double>> keySumCost = setKeySumCost(array_k, array_d);\n double minCost = getMinCost(keySumCost);\n cout << fixed << setprecision(12) << minCost << endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 7100, "score_of_the_acc": -0.5063, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_10_D_10265713", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n#include <algorithm>\nusing namespace std;\n\n// 各範囲のキーのコストの合計を求める\nvector<vector<double>> setKeySumCost(const vector<double> &array_k, const vector<double> &array_d)\n{\n int n = array_k.size() + 1;\n vector<vector<double>> keySumCost(n);\n for (int i = 0; i < n; i++)\n {\n keySumCost[i].resize(n);\n keySumCost[i][i] = array_d[i];\n for (int j = i + 1; j < n; j++)\n {\n keySumCost[i][j] = keySumCost[i][j - 1] + array_k[j - 1] + array_d[j];\n }\n }\n return keySumCost;\n}\n\n// 最小のコストを求める\ndouble getMinCost(const vector<vector<double>> &keySumCost)\n{\n int n = keySumCost.size();\n vector<vector<double>> optCost(n);\n\n // ダミーキー単体のコストを設定\n for (int i = 0; i < n; i++)\n {\n optCost[i].resize(n);\n optCost[i][i] = keySumCost[i][i];\n }\n // 内部節点の下にダミーキーしかない時のコストを求める\n for (int i = 0; i < n - 1; i++)\n {\n optCost[i][i + 1] = keySumCost[i][i + 1] + optCost[i][i] + optCost[i + 1][i + 1];\n }\n\n // 範囲の長さを指定\n // 最初は短い範囲から、最後は全体の範囲で最小のコストを求める\n for (int len = 2; len < n; len++)\n {\n // 起点を設定する\n // 最初は k1~k2, k2~k3\n for (int begin = 0; begin < n - len; begin++)\n {\n // 範囲内でどのキーを中央にすると最小のコストになるか求める\n vector<double> sums;\n for (int r = begin + 1; r <= begin + len; r++)\n {\n double left = begin + 1 < r ? optCost[begin][r - 1] : optCost[begin][begin];\n double right = r < begin + len ? optCost[r][begin + len] : optCost[begin + len][begin + len];\n sums.push_back(left + right);\n }\n vector<double>::iterator iter = min_element(sums.begin(), sums.end());\n size_t index = distance(sums.begin(), iter);\n optCost[begin][begin + len] = keySumCost[begin][begin + len] + sums[index];\n }\n }\n\n return optCost[0][n - 1];\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<double> array_k;\n vector<double> array_d;\n for (int i = 0; i < n; i++)\n {\n double num;\n cin >> num;\n array_k.push_back(num);\n }\n for (int i = 0; i < n + 1; i++)\n {\n double num;\n cin >> num;\n array_d.push_back(num);\n }\n vector<vector<double>> keySumCost = setKeySumCost(array_k, array_d);\n double minCost = getMinCost(keySumCost);\n cout << fixed << setprecision(12) << minCost << endl;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 7100, "score_of_the_acc": -0.6174, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_10_D_10250646", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n\ndouble solve(const std::vector<double>& p, std::vector<double>& q) {\n std::vector<std::vector<double>> sumMem(q.size(), std::vector<double>(q.size(), 0));\n for (int i = 0; i < sumMem.size(); ++i) {\n sumMem[i][i] = q[i]; \n for (int j = i + 1; j < sumMem[i].size(); ++j) {\n sumMem[i][j] = sumMem[i][j-1] + p[j-1] + q[j];\n }\n }\n std::vector<std::vector<double>> minCostMem(q.size(), std::vector<double>(q.size(), 0));\n for (int len = 0; len < q.size(); ++len) {\n for (int i = 0; i + len < q.size(); ++i) {\n int k = i + len;\n std::vector<double> c;\n c.reserve(len);\n for (int j = i + 1; j <= k; ++j) {\n c.push_back(minCostMem[i][j-1] + minCostMem[j][k]);\n }\n minCostMem[i][k] = (c.empty() ? 0 : *std::min_element(c.begin(), c.end())) + sumMem[i][k];\n }\n }\n return minCostMem[0][p.size()];\n}\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<double> p(n);\n for (double& v : p) {\n std::cin >> v;\n }\n std::vector<double> q(n+1);\n for (double& v : q) {\n std::cin >> v;\n }\n\n std::cout << solve(p, q) << std::endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7560, "score_of_the_acc": -0.3152, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_10_D_10250626", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n\ndouble solve(const std::vector<double>& p, std::vector<double>& q) {\n std::vector<std::vector<double>> sumMem(q.size(), std::vector<double>(q.size(), 0));\n for (int i = 0; i < sumMem.size(); ++i) {\n sumMem[i][i] = q[i]; \n for (int j = i + 1; j < sumMem[i].size(); ++j) {\n sumMem[i][j] = sumMem[i][j-1] + p[j-1] + q[j];\n }\n }\n std::vector<std::vector<double>> minCostMem(q.size(), std::vector<double>(q.size(), 0));\n for (int len = 0; len < q.size(); ++len) {\n for (int i = 0; i + len < q.size(); ++i) {\n int k = i + len;\n double m = INFINITY;\n for (int j = i + 1; j <= k; ++j) {\n m = std::min(m, minCostMem[i][j-1] + minCostMem[j][k]);\n }\n minCostMem[i][k] = (std::isinf(m) ? 0 : m) + sumMem[i][k];\n }\n }\n return minCostMem[0][p.size()];\n}\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<double> p(n);\n for (double& v : p) {\n std::cin >> v;\n }\n std::vector<double> q(n+1);\n for (double& v : q) {\n std::cin >> v;\n }\n\n std::cout << solve(p, q) << std::endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7092, "score_of_the_acc": -0.1724, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_10_D_10250165", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n#include <algorithm>\nusing namespace std;\n\n// 各範囲のキーのコストの合計を求める\nvector<vector<double>> setKeySumCost(const vector<double> &array_k, const vector<double> &array_d)\n{\n int n = array_k.size() + 1;\n vector<vector<double>> keySumCost(n);\n for (int i = 0; i < n; i++)\n {\n keySumCost[i].resize(n);\n keySumCost[i][i] = array_d[i];\n for (int j = i + 1; j < n; j++)\n {\n keySumCost[i][j] = keySumCost[i][j - 1] + array_k[j - 1] + array_d[j];\n }\n }\n return keySumCost;\n}\n\n// 最小のコストを求める\ndouble getMinCost(const vector<vector<double>> &keySumCost)\n{\n int n = keySumCost.size();\n vector<vector<double>> optCost(n);\n for (int i = 0; i < n; i++)\n {\n optCost[i].resize(n);\n optCost[i][i] = keySumCost[i][i];\n }\n for (int i = 0; i < n - 1; i++)\n {\n optCost[i][i + 1] = keySumCost[i][i + 1] + optCost[i][i] + optCost[i + 1][i + 1];\n }\n\n // 範囲の長さを指定\n // 最初は短い範囲から、最後は全体の範囲で最小のコストを求める\n for (int len = 2; len < n; len++)\n {\n // 起点を設定する\n // 最初は 1~2, 2~3\n for (int begin = 0; begin < n - len; begin++)\n {\n // 範囲内でどのキーを中央にすると最小のコストになるか求める\n // 1 , (2) or (1), 2\n vector<double> sums;\n for (int r = begin + 1; r <= begin + len; r++)\n {\n double left = begin + 1 < r ? optCost[begin][r - 1] : optCost[begin][begin];\n double right = r < begin + len ? optCost[r][begin + len] : optCost[begin + len][begin + len];\n sums.push_back(left + right);\n }\n vector<double>::iterator iter = min_element(sums.begin(), sums.end());\n size_t index = distance(sums.begin(), iter);\n optCost[begin][begin + len] = keySumCost[begin][begin + len] + sums[index];\n }\n }\n\n return optCost[0][n - 1];\n}\n\nint main()\n{\n int n;\n cin >> n;\n vector<double> array_k;\n vector<double> array_d;\n for (int i = 0; i < n; i++)\n {\n double num;\n cin >> num;\n array_k.push_back(num);\n }\n for (int i = 0; i < n + 1; i++)\n {\n double num;\n cin >> num;\n array_d.push_back(num);\n }\n vector<vector<double>> keySumCost = setKeySumCost(array_k, array_d);\n double minCost = getMinCost(keySumCost);\n cout << fixed << setprecision(12) << minCost << endl;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 7124, "score_of_the_acc": -0.619, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_10_D_10250151", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n\ndouble solve(const std::vector<double>& p, std::vector<double>& q) {\n std::vector<std::vector<double>> minCostMem(q.size(), std::vector<double>(q.size(), 0));\n std::vector<std::vector<double>> sumMem(q.size(), std::vector<double>(q.size(), 0));\n\n for (int i = 0; i < sumMem.size(); ++i) {\n sumMem[i][i] = q[i]; \n for (int j = i + 1; j < sumMem[i].size(); ++j) {\n sumMem[i][j] = sumMem[i][j-1] + p[j-1] + q[j];\n }\n }\n for (int len = 0; len < q.size(); ++len) {\n for (int i = 0; i < q.size() - len; ++i) {\n int k = i + len;\n double m = INFINITY;\n for (int j = i + 1; j <= k; ++j) {\n m = std::min(m, minCostMem[i][j-1] + minCostMem[j][k]);\n }\n minCostMem[i][k] = (std::isinf(m) ? 0 : m) + sumMem[i][k];\n }\n }\n return minCostMem[0][p.size()];\n}\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<double> p(n);\n for (double& v : p) {\n std::cin >> v;\n }\n std::vector<double> q(n+1);\n for (double& v : q) {\n std::cin >> v;\n }\n\n std::cout << solve(p, q) << std::endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7108, "score_of_the_acc": -0.1735, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_10_D_10250130", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n\ndouble solve(const std::vector<double>& p, std::vector<double>& q) {\n std::vector<std::vector<double>> minCostMem(q.size(), std::vector<double>(q.size(), 0));\n std::vector<std::vector<double>> sumMem(q.size(), std::vector<double>(q.size(), 0));\n\n for (int i = 0; i < sumMem.size(); ++i) {\n sumMem[i][i] = q[i]; \n for (int j = i + 1; j < sumMem[i].size(); ++j) {\n sumMem[i][j] = sumMem[i][j-1] + p[j-1] + q[j];\n }\n }\n\n for (int i = 0; i < q.size(); ++i) {\n minCostMem[i][i] = q[i];\n }\n for (int len = 1; len < q.size(); ++len) {\n for (int i = 0; i < q.size() - len; ++i) {\n int k = i + len;\n double m = INFINITY;\n for (int j = i + 1; j <= k; ++j) {\n m = std::min(m, minCostMem[i][j-1] + minCostMem[j][k]);\n }\n minCostMem[i][k] = m + sumMem[i][k];\n }\n }\n return minCostMem[0][p.size()];\n}\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<double> p(n);\n for (double& v : p) {\n std::cin >> v;\n }\n std::vector<double> q(n+1);\n for (double& v : q) {\n std::cin >> v;\n }\n\n std::cout << solve(p, q) << std::endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7136, "score_of_the_acc": -0.1754, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_10_D_10250112", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n\nclass Solver {\n const std::vector<double> p;\n const std::vector<double> q;\n std::vector<std::vector<double>> minCostMem;\n std::vector<std::vector<double>> sumMem;\n\npublic:\n Solver(const std::vector<double>& p, std::vector<double>& q) : p(p), q(q)\n {\n minCostMem = std::vector<std::vector<double>>(q.size(), std::vector<double>(q.size(), 0));\n sumMem = std::vector<std::vector<double>>(q.size(), std::vector<double>(q.size(), 0));\n\n for (int i = 0; i < sumMem.size(); ++i) {\n sumMem[i][i] = q[i]; \n for (int j = i + 1; j < sumMem[i].size(); ++j) {\n sumMem[i][j] = sumMem[i][j-1] + p[j-1] + q[j];\n }\n }\n\n for (int i = 0; i < q.size(); ++i) {\n minCostMem[i][i] = q[i];\n }\n for (int len = 1; len < q.size(); ++len) {\n for (int i = 0; i < q.size() - len; ++i) {\n int k = i + len;\n double m = INFINITY;\n for (int j = i + 1; j <= k; ++j) {\n m = std::min(m, minCostMem[i][j-1] + minCostMem[j][k] + sumMem[i][k]);\n }\n minCostMem[i][k] = m;\n }\n }\n\n }\n double minCost(int i, int k) {\n return minCostMem[i][k];\n }\n};\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<double> p(n);\n for (double& v : p) {\n std::cin >> v;\n }\n std::vector<double> q(n+1);\n for (double& v : q) {\n std::cin >> v;\n }\n\n Solver solver(p, q);\n std::cout << solver.minCost(0,n) << std::endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7492, "score_of_the_acc": -0.1995, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_10_D_10250057", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n\nclass Solver {\n const std::vector<double> p;\n const std::vector<double> q;\n std::vector<std::vector<double>> minCostMem;\n std::vector<std::vector<double>> sumMem;\n\n double sum(int i, int k) {\n return sumMem[i][k];\n }\npublic:\n Solver(const std::vector<double>& p, std::vector<double>& q) : p(p), q(q)\n {\n minCostMem = std::vector<std::vector<double>>(q.size(), std::vector<double>(q.size(), 0));\n sumMem = std::vector<std::vector<double>>(q.size(), std::vector<double>(q.size(), 0));\n\n for (int i = 0; i < sumMem.size(); ++i) {\n sumMem[i][i] = q[i]; \n for (int j = i + 1; j < sumMem[i].size(); ++j) {\n sumMem[i][j] = sumMem[i][j-1] + p[j-1] + q[j];\n }\n }\n }\n double minCost(int i, int k) {\n if (minCostMem[i][k]) return minCostMem[i][k];\n if (i == k) return q[i];\n double m = INFINITY;\n for (int j = i + 1; j <= k; ++j) {\n m = std::min(m, minCost(i, j-1) + minCost(j, k) + sum(i, k));\n }\n minCostMem[i][k] = m;\n return m;\n }\n};\n\nint main() {\n int n;\n std::cin >> n;\n std::vector<double> p(n);\n for (double& v : p) {\n std::cin >> v;\n }\n std::vector<double> q(n+1);\n for (double& v : q) {\n std::cin >> v;\n }\n\n Solver solver(p, q);\n std::cout << solver.minCost(0,n) << std::endl;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 7580, "score_of_the_acc": -1.2055, "final_rank": 19 } ]
aoj_ALDS1_10_C_cpp
Longest Common Subsequence For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater. Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters. Input The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given. Output For each dataset, print the length of LCS of $X$ and $Y$ in a line. Constraints $1 \leq q \leq 150$ $1 \leq$ length of $X$ and $Y$ $\leq 1,000$ $q \leq 20$ if the dataset includes a sequence whose length is more than 100 Sample Input 1 3 abcbdab bdcaba abc abc abc bc Sample Output 1 4 3 2 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.
[ { "submission_id": "aoj_ALDS1_10_C_11058892", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\nusing ll=long long;\nconst ll INF=1ll<<60;\nint main(){\n int q;\n cin>>q;\n while(q--){\n string s,t;\n cin>>s>>t;\n vector dp(s.size()+1,vector<int>(t.size()+1));\n rep(i,s.size()+1)dp[i][0]=0;\n rep(i,t.size()+1)dp[0][i]=0;\n rep(i,s.size()){\n rep(j,t.size()){\n if(s[i]==t[j]){\n dp[i+1][j+1]=dp[i][j]+1;\n }else{\n dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);\n }\n }\n }\n cout<<dp[s.size()][t.size()]<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7424, "score_of_the_acc": -0.5189, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_10_C_11057766", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\n// 動的計画法による最長共通部分列の最適解を計算する関数\nvoid lcs(vvl &c, string x, string y) {\n ll m = x.size();\n ll n = y.size();\n\n /*\n c[i][j]を以下の漸化式で計算する\n 0 if i = 0 or j = 0\n c[i][j] = c[i-1][j-1] + 1 if i, j > 0 and xi = yi\n max(c[i][j-1], c[i-1][j]) if i, j > 0 and xi != yi\n */\n for (int i = 1; i < m+1; i++) {\n for (int j = 1; j < n+1; j++) {\n if (x[i-1] == y[j-1]) {\n c[i][j] = c[i-1][j-1] + 1;\n }\n else c[i][j] = max(c[i][j-1], c[i-1][j]);\n }\n }\n}\n\n// main\nvoid solve() {\n ll q;\n cin >> q;\n while(q--) {\n string x, y;\n cin >> x >> y;\n ll m = x.size();\n ll n = y.size();\n // c[i][j]をxi, yjのLCS(最長共通部分列)の長さとする2次元配列\n vector<vector<ll>> memo(m+1, vector<ll>(n+1, 0));\n lcs(memo, x, y);\n cout << memo[m][n] << endl;\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 11264, "score_of_the_acc": -1.5, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_10_C_11047315", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <vector>\nusing namespace std;\n\nint lcs(const string& X, const string& Y) {\n int m = X.length();\n int n = Y.length();\n \n // dp[i][j] = XのiつまでとYのjつまでのLCSの長さ\n vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));\n \n // dp\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (X[i - 1] == Y[j - 1]) {\n // 文字が一致する場合、前の状態に1を加える\n dp[i][j] = dp[i - 1][j - 1] + 1;\n } else {\n // 文字が一致しない場合、XかYのどちらかを1つ減らした状態の最大値\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n \n return dp[m][n];\n}\n\nint main() {\n int q;\n cin >> q;\n \n for (int i = 0; i < q; i++) {\n string X, Y;\n cin >> X >> Y;\n cout << lcs(X, Y) << endl;\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 7012, "score_of_the_acc": -0.6161, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_10_C_11047309", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint L[1001][1001];\n\nint main() {\n int q;\n cin >> q;\n for (int idx=1; idx<q+1; idx++) {\n string X, Y;\n cin >> X >> Y;\n\n int n = X.size();\n int m = Y.size();\n\n for (int i=0; i<n+1; i++) {\n for (int j=0; j<m+1; j++) {\n if (i == 0 || j == 0) {\n L[i][j] = 0;\n }\n else if (X[i-1]==Y[j-1]) {\n L[i][j] = 1 + L[i-1][j-1];\n }\n else {\n L[i][j] = max(L[i][j-1], L[i-1][j]);\n }\n }\n }\n cout << L[n][m] << endl;\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7268, "score_of_the_acc": -0.4926, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_10_C_11045558", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint f[1005][1005];\nint main()\n{\n int q;\n cin >> q;\n while (q--)\n {\n string s1, s2;\n cin >> s1 >> s2;\n s1=' '+s1;\n s2=' '+s2;\n int n = s1.size()-1, m = s2.size()-1;\n memset(f,0,sizeof(f));\n int ans=0;\n for (int i = 1; i <= n; i++)\n {\n for (int j = 1; j <= m; j++)\n {\n if(s1[i]==s2[j])\n f[i][j]=f[i-1][j-1]+1;\n else{\n f[i][j]=max(f[i-1][j],f[i][j-1]);\n }\n \n }\n }\n cout<<f[n][m]<<endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7312, "score_of_the_acc": -0.3333, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_10_C_11042813", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nint lcs(const std::string& X, const std::string& Y) {\n int m = X.size();\n int n = Y.size();\n std::vector<std::vector<int>> c(m + 1, std::vector<int>(n + 1, 0));\n\n for (int i = 1; i <= m; ++i) {\n for (int j = 1; j <= n; ++j) {\n if (X[i - 1] == Y[j - 1])\n c[i][j] = c[i - 1][j - 1] + 1;\n else\n c[i][j] = std::max(c[i - 1][j], c[i][j - 1]);\n }\n }\n return c[m][n]; // LCS の長さ\n}\n\nint main() {\n int n;\n std::cin >> n;\n\n for (int i = 0; i < n; ++i) {\n std::string s1, s2;\n std::cin >> s1 >> s2;\n std::cout << lcs(s1, s2) << \"\\n\";\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 7036, "score_of_the_acc": -0.6201, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_10_C_11042685", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); ++i)\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n int N;\n cin >> N;\n vector<int> res_list(N);\n\n rep(i, N) {\n string X, Y;\n cin >> X >> Y;\n int S = X.size();\n int T = Y.size();\n\n vector<vector<int>> dp(S + 1, vector<int>(T + 1, 0));\n for (int j = 1; j < S + 1; ++j) {\n for (int k = 1; k < T + 1; ++k) {\n char x = X[j - 1], y = Y[k - 1];\n if (x == y) dp[j][k] = dp[j - 1][k - 1] + 1;\n dp[j][k] = max({dp[j][k], dp[j - 1][k], dp[j][k - 1]});\n }\n }\n\n res_list[i] = dp[S][T];\n }\n rep(i, N) cout << res_list[i] << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 7032, "score_of_the_acc": -0.6194, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_10_C_11034050", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\n#if 0\nAOJで正しいことが確認された。\n#endif\n\nint main() {\n int k;\n cin >> k;\n for (int i = 1; i <= k; i++) {\n string X, Y;\n cin >> X >> Y;\n int m = X.length();\n int n = Y.length();\n int L[1001][1001];\n for (int i = 0; i <= m; i++) {\n L[i][0] = 0;\n }\n for (int j = 0; j <= n; j++) {\n L[0][j] = 0;\n }\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (X[i - 1] == Y[j - 1]) {\n L[i][j] = L[i - 1][j - 1] + 1;\n } else {\n L[i][j] = max(L[i - 1][j], L[i][j - 1]);\n } \n }\n }\n cout << L[m][n] << endl;\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7356, "score_of_the_acc": -0.3408, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_10_C_11024376", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cstdint>\n\n// コンパイラに対するヒントのためのマクロ変数\n#define likely(x) __builtin_expect(!!(x), 1) // よく起こりやすい条件分岐\n#define unlikely(x) __builtin_expect(!!(x), 0) // あまり起きない条件分岐\n\nuint16_t N; // データセットの数\n\nint main() {\n std::cin >> N; // データセットの数の挿入\n\n std::string x; // 最初の文字列\n std::string y; // 二番目の文字列\n\n uint16_t xs, ys; // x, y の文字列の長さを保存する変数\n\n std::vector<std::vector<uint16_t>> table; // q は高々 99 なので uint16_t 型の二次元配列を用意する\n\n for (uint16_t i = 0; i<N; ++i) {\n // 文字列の読み込み\n std::cin >> x;\n std::cin >> y;\n xs = x.size();\n ys = y.size();\n\n table.assign(ys+1, std::vector<uint16_t>(xs+1, 0)); // 文字列の長さ +1 分の配列の長さを確保する\n\n for (uint16_t r=0; r<ys; ++r) { // 行に関するループ\n for (uint16_t c=0; c<xs; ++c) { // 列に関するループ\n if (x[c] == y[r]) { // 文字が一致する場合\n table[r+1][c+1] = table[r][c] + 1;\n } else {\n table[r+1][c+1] = std::max(table[r][c+1], table[r+1][c]);\n }\n }\n }\n \n std::cout << table[ys][xs] << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5336, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_10_C_11024374", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cstdint>\n\n// コンパイラに対するヒントのためのマクロ変数\n#define likely(x) __builtin_expect(!!(x), 1) // よく起こりやすい条件分岐\n#define unlikely(x) __builtin_expect(!!(x), 0) // あまり起きない条件分岐\n\nuint16_t N; // データセットの数\n\nint main() {\n std::cin >> N; // データセットの数の挿入\n\n std::string x; // 最初の文字列\n std::string y; // 二番目の文字列\n\n uint16_t xs, ys; // x, y の文字列の長さを保存する変数\n\n std::vector<std::vector<uint16_t>> table; // q は高々 99 なので uint16_t 型の二次元配列を用意する\n\n for (uint16_t i = 0; i<N; ++i) {\n // 文字列の読み込み\n std::cin >> x;\n std::cin >> y;\n xs = x.size();\n ys = y.size();\n\n table.assign(ys+1, std::vector<uint16_t>(xs+1, 0)); // 文字列の長さ +1 分の配列の長さを確保する\n\n for (uint16_t r=0; r<ys; ++r) { // 行に関するループ\n for (uint16_t c=0; c<xs; ++c) { // 列に関するループ\n if (unlikely(x[c] == y[r])) { // 文字が一致する場合\n table[r+1][c+1] = table[r][c] + 1;\n } else {\n table[r+1][c+1] = std::max(table[r][c+1], table[r+1][c]);\n }\n }\n }\n \n std::cout << table[ys][xs] << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 5344, "score_of_the_acc": -0.168, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_10_C_11022521", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint lcs(string& x, string& y)\n{\n vector<vector<int>> dp(x.length()+1, vector<int>(y.length()+1));\n\n for(int i = 0; i <= (int)x.length(); i++)\n for(int j = 0; j <= (int)y.length(); j++)\n {\n if(i == 0 || j == 0)\n {\n dp[i][j] = 0;\n }\n else if(x[i-1] == y[j-1])\n {\n dp[i][j] = dp[i-1][j-1] + 1;\n }\n else\n {\n dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n }\n }\n \n return dp[x.length()][y.length()];\n}\n\nint main()\n{\n int q;\n cin >> q;\n for(int query = 0; query < q; query++)\n {\n string x, y;\n cin >> x >> y;\n cout << lcs(x, y) << endl;\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 6980, "score_of_the_acc": -0.6107, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_10_C_11021716", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <cstring>\nusing namespace std;\n\nint lcs(char* A, char* B) {\n int m = strlen(A);\n int n = strlen(B);\n int L[m+1][n+1];\n for (int i = 0; i <= m; i++) {\n for (int j = 0; j <= n; j++) {\n if (i == 0 || j == 0) {\n L[i][j] = 0;\n } else if (A[i-1] == B[j-1]) {\n L[i][j] = L[i-1][j-1] + 1;\n } else {\n L[i][j] = max(L[i-1][j], L[i][j-1]);\n }\n }\n }\n return L[m][n];\n}\n\nint main() {\n int N;\n cin >> N;\n for (int i = 0; i < N; i++) {\n char A[1000], B[1000];\n cin >> A >> B;\n int result = lcs(A, B);\n cout << result << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7272, "score_of_the_acc": -0.3266, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_10_C_11016254", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct Init {\n Init() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n }\n} init;\n\n#ifdef LOCAL\n#define d(x) cout << \"\\033[36m\" << #x << \"\\033[0m\" << \" = \" << (x) << '\\n'\n#else\n#define d(x) ((void)0)\n#endif\n\nusing ll = long long;\nusing i128 = __int128;\ntemplate <class T>\nusing pq_max = priority_queue<T>;\ntemplate <class T>\nusing pq_min = priority_queue<T, vector<T>, greater<T>>;\ntemplate <class T>\nusing vc = vector<T>;\n#define all(x) (x).begin(), (x).end()\n#define len(x) ll(x.size())\n#define eb emplace_back\n#define rep(i, a, b) for (ll i = (a); i < (b); i++)\n\ntemplate <typename T, typename U>\nT SUM(const U& A) {\n return std::accumulate(A.begin(), A.end(), T{});\n}\n#define MIN(v) *min_element(all(v))\n#define MAX(v) *max_element(all(v))\n\ntemplate <class C, class T>\ninline long long LB(const C& c, const T& x) {\n return lower_bound(c.begin(), c.end(), x) - c.begin();\n}\ntemplate <class C, class T>\ninline long long UB(const C& c, const T& x) {\n return upper_bound(c.begin(), c.end(), x) - c.begin();\n}\ntemplate <class T, class S>\ninline bool chmax(T& a, const S& b) {\n return (a < b ? a = b, 1 : 0);\n}\ntemplate <class T, class S>\ninline bool chmin(T& a, const S& b) {\n return (a > b ? a = b, 1 : 0);\n}\ntemplate <typename T, typename U>\nvector<T> cumsum(const vector<U>& A, int off = 1) {\n int N = A.size();\n vector<T> B(N + 1);\n for (int i = 0; i < N; i++) {\n B[i + 1] = B[i] + A[i];\n }\n if (off == 0) B.erase(B.begin());\n return B;\n}\nvoid solve() {\n string a, b;\n cin >> a >> b;\n vc<vc<int>> dp(len(a) + 1, vc<int>(len(b) + 1));\n rep(i, 1, len(a) + 1) rep(j, 1, len(b) + 1) {\n if (a[i - 1] == b[j - 1]) chmax(dp[i][j], dp[i - 1][j - 1] + 1);\n chmax(dp[i][j], dp[i - 1][j]);\n chmax(dp[i][j], dp[i][j - 1]);\n }\n cout << dp[len(a)][len(b)] << '\\n';\n}\nint main() {\n int n;\n cin >> n;\n while (n--) solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 6940, "score_of_the_acc": -0.6039, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_10_C_11014793", "code_snippet": "#include <bits/stdc++.h>\n#pragma GCC target(\"avx2\")\n#ifndef LOCAL\n#pragma GCC optimize(\"O3\")\n#endif\n#pragma GCC optimize(\"unroll-loops\")\n\n#ifdef ONLINE_JUDGE\n#include <boost/multiprecision/cpp_int.hpp>\n#include <atcoder/all>\n#endif\n#ifdef LOCAL\n#define GLIBCXX_DEBUG\n#define endl endl<<flush\n#else\n#define endl \"\\n\"\n#endif\nusing namespace std;using ll=long long;using ull=unsigned long long;using dl=long double;\n#define rep(i,n) for(ll i=0; i<(n); i++)\n#define rrep(i,n) for(ll i=1; i<=(n); i++)\n#define drep(i,n) for(ll i=(n)-1; i>=0; i--)\n#define xfor(i,s,e) for(ll i=(s); i<(e); i++)\n#define rxfor(i,s,e) for(ll i=(s); i<=(e); i++)\n#define dfor(i,s,e) for(ll i=(s)-1; i>=(e); i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define chmax(x,y) x = max(x,y)\n#define chmin(x,y) x = min(x,y)\n#define popcnt(s) ll(__popcount<ull>(uint64_t(s)))\ntemplate<typename T>istream&operator>>(istream&is,pair<T,T>&v){is>>v.first>>v.second;return is;}\ntemplate<typename T>istream&operator>>(istream&is,vector<T>&v){for(auto&in:v)is>>in;return is;}\ntemplate<typename T, typename U>ostream&operator<<(ostream&os,pair<T,U>&v){os<<v.first<<\" \"<<v.second;return os;}\ntemplate<typename T>ostream&operator<<(ostream&os,vector<T>&v){for(auto&in:v)os<<in<<' ';return os;}\nll modpow(ll a, ll b, ll mod) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a) % mod;a = (a * a) % mod;b >>= 1;}return res;}\nll powl(ll a, ll b) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a);a = (a * a);b >>= 1;}return res;}\n#define pow2(a) (a)*(a)\n/*MOD MUST BE A PRIME NUMBER!!*/ll moddiv(const ll a, const ll b, const ll mod) {ll modinv = modpow(b, mod-2, mod);return (a * modinv) % mod;}\nconstexpr ll INF = 2e15;\nll nC2(const ll i){return i>2?i*(i-1)/2:0;}ll nC3(const ll i){return i>3?i*(i-1)*(i-2)/6:0;}ll nC4(const ll i){return i>4?i*(i-1)*(i-2)*(i-3)/24:0;}ll nC5(const ll i){return i>5?i*(i-1)*(i-2)*(i-3)*(i-4)/120:0;}ll nC6(const ll i){return i>6?i*(i-1)*(i-2)*(i-3)*(i-4)*(i-5)/720:0;}\nvoid warshall_floyd(vector<vector<ll>>& dist) {const ull n = dist.size();rep(k, n) rep(i, n) rep(j, n) {dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j]);}}\n#define YES {cout<<\"Yes\\n\";return 0;}\n#define NO {cout<<\"No\\n\";return 0;}\n#define yn YES else NO\n#ifdef ONLINE_JUDGE\nusing lll = boost::multiprecision::cpp_int;\n//using lll = boost::multiprecision::int128_t;\nusing namespace atcoder;\n//using mint = modint1000000007;\nusing mint = modint998244353;\n//using mint = modint; // custom mod\n//atcoder::modint::set_mod(m);\n// DSU == UnionFind\n#endif\n#define vc vector\nusing P = pair<ll, ll>;using vl = vc<ll>;using vb=vc<bool>;using vs=vc<string>;using vvl=vc<vl>;using vp=vc<P>;\ntemplate<typename T>void cs(vector<T>&v){xfor(i,1,v.size())v[i]+=v[i-1];}\n\nvl dx = {-1, 1, 0, 0, -1, 1, -1, 1};\nvl dy = {0, 0, 1, -1, -1, -1, 1, 1};\n\nconstexpr ll mod = 998244353;\n\nvoid solve() {\n string x,y;\n cin>>x>>y;\n vvl dp(x.size()+1, vl(y.size()+1, -INF));\n dp[0][0]=0;\n rep(i,x.size())rep(j,y.size()){\n if (x[i]==y[j]){\n ++dp[i][j];\n chmax(dp[i+1][j+1], dp[i][j]);\n } else {\n chmax(dp[i+1][j+1], dp[i][j]);\n chmax(dp[i+1][j], dp[i][j]);\n chmax(dp[i][j+1], dp[i][j]);\n }\n }\n rep(i,y.size()){\n chmax(dp[x.size()][i+1], dp[x.size()][i]);\n }\n rep(i, x.size()) {\n chmax(dp[i+1][y.size()], dp[i][y.size()]);\n }\n\n cout << dp[x.size()][y.size()] << endl;\n}\n\nint main() {\n ios_base::sync_with_stdio(false);\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n cout << fixed << setprecision(50);\n\n ll n = 1;\n cin >> n;\n while (n--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 11056, "score_of_the_acc": -1.9649, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_10_C_11014701", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main(){\n int q;\n cin >> q;\n\n for (int i=0; i<q; i++){\n string X, Y;\n cin >> X;\n cin >> Y;\n\n int x_length = X.length();\n int y_length = Y.length();\n\n vector<vector<int>> dp(x_length+1, vector<int>(y_length+1, 0));\n \n for (int x=0; x<x_length; x++){\n for (int y=0; y<y_length; y++){\n if (X[x] == Y[y]) dp[x+1][y+1] = dp[x][y]+1;\n dp[x+1][y+1] = max(dp[x+1][y+1], dp[x+1][y]);\n dp[x+1][y+1] = max(dp[x+1][y+1], dp[x][y+1]);\n }\n }\n cout << dp[x_length][y_length] << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7396, "score_of_the_acc": -0.5142, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_10_C_11004341", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main ()\n{\n int t;\n cin>>t;\n while(t--)\n {\n string s1,s2;\n cin >> s1>>s2;\n int n=s1.size() , m= s2.size();\n int arr[n+1][m+1];\n for (int i =0;i<=n;i++)\n {\n arr[i][0]=0;\n }\n for (int i=0;i<=m;i++)\n {\n arr[0][i]=0;\n }\n for (int i=1;i<=n;i++)\n {\n for (int j=1;j<=m;j++)\n {\n if (s1[i-1]==s2[j-1])\n {\n arr[i][j]=arr[i-1][j-1]+1;\n }\n else{\n if(arr[i-1][j]>= arr[i][j-1])\n {\n arr[i][j]= arr[i-1][j];\n }\n else{\n arr[i][j]= arr[i][j-1];\n }\n }\n }\n }\n cout <<arr[n][m] << endl;\n }\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7188, "score_of_the_acc": -0.3124, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_10_C_11001572", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\n#include <random>\n#include <chrono>\nusing namespace std;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 5000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\nconst int INF = 2147483647;\n//using ll = long long;\n\nint Q;\nstring X;\nstring Y;\n\n\nint main() {\n\n\tcin >> Q;\n\tfor (int q = 0; q < Q; q++) {\n\t\tcin >> X;\n\t\tcin >> Y;\n\n\t\tvector<vector<int>> dp(X.length() + 1, vector<int>(Y.length() + 1));\n\n\t\tfor (int i = 0; i < X.length(); i++) {\n\t\t\tfor (int j = 0; j < Y.length(); j++) {\n\t\t\t\tdp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i + 1][j]);\n\t\t\t\tdp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j + 1]);\n\t\t\t\tif (X[i] == Y[j]) {\n\t\t\t\t\tdp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << dp[X.length()][Y.length()] << endl;\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7300, "score_of_the_acc": -0.498, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_10_C_10998995", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n string s1, s2;\n cin >> s1 >> s2;\n int n = s1.size(), m = s2.size();\n int a[n+1][m+1];\n char track[n+1][m+1];\n for(int i=0; i<=n; i++)\n {\n a[i][0] = 0;\n }\n for(int i=0; i<=m; i++)\n {\n a[0][i] = 0;\n }\n for(int i=1; i<=n; i++)\n {\n for(int j=1; j<=m; j++)\n {\n if(s1[i-1] == s2[j-1])\n {\n a[i][j] = a[i-1][j-1] + 1;\n track[i][j] = 'D';\n }\n else\n {\n if(a[i-1][j] >= a[i][j-1])\n {\n a[i][j] = a[i-1][j];\n track[i][j] = 'U';\n }\n else\n {\n a[i][j] = a[i][j-1];\n track[i][j] = 'L';\n }\n }\n }\n \n }\n cout << a[n][m] << endl;\n }\n \n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8224, "score_of_the_acc": -0.4872, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_10_C_10998096", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <map>\n \nusing namespace std;\n\nint main(){\n int q;\n cin >> q;\n\n for(int i=0; i<q; i++){\n string s, t;\n cin >> s >> t;\n int ss = (int)s.size();\n int tt = (int)t.size();\n vector<vector<int>> dp(ss+1, vector<int>(tt+1, 0));\n \n for(int i=1; i<=ss; i++){\n for(int j=1; j<=tt; j++){\n if(s[i-1] == t[j-1])dp[i][j] = dp[i-1][j-1]+1;\n else dp[i][j] = max(dp[i][j-1], dp[i-1][j]);\n }\n }\n cout << dp[ss][tt] << endl;\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7400, "score_of_the_acc": -0.5148, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_10_C_10996268", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define all(T) T.begin(), T.end()\nusing ll = long long;\nusing P = pair<int, int>;\nconst int di[] = {-1, 0, 1, 0};\nconst int dj[] = {0, -1, 0, 1};\nvoid chmax(ll& x, ll y) { x = max(x, y); }\nvoid chmin(ll& x, ll y) { x = min(x, y); }\n\nvoid solve() {\n string x, y;\n cin >> x >> y;\n ll n = x.size(), m = y.size();\n vector dp(n + 1, vector<ll>(m + 1));\n dp[0][0] = 0;\n rep(i, n) {\n rep(j, m) {\n if (x[i] == y[j]) chmax(dp[i + 1][j + 1], dp[i][j] + 1);\n chmax(dp[i + 1][j + 1], dp[i + 1][j]);\n chmax(dp[i + 1][j + 1], dp[i][j + 1]);\n }\n }\n cout << dp[n][m] << '\\n';\n}\n\nint main() {\n // LCS\n ll t;\n cin >> t;\n rep(ti, t) solve();\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 11264, "score_of_the_acc": -1.6667, "final_rank": 19 } ]
aoj_ALDS1_13_A_cpp
8 Queens Problem The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure. For a given chess board where $k$ queens are already placed, find the solution of the 8 queens problem. Input In the first line, an integer $k$ is given. In the following $k$ lines, each square where a queen is already placed is given by two integers $r$ and $c$. $r$ and $c$ respectively denotes the row number and the column number. The row/column numbers start with 0. Output Print a $8 \times 8$ chess board by strings where a square with a queen is represented by ' Q ' and an empty square is represented by ' . '. Constraints There is exactly one solution Sample Input 1 2 2 2 5 3 Sample Output 1 ......Q. Q....... ..Q..... .......Q .....Q.. ...Q.... .Q...... ....Q...
[ { "submission_id": "aoj_ALDS1_13_A_10595759", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <queue>\n#include <iomanip>\n#include <functional>\n#include <stack>\n\nusing namespace std;\nusing l = long long;\nusing ul = unsigned long long;\n\nconst int inf = 2147483647; // 2e9 1 << 30\nconst l INF = 9223372036854775807; // 9e18 1LL << 60\n\n#define r(i, n) for (l i = 0; i < n; ++i)\n#define r1(i, n) for (l i = 1; i < n; ++i)\n#define r0(i) for (l i = -1; i < 2; ++i)\n#define pll pair<l, l>\n\n\nvoid YesNo(bool s=false) {\n if (s) cout<<\"Yes\"<<endl;\n else cout<<\"No\"<<endl;\n}\n\nvoid nans(l ans) {\n if (ans==INF) cout<<-1<<endl;\n else cout<<ans<<endl;\n}\n\nstruct UnionFind {\n vector<l> parent, rank, size;\n l tree_count;\n\n UnionFind(l n) : parent(n), rank(n, 0), size(n, 1), tree_count(n) {\n for (l i = 0; i < n; i++) parent[i] = i;\n }\n \n l find(l x) {\n if (parent[x] == x) return x;\n return parent[x] = find(parent[x]); // パス圧縮\n }\n bool unite(pll xy) {\n l rx = find(xy.first);\n l ry = find(xy.second);\n if (rx == ry) return false;\n if (rank[rx] < rank[ry]) swap(rx, ry);\n parent[ry] = rx;\n size[rx] += size[ry];\n if (rank[rx] == rank[ry]) rank[rx]++;\n\n tree_count--;\n\n return true;\n }\n \n bool same(pll xy) {\n return find(xy.first) == find(xy.second);\n }\n \n l getSize(l x) {\n return size[find(x)];\n }\n};\n\n\nint main() {\n l n;cin>>n;\n\n vector<string> f(8, \"........\");\n\n r(i, n) {\n l x, y;cin>>x>>y;\n\n f[x][y]='Q';\n }\n\n if (n==8) {\n r(i, 8) cout<<f[i]<<endl;\n return 0;\n }\n\n function<void(vector<string>, l, l, l)> dfs=[&](vector<string> sp, l x, l y, l cnt) {\n sp[x][y]='Q';\n\n if (++cnt==8) {\n r(i, 8) cout<<sp[i]<<endl;\n\n exit(0);\n }\n\n r(i, 8) r(j, 8) {\n bool flag=false;\n\n r0(dy)r0(dx) {\n r(k, 8) {\n l nx=i+dx*k, ny=j+dy*k;\n\n if (nx<0 || nx>=8 || ny<0 || ny>=8) continue;\n\n if (sp[nx][ny]=='Q') flag=true;\n }\n }\n\n if (flag) continue;\n\n dfs(sp, i, j, cnt);\n }\n };\n\n r(i, 8) r(j, 8) {\n bool flag=false;\n\n r0(dy)r0(dx) {\n r(k,8) {\n l nx=i+dx*k, ny=j+dy*k;\n if (nx<0 || nx>=8 || ny<0 || nx>=8) continue;\n\n if (f[nx][ny]=='Q') flag=true;\n }\n }\n\n if (flag) continue;\n\n dfs(f, i, j, n);\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3440, "score_of_the_acc": -0.0741, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_13_A_10489958", "code_snippet": "#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i=0;i<(n);++i)\n#define all(a) (a).begin(),(a).end()\nusing ll = long long;\n\ntemplate<class T> istream& operator>>(istream& i,vector<T>& v) {rep(j,v.size()) i>>v[j]; return i;}\ntemplate <typename T> void vecout(const vector<T> &v) {\n rep(i, v.size()) {\n cout << v[i];\n cout << (i == v.size()-1 ? '\\n' : ' ');\n }\n}\n\n// ------------------------------------------------------------------------------------------------\n\nint main() {\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n\n int k; cin >> k;\n set<int> row, column, sum, diff;\n vector<vector<char>> grid(8, vector<char>(8, '.'));\n rep(_,k) {\n int r, c; cin >> r >> c;\n row.insert(r);\n column.insert(c);\n sum.insert(r+c);\n diff.insert(r-c);\n grid[r][c] = 'Q';\n }\n\n vector<int> p(8);\n iota(all(p), 0);\n do {\n set<int> r = row, c = column, s = sum, d = diff;\n bool ok = true;\n rep(i,8) {\n int j = p[i];\n if(grid[i][j] != 'Q' && (r.count(i) || c.count(j) || s.count(i+j) || d.count(i-j))) {\n ok = false;\n break;\n } else {\n r.insert(i);\n c.insert(j);\n s.insert(i+j);\n d.insert(i-j);\n }\n }\n if(ok) {\n rep(i,8) {\n grid[i][p[i]] = 'Q';\n }\n break;\n }\n } while(next_permutation(all(p)));\n \n rep(i,8) {\n rep(j,8) cout << grid[i][j];\n cout << '\\n';\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3540, "score_of_the_acc": -1.0267, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_13_A_10408630", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for(int i = 0; i < (int)(n); i++)\n\nint main(){\n int k;\n cin >> k;\n\n set<pair<int, int>> st;\n\n rep(i, k){\n int r, c;\n cin >> r >> c;\n st.insert(make_pair(r, c));\n }\n\n vector<int> ord(8);\n iota(ord.begin(), ord.end(), 0);\n\n do{\n vector<pair<int, int>> a(8);\n rep(i, 8) a.at(i) = make_pair(i, ord.at(i));\n\n bool ok = true;\n for(pair<int, int> p : st){\n if(find(a.begin(), a.end(), p) == a.end()) ok = false;\n }\n\n set<int> wa, sa;\n rep(i, 8){\n if(wa.count(a.at(i).first + a.at(i).second)) ok = false;\n wa.insert(a.at(i).first + a.at(i).second);\n }\n\n rep(i, 8){\n if(sa.count(a.at(i).first - a.at(i).second)) ok = false;\n sa.insert(a.at(i).first - a.at(i).second);\n }\n\n if(ok){\n vector<string> ans(8);\n rep(i, 8) ans.at(i) = \"........\";\n rep(i, 8) ans.at(i).at(ord.at(i)) = 'Q';\n\n rep(i, 8){\n cout << ans.at(i) << endl;\n }\n return 0;\n }\n\n }while(next_permutation(ord.begin(), ord.end()));\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3448, "score_of_the_acc": -0.1481, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_13_A_10349369", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n// #include<atcoder/all>\n// using namespace atcoder;\n// if using this, use \"g++ *.cpp -I ~/atcoder/ac...\" to complile\n\ntypedef long long int ll;\ntypedef unsigned long long int ull;\n#define rep(i, n) for (int i = 0; i < (n); i++)\n\nint main()\n{\n\tint k;\n\tcin >> k;\n\tvector<pair<int, int>> v(k);\n\trep(i, k) cin >> v[i].first >> v[i].second;\n\n\tvector<int> ord(8);\n\trep(i, 8) ord[i] = i;\n\n\tdo {\n\t\tbool b = true;\n\t\tset<pair<int, int>> st;\n\t\tvector<vector<bool>> fi(8, vector<bool>(8, false));\n\t\tfor (int i = 0; i < 8; i++) {\n\t\t\tint x = i;\n\t\t\tint y = ord[i];\n\t\t\t\n\t\t\tif (fi[x][y]) {\n\t\t\t\tb = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfi[x][y] = true;\n\t\t\tst.insert({x, y});\n\n\t\t\tint d = 0;\n\t\t\twhile (1) {\n\t\t\t\tbool flag = false;\n\t\t\t\tif (x+d < 8) {\n\t\t\t\t\tfi[x+d][y] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (0 <= x-d) {\n\t\t\t\t\tfi[x-d][y] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (y+d < 8) {\n\t\t\t\t\tfi[x][y+d] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (0 <= y-d) {\n\t\t\t\t\tfi[x][y-d] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (x+d < 8 && y+d < 8) {\n\t\t\t\t\tfi[x+d][y+d] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (x+d < 8 && y-d >= 0) {\n\t\t\t\t\tfi[x+d][y-d] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (0 <= x-d && y+d < 8) {\n\t\t\t\t\tfi[x-d][y+d] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (x-d >= 0 && y-d >= 0) {\n\t\t\t\t\tfi[x-d][y-d] = true;\n\t\t\t\t\tflag = true;\n\t\t\t\t}\n\t\t\t\tif (!flag) break;\n\t\t\t\td++;\n\t\t\t}\n\t\t}\n\n\t\tif (b) {\n\t\t\tbool flag = true;\n\t\t\trep(i, k) {\n\t\t\t\tif (!st.count(v[i])) flag = false;\n\t\t\t}\n\n\t\t\tif (flag) {\n\t\t\t\trep(i, 8) {\n\t\t\t\t\trep(j, 8) {\n\t\t\t\t\t\tif (st.count({i, j})) cout << 'Q';\n\t\t\t\t\t\telse cout << '.';\n\t\t\t\t\t}\n\t\t\t\t\tcout << '\\n';\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t} while (next_permutation(ord.begin(), ord.end()));\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3452, "score_of_the_acc": -0.1985, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_13_A_10348120", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i, n, m) for (int i = (int)n; i < (int)m; i++)\n\nbool put(int i, int j, vector<vector<bool>> &board) {\n if (board[i][j] == true) return false;\n\n rep(k, 0, 8) board[i][k] = true;\n rep(k, 0, 8) board[k][j] = true;\n rep(k, 0, 8) {\n if (j + (i - k) >= 0 && j + (i - k) < 8) board[k][j + (i - k)] = true;\n }\n rep(k, 0, 8) {\n if (j - (i - k) >= 0 && j - (i - k) < 8) board[k][j - (i - k)] = true;\n }\n\n return true;\n}\n\nint main() {\n int k;\n cin >> k;\n vector<int> rc(8, -1);\n rep(i, 0, k) {\n int r, c;\n cin >> r >> c;\n rc[r] = c;\n }\n\n vector<int> ord(8);\n rep(i, 0, 8) ord[i] = i;\n do {\n bool f = true;\n vector<int> q(8, -1);\n vector<vector<bool>> board(8, vector<bool>(8, false));\n rep(i, 0, 8) {\n int j = ord[i];\n if (rc[i] != -1 && rc[i] != j) break;\n\n if (put(i, j, board)) {\n q[i] = j;\n } else {\n break;\n }\n }\n\n if (q[7] != -1) {\n rep(i, 0, 8) {\n rep(j, 0, 8) {\n if (q[i] == j) {\n cout << 'Q';\n } else {\n cout << '.';\n }\n }\n cout << '\\n';\n }\n }\n } while(next_permutation(ord.begin(), ord.end()));\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3432, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_13_A_10339714", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i, n) for (int i = 0; i < (n); i++)\ntypedef unsigned long long int ull;\ntypedef long long ll;\nusing namespace std;\nconst int INTINF = 1001001001;\nconst long long LLINF = 1e18;\nconst int MOD = 998244353;\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define display(a) {for (auto b : (a)) cout << b << \" \"; cout << endl; }\n#define Pii pair<int, int>\n#define Pli pair<long long, int>\n#define Pil pair<int, long long>\n#define Pid pair<int, double>\n#define Pdi pair<double, int>\n#define Psi pair<string, int>\n#define Tiii tuple<int, int, int>\n#define Tlii tuple<long long, int, int>\n#define Till tuple<int, long long, long long>\n#define Tdii tuple<double, int, int>\n#define chmax(x, y) x = max(x, y)\n#define pqueue priority_queue\n#define pb push_back\n\nint dy[] = {-1, 0, 1, 0};\nint dx[] = {0, 1, 0, -1};\nint ddy[] = {-1, -1, -1, 0, 0, 0, 1, 1, 1};\nint ddx[] = {-1, 0, 1, -1, 0, 1, -1, 0, 1};\n\ndouble calcDist(int x1, int y1, int x2, int y2)\n{ return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); }\ndouble calcDist(Pii &A, Pii &B)\n{ return sqrt((A.first-B.first)*(A.first-B.first) + (A.second-B.second)*(A.second-B.second)); }\ndouble calcDist(double x1, double y1, double z1, double x2, double y2, double z2)\n{ return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(z1-z2)); }\n\nint main()\n{\n\tint N = 8, M;\n\tcin >> M;\n\tvector<int> Y(M), X(M);\n\trep (i, M) cin >> Y[i] >> X[i];\n\tvector<int> O(N);\n\trep (i, N) O[i] = i;\n\tdo {\n\t\tvector<vector<char>> S(N, vector<char> (N, '.'));\n\t\trep (i, N) S[i][O[i]] = 'Q';\n\t\trep (i, M) S[Y[i]][X[i]] = 'Q';\n\t\tbool ok = true;\n\t\trep (i, N) rep (j, N)\n\t\t{\n\t\t\tif (S[i][j] != 'Q') continue;\n\t\t\tfor (int k = i + 1; k < N; k++) if (S[k][j] == 'Q') ok = false;\n\t\t\tfor (int k = j + 1; k < N; k++) if (S[i][k] == 'Q') ok = false;\n\t\t\tfor (int k = 1; i+k < N && j+k < N; k++) if (S[i+k][j+k] == 'Q') ok = false;\n\t\t\tfor (int k = 1; 0 <= i-k && j+k < N; k++) if (S[i-k][j+k] == 'Q') ok = false;\n\t\t}\n\t\tif (ok)\n\t\t{\n\t\t\tfor (auto ss : S) { for (auto s : ss) cout << s; cout << endl; }\n\t\t\treturn 0;\n\t\t}\n\t} while (next_permutation(O.begin(), O.end()));\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3452, "score_of_the_acc": -0.1852, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_13_A_10322932", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i, n) for (int i = 0; i < (n); i++)\ntypedef unsigned long long int ull;\ntypedef long long ll;\nusing namespace std;\nconst int INTINF = 1001001001;\nconst long long LLINF = 1e18;\nconst int MOD = 998244353;\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define Pii pair<int, int>\n#define Pli pair<long long, int>\n#define Pil pair<int, long long>\n#define Pid pair<int, double>\n#define Pdi pair<double, int>\n#define Psi pair<string, int>\n#define Tiii tuple<int, int, int>\n#define Tlii tuple<long long, int, int>\n#define chmax(x, y) x = max(x, y)\n#define pqueue priority_queue\n#define pb push_back\n\nint dy[] = {-1, 0, 1, 0};\nint dx[] = {0, 1, 0, -1};\nint ddy[] = {-1, -1, -1, 0, 0, 0, 1, 1, 1};\nint ddx[] = {-1, 0, 1, -1, 0, 1, -1, 0, 1};\n\ndouble calcDist(int x1, int y1, int x2, int y2)\n{ return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); }\ndouble calcDist(Pii &A, Pii &B)\n{ return sqrt((A.first-B.first)*(A.first-B.first) + (A.second-B.second)*(A.second-B.second)); }\n\nint main()\n{\n\tint M, N = 8;\n\tcin >> M;\n\tvector<int> Y(M), X(M);\n\trep (i, M) cin >> Y[i] >> X[i];\n\tvector<int> O(N);\n\trep (i, N) O[i] = i;\n\tdo {\n\t\tvector<vector<char>> ban(N, vector<char> (N, '.'));\n\t\trep (i, N) ban[i][O[i]] = 'Q';\n\t\trep (i, M) ban[Y[i]][X[i]] = 'Q';\n\t\tbool ok = true;\n\t\trep (i, N) rep (j, N)\n\t\t{\n\t\t\tif (ban[i][j] != 'Q') continue;\n\t\t\tfor (int k = i + 1; k < N; k++) if (ban[k][j] == 'Q') ok = false;\n\t\t\tfor (int k = j + 1; k < N; k++) if (ban[i][k] == 'Q') ok = false;\n\t\t\tfor (int k = 1; i+k < N && j+k < N; k++) if (ban[i+k][j+k]=='Q') ok = false;\n\t\t\tfor (int k = 1; i+k < N && 0 <= j-k; k++) if (ban[i+k][j-k]=='Q') ok = false;\n\t\t}\n\t\tif (ok)\n\t\t{\n\t\t\trep (i, N)\n\t\t\t{\n\t\t\t\trep (j, N) cout << ban[i][j];\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t} while (next_permutation(O.begin(), O.end()));\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3448, "score_of_the_acc": -0.1481, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_13_A_10307590", "code_snippet": "// ALDS1_13_A\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n\tint N = 8, M;\n\tcin >> M;\n\tvector<int> Y(M), X(M), O(N);\n\tfor (int i = 0; i < M; i++) cin >> Y[i] >> X[i];\n\tfor (int i = 0; i < N; i++) O[i] = i;\n\tdo {\n\t\tvector<vector<char>> B(N, vector<char>(N, '.'));\n\t\tfor (int i = 0; i < M; i++) B[Y[i]][X[i]] = 'Q';\n\t\tfor (int i = 0; i < N; i++) B[i][O[i]] = 'Q';\n\t\tbool ok = true;\n\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < N; j++)\n\t\t\t{\n\t\t\t\tif (B[i][j] == '.') continue;\n\t\t\t\tfor (int k = j + 1; k < N; k++) if (B[i][k] == 'Q') ok = false;\n\t\t\t\tfor (int k = i + 1; k < N; k++) if (B[k][j] == 'Q') ok = false;\n\t\t\t\tfor (int k = 1; i + k < N && j + k < N; k++) if (B[i + k][j + k] == 'Q') ok = false;\n\t\t\t\tfor (int k = 1; i + k < N && 0 <= j - k; k++) if (B[i + k][j - k] == 'Q') ok = false;\n\t\t\t}\n\t\t}\n\n\t\tif (ok)\n\t\t{\n\t\t\tfor (int i = 0; i < N; i++)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < N; j++) cout << B[i][j];\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t} while (next_permutation(O.begin(), O.end()));\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3452, "score_of_the_acc": -0.1852, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_13_A_10283737", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i, n) for (int i = 0; i < (n); i++)\ntypedef unsigned long long int ull;\ntypedef long long ll;\nusing namespace std;\nconst int INF = 1001001001;\nconst int MOD = 998244353;\n#define Pint pair<int, int>\n#define Pli pair<long long, int>\n#define Pid pair<int, double>\n#define Pdi pair<double, int>\n#define Tint tuple<int, int, int>\n#define chmax(x, y) x = max(x, y)\n#define pqueue priority_queue\n#define pb push_back\n\nvoid solve()\n{\n\tint N, M = 8;\n\tcin >> N;\n\tvector<int> Y(N), X(N);\n\trep (i, N) cin >> Y[i] >> X[i];\n\tvector<int> order(M);\n\trep (i, M) order[i] = i;\n\tdo {\n\t\tvector<vector<char>> ban(M, vector<char> (M, '.'));\n\t\trep (i, M)\n\t\t{\n\t\t\tban[i][order[i]] = 'Q';\n\t\t}\n\t\trep (i, N) ban[Y[i]][X[i]] = 'Q';\n\t\tbool ok = true;\n\t\trep (i, M)\n\t\t{\n\t\t\trep (j, M)\n\t\t\t{\n\t\t\t\tif (ban[i][j] != 'Q') continue;\n\t\t\t\tfor (int k = i+1; k < M; k++) if (ban[k][j] == 'Q') ok = false;\n\t\t\t\tfor (int k = j+1; k < M; k++) if (ban[i][k] == 'Q') ok = false;\n\t\t\t\tfor (int k = 1; i+k < M && j+k < M; k++) if (ban[i+k][j+k] == 'Q') ok = false;\n\t\t\t\tfor (int k = 1; j-k >= 0 && i+k < M; k++) if (ban[i+k][j-k] == 'Q') ok = false;\n\n\t\t\t}\n\t\t}\n\t\tif (ok)\n\t\t{\n\t\t\trep (i, M)\n\t\t\t{\n\t\t\t\trep (j, M) cout << ban[i][j];\n\t\t\t\tcout << '\\n';\n\t\t\t}\n\t\t}\n\t} while (next_permutation(order.begin(), order.end()));\n}\n\n#ifdef DEBUG\nint Qnum = 3;\n#else\nint Qnum = 1;\n#endif\n\nint main()\n{\n\twhile (Qnum--)\n\t{\n\t\tsolve();\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3448, "score_of_the_acc": -0.1481, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_13_A_10264935", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i, n) for (int i = 0; i < (n); i++)\ntypedef unsigned long long int ull;\ntypedef long long ll;\nusing namespace std;\nconst int INF = 1001001001;\nconst int MOD = 998244353;\n// #define P pair<int, int>\n#define chmax(x, y) x = max(x, y)\n\nvoid solve(void)\n{\n\tint N, M = 8;\n\tcin >> N;\n\tvector<int> Y(N), X(N);\n\trep(i, N) cin >> Y[i] >> X[i];\n\tvector<int> order(M);\n\trep(i, M) order[i] = i;\n\tdo {\n\t\tvector<vector<char>> ban(M, vector<char> (M, '.'));\n\t\trep(i, M) ban[i][order[i]] = 'Q';\n\t\trep(i, N) ban[Y[i]][X[i]] = 'Q';\n\t\tbool ok = true;\n\t\trep(s, M) rep(t, M)\n\t\t{\n\t\t\tif (ban[s][t] != 'Q') continue;\n\t\t\tfor (int k = s + 1; k < M; k++) if (ban[k][t] == 'Q') ok = false;\n\t\t\tfor (int k = t + 1; k < M; k++) if (ban[s][k] == 'Q') ok = false;\n\t\t\tfor (int k = 1; max(s+k, t+k) < M; k++) if (ban[s+k][t+k] == 'Q') ok = false;\n\t\t\tfor (int k = 1; s+k < M&&t-k >= 0; k++) if (ban[s+k][t-k] == 'Q') ok = false;\n\t\t}\n\t\tif (ok)\n\t\t{\n\t\t\tfor (auto cc : ban)\n\t\t\t{\n\t\t\t\tfor (auto c : cc) cout << c;\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t} while (next_permutation(order.begin(), order.end()));\n}\n\n#ifdef DEBUG\nint Qnum = 3;\n#else\nint Qnum = 1;\n#endif\n\nint main()\n{\n\twhile (Qnum--)\n\t{\n\t\tsolve();\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3436, "score_of_the_acc": -0.037, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_13_A_10220589", "code_snippet": "/* Last modified: <2025-02-15 01:09:53> */\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\ntemplate <typename T> bool next_combination(const T first, const T last, int k) {\n const T subset = first + k;\n // empty container | k = 0 | k == n\n if (first == last || first == subset || last == subset) {\n return false;\n }\n T src = subset;\n while (first != src) {\n src--;\n if (*src < *(last - 1)) {\n T dest = subset;\n while (*src >= *dest) {\n dest++;\n }\n iter_swap(src, dest);\n rotate(src + 1, dest + 1, last);\n rotate(subset, subset + (last - dest) - 1, last);\n return true;\n }\n }\n // restore\n rotate(first, subset, last);\n return false;\n}\n\ninline int convertXY2N(int x, int y) {\n return y * 8 + x;\n}\n\ninline pair<int, int> convertN2XY(int n) {\n return make_pair(n % 8, n / 8);\n}\n\nvector<int> pathOfQueen(int Q) {\n vector<int> path_of_queen = {Q};\n int x, y;\n tie(x, y) = convertN2XY(Q);\n int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\n int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n int max_k = max(max(x, 7-x), max(y, 7-y));\n for (int k = 1; k <= max_k; ++k) {\n for (int i = 0; i < 8; ++i) {\n int nx = x + k * dx[i];\n int ny = y + k * dy[i];\n if (nx < 0 || nx >= 8 || ny < 0 || ny >= 8) continue;\n path_of_queen.push_back(convertXY2N(nx, ny));\n }\n }\n return path_of_queen;\n}\n\nvoid print(vector<int> &Q) {\n vector<vector<char> > v(8, vector<char>(8, '.'));\n if (! Q.empty()) {\n for (auto q: Q) {\n int x, y;\n tie(x, y) = convertN2XY(q);\n v.at(y).at(x) = 'Q';\n }\n }\n for (int i = 0; i < 8; ++i) {\n for (int j = 0; j < 8; ++j) {\n cout << v.at(i).at(j);\n if (j == 7) {\n cout << endl;\n }\n }\n }\n}\n\nint main(void) {\n int K; cin >> K;\n vector<int> Q(8, -1), Q_orig(8, -1);\n for (int i = 0; i < K; ++i) {\n int x, y;\n cin >> x >> y;\n Q.at(i) = convertXY2N(y, x);\n Q_orig.at(i) = Q.at(i);\n }\n if (K == 8) {\n print(Q);\n return 0;\n }\n set<int> movable_grids;\n for (int i = 0; i < 64; ++i) {\n movable_grids.insert(i);\n }\n for (auto q: Q) {\n if (q == -1) continue;\n vector<int> v = pathOfQueen(q);\n for (auto p: v) {\n movable_grids.erase(p);\n }\n }\n vector<int> grids;\n for (auto p: movable_grids) {\n grids.push_back(p);\n }\n\n int n = 1;\n do {\n copy(Q_orig.begin(), Q_orig.end(), Q.begin());\n for (int i = K; i < 8; ++i) {\n Q.at(i) = grids.at(i - K);\n }\n set<int> immovable_grids;\n for (int i = 0; i < 8; ++i) {\n vector<int> v = pathOfQueen(Q.at(i));\n for (auto p: v) {\n if (p != Q.at(i)) {\n immovable_grids.insert(p);\n }\n }\n }\n\n bool failed = false;\n for (int i = 0; i < 8; ++i) {\n auto it = immovable_grids.find(Q.at(i));\n if (it != immovable_grids.end()) {\n failed = true;\n break;\n }\n }\n if (! failed) {\n print(Q);\n return 0;\n }\n ++n;\n } while (next_combination(grids.begin(), grids.end(), 8 - K));\n cout << \"Not found\" << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 760, "memory_kb": 3460, "score_of_the_acc": -1.2593, "final_rank": 11 } ]
aoj_ALDS1_9_C_cpp
Priority Queue A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations: $insert(S, k)$: insert an element $k$ into the set $S$ $extractMax(S)$: remove and return the element of $S$ with the largest key Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$. The priority queue manages a set of integers, which are also keys for the priority. Input Multiple operations to the priority queue $S$ are given. Each operation is given by " insert $k$", " extract " or " end " in a line. Here, $k$ represents an integer element to be inserted to the priority queue. The input ends with " end " operation. Output For each " extract " operation, print the element extracted from the priority queue $S$ in a line. Constraints The number of operations $\leq 2,000,000$ $0 \leq k \leq 2,000,000,000$ Sample Input 1 insert 8 insert 2 extract insert 10 extract insert 11 extract extract end Sample Output 1 8 10 11 2
[ { "submission_id": "aoj_ALDS1_9_C_11064162", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\nconst int mod = 1000000007;\n#define srt(v) sort(v.begin(), v.end());\n#define srt_Dec(v) sort(v.begin(), v.end(), greater<int>());\n\nint solve1(){\n\n return 0;\n}\nint32_t main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n\n string s;\n priority_queue<int> pq;\n while(cin>>s){\n if (s == \"insert\"){\n int n;\n cin >> n;\n\n pq.push(n);\n }\n else if (s == \"extract\"){\n cout << pq.top() << \"\\n\";\n pq.pop();\n }\n\n else if(s==\"end\"){\n break;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 11428, "score_of_the_acc": -0.7695, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_9_C_11059317", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main() \n{\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n priority_queue<long long> pq; \n string cmd;\n while(cin>>cmd){\n if(cmd==\"insert\"){\n long long k;\n cin>>k;\n pq.push(k);\n }\n else if(cmd==\"extract\"){\n long long mx=pq.top();\n pq.pop();\n cout<<mx<<\"\\n\";\n }\n else if(cmd==\"end\"){\n break;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 240, "memory_kb": 11460, "score_of_the_acc": -0.7893, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_9_C_11059161", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n#define dd double\n\nint main(){\n\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n string s;\n int k;\n priority_queue<int> pq;\n while(cin >> s && s != \"end\"){\n if(s == \"insert\"){\n cin >> k;\n pq.push(k);\n }else{\n cout << pq.top() << endl;\n pq.pop();\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 570, "memory_kb": 7760, "score_of_the_acc": -0.6517, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_9_C_11058935", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n priority_queue<int>p;\n while(1)\n {\n string c;\n cin >> c;\n\n if (c==\"end\")\n {\n break;\n }\n else if (c==\"insert\")\n {\n int n;\n cin >> n;\n p.push(n);\n }\n else if (c==\"extract\")\n {\n int topValue=p.top();\n cout << topValue << \"\\n\";\n p.pop();\n }\n }\n}", "accuracy": 1, "time_ms": 900, "memory_kb": 8796, "score_of_the_acc": -1.3024, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_9_C_11057411", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n priority_queue<int> PQ;\n while(1)\n {\n string str;\n cin>>str;\n if(str==\"end\")break;\n else if(str==\"insert\")\n {\n int value;\n cin>>value;\n PQ.push(value);\n }\n else if(str==\"extract\")\n {\n cout<<PQ.top()<<endl;\n PQ.pop();\n }\n\n }\n}", "accuracy": 1, "time_ms": 900, "memory_kb": 7560, "score_of_the_acc": -1.0967, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_9_C_11057343", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{ priority_queue<long long >pq;\n\n string s;\n long long a;\n while(cin>>s)\n {\n if(s==\"insert\")\n {\n cin>>a;\n pq.push(a);\n }\n else if(s==\"extract\")\n {\n long long mx=pq.top();\n pq.pop();\n cout<<mx<<endl;\n }\n else if(s==\"end\")\n {\n break;\n }\n }\n\n\n\n\n\n}", "accuracy": 1, "time_ms": 900, "memory_kb": 11764, "score_of_the_acc": -1.7964, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_9_C_11055753", "code_snippet": "#include <bits/stdc++.h>\n// #include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nll INF = 2e18;\n#define PI 3.14159265358979323846264338327950l\n// namespace multip = boost::multiprecision;\n// using lll = multip::int128_t;\nusing P = pair<ll, ll>;\ntemplate<typename T> using vc = vector<T>;\ntemplate<typename T> using vv = vc<vc<T>>;\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define drep(i,n) for (ll i = (n)-1; i >= 0; i--)\n#define nfor(i, s, n) for (ll i = (s); i < (n); i++)\n#define dfor(i, s, n) for (ll i = (s)-1; i>=n; i--)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define Yes cout << \"Yes\" << endl\n#define No cout << \"No\" << endl\n#define YES cout << \"YES\" << endl\n#define NO cout << \"NO\" << endl\n#define YN { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }\n#define dame cout << -1 << endl\n#define minval(vec) *min_element(nall(vec))\n#define maxval(vec) *max_element(nall(vec))\n#define binaryS(vec, x) *lower_bound(nall(vec), x)\n#define yu_qurid(x, y) (x) * (x) + (y) * (y)\n#define mannhattan(x1, x2, y1, y2) abs(x1-x2)+abs(y1-y2)\n#define vc_cout(v){ll n= size(v); rep(i,n)cout<<v[i]<<\" \";cout << endl;}\n#define vvc_cout(v){ll n= size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<\" \";}cout<<endl;}}\n// 少数の出力\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\n// グリット用\nvector<ll> dx = {1, 0, -1, 0};\nvector<ll> dy = {0, 1, 0, -1};\nbool in_grid(ll i, ll j, ll h, ll w) {\n return 0 <= i and i < h and 0 <= j and j < w;\n}\n\nvector<ll> pq = {-1};\nll used = 0;\n\n\nvoid set_heap(ll k) {\n pq.push_back(k);\n ++used;\n ll point = used;\n while (point > 1 and pq[point / 2] < pq[point]) {\n swap(pq[point], pq[point / 2]);\n point = point / 2;\n }\n}\n// 節点iを根とする部分木がmax-ヒープとなるようA[i]の値をmax-ヒープの葉へ向かって下降させる\nvoid maxHeapify(ll i) {\n ll left = i * 2;\n ll right = i * 2 + 1;\n // 左の子, 右の子, 自分で値が最大なノードを選ぶ\n ll largest = i;\n if (left <= used and pq[left] > pq[largest]) {\n largest = left;\n }\n if (right <= used and pq[right] > pq[largest]) {\n largest = right;\n }\n // iの子の方が大きかったら\n if (largest != i) {\n swap(pq[i], pq[largest]);\n maxHeapify(largest);\n }\n}\n\n// main\nvoid solve() {\n // 最大ヒープを使って優先度付きキューを作成する\n string type;\n while (1) {\n cin >> type;\n if (type == \"end\") break;\n else if (type == \"insert\") {\n ll k;\n cin >> k;\n set_heap(k);\n }\n else if (type == \"extract\") {\n cout << pq[1] << endl;\n pq[1] = pq[used];\n pq.pop_back();\n used--;\n maxHeapify(1);\n }\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 650, "memory_kb": 11740, "score_of_the_acc": -1.4301, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_9_C_11043151", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#pragma GCC optimize (\"O3\")\n#pragma GCC target (\"sse4\")\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pi;\ntypedef pair<ll,ll> pl;\ntypedef pair<ld,ld> pd;\n\n#define sz(x) (int)(x).size()\n#define mp make_pair\n#define pb push_back\n#define f first\n#define s second\n#define lb lower_bound\n#define ub upper_bound\n#define all(x) x.begin(), x.end()\n#define endl \"\\n\"\n\nconst ll MOD = 1e7 + 9;\nconst ll INF = 1e18;\nconst int MX = 100001;\n\nvoid solve2() {\n priority_queue<int> PQ;\n\n while(true) {\n string S; cin >> S;\n if(S == \"end\") break;\n else if(S == \"insert\") {\n int N;\n cin >> N;\n PQ.push(N);\n }\n else if (S == \"extract\") {\n if(!PQ.empty()) {\n cout << PQ.top() <<endl;\n PQ.pop();\n }\n }\n }\n}\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int T = 1;\n //cin >> T;\n while(T--) solve2();\n\n \n return 0;\n}", "accuracy": 1, "time_ms": 240, "memory_kb": 8116, "score_of_the_acc": -0.2327, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_9_C_11037086", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long int\nusing namespace std;\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);cout.tie(nullptr);\n\n \n priority_queue<int>pq;\n while(1){\n string type;\n cin>>type;\n if(type==\"insert\"){\n int x;\n cin>>x;\n pq.push(x);\n }\n\n else if(type==\"extract\"){\n cout<<pq.top()<<\"\\n\";\n pq.pop();\n }\n\n else if(type==\"end\"){\n return 0;\n }\n }\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 9156, "score_of_the_acc": -0.3913, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_9_C_11033829", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\npriority_queue<int> pq;\nstring s;\nint k;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0); cout.tie(0);\n\n while(cin >> s) {\n if(s == \"end\") break;\n if(s == \"insert\") {\n cin >> k;\n pq.push(k);\n }else {\n cout << pq.top() << '\\n';\n pq.pop();\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 240, "memory_kb": 8184, "score_of_the_acc": -0.244, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_9_C_11027244", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <string>\n\nconstexpr int MAX = 2000000;\nconstexpr int INFTY = 1 << 30;\n\nvoid maxHeapify(int A[], int& H, int i) {\n while (true) {\n int l = 2 * i;\n int r = 2 * i + 1;\n int largest = i;\n if (l <= H && A[l] > A[largest]) largest = l;\n if (r <= H && A[r] > A[largest]) largest = r;\n if (largest == i) break;\n std::swap(A[i], A[largest]);\n i = largest;\n }\n}\n\nint extract(int A[], int& H) {\n if (H < 1) return -INFTY;\n int maxv = A[1];\n A[1] = A[H--];\n maxHeapify(A, H, 1);\n return maxv;\n}\n\nvoid increaseKey(int A[], int i, int key) {\n if (key < A[i]) return;\n A[i] = key;\n while (i > 1 && A[i / 2] < A[i]) {\n std::swap(A[i], A[i / 2]);\n i /= 2;\n }\n}\n\nvoid insert(int A[], int& H, int key) {\n A[++H] = -INFTY;\n increaseKey(A, H, key);\n}\n\nint main() {\n static int A[MAX + 1];\n int H = 0;\n\n std::string com;\n int key;\n\n while (true) {\n if (!(std::cin >> com)) break;\n\n if (com.size() >= 2 && com[0] == 'e' && com[1] == 'n') {\n break;\n } else if (!com.empty() && com[0] == 'i') {\n std::cin >> key;\n insert(A, H, key);\n } else {\n std::cout << extract(A, H) << '\\n';\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 890, "memory_kb": 7424, "score_of_the_acc": -1.0596, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_9_C_11022359", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int CAPACITY = 2000000;\nint H = 0;\n\nvoid swap(vector<int>& a, int x, int y)\n{\n int tmp = a[x];\n a[x] = a[y];\n a[y] = tmp;\n}\n\n\nvoid max_heapify(vector<int>& a, int i)\n{\n int l_id = i*2;\n int r_id = i*2+1;\n\n int largest_id = i;\n if(l_id <= H && a[l_id] > a[largest_id])\n largest_id = l_id;\n if(r_id <= H && a[r_id] > a[largest_id])\n largest_id = r_id;\n\n if(largest_id != i)\n {\n swap(a, i, largest_id);\n max_heapify(a, largest_id);\n }\n}\n\nvoid insert(vector<int>& a, int k)\n{\n H++;\n int i = H;\n a[i] = k;\n while(i > 1 && a[i/2] < a[i])\n {\n swap(a, i, i/2);\n i /= 2;\n }\n}\n\nvoid extract(vector<int>& a)\n{\n cout << a[1] << endl;\n a[1] = a[H];\n a[H] = -1;\n H--;\n max_heapify(a, 1);\n}\n\nint main()\n{\n vector<int> a(CAPACITY + 1);\n for(int i = 0; i <= CAPACITY; i++)\n a[i] = -1;\n\n bool end = false;\n while(!end)\n {\n char op[10];\n scanf(\"%s\", op);\n if(op[0] == 'i')\n {\n int k;\n scanf(\"%d\", &k);\n insert(a, k);\n }\n if(op[0] == 'e' && op[1] == 'x')\n {\n extract(a);\n }\n if(op[0] == 'e' && op[1] == 'n')\n end = true;\n }\n}", "accuracy": 1, "time_ms": 580, "memory_kb": 10584, "score_of_the_acc": -1.1363, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_9_C_11015633", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n string s;\n int n;\n priority_queue<int> pq;\n while (cin >> s)\n {\n if (s == \"insert\")\n {\n cin >> n;\n pq.push(n);\n }\n else if (s == \"extract\")\n {\n cout << pq.top() << \"\\n\";\n pq.pop();\n }\n else if (s == \"end\")\n break;\n }\n}", "accuracy": 1, "time_ms": 890, "memory_kb": 8620, "score_of_the_acc": -1.2586, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_9_C_11012058", "code_snippet": "#include <queue>\n#include <string>\n#include <iostream>\nusing namespace std;\n\nint main() {\n string cmd; // whileの外側で定義して一つの変数を再利用する\n priority_queue<int> Q;\n\n while (cin >> cmd && cmd != \"end\") {\n if (cmd == \"insert\") {\n int k;\n cin >> k;\n Q.push(k);\n } else if (cmd == \"extract\") {\n cout << Q.top() << endl;\n Q.pop();\n }\n }\n}", "accuracy": 1, "time_ms": 910, "memory_kb": 7704, "score_of_the_acc": -1.1352, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_9_C_11011365", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <climits>\n#include <cfloat>\n#include <cassert>\n#include <cstdio>\n#include <cstring>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <bitset>\n#include <numeric>\n#include <iomanip>\n#include <sstream>\n#include <tuple>\n#include <utility>\n#include <iterator>\n#include <limits>\n#include <functional>\n#include <array>\n#include <type_traits>\n#include <chrono>\n#include <list>\n#include <forward_list>\n#include <complex>\n#include <typeinfo>\n#include <stdexcept>\n\nusing namespace std;\n\ninline void Fast_IO() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n}\n\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\n\n#define endl '\\n'\n#define MOD 1000000007\n#define PI 3.14159265358979323846\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define pb push_back\n#define ft first\n#define sd second\n\n\nvoid solve(){\n \n priority_queue<ll> pq;\n\n while(true){\n string str;\n cin >> str;\n\n if(str == \"end\"){\n break;\n }\n\n if(str == \"insert\"){\n ll x;\n cin >> x;\n\n pq.push(x);\n }\n\n if(str == \"extract\"){\n cout << pq.top() << endl;\n pq.pop();\n }\n }\n \n}\n\n\nint main(){\n\n Fast_IO();\n\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 12900, "score_of_the_acc": -1.1304, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_9_C_10998914", "code_snippet": "#include <queue>\n#include <string>\n#include <iostream>\nusing namespace std;\nint main() {\n string cmd; // \\texttt{while}の外側で定義して一つの変数を再利用する\n priority_queue<int> Q;\n while (cin >> cmd && cmd != \"end\") {\n if (cmd == \"insert\") {\n int k;\n cin >> k;\n Q.push(k); // 集合 Sに要素 kを挿入する\n } else if (cmd == \"extract\") {\n // 最大のキーを持つ Sの要素を Sから削除してその値を返す\n cout << Q.top() << endl;\n Q.pop();\n }\n }\n }", "accuracy": 1, "time_ms": 900, "memory_kb": 8772, "score_of_the_acc": -1.2984, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_9_C_10998852", "code_snippet": "#include <queue> \n#include <string> \n#include <iostream> \nusing namespace std;\n\nint main() { \n string cmd; // \\texttt{while}の外側で定義して一つの変数を再利用する \n priority_queue<int> Q; \n while (cin >> cmd && cmd != \"end\") { \n if (cmd == \"insert\") { \n // 何かする \n int x;\n cin >> x;\n Q.push(x);\n } else if (cmd == \"extract\") { \n // 何かする \n cout << Q.top() << endl;\n Q.pop();\n } \n } \n}", "accuracy": 1, "time_ms": 900, "memory_kb": 7312, "score_of_the_acc": -1.0554, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_9_C_10998741", "code_snippet": "#include <iostream>\n#include <queue>\nusing namespace std;\n\nint main(){\n string cmd;\n priority_queue<int> que;\n while(cin >> cmd){\n if (cmd == \"end\"){\n break;\n }\n if (cmd == \"insert\"){\n int x;\n cin >> x;\n que.push(x);\n }else if(cmd == \"extract\"){\n int x = que.top();\n que.pop();\n cout << x << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 900, "memory_kb": 8900, "score_of_the_acc": -1.3197, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_9_C_10952962", "code_snippet": "#include<cstdio>\n#include<cstring>\n#include<algorithm>\nusing namespace std;\n#define MAX 2000000\n#define INF (1<<20)\n\nint H, A[MAX+1];\n\nint parent(int k) { return k / 2; }\nint left(int k) { return 2 * k; }\nint right(int k) { return 2 * k + 1; }\n\nvoid maxHeapify(int k, int B[], int h) {\n int largest = k;\n if ( left(k) <= h && B[k] < B[left(k)] ) largest = left(k);\n if ( right(k) <= h && B[largest] < B[right(k)] ) largest = right(k);\n if ( largest != k ) {\n swap(B[k], B[largest]);\n maxHeapify(largest, B, h);\n }\n}\n\nvoid buildMaxHeap(int B[], int h) {\n for (int i = h / 2; i > 0; i--) {\n maxHeapify(i, B, h);\n }\n}\n\nvoid heepIncreaseKey(int i, int key) {\n A[i] = key;\n while ( i > 1 && A[parent(i)] < A[i]) {\n swap(A[parent(i)], A[i]);\n i = parent(i);\n }\n}\n\nvoid insert(int k) {\n H++;\n A[H] = -INF;\n heepIncreaseKey(H, k);\n}\n\nvoid extract() {\n printf(\"%d\\n\", A[1]);\n A[1] = A[H];\n H--;\n maxHeapify(1, A, H);\n\n}\n\nint main() {\n H = 0;\n int k;\n char com[10];\n while ( true ) {\n scanf(\"%s\", com);\n if ( com[0] == 'i' ) {\n scanf(\"%d\", &k);\n insert(k);\n }\n else if ( com[1] == 'x' ) extract();\n else return 0;\n }\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 6892, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_9_C_10946284", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n string s;\n priority_queue<int>p;\n while(1){\n cin>>s;\n if(s==\"insert\"){\n int x;\n cin>>x;\n p.push(x);\n\n \n }\n else if(s==\"extract\"){\n cout<<p.top()<<endl;\n p.pop();\n \n }\n else if(s==\"end\") break;\n \n \n }\n}", "accuracy": 1, "time_ms": 890, "memory_kb": 7764, "score_of_the_acc": -1.1162, "final_rank": 11 } ]
aoj_ALDS1_12_C_cpp
Single Source Shortest Path II For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Constraints $1 \leq n \leq 10,000$ $0 \leq c_i \leq 100,000$ $|E| < 500,000$ All vertices are reachable from vertex $0$ Sample Input 1 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Sample Output 1 0 0 1 2 2 2 3 1 4 3 Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.
[ { "submission_id": "aoj_ALDS1_12_C_11041168", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<queue>\nusing namespace std;\nstatic const int MAX = 10000;\nstatic const int INFTY = (1<<20);\nstatic const int WHITE = 0;\nstatic const int GRAY = 1;\nstatic const int BLACK = 2;\n\nint n;\nvector<pair<int,int>> adj[MAX];\n\nvoid dijkstra(){\n int color[MAX],d[MAX];\n priority_queue<pair<int,int>> PQ;\n \n for(int i = 0 ; i < n; i++){\n d[i] = INFTY;\n color[i] = WHITE;\n }\n\n d[0] = 0;\n color[0] = GRAY;\n PQ.push(make_pair(0,0));\n\n while(!PQ.empty()){\n pair<int,int> f = PQ.top();\n PQ.pop();\n int u = f.second;\n \n color[u] = BLACK;\n\n if(d[u] < f.first * (-1)) continue;//PQは降順にソート\n\n for(int i = 0 ; i< adj[u].size(); i++){\n int v = adj[u][i].first;\n int c = adj[u][i].second;\n if(d[v] > d[u] + c){\n d[v] = d[u] + c;\n PQ.push(make_pair( (-1) * d[v], v));\n color[v] = GRAY;\n }\n\n }\n\n }\n\n for(int i = 0; i < n; i++){\n cout << i << \" \" << d[i] << endl;\n }\n \n}\n\nint main(){\n int k,u,v,c;\n\n cin >> n;\n for(int i = 0; i < n; i++){\n cin >> u >> k;\n for(int j = 0; j < k; j++){\n cin >> v >> c;\n adj[u].push_back(make_pair(v,c));\n }\n }\n\n dijkstra();\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8240, "score_of_the_acc": -0.3708, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_12_C_11035168", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for(int i = 0; i < (int)(n); i++)\nconst int INF = 100000000;\n\nstruct priority_lesser {\n bool operator()(const pair<int,int>& a, const pair<int,int>& b) const {\n return a.second > b.second; // second が小さい方を優先\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n //pair(v, c)を保存\n vector<vector<pair<int, int>>> adj(n);\n rep(i, n)\n {\n int u, k;\n cin >> u >> k;\n adj[u] = vector<pair<int, int>>(k);\n rep(j, k)\n {\n cin >> adj[u][j].first;\n cin >> adj[u][j].second;\n }\n }\n\n //-1:到達不可, 0:隣接未訪問, 1:訪問済み\n vector<int> state(n, -1);\n priority_queue<pair<int, int>, vector<pair<int, int>>, priority_lesser> pq;\n vector<int> d(n, INF);\n\n state[0] = 0;\n d[0] = 0;\n pq.push({0, 0});\n \n while(true)\n {\n //未訪問の頂点につながる辺がtopに来るまでpopする\n while(state[pq.top().first] == 1 && !pq.empty())\n pq.pop();\n\n if(pq.empty())\n break;\n\n int u = pq.top().first;\n state[u] = 1;\n pq.pop();\n\n for(pair<int, int> uv : adj[u]) if(state[uv.first] != 1)\n {\n int v = uv.first;\n if(state[v] == -1)\n state[v] = 0;\n\n pair<int, int> path = {v, d[u] + uv.second};\n if(path.second < d[v])\n {\n d[v] = path.second;\n pq.push(path);\n }\n }\n }\n\n rep(i, n)\n {\n cout << i << \" \" << d[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 7180, "score_of_the_acc": -0.32, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_12_C_11035148", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for(int i = 0; i < (int)(n); i++)\nconst int INF = 100000000;\n\nstruct priority_lesser {\n bool operator()(const pair<int,int>& a, const pair<int,int>& b) const {\n return a.second > b.second; // second が小さい方を優先\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n //pair(v, c)を保存\n vector<vector<pair<int, int>>> adj(n);\n rep(i, n)\n {\n int u, k;\n cin >> u >> k;\n adj[u] = vector<pair<int, int>>(k);\n rep(j, k)\n {\n cin >> adj[u][j].first;\n cin >> adj[u][j].second;\n }\n }\n\n //-1:到達不可, 0:隣接未訪問, 1:訪問済み\n vector<int> state(n, -1);\n priority_queue<pair<int, int>, vector<pair<int, int>>, priority_lesser> pq;\n vector<int> d(n, INF);\n\n state[0] = 0;\n d[0] = 0;\n pq.push({0, 0});\n \n while(true)\n {\n //未訪問の頂点につながる辺がtopに来るまでpopする\n while(state[pq.top().first] == 1 && !pq.empty())\n pq.pop();\n\n if(pq.empty())\n break;\n\n int u = pq.top().first;\n state[u] = 1;\n pq.pop();\n for(pair<int, int> uv : adj[u]) if(state[uv.first] != 1)\n {\n int v = uv.first;\n if(state[v] == -1)\n state[v] = 0;\n\n pair<int, int> path = {v, d[u] + uv.second};\n if(path.second < d[v])\n {\n d[v] = path.second;\n pq.push(path);\n }\n }\n }\n\n rep(i, n)\n {\n cout << i << \" \" << d[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 7484, "score_of_the_acc": -0.3346, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_12_C_11035116", "code_snippet": "#include <bits/stdc++.h>\n#include <queue>\nusing namespace std;\n#define rep(i, n) for(int i = 0; i < (int)(n); i++)\nconst int INF = 100000000;\n\nstruct priority_lesser {\n bool operator()(const pair<int,int>& a, const pair<int,int>& b) const {\n return a.second > b.second; // second が小さい方を優先\n }\n};\n\nint main()\n{\n int n;\n cin >> n;\n //pair(v, c)を保存\n vector<vector<pair<int, int>>> adj(n);\n rep(i, n)\n {\n int u, k;\n cin >> u >> k;\n adj[u] = vector<pair<int, int>>(k);\n rep(j, k)\n {\n cin >> adj[u][j].first;\n cin >> adj[u][j].second;\n }\n }\n\n //-1:到達不可, 0:隣接未訪問, 1:訪問済み\n vector<int> state(n, -1);\n priority_queue<pair<int, int>, vector<pair<int, int>>, priority_lesser> pq;\n vector<int> d(n, INF);\n\n state[0] = 1;\n d[0] = 0;\n rep(i, adj[0].size())\n pq.push(adj[0][i]);\n \n while(true)\n {\n //未訪問の頂点につながる辺がtopに来るまでpopする\n while(state[pq.top().first] == 1 && !pq.empty())\n pq.pop();\n\n if(pq.empty())\n break;\n\n int u = pq.top().first;\n d[u] = pq.top().second;\n state[u] = 1;\n pq.pop();\n for(pair<int, int> uv : adj[u]) if(state[uv.first] != 1)\n {\n if(state[uv.first] == -1)\n state[uv.first] = 0;\n\n pair<int, int> path = pair(uv.first, d[u] + uv.second);\n pq.push(path);\n }\n }\n\n rep(i, n)\n {\n cout << i << \" \" << d[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 10560, "score_of_the_acc": -0.4421, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_12_C_10953314", "code_snippet": "#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <queue>\nusing namespace std;\n#define INF 0x3f3f3f\n#define NIL -1\nconst int ma=10000;\nint n; \nint color[ma];\nint d[ma];\nvector<pair<int,int>> adj[ma];\nvoid dijkstra(){\n priority_queue<pair<int,int>> PQ;//优先级队列默认比较前一个值,所以应该是前一个值是距离,后一个值是顶点,而且要是最小堆,可以取巧,存入相反数\n for(int i=0;i<n;i++){\n color[i]=0;\n d[i]=INF;\n }\n d[0]=0;\n PQ.push(make_pair(0,0));\n while(!PQ.empty()){\n pair<int,int> u=PQ.top();\n PQ.pop();\n color[u.second]=2;\n if(d[u.second]<u.first*(-1)){//比较现在u的成本和历史u的成本,因为下面可能会把同一个在不同时间不同的距离的值加进去,我们只要等于历史的那个u\n continue;\n }\n for(int i=0;i<(int)adj[u.second].size();i++){//\n int v=adj[u.second][i].first;//相邻结点\n if(color[v]!=2){\n if(d[u.second]+adj[u.second][i].second<d[v]){\n d[v]=d[u.second]+adj[u.second][i].second;\n color[v]=1;\n PQ.push(make_pair((-1)*d[v],adj[u.second][i].first));\n }\n }\n }\n }\n}\nint main(){\n scanf(\"%d\",&n);\n for(int i=0;i<n;i++){\n int m,k;\n scanf(\"%d %d\",&m,&k);\n for(int j=0;j<k;j++){\n int c,d;\n scanf(\"%d %d\",&c,&d);\n adj[m].push_back(make_pair(c,d));\n }\n }\n dijkstra();\n for(int i=0;i<n;i++){\n printf(\"%d %d\\n\",i,d[i]);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8640, "score_of_the_acc": -0.11, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_12_C_10899380", "code_snippet": "#pragma region Macros\n#include <bits/stdc++.h>\n\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\nusing lint = long long;\nusing mint = modint998244353;\nusing ull = unsigned long long;\nusing ld = long double;\nusing int128 = __int128_t;\n#define all(x) (x).begin(), (x).end()\n#define EPS 1e-8\n#define uniqv(v) v.erase(unique(all(v)), v.end())\n#define OVERLOAD_REP(_1, _2, _3, name, ...) name\n#define REP1(i, n) for (auto i = std::decay_t<decltype(n)>{}; (i) != (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\n#define log(x) cout << x << endl\n#define logfixed(x) cout << fixed << setprecision(10) << x << endl;\n#define logy(bool) \\\n if (bool) { \\\n cout << \"Yes\" << endl; \\\n } else { \\\n cout << \"No\" << endl; \\\n }\n\nostream &operator<<(ostream &dest, __int128_t value) {\n ostream::sentry s(dest);\n if (s) {\n __uint128_t tmp = value < 0 ? -value : value;\n char buffer[128];\n char *d = end(buffer);\n do {\n --d;\n *d = \"0123456789\"[tmp % 10];\n tmp /= 10;\n } while (tmp != 0);\n if (value < 0) {\n --d;\n *d = '-';\n }\n int len = end(buffer) - d;\n if (dest.rdbuf()->sputn(d, len) != len) {\n dest.setstate(ios_base::badbit);\n }\n }\n return dest;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v) {\n for (int i = 0; i < (int)v.size(); i++) {\n os << v[i] << (i + 1 != (int)v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const set<T> &set_var) {\n for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {\n os << *itr;\n ++itr;\n if (itr != set_var.end()) os << \" \";\n itr--;\n }\n return os;\n}\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const map<T, U> &map_var) {\n for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {\n os << itr->first << \" -> \" << itr->second << \"\\n\";\n }\n return os;\n}\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const pair<T, U> &pair_var) {\n os << \"(\" << pair_var.first << \", \" << pair_var.second << \")\";\n return os;\n}\n\nvoid out() { cout << '\\n'; }\ntemplate <class T, class... Ts>\nvoid out(const T &a, const Ts &...b) {\n cout << a;\n (cout << ... << (cout << ' ', b));\n cout << '\\n';\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v) {\n for (T &in : v) is >> in;\n return is;\n}\n\ninline void in(void) { return; }\ntemplate <typename First, typename... Rest>\nvoid in(First &first, Rest &...rest) {\n cin >> first;\n in(rest...);\n return;\n}\n\ntemplate <typename T>\nbool chmax(T &a, const T &b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T &b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n\nvector<lint> dx8 = {1, 1, 0, -1, -1, -1, 0, 1};\nvector<lint> dy8 = {0, 1, 1, 1, 0, -1, -1, -1};\nvector<lint> dx4 = {1, 0, -1, 0};\nvector<lint> dy4 = {0, 1, 0, -1};\n\n#pragma endregion\n\ntemplate <class T>\nclass Dijkstra {\n private:\n vector<vector<pair<int, T>>> g;\n vector<T> dist;\n vector<int> prev;\n int n;\n\n public:\n Dijkstra(vector<vector<pair<int, T>>> _g, int start = 0) {\n g = _g;\n n = g.size();\n dist.assign(n, -1);\n prev.assign(n, -1);\n vector<bool> fin(n, false);\n priority_queue<tuple<T, int, int>, vector<tuple<T, int, int>>, greater<tuple<T, int, int>>> q;\n dist[start] = 0;\n q.emplace(0, start, -1);\n while (!q.empty()) {\n int cur = get<1>(q.top());\n int pre = get<2>(q.top());\n q.pop();\n if (fin[cur]) continue;\n fin[cur] = true;\n prev[cur] = pre;\n for (auto p : g[cur]) {\n int nex = p.first;\n int weight = p.second;\n if (dist[nex] == -1 or dist[nex] > dist[cur] + weight) {\n dist[nex] = dist[cur] + weight;\n q.emplace(dist[nex], nex, cur);\n }\n }\n }\n }\n\n void rebuild(int start) {\n dist.assign(n, -1);\n prev.assign(n, -1);\n vector<bool> fin(n, false);\n priority_queue<tuple<T, int, int>, vector<tuple<T, int, int>>, greater<tuple<T, int, int>>> q;\n dist[start] = 0;\n q.emplace(0, start, -1);\n while (!q.empty()) {\n int cur = get<1>(q.top());\n int pre = get<2>(q.top());\n q.pop();\n if (fin[cur]) continue;\n fin[cur] = true;\n prev[cur] = pre;\n for (auto p : g[cur]) {\n int nex = p.first;\n int weight = p.second;\n if (dist[nex] == -1 or dist[nex] > dist[cur] + weight) {\n dist[nex] = dist[cur] + weight;\n q.emplace(dist[nex], nex, cur);\n }\n }\n }\n }\n\n vector<T> get_dist() {\n return dist;\n }\n\n T get_dist(int t) {\n return dist[t];\n }\n\n vector<int> get_route(int t) {\n vector<int> ret;\n if (dist[t] == -1) return ret;\n\n int cur = t;\n while (cur != -1) {\n ret.emplace_back(cur);\n cur = prev[cur];\n }\n reverse(ret.begin(), ret.end());\n return ret;\n }\n};\n\nint main() {\n cin.tie(0)->sync_with_stdio(0);\n\n int n;\n in(n);\n vector<vector<pair<int, lint>>> g(n);\n rep(i, n) {\n int u, k;\n in(u, k);\n rep(j, k) {\n int v, c;\n in(v, c);\n g[u].emplace_back(v, c);\n }\n }\n\n Dijkstra<lint> d(g);\n rep(i, n) {\n out(i, d.get_dist(i));\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 28032, "score_of_the_acc": -1, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_12_C_10884299", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define rep2(i, s, n) for (ll i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nll minval(vector<ll> vec) {\n return *min_element(begin(vec), end(vec));\n}\nll maxval(vector<ll> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\nvector<string> color;\nvector<ll> d;\nvector<ll> p;\nvector<pair<ll, ll>> adj[10000];\nll INFTY = 1000000;\npriority_queue<pair<ll, ll>> PQ;\n\n// ヒープによるダイクストラ法\nvoid dijkstra() {\n rep(u, color.size()) {\n color[u] = \"white\";\n d[u] = INFTY;\n }\n d[0] = 0;\n PQ.push({0, 0});\n color[0] = \"gray\";\n while (PQ.size() != 0) {\n pair<ll, ll> f = PQ.top();\n PQ.pop();\n ll u = f.second;\n color[u] = \"black\";\n if (d[u] < f.first * (-1)) {\n continue;\n }\n for (int j = 0; j < adj[u].size(); j++) {\n ll v = adj[u][j].first;\n if (color[v] == \"black\") {\n continue;\n }\n if (d[v] > d[u] + adj[u][j].second) {\n d[v] = d[u] + adj[u][j].second;\n PQ.push(make_pair(d[v] * (-1), v));\n color[v] = \"gray\";\n }\n }\n }\n rep(i,d.size()) {\n cout << i << \" \" << (d[i] == INFTY ? -1 : d[i]) << endl;\n }\n}\n\nvoid solve() {\n ll k, u, v, c, n;\n cin >> n;\n color.resize(n);\n d.resize(n);\n p.resize(n);\n rep(i,n) {\n cin >> u >> k;\n rep(j, k) {\n cin >> v >> c;\n adj[u].push_back(make_pair(v,c));\n }\n }\n dijkstra();\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 12672, "score_of_the_acc": -0.5034, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_12_C_10849798", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\nusing P = pair<int,int>;\n\nstruct Edge {\n int to, cost;\n Edge() {}\n Edge(int to, int cost) : to(to), cost(cost) {}\n};\n\nint main()\n{\n int n;\n cin >> n;\n vector<vector<Edge>> g(n);\n rep(i,n) {\n int u,k;\n cin >> u >> k;\n rep(j,k) {\n int v,c;\n cin >> v >> c;\n g[u].emplace_back(v,c);\n }\n }\n\n const int INF = 1e9;\n priority_queue<P,vector<P>,greater<P>> q;\n vector<int> dist(n,INF);\n dist[0] = 0;\n q.emplace(0,0);\n\n while (!q.empty()) {\n auto [c, v] = q.top(); q.pop();\n if (dist[v] != c) continue;\n for (Edge e : g[v]) {\n int nd = e.cost + dist[v];\n if (nd >= dist[e.to]) continue;\n dist[e.to] = nd;\n q.emplace(nd,e.to);\n }\n }\n\n rep(i,n) cout << i << ' ' << dist[i] << '\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8264, "score_of_the_acc": -0.372, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_12_C_10767203", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int WHITE = 0;\nconst int GRAY = 1;\nconst int BLACK = 2;\nconst int INFTY = 1<<30;\nint n;\n\nconst int MAX = 10000;\n\nint d[MAX], color[MAX];\n\nvector<pair<int, int>> M[MAX];\n\nvoid dijkstra()\n{\n for (int i = 0; i < n; i++)\n {\n d[i] = INFTY;\n color[i] = WHITE;\n }\n\n d[0] = 0;\n priority_queue<pair<int, int>> PQ;\n PQ.push(make_pair(0, 0));\n\n while (!PQ.empty())\n {\n pair<int, int> f = PQ.top(); PQ.pop();\n int u = f.second;\n\n color[u] = BLACK;\n\n if (d[u] < f.first*(-1)) continue;\n\n for (int i = 0; i < M[u].size(); i++)\n {\n int v = M[u][i].first;\n if (color[v] != BLACK && d[v] > d[u] + M[u][i].second)\n {\n d[v] = M[u][i].second + d[u];\n color[v] = GRAY;\n PQ.push(make_pair(d[v] * -1, v));\n }\n }\n } \n}\n\nint main()\n{\n cin >> n;\n for (int i = 0; i < n; i++)\n {\n int u, k;\n cin >> u >> k;\n for (int j = 0; j < k; j++)\n {\n int v, c;\n cin >> v >> c;\n M[u].push_back(make_pair(v, c));\n }\n }\n\n dijkstra();\n\n for (int i = 0; i < n; i++)\n {\n cout << i << \" \" << d[i] << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8464, "score_of_the_acc": -0.3816, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_12_C_10757638", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nstatic const int INFTY = 1<<20;\nstatic const int N_MAX = 10000;\n\nstatic const int NIL = -1;\n\nstatic const int WHITE = 0; // Not visited (initial state)\nstatic const int GRAY = 1; // Candidate of next visit\nstatic const int BLACK = 2; // Visited\n\n// weight of all edges\n// int W[N_MAX][N_MAX];\nvector<pair<int, int>> W[N_MAX];\n\n// Visiting state\nint colors[N_MAX];\n\n// minimum cost to connect\nint d[N_MAX];\nauto compare = [](pair<int, int> a, pair<int, int> b) {\n return a.second > b.second;\n};\npriority_queue<\n pair<int, int>,\n vector<pair<int, int>>,\n decltype(compare)\n> PQ(compare);\n\n// parent\nint p[N_MAX];\n\n/*\nFind the minimum cost to go to all nodes from node `start`.\n`n` is the number of total nodes\n*/\nvoid dijkstra(int start, int n){\n\n d[start] = 0;\n PQ.push(make_pair(start, 0));\n // int u;\n pair<int, int> u;\n while(!(PQ.empty())) {\n // Find the node u\n // that we can go with minimum cost from Minimum Path\n u = PQ.top();\n PQ.pop();\n\n // It may not be the minimum path\n // because PQ has the path which is not minimum.\n if( d[u.first] < u.second) continue;\n\n colors[u.first] = BLACK;\n\n // d[*]の更新\n // uと隣接するvにおいて、d[u] + weight(u, v)の値を\n // ヒープにpushする\n for(\n int i=0;\n i < W[u.first].size();\n i++\n ){\n // adjacent node of u.\n pair<int, int> v = W[u.first][i];\n if(colors[v.first] != BLACK){\n if(\n d[u.first] + v.second < d[v.first]\n ){\n d[v.first] = d[u.first] + v.second;\n colors[v.first] = GRAY;\n PQ.push(make_pair(v.first, d[v.first]));\n }\n }\n }\n }\n}\n\nint main () {\n\n // Read data\n int n;\n cin >> n;\n int from, to, weight, n_edges;\n // for(int i=0; i<n; i++) {\n // for(int j=0; j<n; j++){\n // W[i][j] = NIL;\n // }\n // }\n for(int i=0; i<n; i++){\n cin >> from >> n_edges;\n for(int j=0; j<n_edges; j++) {\n scanf(\"%d %d\", &to, &weight);\n // W[from][to] = weight;\n W[from].push_back(make_pair(to, weight));\n }\n }\n\n // for(int i=0; i<n; i++) {\n // for(int j=0; j<n; j++){\n // // W[i][j] = NIL;\n // cout << W[i][j] << \" \";\n // }\n // cout << endl;\n // }\n\n // initialize\n for(int i=0; i<n; i++){\n colors[i] = WHITE;\n d[i] = INFTY;\n p[i] = NIL;\n }\n\n dijkstra(0, n);\n \n for(int i=0; i<n; i++){\n cout << i << \" \" << d[i] << endl;\n }\n\n return 0;\n\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8396, "score_of_the_acc": -0.0983, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_12_C_10719804", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nconst int N=1e4+5;\nconst int INF=2e9;\nvector<int>E[N],W[N];\nint n,dis[N];\nstruct Comp{\n bool operator()(PII a,PII b){\n return a.first>b.first;\n }\n}; \nvoid solve(){\n cin>>n;\n for(int i=0;i<n;i++){\n int u,k;cin>>u>>k;\n for(int j=0;j<k;j++){\n int v,w;cin>>v>>w;\n E[u].push_back(v);\n W[u].push_back(w);\n }\n }\n priority_queue<PII,vector<PII>,Comp>q;\n q.push({0,0});\n for(int i=0;i<n;i++){\n dis[i]=INF;\n }\n while(!q.empty()){\n PII p=q.top();q.pop();\n int d=p.first,u=p.second;\n if(dis[u]!=INF) continue;\n dis[u]=d;\n int len=E[u].size();\n for(int i=0;i<len;i++){\n int v=E[u][i],w=W[u][i];\n if(dis[v]!=INF) continue;\n q.push({d+w,v});\n }\n }\n for(int i=0;i<n;i++){\n cout<<i<<\" \"<<dis[i]<<endl;\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 18020, "score_of_the_acc": -0.6399, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_12_C_10676743", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility> // for std::pair\n\nstatic const int INFTY = (1 << 21);\n\nint n;\nstd::vector<std::vector<std::pair<int, int>>> adj; // adjacency list\nstd::vector<int> d; // distance array\n\nvoid dijkstra() {\n d.assign(n, INFTY); // initialize all distances\n d[0] = 0;\n\n std::priority_queue<std::pair<int, int>,\n std::vector<std::pair<int, int>>,\n std::greater<std::pair<int, int>>> pq;\n\n pq.push(std::make_pair(0, 0)); // (distance, vertex)\n\n while (!pq.empty()) {\n std::pair<int, int> top = pq.top();\n pq.pop();\n\n int dist_u = top.first;\n int u = top.second;\n\n if (dist_u > d[u]) continue; // skip outdated entry\n\n for (size_t i = 0; i < adj[u].size(); i++) {\n std::pair<int, int> edge = adj[u][i];\n int v = edge.first;\n int cost = edge.second;\n\n if (d[u] + cost < d[v]) {\n d[v] = d[u] + cost;\n pq.push(std::make_pair(d[v], v));\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n std::cout << i << \" \" << d[i] << std::endl;\n }\n}\n\nint main() {\n int k, u, v, c;\n\n std::cin >> n;\n adj.resize(n); // allocate exactly n nodes\n\n for (int i = 0; i < n; i++) {\n std::cin >> u >> k;\n for (int j = 0; j < k; j++) {\n std::cin >> v >> c;\n adj[u].emplace_back(v, c);\n }\n }\n\n dijkstra();\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8332, "score_of_the_acc": -0.3752, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_12_C_10676693", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility> // for std::pair\n\n// global variables\nstatic const int N = 1000;\nstatic const int INFTY = (1 << 21);\n\nint n;\nstd::vector<std::pair<int, int>> adj[N]; // adjacency list: [(neighbor, cost),...]\nint d[N];\n\n// algorithm\nvoid dijkstra() {\n std::priority_queue<std::pair<int, int>,\n std::vector<std::pair<int, int>>,\n std::greater<std::pair<int, int>>> pq;\n\n for (int i = 0; i < n; i++) {\n d[i] = INFTY;\n }\n d[0] = 0;\n pq.push(std::make_pair(0, 0)); // (distance, vertex)\n\n while (!pq.empty()) {\n std::pair<int, int> top = pq.top();\n pq.pop();\n\n int dist_u = top.first;\n int u = top.second;\n\n if (dist_u > d[u]) continue; // outdated entry\n\n for (size_t i = 0; i < adj[u].size(); i++) {\n std::pair<int, int> edge = adj[u][i];\n int v = edge.first;\n int cost = edge.second;\n\n if (d[u] + cost < d[v]) {\n d[v] = d[u] + cost;\n pq.push(std::make_pair(d[v], v));\n }\n }\n }\n\n // Output result\n for (int i = 0; i < n; i++) {\n std::cout << i << \" \" << d[i] << std::endl;\n }\n}\n\nint main() {\n int k, u, v, c;\n\n std::cin >> n;\n for (int i = 0; i < n; i++) {\n std::cin >> u >> k;\n for (int j = 0; j < k; j++) {\n std::cin >> v >> c;\n adj[u].emplace_back(v, c);\n }\n }\n\n dijkstra();\n}", "accuracy": 0.875, "time_ms": 110, "memory_kb": 8244, "score_of_the_acc": -0.371, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_12_C_10625860", "code_snippet": "#include <iostream>\n#include <string>\n#include <map>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <stack>\n#include <limits.h>\nusing namespace std;\n\nenum VisitColor {\n WHITE,\n GRAY,\n BLACK\n};\n\nint main() {\n int n;\n int o; // 出次数(隣接点の数)\n int p; // 頂点の番号\n //int M[100][100];\n vector<vector<pair<int, int>>>M; // 隣接する点の番号・辺の重みをMに点毎に格納する\n M.resize(10000);\n priority_queue<pair<int, int>> PQ; // キューを構成するペアの1つ目は、点への最短距離 2つ目は点の番号\n int color[10000]; // 各点の訪問状態\n\n int d[10000]; // 始点から各点への最短距離を格納する配列\n\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> p >> o;\n for (int j = 0; j < o; j++) {\n pair<int, int> tmpPair;\n\n // 隣接点番号, 隣接点への辺の重みを入力\n cin >> tmpPair.first >> tmpPair.second;\n M[i].push_back(tmpPair); // 隣接リストを構成する\n }\n\n d[i] = INT_MAX; // 最終的に最小値が入るため、大きな値に初期化\n color[i] = WHITE; // 全ての点を未訪問に初期化\n }\n\n // 0番目の点から探索をスタートする\n d[0] = 0; // 最初は、始点から始点に探索すると考える。始点から始点のコストは0\n color[0] = GRAY;\n\n // プライオリティーキューの初期化\n PQ.push(make_pair(0, 0)); //始点への最短距離, 始点番号\n\n // PQが空になるまで続く\n // PQには、最短経路木Tと、Tに隣接する点への距離と点の番号が格納されている。\n // PQが空→PQのトップには、最短経路木Tと、Tに隣接する点の中で、最短距離をとる点への距離と、その点の番号が格納されているが、これが全てなくなると、全ての点への最短距離が確定したことになる\n while (!PQ.empty()) {\n pair<int, int> minPair = PQ.top();\n PQ.pop();\n\n int u = minPair.second; // 最短経路木に隣接する点の中で最短距離をとる点を起点として探索を行う\n color[u] = BLACK; // 訪問済み\n\n //if(d[u] < minPair.first * (-1)) continue;\n\n // uを起点として隣接点へ探索を行う\n for (int i = 0; i < M[u].size(); i++) {\n int v = M[u][i].first;\n\n // vへ未訪問\n if (color[v] != BLACK) {\n // vへの最短距離更新\n if (d[v] > d[u] + M[u][i].second) { // ここでアウト\n d[v] = d[u] + M[u][i].second;\n color[v] = GRAY; // 探索済み\n\n // キュー更新\n PQ.push(make_pair(d[v] * (-1), v));\n }\n }\n }\n }\n\n // 各点への最短距離が求まったため。結果を出力する\n int sum = 0;\n for (int i = 0; i < n; i++) {\n cout << i << \" \" << d[i] << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 8324, "score_of_the_acc": -0.4149, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_12_C_10534674", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<queue>\nusing namespace std;\nstatic const int MAX = 10000;\nstatic const int INFTY = (1 << 20);\nstatic const int WHITE = 0;\nstatic const int GRAY = 1;\nstatic const int BLACK = 2;\n\nint n;\nvector<pair<int, int>> adj[MAX];\n\nvoid dijkstra() {\n priority_queue<pair<int, int>> PQ;\n int color[MAX];\n int d[MAX];\n for (int i = 0; i < n; i++) {\n d[i] = INFTY;\n color[i] = WHITE;\n }\n \n d[0] = 0;\n PQ.push(make_pair(0, 0));\n color[0] = GRAY;\n\n while (!PQ.empty())\n {\n pair<int, int> f = PQ.top(); PQ.pop();\n int u = f.second;\n color[u] = BLACK;\n\n if (d[u] < f.first * (-1)) continue;\n\n for (int j = 0; j < adj[u].size(); j++) {\n int v = adj[u][j].first;\n if (color[v] == BLACK) continue;\n if (d[v] > d[u] + adj[u][j].second) {\n d[v] = d[u] + adj[u][j].second;\n PQ.push(make_pair(d[v] * (-1), v));\n color[v] = GRAY;\n }\n }\n }\n \n for (int i = 0; i < n; i++) {\n cout << i << \" \" << (d[i] == INFTY ? -1 : d[i] ) << endl;\n }\n}\n\nint main() {\n int k, u, v, c;\n \n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> u >> k;\n for (int j = 0; j < k; j++) {\n cin >> v >> c;\n adj[u].push_back(make_pair(v, c));\n }\n }\n\n dijkstra();\n \n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8288, "score_of_the_acc": -0.3731, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_12_C_10512374", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n vector<vector<pair<unsigned int, int>>> routes(n); // <cost, destination>\n for (int i = 0; i < n; i++)\n {\n int start, num;\n cin >> start >> num;\n for (int j = 0; j < num; j++)\n {\n unsigned int cost;\n int dest;\n cin >> dest >> cost;\n routes[start].push_back(pair<unsigned int, int>(cost, dest));\n }\n }\n\n vector<unsigned int> distances(n, -1); // ノードまでの距離一覧\n vector<bool> explored(n); // 探索したノード一覧\n distances[0] = 0;\n explored[0] = true;\n int explored_num = 1;\n int currentNode = 0;\n priority_queue<pair<unsigned int, int>, vector<pair<unsigned int, int>>, greater<>> pq; // <cost, dest>\n\n while (explored_num != n)\n {\n for (auto [cost, dest] : routes[currentNode])\n {\n // 保存したコストより「道中のコスト+対象までのコスト」の方が小さいかつ未探索の場合は更新\n if (distances[dest] > distances[currentNode] + cost && !explored[dest])\n {\n distances[dest] = distances[currentNode] + cost;\n pq.push({distances[dest], dest});\n }\n }\n while (true)\n {\n auto [cost, dest] = pq.top();\n pq.pop();\n if (!explored[dest])\n {\n currentNode = dest;\n explored[dest] = true;\n explored_num++;\n break;\n }\n }\n }\n\n for (int i = 0; i < n; i++)\n {\n cout << i << \" \" << distances[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8236, "score_of_the_acc": -0.3706, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_12_C_10512373", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n vector<vector<pair<unsigned int, int>>> routes(n); // <cost, destination>\n for (int i = 0; i < n; i++)\n {\n int start, num;\n cin >> start >> num;\n for (int j = 0; j < num; j++)\n {\n unsigned int cost;\n int dest;\n cin >> dest >> cost;\n routes[start].push_back(pair<unsigned int, int>(cost, dest));\n }\n }\n\n vector<unsigned int> destances(n, -1); // ノードまでの距離一覧\n vector<bool> explored(n); // 探索したノード一覧\n destances[0] = 0;\n explored[0] = true;\n int explored_num = 1;\n int currentNode = 0;\n priority_queue<pair<unsigned int, int>, vector<pair<unsigned int, int>>, greater<>> pq; // <cost, dest>\n\n while (explored_num != n)\n {\n for (auto [cost, dest] : routes[currentNode])\n {\n // 保存したコストより「道中のコスト+対象までのコスト」の方が小さいかつ未探索の場合は更新\n if (destances[dest] > destances[currentNode] + cost && !explored[dest])\n {\n destances[dest] = destances[currentNode] + cost;\n pq.push({destances[dest], dest});\n }\n }\n while (true)\n {\n auto [cost, dest] = pq.top();\n pq.pop();\n if (!explored[dest])\n {\n currentNode = dest;\n explored[dest] = true;\n explored_num++;\n break;\n }\n }\n }\n\n for (int i = 0; i < n; i++)\n {\n cout << i << \" \" << destances[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8248, "score_of_the_acc": -0.3712, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_12_C_10512363", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n vector<vector<pair<unsigned int, int>>> routes(n); // <cost, dist>\n for (int i = 0; i < n; i++)\n {\n int start, num;\n cin >> start >> num;\n for (int j = 0; j < num; j++)\n {\n unsigned int cost;\n int dist;\n cin >> dist >> cost;\n routes[start].push_back(pair<unsigned int, int>(cost, dist));\n }\n }\n\n vector<unsigned int> distances(n, -1); // ノードまでの距離一覧\n vector<bool> explored(n); // 探索したノード一覧\n distances[0] = 0;\n explored[0] = true;\n int explored_num = 1;\n int currentNode = 0;\n priority_queue<pair<unsigned int, int>, vector<pair<unsigned int, int>>, greater<>> pq; // <cost, dist>\n\n while (explored_num != n)\n {\n for (auto [cost, dist] : routes[currentNode])\n {\n // 保存したコストより「道中のコスト+対象までのコスト」の方が小さいかつ未探索の場合は更新\n if (distances[dist] > distances[currentNode] + cost && !explored[dist])\n {\n distances[dist] = distances[currentNode] + cost;\n pq.push({distances[dist], dist});\n }\n }\n while (true)\n {\n auto [cost, dist] = pq.top();\n pq.pop();\n if (!explored[dist])\n {\n currentNode = dist;\n explored[dist] = true;\n explored_num++;\n break;\n }\n }\n }\n\n for (int i = 0; i < n; i++)\n {\n cout << i << \" \" << distances[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8236, "score_of_the_acc": -0.3706, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_12_C_10504337", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n vector<vector<pair<unsigned int, int>>> routes(n); // <cost, dist>\n for (int i = 0; i < n; i++)\n {\n int start, num;\n cin >> start >> num;\n for (int j = 0; j < num; j++)\n {\n unsigned int cost;\n int dist;\n cin >> dist >> cost;\n routes[start].push_back(pair<unsigned int, int>(cost, dist));\n }\n }\n\n vector<unsigned int> distances(n, -1); // ノードまでの距離一覧\n vector<bool> explored(n); // 探索したノード一覧\n distances[0] = 0;\n explored[0] = true;\n int explored_num = 1;\n int currentNode = 0;\n priority_queue<pair<unsigned int, int>, vector<pair<unsigned int, int>>, greater<>> pq; // <cost, dist>\n\n while (explored_num != n)\n {\n for (pair<unsigned int, int> route : routes[currentNode])\n {\n unsigned int cost = route.first;\n int dist = route.second;\n // 保存したコストより「道中のコスト+対象までのコスト」の方が小さいかつ未探索の場合は更新\n if (distances[dist] > distances[currentNode] + cost && !explored[dist])\n {\n distances[dist] = distances[currentNode] + cost;\n pq.push({distances[dist], dist});\n }\n }\n while (true)\n {\n pair<int, unsigned int> p = pq.top();\n int dist = p.second;\n pq.pop();\n if (!explored[dist])\n {\n currentNode = dist;\n explored[dist] = true;\n explored_num++;\n break;\n }\n }\n }\n\n for (int i = 0; i < n; i++)\n {\n cout << i << \" \" << distances[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 8092, "score_of_the_acc": -0.3637, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_12_C_10504109", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n vector<vector<pair<unsigned int, unsigned>>> routes(n); // <dist, cost>\n for (int i = 0; i < n; i++)\n {\n int start, num;\n cin >> start >> num;\n for (int j = 0; j < num; j++)\n {\n unsigned int dist, cost;\n cin >> dist >> cost;\n routes[start].push_back(pair<unsigned int, unsigned int>(dist, cost));\n }\n }\n\n vector<unsigned int> distances(n, -1); // ノードまでの距離一覧\n vector<bool> explored(n); // 探索したノード一覧\n distances[0] = 0;\n explored[0] = true;\n int explored_num = 1;\n int currentNode = 0;\n\n while (explored_num != n)\n {\n for (pair<unsigned int, unsigned> route : routes[currentNode])\n {\n unsigned int dist = route.first;\n unsigned int cost = route.second;\n // 保存したコストより「道中のコスト+対象までのコスト」の方が小さいかつ未探索の場合は更新\n if (distances[dist] > distances[currentNode] + cost && !explored[dist])\n {\n distances[dist] = distances[currentNode] + cost;\n }\n }\n int minNode = -1;\n unsigned int min = -1;\n for (int i = 0; i < n; i++)\n {\n // 未探索で最小のノードを取得\n if (!explored[i] && distances[i] < min)\n {\n min = distances[i];\n minNode = i;\n }\n }\n currentNode = minNode;\n explored[minNode] = true;\n explored_num++;\n }\n\n for (int i = 0; i < n; i++)\n {\n cout << i << \" \" << distances[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 8132, "score_of_the_acc": -1.0457, "final_rank": 19 } ]
aoj_ALDS1_11_D_cpp
Connected Components Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network. Input In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$. In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other). In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character. Output For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise. Constraints $2 \leq n \leq 100,000$ $0 \leq m \leq 100,000$ $1 \leq q \leq 10,000$ Sample Input 10 9 0 1 0 2 3 4 5 7 5 6 6 7 6 8 7 8 8 9 3 0 1 5 9 1 3 Sample Output yes yes no
[ { "submission_id": "aoj_ALDS1_11_D_11066465", "code_snippet": "#include <iostream>\n#include <vector>\n#include <stack>\nusing namespace std;\nstatic const int MAX = 100000;\nstatic const int NIL = -1;\n\nint n;\nvector<int> G[MAX];\nint color[MAX];\n\nvoid dfs(int r, int c) {\n stack<int> S;\n S.push(r);\n color[r] = c;\n while ( !S.empty() ) {\n int u = S.top(); S.pop();\n for ( int i = 0; i < G[u].size(); i++ ) {\n int v = G[u][i];\n if ( color[v] == NIL ) {\n color[v] = c;\n S.push(v);\n }\n }\n }\n}\n\nvoid assignColor() {\n int id = 1;\n for ( int i = 0; i < n; i++ ) color[i] = NIL;\n for ( int u = 0; u < n; u++ ) {\n if ( color[u] == NIL ) dfs(u, id++);\n }\n}\n\nint main() {\n int s, t, m, q;\n\n cin >> n >> m;\n\n for ( int i = 0; i < m; i++ ) {\n cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n assignColor();\n\n cin >> q;\n\n for ( int i = 0; i < q; i++ ) {\n cin >> s >> t;\n if ( color[s] == color[t] ) {\n cout << \"yes\" << \"\\n\";\n } else {\n cout << \"no\" << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 9124, "score_of_the_acc": -0.4212, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_11_D_11044845", "code_snippet": "#include<iostream>\n#include<vector>\n#include<stack>\nusing namespace std;\nstatic const int MAX = 100000;\nstatic const int NIL = -1;\n\nint n;\nvector<int> G[MAX];\nint color[MAX];\n\nvoid dfs(int r, int c){\n stack<int> S;\n S.push(r);\n color[r] = c;\n while(!S.empty()){\n int u = S.top();\n S.pop();\n for(int i = 0; i < G[u].size() ; i++){\n int v = G[u][i];\n if(color[v] == NIL){\n color[v] = c;\n S.push(v);\n }\n }\n }\n}\n\nvoid assingColor(){\n int id = 1;\n for(int i = 0; i < n; i++) color[i] = NIL;\n for(int u = 0; u < n; u++){\n if(color[u] == NIL) dfs(u,id++);\n }\n}\n\nint main(){\n int s, t, m ,q;\n\n cin >> n >> m;\n\n for(int i = 0; i < m; i++){\n cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n assingColor();\n\n cin >> q;\n\n for(int i = 0; i < q; i++){\n cin >> s >> t;\n if(color[s] == color[t]){\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n \n}", "accuracy": 1, "time_ms": 40, "memory_kb": 9224, "score_of_the_acc": -0.428, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_11_D_11033589", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n vector<vector<int>> adj(n);\n int m;\n cin >> m;\n for(int i = 0; i < m; i++)\n {\n int s, t;\n cin >> s >> t;\n adj[s].push_back(t);\n adj[t].push_back(s);\n }\n\n vector<int> group(n, -1);\n int group_count = 0;\n bool finished = false;\n stack<int> a;\n while(!finished)\n {\n finished = true;\n for(int i = 0; i < n; i++)\n {\n if (group[i] == -1)\n {\n a.push(i);\n finished = false;\n break;\n }\n }\n\n while(a.size() != 0)\n {\n int v = a.top();\n a.pop();\n group[v] = group_count;\n for(int u : adj[v])\n if(group[u] == -1)\n a.push(u);\n }\n\n group_count++;\n }\n \n int q;\n cin >> q;\n deque<bool> result(q, false);\n for(int query = 0; query < q; query++)\n {\n int s, t;\n cin >> s >> t;\n if (group[s] == group[t])\n result[query] = true;\n }\n\n for(bool r : result)\n {\n if(r)\n cout << \"yes\" << endl;\n else\n cout << \"no\" << endl;\n }\n}", "accuracy": 1, "time_ms": 530, "memory_kb": 8724, "score_of_the_acc": -1.3366, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_11_D_10945586", "code_snippet": "#include <cstdio>\n#include <vector>\n#include <iterator>\n#define NIL -1\n#define max 100000\nusing namespace std;\nint n;\nvector<int> g[max];\nint color[max];\nint c;\nvoid search(int a){\n color[a]=c;\n for(int i=0;i<(int)g[a].size();i++){\n if(color[g[a][i]]==NIL){\n search(g[a][i]);\n }\n }\n return;\n}\nint main(void){\n scanf(\"%d\",&n);\n int m;\n for(int i=0;i<n;i++){\n color[i]=NIL;\n }\n c=0;\n scanf(\"%d\",&m);\n for(int i=0;i<m;i++){\n int s,t;\n scanf(\"%d %d\",&s,&t);\n g[s].push_back(t);\n g[t].push_back(s);\n }\n for(int i=0;i<n;i++){\n if(color[i]==NIL){\n search(i);\n c++;\n }\n }\n int q;\n scanf(\"%d\",&q);\n for(int i=0;i<q;i++){\n int d,f;\n scanf(\"%d %d\",&d,&f);\n if(color[d]==color[f]){\n printf(\"yes\\n\");\n }else printf(\"no\\n\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11868, "score_of_the_acc": -0.5485, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_11_D_10919984", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n, m;\n cin >> n >> m;\n vector<vector<int>> g(n, vector<int>());\n for (int i = 0; i < m; i++) {\n int a, b;\n cin >> a >> b;\n g[a].push_back(b);\n g[b].push_back(a);\n }\n vector<int> colors(n, 0);\n queue<int> que;\n int cnt = 0;\n for (int i = 0; i < n; i++) {\n if (colors[i] != 0) continue;\n cnt++;\n que.push(i);\n while (!que.empty()) {\n int cur = que.front();\n que.pop();\n colors[cur] = cnt;\n for (auto nex : g[cur]) {\n if (colors[nex] == 0) {\n colors[nex] = cnt;\n que.push(nex);\n }\n }\n }\n }\n int q;\n cin >> q;\n for (int i = 0; i < q; i++) {\n int s, t;\n cin >> s >> t;\n cout << (colors[s] == colors[t] ? \"yes\" : \"no\") << '\\n';\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 9204, "score_of_the_acc": -0.4074, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_11_D_10893254", "code_snippet": "#include <iostream>\n#include <vector>\n#include <stack>\n\nint n;\nconst int MAXN = 100000;\nstd::vector<int> G[MAXN];\nint color[MAXN];\nconst int NIL = -1;\n\nvoid dfs(int u, int c)\n{\n std::stack<int> si;\n si.push(u);\n color[u] = c;\n while (!si.empty()) {\n int v = si.top();\n si.pop();\n for (int i = 0; i < G[v].size(); ++i) {\n if (color[G[v][i]] == NIL) {\n color[G[v][i]] = c;\n si.push(G[v][i]);\n }\n }\n }\n}\n\nvoid assign_color() {\n for (int i = 0; i < n; ++i) color[i] = NIL;\n\n int c = 1;\n for (int i = 0; i < n; ++i) {\n if (color[i] == NIL) {\n dfs(i, c++);\n }\n }\n}\n\nint main()\n{\n int m;\n std::cin >> n >> m;\n for (int i = 0; i < m; ++i) {\n int s, t;\n std::cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n assign_color();\n\n int q;\n std::cin >> q;\n for (int i = 0; i < q; ++i) {\n int s, t;\n std::cin >> s >> t;\n if (color[s] == color[t]) {\n std::cout << \"yes\";\n } else {\n std::cout << \"no\";\n }\n std::cout << std::endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 9172, "score_of_the_acc": -0.4245, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_11_D_10874158", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nstruct unionfind{\n vector<int> par,size;\n unionfind(int n):par(n),size(n){\n for(int i=0;i<n;i++)par[i]=i;\n }\n int find(int x){\n if(par[x]==x)return x;\n return par[x]=find(par[x]);\n }\n bool unite(int x,int y){\n x=find(x);\n y=find(y);\n if(x==y)return false;\n if(size[x]<size[y])swap(x,y);\n par[y]=x;\n size[x]+=size[y];\n return true;\n }\n bool same(int a,int b){\n return find(a)==find(b);\n }\n};\nint main(){\n int n,m;\n cin >> n >> m;\n unionfind uf(n+1);\n for(int i=0;i<m;i++){\n int a,b;\n cin >> a >> b;\n uf.unite(a,b);\n }\n int q;\n cin >> q;\n for(int i=0;i<q;i++){\n int a,b;\n cin >> a >> b;\n if(uf.same(a,b))cout << \"yes\" << endl;\n else cout << \"no\" << endl;\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3860, "score_of_the_acc": -0.0663, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_11_D_10870306", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define rep2(i, s, n) for (ll i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nint minval(vector<ll> vec) {\n return *min_element(begin(vec), end(vec));\n}\nint maxval(vector<ll> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\nll n;\nvector<ll> G[100000];\nll color[1000000];\n\nvoid dfs(ll r, ll c) {\n stack<ll> s;\n s.push(r);\n color[r] = c;\n while (!s.empty()) {\n ll u = s.top();\n s.pop();\n rep(i,G[u].size()) {\n ll v = G[u][i];\n if (color[v] == -1) {\n color[v] = c;\n s.push(v);\n }\n }\n }\n}\n\nvoid solve() {\n ll m, s, t, q;\n cin >> n >> m;\n rep(i,m) {\n cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n ll id = 1;\n rep(i,n) {\n color[i] = -1;\n }\n rep(u, n) {\n if (color[u] == -1) {\n dfs(u, id++);\n }\n }\n cin >> q;\n rep(i,q) {\n cin >> s >> t;\n if (color[s] == color[t]) {\n cout << \"yes\" << endl;\n }\n else {\n cout << \"no\" << endl;\n }\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 11848, "score_of_the_acc": -0.5857, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_11_D_10853863", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <cmath>\n#include <cstdlib>\nusing namespace std;\n\nconst int MAX = 100010;\nint v, e;\nvector<int> G[MAX];\nint q;\nint color[MAX];\nint c;\n\nvoid dfs(int p, int co) {\n if (color[p] != -1) return ;\n color[p] = co;\n for (int i = 0; i < G[p].size(); i++) {\n int node = G[p][i];\n dfs(node, co);\n }\n}\n\nint main() {\n //freopen(\"in.txt\", \"r\", stdin);\n //freopen(\"out.txt\", \"w\", stdout);\n scanf(\"%d %d\", &v, &e);\n for (int i = 0; i < e; i++) {\n int a, b;\n scanf(\"%d %d\", &a, &b);\n G[a].push_back(b);\n G[b].push_back(a);\n }\n memset(color, -1, sizeof(color));\n c = 0;\n for (int i = 0; i < v; i++) {\n if (color[i] == -1) {\n dfs(i, c++);\n }\n }\n scanf(\"%d\", &q);\n while (q--) {\n int a, b;\n scanf(\"%d %d\", &a, &b);\n if (color[a] == color[b]) printf(\"yes\\n\");\n else printf(\"no\\n\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 12468, "score_of_the_acc": -0.589, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_11_D_10842870", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\n\nint main()\n{\n int n,m;\n cin >> n >> m;\n vector<vector<int>> to(n);\n rep(i,m) {\n int s, t;\n cin >> s >> t;\n to[s].push_back(t);\n to[t].push_back(s);\n }\n vector<int> color(n, -1);\n vector<bool> visited(n);\n auto dfs = [&] (auto f, int v, int c) -> void {\n if (visited[v]) return;\n visited[v] = true;\n color[v] = c;\n for (int x : to[v]) {\n f(f, x, c);\n }\n };\n\n int g = 0;\n rep(i,n) {\n if (!visited[i]) {\n dfs(dfs,i,g);\n g++;\n }\n }\n\n int q;\n cin >> q;\n rep(qi,q) {\n int s,t;\n cin >> s >> t;\n if (color[s] == -1 || color[t] == -1 || color[s] != color[t]) cout << \"no\\n\";\n else cout << \"yes\\n\";\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 15256, "score_of_the_acc": -0.8539, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_11_D_10740367", "code_snippet": "#include<iostream>\n#include<vector>\n#include<stack>\nusing namespace std;\nstatic const int MAX = 100000;\nstatic const int NIL = -1;\n\nint n;\nvector<int> G[MAX];\nint color[MAX];\n\nvoid dfs(int r, int c){\n stack<int> S;\n S.push(r);\n color[r] = c;\n while(!S.empty()){\n int u = S.top();\n S.pop();\n for(int i=0; i < G[u].size(); i++){\n int v = G[u][i];\n if(color[v] == NIL){\n color[v] = c;\n S.push(v);\n }\n }\n }\n}\n\nvoid assignColor(){\n int id=1;\n for(int i=0; i < n; i++){\n color[i] = NIL;\n }\n for(int i=0; i < n; i++){\n if(color[i] == NIL){\n dfs(i, id++);\n }\n }\n}\n\nint main(){\n int s,t,m,q;\n cin >> n >> m;\n\n for(int i=0; i < m; i++){\n cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n assignColor();\n cin >> q;\n for(int i=0; i < q; i++){\n cin >> s >> t;\n if(color[s] == color[t]){\n cout << \"yes\" << endl;\n } else {\n cout << \"no\" << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 9232, "score_of_the_acc": -0.4285, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_11_D_10739106", "code_snippet": "#include<iostream>\n#include<vector>\n#include<stack>\n#include<set>\n\nusing namespace std;\nstatic const int NIL = -1;\nstatic const int N_MAX = 100000;\n\nvector<int> friends[N_MAX];\nint colors[N_MAX];\n\nvoid dfs(int a, int color) {\n // aから友達関係を辿りbに辿り着けるかどうか\n stack<int> visit;\n set<int> visited;\n\n visit.push(a);\n // cout << visit.empty() << endl;\n while(!visit.empty()) {\n int c = visit.top();\n visit.pop();\n // cにまず色をつける\n colors[c] = color;\n // cと直接繋がっているユーザをpushしていく\n for(vector<int>::iterator it=friends[c].begin(); it != friends[c].end(); it++) {\n \n if(colors[(*it)] == NIL)\n visit.push((*it)); \n }\n }\n}\n\n\nvoid assignColor(int n) {\n // すべてのユーザーを、繋がってる順に色分け\n for(int i=0; i<n; i++ ) {\n colors[i] = NIL;\n }\n int color = 0;\n for(int i=0; i<n; i++){\n // すでにいずれかのグループに属している場合、スキップ\n if(colors[i] != NIL) continue;\n dfs(i, color++);\n }\n}\n\n\nint main() {\n int n, m;\n\n cin >> n >> m;\n\n int from, to;\n for(int i=0; i<m; i++) {\n scanf(\"%d %d\", &from, &to);\n friends[from].push_back(to);\n friends[to].push_back(from);\n }\n\n assignColor(n);\n // for(int i=0; i<n; i++){\n // cout << i << \": \" << colors[i] << endl;\n // }\n int q;\n cin >> q;\n for(int i=0; i<q; i++){\n scanf(\"%d %d\", &from, &to);\n if(colors[from] == colors[to]) {\n cout << \"yes\" << endl;\n }else{\n cout << \"no\" << endl;\n }\n }\n\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 9220, "score_of_the_acc": -0.3892, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_11_D_10737720", "code_snippet": "#include <stdio.h>\n\n#define MAX_N 100000\n\nint parent[MAX_N];\n\n// Union-Find木を初期化\nvoid init(int n) {\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n}\n\n// 木の根を求める (経路圧縮あり)\nint find(int x) {\n if (parent[x] == x) {\n return x;\n } else {\n // 親を根に直接つなぎ替える(経路圧縮)\n return parent[x] = find(parent[x]);\n }\n}\n\n// xとyの属する集合を併合\nvoid unite(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n parent[rootX] = rootY;\n }\n}\n\n// xとyが同じ集合に属するか判定\nint same(int x, int y) {\n return find(x) == find(y);\n}\n\nint main() {\n int n, m, s, t, q;\n\n scanf(\"%d %d\", &n, &m);\n init(n);\n\n for (int i = 0; i < m; i++) {\n scanf(\"%d %d\", &s, &t);\n unite(s, t);\n }\n\n scanf(\"%d\", &q);\n for (int i = 0; i < q; i++) {\n scanf(\"%d %d\", &s, &t);\n if (same(s, t)) {\n printf(\"yes\\n\");\n } else {\n printf(\"no\\n\");\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3736, "score_of_the_acc": -0.0003, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_11_D_10737709", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\n// Union-Find用の構造体\nstruct UnionFind {\n vector<int> parent, rank;\n\n UnionFind(int n) {\n parent.resize(n);\n rank.resize(n, 0);\n // 最初は各ノードが自分自身を親として持つ\n for (int i = 0; i < n; ++i) {\n parent[i] = i;\n }\n }\n\n // find関数:経路圧縮を使って親を探す\n int find(int x) {\n if (parent[x] != x) {\n parent[x] = find(parent[x]); // 経路圧縮\n }\n return parent[x];\n }\n\n // union関数:2つの集合を統合する(ランクによる)\n void unionSets(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n\n if (rootX != rootY) {\n // ランクが低い方を高い方にくっつける\n if (rank[rootX] > rank[rootY]) {\n parent[rootY] = rootX;\n } else if (rank[rootX] < rank[rootY]) {\n parent[rootX] = rootY;\n } else {\n parent[rootY] = rootX;\n rank[rootX]++;\n }\n }\n }\n};\n\nint main() {\n int n, m;\n cin >> n >> m;\n\n // Union-Findの初期化\n UnionFind uf(n);\n\n // 友達関係の入力\n for (int i = 0; i < m; ++i) {\n int s, t;\n cin >> s >> t;\n uf.unionSets(s, t);\n }\n\n int q;\n cin >> q;\n\n // 質問の処理\n for (int i = 0; i < q; ++i) {\n int s, t;\n cin >> s >> t;\n if (uf.find(s) == uf.find(t)) {\n cout << \"yes\" << endl;\n } else {\n cout << \"no\" << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3836, "score_of_the_acc": -0.0647, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_11_D_10737688", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nstruct UnionFind {\n vector<int> parent, rank;\n UnionFind(int n) {\n parent.resize(n);\n rank.assign(n, 0);\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n int find(int x) {\n if (parent[x] == x) return x;\n return parent[x] = find(parent[x]); \n }\n void unite(int x, int y) {\n int rx = find(x), ry = find(y);\n if (rx == ry) return;\n if (rank[rx] < rank[ry]) parent[rx] = ry;\n else {\n parent[ry] = rx;\n if (rank[rx] == rank[ry]) rank[rx]++;\n }\n }\n bool same(int x, int y) {\n return find(x) == find(y);\n }\n};\n\nint main() {\n int n, m;\n cin >> n >> m;\n UnionFind uf(n);\n for (int i = 0; i < m; i++) {\n int s, t;\n cin >> s >> t;\n uf.unite(s, t);\n }\n int q;\n cin >> q;\n for (int i = 0; i < q; i++) {\n int s, t;\n cin >> s >> t;\n if (uf.same(s, t)) cout << \"yes\" << endl;\n else cout << \"no\" << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3876, "score_of_the_acc": -0.0482, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_11_D_10719760", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nconst int N=1e5+5;\nvector<int>E[N];\nint n,type[N],idx=0,m;\nvoid bfs(int u){\n int t=idx++;\n queue<int>q;\n q.push(u);\n type[u]=t;\n while(!q.empty()){\n int u=q.front();q.pop();\n for(auto v:E[u]){\n if(type[v]!=-1) continue;\n type[v]=t;\n q.push(v);\n }\n }\n}\nvoid solve(){\n cin>>n>>m;\n for(int i=0;i<m;i++){\n int u,v;cin>>u>>v;\n E[u].push_back(v);\n E[v].push_back(u);\n }\n for(int i=0;i<n;i++) type[i]=-1;\n for(int i=0;i<n;i++){\n if(type[i]!=-1) continue;\n bfs(i);\n }\n int q;cin>>q;\n while(q--){\n int u,v;cin>>u>>v;\n if(type[u]==type[v]) cout<<\"yes\"<<endl;\n else cout<<\"no\"<<endl;\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 10040, "score_of_the_acc": -0.4445, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_11_D_10716363", "code_snippet": "#include <iostream>\n#include <climits>\n#include <vector>\n#include <stack>\n#include <algorithm>\n#include <memory>\n#include <string>\n#include <cmath>\n#include <iomanip>\n#include <array>\nusing namespace std;\n\n#define MAX (100001)\n\n\nint getNext(vector<vector<int> > &graph, vector<int> &g_ifsearch, vector<int> &g_next, int n, int id)\n{\n int size = graph[id].size();\n for (int i = g_next[id]; i < size; ++i)\n {\n int sid = graph[id][i];\n if (g_ifsearch[sid] == 0)\n {\n ++g_next[id];\n return graph[id][i];\n } \n }\n return -1;\n}\n\nint depthSearch(vector<vector<int> > &graph, vector<int> &g_ifsearch, vector<int> &g_next, int n, int id, int color)\n{\n stack<int> s;\n int next = 0;\n int top = 0;\n s.push(id);\n while (!s.empty())\n {\n top = s.top();\n g_ifsearch[top] = color;\n next = getNext(graph, g_ifsearch, g_next, n, top);\n if (next == -1)\n {\n s.pop();\n }\n else\n {\n s.push(next);\n }\n }\n return 0;\n}\n\n\nint main()\n{\n int n = 0, m = 0, p = 0;\n int id = 0;\n int result = 0;\n int color = 1;\n cin >> n;\n vector<vector<int> > graph(n);\n vector<int> g_ifsearch(n);\n vector<int> g_next(n);\n cin >> m;\n for (int i = 0; i < m; ++i)\n {\n int r = 0, c = 0;\n cin >> r;\n cin >> c;\n graph[r].push_back(c);\n graph[c].push_back(r);\n }\n for (int i = 0; i < n; ++i)\n {\n if (g_ifsearch[i] == 0)\n {\n depthSearch(graph, g_ifsearch, g_next, n, i, ++color);\n }\n }\n\n cin >> p;\n for (int i = 0; i < p; ++i)\n {\n int c1 = 0, c2 = 0;\n cin >> c1;\n cin >> c2;\n cout << ((g_ifsearch[c1] == g_ifsearch[c2]) ? \"yes\" : \"no\") << endl;\n }\n // for (auto i : results)\n // {\n // cout << ((i == 1) ? \"yes\" : \"no\") << endl;\n // }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 9572, "score_of_the_acc": -0.4514, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_11_D_10534166", "code_snippet": "#include<iostream>\n#include<vector>\n#include<stack>\nusing namespace std;\nstatic const int MAX = 100000;\nstatic const int NIL = -1;\n\nint n;\nvector<int> G[MAX];\nint color[MAX];\n\nvoid dfs(int r, int c)\n{\n stack<int> S;\n S.push(r);\n color[r] = c;\n while (!S.empty())\n {\n int u = S.top(); S.pop();\n for (int i = 0; i < G[u].size(); i++) {\n int v = G[u][i];\n if (color[v] == NIL)\n {\n color[v] = c;\n S.push(v);\n }\n }\n }\n}\n\nvoid assignColors()\n{\n int id = 0;\n for (int i = 0; i < n; i++) color[i] = NIL;\n for (int u = 0; u < n; u++)\n {\n if (color[u] == NIL) dfs(u, id++);\n }\n}\n\n\nint main()\n{\n int s, t, m, q;\n\n cin >> n >> m;\n\n for (int i = 0; i < m; i++) {\n cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n assignColors();\n\n cin >> q;\n\n for (int i = 0; i < q; i++) {\n cin >> s >> t;\n if (color[s] == color[t]) {\n cout << \"yes\" << endl;\n } else {\n cout << \"no\" << endl;\n }\n }\n\n return 0;\n }", "accuracy": 1, "time_ms": 40, "memory_kb": 9220, "score_of_the_acc": -0.4277, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_11_D_10520451", "code_snippet": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nclass UnionFind {\npublic:\n vector<int> parent, rank;\n\n UnionFind(int n) {\n parent.resize(n);\n rank.resize(n, 0);\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n }\n\n int find(int x) {\n if (parent[x] != x) {\n parent[x] = find(parent[x]); // 経路圧縮\n }\n return parent[x];\n }\n\n void unite(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n if (rank[rootX] < rank[rootY]) {\n parent[rootX] = rootY;\n } else if (rank[rootX] > rank[rootY]) {\n parent[rootY] = rootX;\n } else {\n parent[rootY] = rootX;\n rank[rootX]++;\n }\n }\n }\n\n bool isConnected(int x, int y) {\n return find(x) == find(y);\n }\n};\n\nint main() {\n int n, m;\n cin >> n >> m;\n\n UnionFind uf(n);\n\n for (int i = 0; i < m; i++) {\n int a, b;\n cin >> a >> b;\n uf.unite(a, b);\n }\n\n int queryCount;\n cin >> queryCount;\n\n for (int i = 0; i < queryCount; i++) {\n int s, t;\n cin >> s >> t;\n\n if (uf.isConnected(s, t)) {\n cout << \"yes\" << endl;\n } else {\n cout << \"no\" << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3732, "score_of_the_acc": -0.0385, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_11_D_10513288", "code_snippet": "#include<iostream>\n#include<queue>\n#include<vector>\nusing namespace std;\n#define MAX_N 500000\nvector<int>X[MAX_N]; queue<int>Q;\nint COLOR[MAX_N], N, M, Q1, A, B;\nint main() {\n\tcin >> N >> M;\n\tfor (int i = 0; i < M; i++) { cin >> A >> B; X[A].push_back(B); X[B].push_back(A); }\n\tint cnt = 0;\n\tfor (int i = 0; i < N; i++) {\n\t\tif (COLOR[i] == 0) {\n\t\t\tQ.push(i); cnt++; COLOR[i] = cnt;\n\t\t\twhile (!Q.empty()) {\n\t\t\t\tint a = Q.front(); Q.pop();\n\t\t\t\tfor (int j = 0; j < X[a].size(); j++) {\n\t\t\t\t\tint to = X[a][j];\n\t\t\t\t\tif (COLOR[to] == 0) {\n\t\t\t\t\t\tCOLOR[to] = cnt;\n\t\t\t\t\t\tQ.push(to);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcin >> Q1;\n\tfor (int i = 0; i < Q1; i++) {\n\t\tcin >> A >> B;\n\t\tif (COLOR[A] == COLOR[B]) {\n\t\t\tcout << \"yes\" << endl;\n\t\t}\n\t\telse {\n\t\t\tcout << \"no\" << endl;\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 18564, "score_of_the_acc": -1.0577, "final_rank": 19 } ]
aoj_ALDS1_13_B_cpp
8 Puzzle The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space. In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below. 1 3 0 4 2 5 7 8 6 You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps). 1 2 3 4 5 6 7 8 0 Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle. Input The $3 \times 3$ integers denoting the pieces or space are given. Output Print the fewest steps in a line. Constraints There is a solution. Sample Input 1 3 0 4 2 5 7 8 6 Sample Output 4
[ { "submission_id": "aoj_ALDS1_13_B_11010942", "code_snippet": "#include <cstdio>\n#include <queue>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <iostream>\nconst int N=3;//计算零点的上下左右\nconst int N2=9;\nusing namespace std;\nstruct Puzzle{\n int f[N2];//拼图按顺序对应的数字\n int space;//零所在的位置\n string path;//对零点实施的各种操作\n bool operator <(const Puzzle&p) const {//定义一种比较规则,这样puzzle才能在map自动比较的数据结构作为键\n for(int i=0;i<N2;i++){\n if(f[i]==p.f[i]) continue;\n return f[i]>p.f[i];\n }\n return false;//所有元素都相等\n }\n};\nconst int dx[4]={-1,1,0,0};//i相同分别对应左右上下的操作\nconst int dy[4]={0,0,-1,1};\nconst char dir[4]={'l','r','u','d'};\nbool isTarget(Puzzle &p){\n for(int i=0;i<N2;i++){\n if(p.f[i]!=(i+1))//比较各个位置是不是放对位置,123...\n return false;\n }\n return true;\n}\nstring bfs(Puzzle s){\n Puzzle u,v;//u是队列开头,v用来更新队列\n map<Puzzle,bool> V;\n queue<Puzzle> Q;\n s.path=\"\";\n Q.push(s);\n V[s]=true;//访问过\n while(!Q.empty()){\n u=Q.front();Q.pop();\n if(isTarget(u)) return u.path;//拼好图后,返回操作最后转为size就是操作数\n int sx=u.space%N;//求出空格的x,y坐标,我把x弄成横的了,答案是竖的\n int sy=u.space/N;\n for(int r=0;r<4;r++){//对零的上下左右操作\n int tx=sx+dx[r];//求出操作空格的x,y坐标\n int ty=sy+dy[r];\n if(tx<0||ty<0||tx>=N||ty>=N) continue;\n v=u;\n swap(v.f[u.space],v.f[ty*N+tx]);//把操作后的空格移到正确的位置\n v.space=ty*N+tx;\n v.path+=dir[r];//加一步操作\n if(!V[v]){//看看操作后这样的排序有没有被访问过\n V[v]=true;\n Q.push(v);\n }\n }\n\n }\n return \"unsolvable\";//此题必有解,所以这个基本没用,但是有返回类型的函数结尾必须加这一句话\n}\nint main(){\n Puzzle in;\n for(int j=0;j<N2;j++){\n int c;\n scanf(\"%d\",&c);\n if(c==0){\n in.f[j]=N2;//零值变成N2才可以和上面对上\n in.space=j;\n }else in.f[j]=c;\n }\n string g=bfs(in);\n printf(\"%d\\n\",(int)g.size());\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 33728, "score_of_the_acc": -0.8549, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_13_B_11010941", "code_snippet": "#include <cstdio>\n#include <queue>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <iostream>\nconst int N=3;//计算零点的上下左右\nconst int N2=9;\nusing namespace std;\nstruct Puzzle{\n int f[N2];//拼图按顺序对应的数字\n int space;//零所在的位置\n string path;//对零点实施的各种操作\n bool operator <(const Puzzle&p) const {//定义一种比较规则,这样puzzle才能在map自动比较的数据结构作为键\n for(int i=0;i<N2;i++){\n if(f[i]==p.f[i]) continue;\n return f[i]>p.f[i];\n }\n return false;//所有元素都相等\n }\n};\nconst int dx[4]={-1,1,0,0};//i相同分别对应左右上下的操作\nconst int dy[4]={0,0,-1,1};\nconst char dir[4]={'l','r','u','d'};\nbool isTarget(Puzzle &p){\n for(int i=0;i<N2;i++){\n if(p.f[i]!=(i+1))//比较各个位置是不是放对位置,123...\n return false;\n }\n return true;\n}\nstring bfs(Puzzle s){\n Puzzle u,v;//u是队列开头,v用来更新队列\n map<Puzzle,bool> V;\n queue<Puzzle> Q;\n s.path=\"\";\n Q.push(s);\n V[s]=true;//访问过\n while(!Q.empty()){\n u=Q.front();Q.pop();\n if(isTarget(u)) return u.path;//拼好图后,返回操作最后转为size就是操作数\n int sx=u.space%N;//求出空格的x,y坐标,我把x弄成横的了,答案是竖的\n int sy=u.space/N;\n for(int r=0;r<4;r++){//对零的上下左右操作\n int tx=sx+dx[r];//求出操作空格的x,y坐标\n int ty=sy+dy[r];\n if(tx<0||ty<0||tx>=N||ty>=N) continue;\n v=u;\n swap(v.f[u.space],v.f[ty*N+tx]);//把操作后的空格移到正确的位置\n v.space=ty*N+tx;\n if(!V[v]){//看看操作后这样的排序有没有被访问过\n V[v]=true;\n v.path+=dir[r];//加一步操作\n Q.push(v);\n }\n }\n\n }\n return \"unsolvable\";//此题必有解,所以这个基本没用,但是有返回类型的函数结尾必须加这一句话\n}\nint main(){\n Puzzle in;\n for(int j=0;j<N2;j++){\n int c;\n scanf(\"%d\",&c);\n if(c==0){\n in.f[j]=N2;//零值变成N2才可以和上面对上\n in.space=j;\n }else in.f[j]=c;\n }\n string g=bfs(in);\n printf(\"%d\\n\",(int)g.size());\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 32692, "score_of_the_acc": -0.8366, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_13_B_10998550", "code_snippet": "#include <cstdio>\n#include <queue>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <iostream>\nconst int N=3;//计算零点的上下左右\nconst int N2=9;\nusing namespace std;\nstruct Puzzle{\n int f[N2];//拼图按顺序对应的数字\n int space;//零所在的位置\n string path;//对零点实施的各种操作\n bool operator <(const Puzzle&p) const {//定义一种比较规则,这样puzzle才能在map自动比较的数据结构作为键\n for(int i=0;i<N2;i++){\n if(f[i]==p.f[i]) continue;\n return f[i]>p.f[i];\n }\n return false;//所有元素都相等\n }\n};\nconst int dx[4]={-1,1,0,0};//i相同分别对应左右上下的操作\nconst int dy[4]={0,0,-1,1};\nconst char dir[4]={'l','r','u','d'};\nbool isTarget(Puzzle &p){\n for(int i=0;i<N2;i++){\n if(p.f[i]!=(i+1))//比较各个位置是不是放对位置,123...\n return false;\n }\n return true;\n}\nstring bfs(Puzzle s){\n Puzzle u,v;//u是队列开头,v用来更新队列\n map<Puzzle,bool> V;\n queue<Puzzle> Q;\n s.path=\"\";\n Q.push(s);\n V[s]=true;//访问过\n while(!Q.empty()){\n u=Q.front();Q.pop();\n if(isTarget(u)) return u.path;//拼好图后,返回操作最后转为size就是操作数\n int sx=u.space%N;//求出空格的x,y坐标,我把x弄成横的了,答案是竖的\n int sy=u.space/N;\n for(int r=0;r<4;r++){//对零的上下左右操作\n int tx=sx+dx[r];//求出操作空格的x,y坐标\n int ty=sy+dy[r];\n if(tx<0||ty<0||tx>=N||ty>=N) continue;\n v=u;\n swap(v.f[u.space],v.f[ty*N+tx]);//把操作后的空格移到正确的位置\n v.space=ty*N+tx;\n if(!V[v]){//看看操作后这样的排序有没有被访问过\n V[v]=true;\n v.path+=dir[r];//加一步操作\n Q.push(v);\n }\n }\n\n }\n return \"unsolvable\";//此题必有解,所以这个基本没用,但是有返回类型的函数结尾必须加这一句话\n}\nint main(){\n Puzzle in;\n for(int j=0;j<N2;j++){\n int c;\n scanf(\"%d\",&c);\n if(c==0){\n in.f[j]=N2;//零值变N;才符合上面n+1的判断,才能按顺序放到最后\n in.space=j;\n }else in.f[j]=c;\n }\n string g=bfs(in);\n printf(\"%d\\n\",(int)g.size());\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 32728, "score_of_the_acc": -0.8373, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_13_B_10973445", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n//幅優先探索で解く\n\nconst int dx[] = {-1, 0, 0, 1};\nconst int dy[] = {0, 1, -1, 0};\n\nconst char dir[] = {'l', 'd', 'u', 'r'};\n\nstruct puzzle\n{\n int grid[9];\n int n;\n int space = -1;\n string path;\n\n bool operator < (const puzzle &p) const\n {\n for (int i = 0; i < 9; i++)\n {\n if (grid[i] == p.grid[i]) continue;\n return p.grid[i] > grid[i];\n }\n\n return false;\n }\n\n string hash()\n {\n string ans = \"\";\n for (int i = 0; i < 9; i++) ans += to_string(grid[i]);\n return ans;\n }\n};\n\nint bfs()\n{\n queue<puzzle> q;\n map<string, bool> checker;\n\n puzzle s;\n for (int i = 0; i < 9; i++)\n {\n cin >> s.grid[i];\n if (s.grid[i] == 0) s.space = i;\n }\n s.n = 0;\n q.push(s);\n checker[s.hash()] = true;\n\n if (s.hash() == \"123456780\") return 0;\n\n while (!q.empty())\n {\n puzzle c = q.front(); q.pop();\n int i = c.space;\n\n for (int d = 0; d < 4; d++)\n {\n int ic = i%3; int ir = i/3;\n int mx = ic+dx[d];\n int my = ir+dy[d];\n int m = i+dx[d]+3*dy[d];\n if ( 0<=mx&&mx<3 && 0<=my&&my<3 )\n {\n c.n++;\n swap(c.grid[i], c.grid[m]);\n if ( !checker[c.hash()] )\n {\n puzzle copy = c;\n copy.space = m;\n copy.path += dir[d];\n\n if (c.hash() == \"123456780\")\n {\n //cout << copy.path << endl;\n return c.n;\n }\n q.push(copy);\n\n checker[c.hash()] = true;\n }\n swap(c.grid[i], c.grid[m]);\n c.n--;\n }\n }\n }\n\n return 0;\n}\n\nint main()\n{\n cout << bfs() << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 510, "memory_kb": 19572, "score_of_the_acc": -1.2578, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_13_B_10973439", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n//幅優先探索で解く\n\nconst int dx[] = {-1, 0, 0, 1};\nconst int dy[] = {0, 1, -1, 0};\n\nconst char dir[] = {'l', 'd', 'u', 'r'};\n\nstruct puzzle\n{\n int grid[9];\n int n;\n int space = -1;\n string path;\n\n bool operator < (const puzzle &p) const\n {\n for (int i = 0; i < 9; i++)\n {\n if (grid[i] == p.grid[i]) continue;\n return p.grid[i] > grid[i];\n }\n\n return false;\n }\n\n string hash()\n {\n string ans = \"\";\n for (int i = 0; i < 9; i++) ans += to_string(grid[i]);\n return ans;\n }\n};\n\nint bfs()\n{\n queue<puzzle> q;\n map<string, bool> checker;\n\n puzzle s;\n for (int i = 0; i < 9; i++)\n {\n cin >> s.grid[i];\n if (s.grid[i] == 0) s.space = i;\n }\n s.n = 0;\n q.push(s);\n checker[s.hash()] = true;\n\n while (!q.empty())\n {\n puzzle c = q.front(); q.pop();\n int i = c.space;\n\n for (int d = 0; d < 4; d++)\n {\n int ic = i%3; int ir = i/3;\n int mx = ic+dx[d];\n int my = ir+dy[d];\n int m = i+dx[d]+3*dy[d];\n if ( 0<=mx&&mx<3 && 0<=my&&my<3 )\n {\n c.n++;\n swap(c.grid[i], c.grid[m]);\n if ( !checker[c.hash()] )\n {\n puzzle copy = c;\n copy.space = m;\n copy.path += dir[d];\n\n if (c.hash() == \"123456780\")\n {\n //cout << copy.path << endl;\n return c.n;\n }\n q.push(copy);\n\n checker[c.hash()] = true;\n }\n swap(c.grid[i], c.grid[m]);\n c.n--;\n }\n }\n }\n\n return -1;\n}\n\nint main()\n{\n cout << bfs() << endl;\n\n return 0;\n}", "accuracy": 0.8214285714285714, "time_ms": 510, "memory_kb": 19728, "score_of_the_acc": -1.2606, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_13_B_10973393", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n//幅優先探索で解く\n\nconst int dx[] = {-1, 0, 0, 1};\nconst int dy[] = {0, 1, -1, 0};\n\nstruct puzzle\n{\n int grid[9];\n int n;\n int space = -1;\n string path;\n\n bool operator < (const puzzle &p) const\n {\n for (int i = 0; i < 9; i++)\n {\n if (grid[i] == p.grid[i]) continue;\n return p.grid[i] > grid[i];\n }\n\n return false;\n }\n\n string hash()\n {\n string ans = \"\";\n for (int i = 0; i < 9; i++) ans += to_string(grid[i]);\n return ans;\n }\n\n void print()\n {\n cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << endl;\n\n for (int i = 0; i < 9;)\n {\n for (int j = i; j+3 > i ; i++)\n cout << grid[i] << \" \";\n cout << endl;\n }\n\n cout << this->hash() << endl;\n }\n};\n\nint bfs()\n{\n queue<puzzle> q;\n map<string, bool> checker;\n\n puzzle s;\n for (int i = 0; i < 9; i++)\n {\n cin >> s.grid[i];\n if (s.grid[i] == 0) s.space = i;\n }\n s.n = 0;\n q.push(s);\n checker[s.hash()] = true;\n\n while (!q.empty())\n {\n puzzle c = q.front(); q.pop();\n int i = c.space;\n\n for (int d = 0; d < 4; d++)\n {\n int m = i+dx[d]+3*dy[d];\n if ( m >= 0 && m < 9 )\n {\n c.n++;\n swap(c.grid[i], c.grid[m]);\n if ( !checker[c.hash()] )\n {\n\n if (c.hash() == \"123456780\")\n {\n return c.n;\n }\n\n int temp = c.space;\n c.space = m;\n q.push(c);\n c.space = temp;\n checker[c.hash()] = true;\n }\n swap(c.grid[i], c.grid[m]);\n c.n--;\n }\n }\n }\n\n return -1;\n}\n\nint main()\n{\n cout << bfs() << endl;\n\n return 0;\n}", "accuracy": 0.39285714285714285, "time_ms": 20, "memory_kb": 4984, "score_of_the_acc": 0, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_13_B_10973370", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n//幅優先探索で解く\n\nconst int dx[] = {-1, 0, 0, 1};\nconst int dy[] = {0, 1, -1, 0};\n\nstruct puzzle\n{\n int grid[9];\n int n;\n string path;\n\n bool operator < (const puzzle &p) const\n {\n for (int i = 0; i < 9; i++)\n {\n if (grid[i] == p.grid[i]) continue;\n return p.grid[i] > grid[i];\n }\n\n return false;\n }\n\n string hash()\n {\n string ans = \"\";\n for (int i = 0; i < 9; i++) ans += to_string(grid[i]);\n return ans;\n }\n\n void print()\n {\n cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << endl;\n\n for (int i = 0; i < 9;)\n {\n for (int j = i; j+3 > i ; i++)\n cout << grid[i] << \" \";\n cout << endl;\n }\n\n cout << this->hash() << endl;\n }\n};\n\nint bfs()\n{\n queue<puzzle> q;\n map<string, bool> checker;\n\n puzzle s;\n for (int i = 0; i < 9; i++)\n {\n cin >> s.grid[i];\n }\n s.n = 0;\n q.push(s);\n checker[s.hash()] = true;\n\n while (!q.empty())\n {\n puzzle c = q.front(); q.pop();\n\n for (int i = 0; i < 9; i++)\n {\n for (int d = 0; d < 4; d++)\n {\n int m = i+dx[d]+3*dy[d];\n if ( m >= 0 && m < 9 )\n {\n c.n++;\n swap(c.grid[i], c.grid[m]);\n if ( !checker[c.hash()] )\n {\n\n if (c.hash() == \"123456780\")\n {\n return c.n;\n }\n\n q.push(c);\n checker[c.hash()] = true;\n }\n swap(c.grid[i], c.grid[m]);\n c.n--;\n }\n }\n }\n }\n\n return -1;\n}\n\nint main()\n{\n cout << bfs() << endl;\n\n return 0;\n}", "accuracy": 0.39285714285714285, "time_ms": 300, "memory_kb": 9720, "score_of_the_acc": -0.6551, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_13_B_10973278", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n//幅優先探索で解く\n\nconst int dx[] = {-1, 0, 0, 1};\nconst int dy[] = {0, 1, -1, 0};\n\nstruct puzzle\n{\n int grid[9];\n int n;\n\n bool operator < (const puzzle &p) const\n {\n for (int i = 0; i < 9; i++)\n {\n if (grid[i] == p.grid[i]) continue;\n return p.grid[i] > grid[i];\n }\n\n return false;\n }\n\n string hash()\n {\n string ans = \"\";\n for (int i = 0; i < 9; i++) ans += to_string(grid[i]);\n return ans;\n }\n\n void print()\n {\n for (int i = 0; i < 9;)\n {\n for (int j = i; j+3 > i ; i++)\n cout << grid[i] << \" \";\n cout << endl;\n }\n\n cout << this->hash() << endl;\n\n cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << endl;\n }\n};\n\nint bfs()\n{\n queue<puzzle> q;\n map<string, bool> checker;\n\n puzzle s;\n for (int i = 0; i < 9; i++)\n {\n cin >> s.grid[i];\n }\n s.n = 0;\n q.push(s);\n checker[s.hash()] = true;\n\n while (!q.empty())\n {\n puzzle c = q.front(); q.pop();\n\n for (int i = 0; i < 9; i++)\n {\n for (int d = 0; d < 4; d++)\n {\n int m = i+dx[d]+3*dy[d];\n if ( m >= 0 && m < 9 )\n {\n c.n++;\n swap(c.grid[i], c.grid[m]);\n if ( !checker[c.hash()] )\n {\n //c.print();\n\n if (c.hash() == \"123456780\")\n {\n return c.n;\n }\n\n q.push(c);\n checker[c.hash()] = true;\n }\n swap(c.grid[i], c.grid[m]);\n c.n--;\n }\n }\n }\n }\n\n return -1;\n}\n\nint main()\n{\n cout << bfs() << endl;\n\n return 0;\n}", "accuracy": 0.39285714285714285, "time_ms": 290, "memory_kb": 8828, "score_of_the_acc": -0.619, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_13_B_10973189", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n//幅優先探索で解く\n\nconst int dx[] = {-1, 0, 0, 1};\nconst int dy[] = {0, 1, -1, 0};\nconst int ans[] = {1, 2, 3, 4, 5, 6, 7, 8, 0};\n\nstruct puzzle\n{\n int grid[9];\n int n;\n\n bool operator < (const puzzle &p) const\n {\n for (int i = 0; i < 9; i++)\n {\n if (grid[i] == p.grid[i]) continue;\n return p.grid[i] > grid[i];\n }\n\n return false;\n }\n\n void print()\n {\n cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << endl;\n\n for (int i = 0; i < 9;)\n {\n for (int j = i; j+3 > i ; i++)\n cout << grid[i] << \" \";\n cout << endl;\n }\n\n cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << endl;\n }\n};\n\nint bfs()\n{\n queue<puzzle> q;\n map<puzzle, bool> checker;\n\n puzzle s;\n for (int i = 0; i < 9; i++)\n {\n cin >> s.grid[i];\n }\n s.n = 0;\n q.push(s);\n checker[s] = true;\n\n while (!q.empty())\n {\n puzzle c = q.front(); q.pop();\n\n for (int i = 0; i < 9; i++)\n {\n for (int d = 0; d < 4; d++)\n {\n int m = i+dx[d]+3*dy[d];\n if ( m >= 0 && m < 9 )\n {\n puzzle copy = c;\n copy.n = c.n + 1;\n swap(copy.grid[i], copy.grid[m]);\n if ( !checker[copy] )\n {\n //copy.print();\n\n if (equal( copy.grid, copy.grid+9, ans ))\n {\n return copy.n;\n }\n\n q.push(copy);\n checker[copy] = true;\n }\n }\n }\n }\n }\n\n return -1;\n}\n\nint main()\n{\n cout << bfs() << endl;\n\n return 0;\n}", "accuracy": 0.39285714285714285, "time_ms": 60, "memory_kb": 9288, "score_of_the_acc": -0.1577, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_13_B_10861181", "code_snippet": "#include <vector>\n#include <iostream>\n#include <cmath>\n#include <unordered_set>\nusing namespace std;\nint main()\n{\n vector<vector<int>> InitPlacement(3, vector<int>(3));\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n cin >> InitPlacement.at(i).at(j);\n }\n }\n unordered_set<int> Visited;\n int64_t InitScore = 0;\n int PlayCount = 0;\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n InitScore += InitPlacement.at(i).at(j) * int64_t(pow(9, 3 * i + j));\n }\n }\n Visited.insert(InitScore);\n vector<vector<int64_t>> AllNowPlacementScore = {{InitScore}};\n while (AllNowPlacementScore.size() > 0 && !Visited.contains(42374116))\n {\n vector<int64_t> NextPlacementScore(0);\n vector<int64_t> NowPlacementScore = AllNowPlacementScore.back();\n AllNowPlacementScore.pop_back();\n for (int64_t Score : NowPlacementScore)\n {\n int64_t CopiedScore = Score;\n vector<vector<int>> ScoreToPlacement(3, vector<int>(3));\n pair<int, int> EmptyPlace = {0, 0};\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n ScoreToPlacement.at(i).at(j) = Score % 9;\n if (Score % 9 == 0)\n {\n EmptyPlace = {i, j};\n }\n Score /= 9;\n }\n }\n if (EmptyPlace.first >= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first - 1).at(EmptyPlace.second) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first - 1) + EmptyPlace.second)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n if (EmptyPlace.first <= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first + 1).at(EmptyPlace.second) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first + 1) + EmptyPlace.second)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n if (EmptyPlace.second >= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first).at(EmptyPlace.second - 1) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first) + EmptyPlace.second - 1)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n if (EmptyPlace.second <= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first).at(EmptyPlace.second + 1) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first) + EmptyPlace.second + 1)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n\n }\n PlayCount ++;\n if (NextPlacementScore.size() > 0){\n AllNowPlacementScore.push_back(NextPlacementScore);\n }\n }\n cout << PlayCount << \"\\n\";\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 13292, "score_of_the_acc": -0.1876, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_13_B_10861180", "code_snippet": "#include <vector>\n#include <iostream>\n#include <cmath>\n#include <unordered_set>\nusing namespace std;\nint main()\n{\n vector<vector<int>> InitPlacement(3, vector<int>(3));\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n cin >> InitPlacement.at(i).at(j);\n }\n }\n unordered_set<int> Visited;\n int64_t InitScore = 0;\n int PlayCount = 0;\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n InitScore += InitPlacement.at(i).at(j) * int64_t(pow(9, 3 * i + j));\n }\n }\n Visited.insert(InitScore);\n vector<vector<int64_t>> AllNowPlacementScore = {{InitScore}};\n while (AllNowPlacementScore.size() > 0)\n {\n vector<int64_t> NextPlacementScore(0);\n vector<int64_t> NowPlacementScore = AllNowPlacementScore.back();\n AllNowPlacementScore.pop_back();\n for (int64_t Score : NowPlacementScore)\n {\n int64_t CopiedScore = Score;\n vector<vector<int>> ScoreToPlacement(3, vector<int>(3));\n pair<int, int> EmptyPlace = {0, 0};\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n ScoreToPlacement.at(i).at(j) = Score % 9;\n if (Score % 9 == 0)\n {\n EmptyPlace = {i, j};\n }\n Score /= 9;\n }\n }\n if (EmptyPlace.first >= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first - 1).at(EmptyPlace.second) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first - 1) + EmptyPlace.second)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n if (EmptyPlace.first <= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first + 1).at(EmptyPlace.second) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first + 1) + EmptyPlace.second)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n if (EmptyPlace.second >= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first).at(EmptyPlace.second - 1) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first) + EmptyPlace.second - 1)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n if (EmptyPlace.second <= 1)\n {\n int64_t NewScore = CopiedScore + ScoreToPlacement.at(EmptyPlace.first).at(EmptyPlace.second + 1) *\n (int64_t(pow(9, 3 * EmptyPlace.first + EmptyPlace.second)) - int64_t(pow(9, 3 * (EmptyPlace.first) + EmptyPlace.second + 1)));\n if (!Visited.contains(NewScore)){\n Visited.insert(NewScore);\n NextPlacementScore.push_back(NewScore);\n }\n }\n\n }\n PlayCount ++;\n if (NextPlacementScore.size() > 0){\n AllNowPlacementScore.push_back(NextPlacementScore);\n }\n if (Visited.contains(42374116)){\n break;\n }\n }\n cout << PlayCount << \"\\n\";\n}", "accuracy": 0.8214285714285714, "time_ms": 20, "memory_kb": 9308, "score_of_the_acc": -0.0764, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_13_B_10740854", "code_snippet": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <queue>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int dx[4] = {-1, 1, 0, 0}; // 上下左右\nconst int dy[4] = {0, 0, -1, 1};\nconst char* goal = \"123456780\";\n\n// パズル状態を文字列として管理する\nstruct State {\n char board[10]; // 9桁+終端\n int step;\n};\n\nint bfs(const char* start) {\n unordered_map<string, int> visited;\n queue<State> q;\n\n State s;\n strcpy(s.board, start);\n s.step = 0;\n q.push(s);\n visited[s.board] = 1;\n\n while (!q.empty()) {\n State cur = q.front(); q.pop();\n\n if (strcmp(cur.board, goal) == 0) {\n return cur.step;\n }\n\n int pos = strchr(cur.board, '0') - cur.board;\n int x = pos / 3, y = pos % 3;\n\n for (int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if (nx < 0 || nx >= 3 || ny < 0 || ny >= 3) continue;\n\n int npos = nx * 3 + ny;\n State next = cur;\n next.board[pos] = cur.board[npos];\n next.board[npos] = '0';\n next.step = cur.step + 1;\n\n if (!visited[next.board]) {\n visited[next.board] = 1;\n q.push(next);\n }\n }\n }\n\n return -1; // 解けない場合(ただし問題文では常に解ける)\n}\n\nint main() {\n char input[10];\n int idx = 0;\n for (int i = 0; i < 9; i++) {\n int x;\n scanf(\"%d\", &x);\n input[idx++] = x + '0';\n }\n input[9] = '\\0';\n\n int ans = bfs(input);\n printf(\"%d\\n\", ans);\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 15784, "score_of_the_acc": -0.2521, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_13_B_10737792", "code_snippet": "#include <stdio.h>\n\n// 状態を表す構造体\ntypedef struct {\n int board[9]; // 3x3の盤面を1次元配列で表現\n int blank_pos; // 空白(0)の位置\n int depth; // 初期状態からの手数\n} State;\n\n// キューの実装\nState queue[362881];\nint head = 0, tail = 0;\n\nvoid enqueue(State s) {\n queue[tail++] = s;\n}\n\nState dequeue() {\n return queue[head++];\n}\n\n// 階乗を事前計算\nint fact[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320};\n\n// 盤面の順列をユニークなIDに変換する関数\nint get_id(int board[]) {\n int id = 0;\n for (int i = 0; i < 9; i++) {\n int count = 0;\n for (int j = i + 1; j < 9; j++) {\n if (board[i] > board[j]) {\n count++;\n }\n }\n id += count * fact[8 - i];\n }\n return id;\n}\n\nint main() {\n State initial_state;\n initial_state.depth = 0;\n\n for (int i = 0; i < 9; i++) {\n scanf(\"%d\", &initial_state.board[i]);\n if (initial_state.board[i] == 0) {\n initial_state.blank_pos = i;\n }\n }\n\n // 訪問済み状態を管理する配列 (0で初期化される)\n char visited[362881] = {0};\n\n // ゴール状態\n int goal[] = {1, 2, 3, 4, 5, 6, 7, 8, 0};\n int goal_id = get_id(goal);\n \n head = tail = 0;\n enqueue(initial_state);\n visited[get_id(initial_state.board)] = 1;\n\n // 移動方向 (上、下、左、右)\n int dr[] = {-3, 3, -1, 1};\n\n while (head < tail) {\n State current = dequeue();\n\n if (get_id(current.board) == goal_id) {\n printf(\"%d\\n\", current.depth);\n return 0;\n }\n\n // 4方向への移動を試す\n for (int i = 0; i < 4; i++) {\n int next_blank_pos = current.blank_pos + dr[i];\n \n // 盤面の左右の端をまたぐ無効な移動をチェック\n if ((i == 2 && current.blank_pos % 3 == 0) || (i == 3 && current.blank_pos % 3 == 2)) {\n continue;\n }\n \n // 盤面外への移動でないかチェック\n if (next_blank_pos >= 0 && next_blank_pos < 9) {\n State next = current;\n // パネルを交換\n next.board[current.blank_pos] = next.board[next_blank_pos];\n next.board[next_blank_pos] = 0;\n \n int next_id = get_id(next.board);\n if (!visited[next_id]) {\n visited[next_id] = 1;\n next.blank_pos = next_blank_pos;\n next.depth = current.depth + 1;\n enqueue(next);\n }\n }\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 11460, "score_of_the_acc": -0.2369, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_13_B_10737784", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <string>\n#include <map>\n#include <queue>\nusing namespace std;\n\n#define N 3\n#define N2 9\n\n// パズルの状態を表す構造体\nstruct Puzzle {\n int f[N2]; // パネルの状態(9マス)\n int space; // 空白の位置\n string path; // ゴールまでの移動履歴\n\n // 状態の比較演算子(mapのキー用)\n bool operator < (const Puzzle &p) const {\n for (int i = 0; i < N2; i++) {\n if (f[i] == p.f[i]) continue;\n return f[i] > p.f[i];\n }\n return false;\n }\n};\n\n// 移動方向(上下左右)とその表現\nstatic const int dx[4] = {-1, 0, 1, 0};\nstatic const int dy[4] = {0, -1, 0, 1};\nstatic const char dir[4] = {'u', 'l', 'd', 'r'};\n\n// ゴール判定\nbool isTarget(Puzzle p) {\n for (int i = 0; i < N2; i++) {\n if (p.f[i] != (i + 1)) return false;\n }\n return true;\n}\n\n// 幅優先探索で最短手数を求める\nstring bfs(Puzzle s) {\n queue<Puzzle> Q;\n map<Puzzle, bool> V;\n Puzzle u, v;\n\n s.path = \"\";\n Q.push(s);\n V[s] = true;\n\n while (!Q.empty()) {\n u = Q.front(); Q.pop();\n if (isTarget(u)) return u.path;\n\n int sx = u.space / N;\n int sy = u.space % N;\n\n for (int r = 0; r < 4; r++) {\n int tx = sx + dx[r];\n int ty = sy + dy[r];\n\n if (tx < 0 || ty < 0 || tx >= N || ty >= N) continue;\n\n v = u;\n swap(v.f[u.space], v.f[tx * N + ty]);\n v.space = tx * N + ty;\n v.path += dir[r];\n\n if (!V[v]) {\n V[v] = true;\n Q.push(v);\n }\n }\n }\n\n return \"unsolvable\";\n}\n\nint main() {\n Puzzle in;\n\n for (int i = 0; i < N2; i++) {\n cin >> in.f[i];\n if (in.f[i] == 0) {\n in.f[i] = N2; // 空白を 9 として扱う\n in.space = i;\n }\n }\n\n string ans = bfs(in);\n cout << ans.size() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 33564, "score_of_the_acc": -0.852, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_13_B_10731578", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n// #define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nint go[4][2]={{0,1},{0,-1},{1,0},{-1,0}};\nbool in(int x,int y){\n return x>=0&&x<3&&y>=0&&y<3;\n}\nint a[3][3];\nvoid build(int x){\n for(int i=2;i>=0;i--){\n for(int j=2;j>=0;j--){\n a[i][j]=x%10;\n x/=10;\n }\n }\n}\nint get(){\n int res=0;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n res=res*10+a[i][j];\n }\n }\n return res;\n}\nunordered_set<int>st;\nvoid solve(){\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n cin>>a[i][j];\n }\n } \n queue<PII>q;\n int x=get(),tag=123456780;\n if(x==tag){\n cout<<0<<endl;\n return;\n }\n q.push({x,0});\n st.insert(x);\n while(!q.empty()){\n PII p=q.front();q.pop();\n int x=p.first,d=p.second;\n build(x);\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(a[i][j]==0){\n for(int k=0;k<4;k++){\n int x1=i+go[k][0],y1=j+go[k][1];\n if(!in(x1,y1)) continue;\n swap(a[x1][y1],a[i][j]);\n int y=get();\n if(y==tag){\n cout<<d+1<<endl;\n return;\n }\n if(!st.count(y)){\n st.insert(y);\n q.push({y,d+1});\n }\n swap(a[x1][y1],a[i][j]);\n }\n }\n }\n }\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 10592, "score_of_the_acc": -0.1195, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_13_B_10706972", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <string>\n#include <map>\n#include <queue>\nusing namespace std;\n\n#define N 3\n#define N2 9\n\n// パズルの状態を表す構造体\nstruct Puzzle {\n int f[N2]; // パネルの状態(9マス)\n int space; // 空白の位置\n string path; // ゴールまでの移動履歴\n\n // 状態の比較演算子(mapのキー用)\n bool operator < (const Puzzle &p) const {\n for (int i = 0; i < N2; i++) {\n if (f[i] == p.f[i]) continue;\n return f[i] > p.f[i];\n }\n return false;\n }\n};\n\n// 移動方向(上下左右)とその表現\nstatic const int dx[4] = {-1, 0, 1, 0};\nstatic const int dy[4] = {0, -1, 0, 1};\nstatic const char dir[4] = {'u', 'l', 'd', 'r'};\n\n// ゴール判定\nbool isTarget(Puzzle p) {\n for (int i = 0; i < N2; i++) {\n if (p.f[i] != (i + 1)) return false;\n }\n return true;\n}\n\n// 幅優先探索で最短手数を求める\nstring bfs(Puzzle s) {\n queue<Puzzle> Q;\n map<Puzzle, bool> V;\n Puzzle u, v;\n\n s.path = \"\";\n Q.push(s);\n V[s] = true;\n\n while (!Q.empty()) {\n u = Q.front(); Q.pop();\n if (isTarget(u)) return u.path;\n\n int sx = u.space / N;\n int sy = u.space % N;\n\n for (int r = 0; r < 4; r++) {\n int tx = sx + dx[r];\n int ty = sy + dy[r];\n\n if (tx < 0 || ty < 0 || tx >= N || ty >= N) continue;\n\n v = u;\n swap(v.f[u.space], v.f[tx * N + ty]);\n v.space = tx * N + ty;\n v.path += dir[r];\n\n if (!V[v]) {\n V[v] = true;\n Q.push(v);\n }\n }\n }\n\n return \"unsolvable\";\n}\n\nint main() {\n Puzzle in;\n\n for (int i = 0; i < N2; i++) {\n cin >> in.f[i];\n if (in.f[i] == 0) {\n in.f[i] = N2; // 空白を 9 として扱う\n in.space = i;\n }\n }\n\n string ans = bfs(in);\n cout << ans.size() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 33576, "score_of_the_acc": -0.8522, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_13_B_10692741", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <string>\n#include <map>\n#include <queue>\n\nconstexpr int N = 3;\nconstexpr int N2 = 9;\n\nstruct Puzzle {\n int f[N2];\n int space;\n std::string path;\n\n bool operator<(const Puzzle& p) const {\n for (int i = 0; i < N2; ++i) {\n if (f[i] == p.f[i]) {\n continue;\n }\n return f[i] > p.f[i];\n }\n return false;\n }\n};\n\nstatic const int dx[4] = {-1, 0, 1, 0};\nstatic const int dy[4] = {0, -1, 0, 1};\nstatic const char dir[4] = {'u', 'l', 'd', 'r'};\n\nbool is_target(Puzzle p) {\n for (int i = 0; i < N2; ++i) {\n if (p.f[i] != (i + 1)) {\n return false;\n }\n }\n return true;\n}\n\nstd::string bfs(Puzzle s) {\n std::queue<Puzzle> Q;\n std::map<Puzzle, bool> V;\n Puzzle u, v;\n s.path = \"\";\n Q.push(s);\n V[s] = true;\n\n while (!Q.empty()) {\n u = Q.front();\n Q.pop();\n if (is_target(u)) {\n return u.path;\n }\n int sx = u.space / N;\n int sy = u.space % N;\n for (int r = 0; r < 4; ++r) {\n int tx = sx + dx[r];\n int ty = sy + dy[r];\n if (tx < 0 || ty < 0 || tx >= N || ty >= N) {\n continue;\n }\n v = u;\n std::swap(v.f[u.space], v.f[tx * N + ty]);\n v.space = tx * N + ty;\n if (!V[v]) {\n V[v] = true;\n v.path += dir[r];\n Q.push(v);\n }\n }\n }\n return \"unsolvable\";\n}\n\nint main() {\n Puzzle in;\n\n for (int i = 0; i < N2; ++i) {\n std::cin >> in.f[i];\n if (in.f[i] == 0) {\n in.f[i] = N2; // set space\n in.space = i;\n }\n }\n std::string ans = bfs(in);\n std::cout << ans.size() << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 32768, "score_of_the_acc": -0.7971, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_13_B_10451178", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint encode(const vector<vector<int>> &b) {\n int res = 0;\n for (auto &row: b)\n for (auto cell: row)\n res = res * 10 + cell;\n return res;\n}\n\nvector<vector<int>> decode(int code) {\n vector<vector<int>> res(3, vector<int>(3));\n for (int i = 2; i >= 0; --i) {\n for (int j = 2; j >= 0; --j) {\n res[i][j] = code % 10;\n code /= 10;\n }\n }\n return res;\n}\n\npair<int, int> findZero(const vector<vector<int>> &b) {\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n if (b[i][j] == 0)\n return {i, j};\n return {-1, -1}; // Should never happen\n}\n\nvector<int> getNeig(int code) {\n auto b = decode(code);\n vector<int> res;\n auto [i, j] = findZero(b);\n for (int di = 0, dj = -1, k = 0; k < 4; ++k) {\n int ni = i + di;\n int nj = j + dj;\n if (ni >= 0 && ni < 3 && nj >= 0 && nj < 3) {\n swap(b[i][j], b[ni][nj]);\n res.push_back(encode(b));\n swap(b[i][j], b[ni][nj]);\n }\n swap(di, dj);\n if (k == 1)dj = 1;\n }\n return res;\n}\n\n/*\n1 3 0\n4 2 5\n7 8 6\n\n130425786\n\n1 3 5\n4 2 0\n7 8 6\n135420786\n\n1 0 3\n4 2 5\n7 8 6\n103425786\n */\nint main() {\n vector<vector<int>> goal = {{1, 2, 3},\n {4, 5, 6},\n {7, 8, 0}}, start(3, vector<int>(3));\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n cin >> start[i][j];\n int startCode = encode(start);\n int goalCode = encode(goal);\n if (startCode == goalCode) {\n cout << 0 << endl;\n return 0;\n }\n queue<int> q;\n q.push(startCode);\n unordered_set<int> vis = {startCode};\n int steps = 0;\n while(q.size()){\n int sz=q.size();\n ++steps;\n while (sz--){\n int u=q.front();\n q.pop();\n for(auto v: getNeig(u))\n if(vis.insert(v).second)\n if (v == goalCode) {\n cout << steps << endl;\n return 0;\n } else\n q.push(v);\n }\n }\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 10864, "score_of_the_acc": -0.1651, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_13_B_10443381", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\nstatic const int N = 3;\nstatic const vector<int> dx = {-1, 0, 1, 0};\nstatic const vector<int> dy = {0, -1, 0, 1};\nstatic const vector<char> dir = {'l', 'd', 'r', 'u'};\n\nstruct Puzzle\n{\n vector<vector<int>> f = vector<vector<int>>(N, vector<int>(N));\n int sx;\n int sy;\n string path;\n\n bool operator<(const Puzzle &p) const\n {\n int i;\n int j;\n rep(i, N)\n {\n rep(j, N)\n {\n if (f.at(i).at(j) == p.f.at(i).at(j))\n {\n continue;\n }\n return f.at(i).at(j) > p.f.at(i).at(j);\n }\n }\n return false;\n }\n};\n\nbool isTgt(Puzzle s, Puzzle t)\n{\n int i;\n int j;\n\n rep(i, N)\n {\n rep(j, N)\n {\n if (s.f.at(i).at(j) != t.f.at(i).at(j))\n {\n return false;\n }\n }\n }\n return true;\n}\n\nstring search(Puzzle s, Puzzle t)\n{\n queue<Puzzle> Q;\n set<Puzzle> V;\n Puzzle u;\n Puzzle v;\n int i;\n int tx;\n int ty;\n\n Q.push(s);\n V.insert(s);\n\n while (!Q.empty())\n {\n u = Q.front();\n Q.pop();\n if (isTgt(u, t))\n {\n return u.path;\n }\n rep(i, 4)\n {\n tx = u.sx + dx.at(i);\n ty = u.sy + dy.at(i);\n if (tx < 0 || tx >= N || ty < 0 || ty >= N)\n {\n continue;\n }\n v = u;\n swap(v.f.at(u.sy).at(u.sx), v.f.at(ty).at(tx));\n v.sx = tx;\n v.sy = ty;\n if (V.count(v) == 0)\n {\n V.insert(v);\n v.path += dir.at(i);\n Q.push(v);\n }\n }\n }\n return \"\";\n}\n\nint main()\n{\n int i;\n int j;\n Puzzle s;\n Puzzle t;\n string ans;\n\n rep(i, N)\n {\n rep(j, N)\n {\n cin >> s.f.at(i).at(j);\n if (s.f.at(i).at(j) == 0)\n {\n s.sx = j;\n s.sy = i;\n }\n t.f.at(i).at(j) = (i * 3 + j + 1) % 9;\n }\n }\n\n s.path = \"\";\n ans = search(s, t);\n cout << ans.size() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 430, "memory_kb": 61568, "score_of_the_acc": -1.8367, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_13_B_10401264", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst string target = \"123456780\";\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\n\nint bfs(string start) {\n\tqueue<pair<string, int>> q;\n\tunordered_set<string> visited;\n\t\n\tq.push({start, 0});\n\tvisited.insert(start);\n\t\n\twhile (!q.empty()) {\n\t\tauto [current, steps] = q.front(); q.pop();\n\t\t\n\t\tif (current == target) return steps;\n\t\t\n\t\tint zeroPos = current.find('0');\n\t\tint row = zeroPos / 3;\n\t\tint col = zeroPos % 3;\n\t\t\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tint newRow = row + dx[i];\n\t\t\tint newCol = col + dy[i];\n\t\t\t\n\t\t\tif (newRow >= 0 && newRow < 3 && newCol >= 0 && newCol < 3) {\n\t\t\t\tint newPos = newRow * 3 + newCol;\n\t\t\t\tstring nextState = current;\n\t\t\t\tswap(nextState[zeroPos], nextState[newPos]);\n\t\t\t\t\n\t\t\t\tif (visited.find(nextState) == visited.end()) {\n\t\t\t\t\tq.push({nextState, steps + 1});\n\t\t\t\t\tvisited.insert(nextState);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nint main() {\n\tstring start;\n\tfor (int i = 0; i < 9; ++i) {\n\t\tchar c; cin >> c;\n\t\tstart += c;\n\t}\n\t\n\tcout << bfs(start) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 16316, "score_of_the_acc": -0.2615, "final_rank": 6 } ]
aoj_ALDS1_15_A_cpp
Change-Making Problem You want to make change for $n$ cents. Assuming that you have infinite supply of coins of 1, 5, 10 and/or 25 cents coins respectively, find the minimum number of coins you need. Input $n$ The integer $n$ is given in a line. 出力 Print the minimum number of coins you need in a line. Constraints $1 \le n \le 10^9$ Sample Input 1 100 Sample Output 1 4 Sample Input 2 54321 Sample Output 2 2175
[ { "submission_id": "aoj_ALDS1_15_A_10945998", "code_snippet": "#include <stdio.h>\n\nint main(){\n\tint count = 0;\n\tint num;\n\tscanf(\"%d\",&num);\n\twhile(num>0){\n\t\twhile(num>=25){\n\t\t\tnum-= 25;\n\t\t\tcount++;\n\t\t}\n\t\twhile(num >= 10){\n\t\t\tnum-= 10;\n\t\t\tcount++;\n\t\t}\n\t\twhile(num >= 5){\n\t\t\tnum -= 5;\n\t\t\tcount++;\n\t\t}\n\t\tif(num == 0 ) break;\n\t\tnum-=1;\n\t\tcount++;\n\t}\n\tprintf(\"%d\\n\",count);\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2976, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_15_A_10357650", "code_snippet": "#include <stdio.h>\nint money[4] = {1, 5, 10, 25};\nint main()\n{\n\tint n, ans = 0;\n\tscanf(\"%d\", &n);\n\tfor(int i = 3; i >= 0; i--)\n\t{\n\t\twhile(n >= money[i])\n\t\t{\n\t\t\tn -= money[i];\n\t\t\tans++;\n\t\t}\n\t}\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2976, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_15_A_9836024", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int n;\n int ans=0;\n cin >> n;\n while(n>=25){\n n-=25;\n ans++;\n }\n while(n>=10){\n n-=10;\n ans++;\n }\n while(n>=5){\n n-=5;\n ans++;\n }\n while(n>=1){\n n-=1;\n ans++;\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3120, "score_of_the_acc": -0.3025, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_15_A_8701351", "code_snippet": "#include<iostream>\n#include<cctype>\n#include<queue>\n#include<cstring>\n#include<cmath>\n#include<cstdio>\n#include<stack>\n#include<string>\n#include<vector>\n#include<set>\n#include<deque>\n\n#define MAX 10001\n\nusing namespace std;\n\nvoid solve()\n{\n\tint n = 0;\n\tint cnt = 0;\n\tcin >> n;\n\twhile (n!= 0)\n\t{\n\t\tif (n - 25 < 0)\n\t\t{\n\t\t\tif (n - 10 < 0)\n\t\t\t{\n\t\t\t\tif (n - 5 < 0)\n\t\t\t\t{\n\t\t\t\t\twhile (n != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tn--;\n\t\t\t\t\t\tcnt++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tn -= 5;\n\t\t\t\t\tcnt++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tn -= 10;\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn -= 25;\n\t\t\tcnt++;\n\t\t}\n\t}\n\tcout << cnt << endl;\n}\n\n\nint main()\n{\n\tsolve();\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3092, "score_of_the_acc": -0.2437, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_15_A_8701338", "code_snippet": "#include<iostream>\n#include<cctype>\n#include<queue>\n#include<cstring>\n#include<cmath>\n#include<cstdio>\n#include<stack>\n#include<string>\n#include<vector>\n#include<set>\n#include<deque>\n\n#define MAX 10001\n\nusing namespace std;\n\nvoid solve()\n{\n\tint n = 0;\n\tint cnt = 0;\n\tcin >> n;\n\twhile (n!= 0)\n\t{\n\t\tif (n - 25 < 0)\n\t\t{\n\t\t\tif (n - 10 < 0)\n\t\t\t{\n\t\t\t\tif (n - 5 < 0)\n\t\t\t\t{\n\t\t\t\t\twhile (n != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tn--;\n\t\t\t\t\t\tcnt++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tn -= 5;\n\t\t\t\t\tcnt++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tn -= 10;\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn -= 25;\n\t\t\tcnt++;\n\t\t}\n\t}\n\tcout << cnt << endl;\n}\n\n\nint main()\n{\n\tsolve();\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3092, "score_of_the_acc": -0.2437, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_15_A_8490649", "code_snippet": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n int n, ans = 0;\n vector<int> coins = {1, 5, 10, 25};\n\n scanf(\"%d\", &n);\n for (int i = coins.size() - 1; i >= 0; i--) {\n int coin = coins[i];\n while (n >= coin) {\n n -= coin;\n ans++;\n }\n }\n printf(\"%d\\n\", ans);\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2976, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_15_A_8396921", "code_snippet": "#include <bits/stdc++.h>\n\n#define log(x) cout << x << endl\n#define logfixed(x) cout << fixed << setprecision(10) << x << endl;\n#define all(x) (x).begin(), (x).end()\nusing namespace std;\nusing lint = long long;\nusing Graph = vector<vector<int>>;\n\nint main() {\n int res = 0;\n int n;\n cin >> n;\n while (n > 0) {\n if (n >= 25) {\n n -= 25;\n } else if (n >= 10) {\n n -= 10;\n } else if (n >= 5) {\n n -= 5;\n } else {\n n--;\n }\n res++;\n }\n log(res);\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3452, "score_of_the_acc": -1, "final_rank": 7 } ]
aoj_ALDS1_13_C_cpp
15 Puzzle The goal of the 15 puzzle problem is to complete pieces on $4 \times 4$ cells where one of the cells is empty space. In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 15 as shown below. 1 2 3 4 6 7 8 0 5 10 11 12 9 13 14 15 You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle. Input The $4 \times 4$ integers denoting the pieces or space are given. Output Print the fewest steps in a line. Constraints The given puzzle is solvable in at most 45 steps. Sample Input 1 2 3 4 6 7 8 0 5 10 11 12 9 13 14 15 Sample Output 8
[ { "submission_id": "aoj_ALDS1_13_C_11003707", "code_snippet": "//迭代加深A*/IDA*\n#include <iostream>\n#include <cmath>\n#include <string>\n#include <algorithm>\nusing namespace std;\n#define N 4\n#define N2 16\nconst int LIMIT=100;\nstruct puzzle{\n int f[N2];\n int space;\n int MD;\n};\nint MDT[N2][N2];\nint limit;\npuzzle state;\nint path[LIMIT];\nint initial(puzzle p){\n int sum=0;\n for(int i=0;i<N2;i++){\n if(p.f[i]==N2) continue;\n sum+=abs(i/N-(p.f[i]-1)/N)+abs(i%N-(p.f[i]-1)%N);\n }\n return sum;\n}\nconst int dx[4]={-1,0,1,0};\nconst int dy[4]={0,-1,0,1};\nchar dir[4]={'u','l','d','r'};\nbool dfs(int depth,int prev){\n if(state.MD==0) return true;\n if(depth+state.MD>limit){\n return false;\n }\n int sx=state.space/N;\n int sy=state.space%N;\n puzzle tem;\n for(int r=0;r<4;r++){\n if(max(prev,r)-min(prev,r)==2) continue;\n int tx=sx+dx[r];\n int ty=sy+dy[r];\n if(tx<0||ty<0||tx>=N||ty>=N) continue;\n tem=state;\n state.MD-=MDT[tx*N+ty][state.f[tx*N+ty]-1];\n state.MD+=MDT[sx*N+sy][state.f[tx*N+ty]-1];\n swap(state.f[state.space],state.f[tx*N+ty]);\n state.space=tx*N+ty;\n if(dfs(depth+1,r)){path[depth]=r; return true;}\n state=tem;\n }\n return false;\n}\nstring deepening(puzzle in){\n state=in;\n state.MD=initial(in);\n for(limit=state.MD;limit<=LIMIT;limit++){\n if(dfs(0,-100)){\n string ans;\n ans=\"\";\n for(int i=0;i<limit;i++){\n ans+=dir[path[i]];\n }\n return ans;\n }\n }\n return \"unsolvable\";\n}\nint main(){\n puzzle in;\n for(int i=0;i<N2;i++){\n for(int j=0;j<N2;j++){\n MDT[i][j]=abs(i/N-j/N)+abs(i%N-j%N);\n }\n }\n for(int i=0;i<N2;i++){\n cin>>in.f[i];\n if(in.f[i]==0){\n in.f[i]=N2;\n in.space=i;\n }\n }\n string answer=deepening(in);\n cout<<(int)answer.size()<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3440, "score_of_the_acc": -0.0121, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_13_C_10849591", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <cmath>\n#include <cstdlib>\nusing namespace std;\n\nstatic const int N = 4;\nstatic const int N2 = 16;\nstatic const int LIMIT = 100;\n\nstatic const int dx[4] = {0, -1, 0, 1};\nstatic const int dy[4] = {1, 0, -1, 0};\nstatic const char dir[4] = {'r', 'u', 'l', 'd'};\nint MDT[N2][N2];\n\nstruct Puzzle {\n int f[N2];\n int space;\n int MD;\n};\n\nPuzzle state;\n\nint limit;\nint path[LIMIT];\n\nint getAllMD(Puzzle pz) {\n int sum = 0;\n for (int i = 0; i < N2; i++) {\n if (pz.f[i] == N2) continue;\n sum += MDT[i][pz.f[i] - 1];\n }\n return sum;\n}\n\nbool isSolved() {\n for (int i = 0; i < N2; i++) {\n if (state.f[i] != i + 1) return false;\n }\n return true;\n}\n\nbool dfs(int depth, int prev) {\n if (state.MD == 0) return true;\n if (depth + state.MD > limit) return false;\n int sx = state.space / N;\n int sy = state.space % N;\n Puzzle tmp;\n\n for (int r = 0; r < 4; r++) {\n int tx = sx + dx[r];\n int ty = sy + dy[r];\n if (tx < 0 || ty < 0 || tx >= N || ty >= N) continue;\n if (max(prev, r) - min(prev, r) == 2) continue;\n tmp = state;\n\n state.MD -= MDT[tx * N + ty][state.f[tx * N + ty] - 1];\n state.MD += MDT[sx * N + sy][state.f[tx * N + ty] - 1];\n swap(state.f[tx * N + ty], state.f[sx * N + sy]);\n state.space = tx * N + ty;\n if (dfs(depth + 1, r)) {\n path[depth] = r; return true;\n }\n state = tmp;\n }\n return false;\n}\n\nstring iterative_deepening(Puzzle in) {\n in.MD = getAllMD(in);\n\n for (limit = in.MD; limit <= LIMIT; limit++) {\n state = in;\n if (dfs(0, -100)) {\n string ans = \"\";\n for (int i = 0; i < limit; i++) ans += dir[path[i]];\n return ans;\n }\n }\n return \"unsolvalbe\";\n}\n\nint main() {\n //freopen(\"in.txt\", \"r\", stdin);\n //freopen(\"out.txt\", \"w\", stdout);\n for (int i = 0; i < N2; i++) {\n for (int j = 0; j < N2; j++) {\n MDT[i][j] = abs(i / N - j / N) + abs(i % N - j % N);\n }\n }\n Puzzle in;\n for (int i = 0; i < N2; i++) {\n cin >> in.f[i];\n if (in.f[i] == 0) {\n in.f[i] = N2;\n in.space = i;\n }\n }\n string ans = iterative_deepening(in);\n cout << ans.size() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3444, "score_of_the_acc": -0.0121, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_13_C_10749519", "code_snippet": "// A*\n#include <iostream>\n#include <cmath>\n#include <map>\n#include <queue>\n\nconstexpr int N = 4;\nconstexpr int N2 = 16;\n\nstatic const int dx[4] = {0, -1, 0, 1};\nstatic const int dy[4] = {1, 0, -1, 0};\nstatic const char dir[4] = {'r', 'u', 'l', 'd'};\n\nint MDT[N2][N2]; // マンハッタン距離算出用配列\n\nstruct Puzzle {\n int f[N2];\n int space;\n int MD;\n int cost;\n\n bool operator<(const Puzzle& p) const {\n for (int i = 0; i < N2; ++i) {\n if (f[i] == p.f[i]) {\n continue;\n }\n return f[i] < p.f[i];\n }\n return false;\n }\n};\n\nstruct State {\n Puzzle puzzle;\n int estimated;\n bool operator<(const State& s) const {\n return estimated > s.estimated;\n }\n};\n\nint get_all_MD(Puzzle pz) {\n int sum = 0;\n for (int i = 0; i < N2; ++i) {\n if (pz.f[i] == N2) {\n continue;\n }\n sum += MDT[i][pz.f[i] - 1];\n }\n return sum;\n}\n\nint astar(Puzzle s) {\n std::priority_queue<State> PQ;\n s.MD = get_all_MD(s);\n s.cost = 0;\n std::map<Puzzle, bool> V;\n Puzzle u, v;\n State initial;\n initial.puzzle = s;\n initial.estimated = get_all_MD(s);\n PQ.push(initial);\n\n while (!PQ.empty()) {\n State st = PQ.top();\n PQ.pop();\n u = st.puzzle;\n\n if (u.MD == 0) {\n return u.cost;\n }\n V[u] = true;\n\n int sx = u.space / N;\n int sy = u.space % N;\n\n for (int r = 0; r < 4; ++r) {\n int tx = sx + dx[r];\n int ty = sy + dy[r];\n if (tx < 0 || ty < 0 || tx >= N || ty >= N) {\n continue;\n }\n v = u;\n\n v.MD -= MDT[tx * N + ty][v.f[tx * N + ty] - 1];\n v.MD += MDT[sx * N + sy][v.f[tx * N + ty] - 1];\n\n std::swap(v.f[sx * N + sy], v.f[tx * N + ty]);\n v.space = tx * N + ty;\n if (!V[v]) {\n ++v.cost;\n State news;\n news.puzzle = v;\n news.estimated = v.cost + v.MD;\n PQ.push(news);\n }\n }\n }\n return -1;\n}\n\nint main() {\n for (int i = 0; i < N2; ++i) {\n for (int j = 0; j < N2; ++j) {\n MDT[i][j] = std::abs(i / N - j / N) + std::abs(i % N - j % N);\n }\n }\n\n Puzzle in;\n\n for (int i = 0; i < N2; ++i) {\n std::cin >> in.f[i];\n if (in.f[i] == 0) {\n in.f[i] = N2;\n in.space = i;\n }\n }\n std::cout << astar(in) << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 1900, "memory_kb": 259284, "score_of_the_acc": -1.9588, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_13_C_10749317", "code_snippet": "// IDA* (Iterative Deepening)\n#include <iostream>\n#include <cmath>\n#include <string>\n\nconstexpr int N = 4;\nconstexpr int N2 = 16;\nconstexpr int LIMIT = 100;\n\nstatic const int dx[4] = {0, -1, 0, 1};\nstatic const int dy[4] = {1, 0, -1, 0};\nstatic const char dir[4] = {'r', 'u', 'l', 'd'};\n\nint MDT[N2][N2]; // マンハッタン距離算出用配列\n\nstruct Puzzle {\n int f[N2];\n int space;\n int MD;\n};\n\nPuzzle state;\nint limit; // 深さの制限\nint path[LIMIT];\n\nint get_all_MD(Puzzle pz) {\n int sum = 0;\n for (int i = 0; i < N2; ++i) {\n if (pz.f[i] == N2) {\n continue;\n }\n sum += MDT[i][pz.f[i] - 1];\n }\n return sum;\n}\n\nbool is_solved() {\n for (int i = 0; i < N2; ++i) {\n if (state.f[i] != i + 1) {\n return false;\n }\n }\n return true;\n}\n\nbool dfs(int depth, int prev) {\n if (state.MD == 0) {\n return true;\n }\n // 現在の深さにヒューリスティックを足して制限を超えたら枝を刈る\n if (depth + state.MD > limit) {\n return false;\n }\n\n int sx = state.space / N;\n int sy = state.space % N;\n Puzzle tmp;\n\n for (int r = 0; r < 4; ++r) {\n int tx = sx + dx[r];\n int ty = sy + dy[r];\n if (tx < 0 || ty < 0 || tx >= N || ty >= N) {\n continue;\n }\n if (std::max(prev, r) - std::min(prev, r) == 2) {\n continue;\n }\n tmp = state;\n // マンハッタン距離の差分を計算しつつ、ピースをスワップ\n state.MD -= MDT[tx * N + ty][state.f[tx * N + ty] - 1];\n state.MD += MDT[sx * N + sy][state.f[tx * N + ty] - 1];\n std::swap(state.f[tx * N + ty], state.f[sx * N + sy]);\n state.space = tx * N + ty;\n if (dfs(depth + 1, r)) {\n path[depth] = r;\n return true;\n }\n state = tmp;\n }\n return false;\n}\n\n// 反復深化\nstd::string iterative_deepening(Puzzle in) {\n in.MD = get_all_MD(in); // 初期状態のマンハッタン距離\n\n for (limit = in.MD; limit <= LIMIT; ++limit) {\n state = in;\n if (dfs(0, -100)) {\n std::string ans = \"\";\n for (int i = 0; i < limit; ++i) {\n ans += dir[path[i]];\n }\n return ans;\n }\n }\n return \"unsolvable\";\n}\n\nint main() {\n for (int i = 0; i < N2; ++i) {\n for (int j = 0; j < N2; ++j) {\n MDT[i][j] = std::abs(i / N - j / N) + std::abs(i % N - j % N);\n }\n }\n\n Puzzle in;\n\n for (int i = 0; i < N2; ++i) {\n std::cin >> in.f[i];\n if (in.f[i] == 0) {\n in.f[i] = N2;\n in.space = i;\n }\n }\n std::string ans = iterative_deepening(in);\n std::cout << ans.size() << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3584, "score_of_the_acc": -0.0075, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_13_C_10743050", "code_snippet": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 4\n#define N2 16\n#define LIMIT 45 // 問題の制約\n\nint puzzle[N2];\nint blank_pos;\nint path[LIMIT];\n\n// ゴール状態の各タイルの座標 (マンハッタン距離計算用)\nint goal_x[] = {3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2};\nint goal_y[] = {3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3};\n\n// 移動方向 (上、下、左、右)\nint dx[] = {0, 0, -1, 1};\nint dy[] = {-1, 1, 0, 0};\n\n// マンハッタン距離を計算するヒューリスティック関数\nint heuristic() {\n int dist = 0;\n for (int i = 0; i < N2; i++) {\n if (puzzle[i] == 0) continue;\n int val = puzzle[i];\n int current_y = i / N;\n int current_x = i % N;\n dist += abs(current_y - goal_y[val]) + abs(current_x - goal_x[val]);\n }\n return dist;\n}\n\n// 反復深化A*の再帰的な探索部分\nint ida_star(int depth, int prev_move, int threshold) {\n int h = heuristic();\n \n // 現在のコスト(depth) + 推定コスト(h) がしきい値を超えたら枝刈り\n if (depth + h > threshold) {\n return depth + h;\n }\n // ゴールに到達\n if (h == 0) {\n return 0; // 成功\n }\n\n int min_threshold = 1000; // 次のしきい値候補\n\n int by = blank_pos / N;\n int bx = blank_pos % N;\n \n for (int i = 0; i < 4; i++) {\n // 直前の手と逆の動きはしない (例: 上に動かした直後に下には動かさない)\n if (prev_move >= 0 && prev_move + i == 1) continue; // 0:上, 1:下\n if (prev_move >= 2 && prev_move + i == 5) continue; // 2:左, 3:右\n\n int ny = by + dy[i];\n int nx = bx + dx[i];\n\n if (ny >= 0 && ny < N && nx >= 0 && nx < N) {\n int next_blank_pos = ny * N + nx;\n\n // パネルを交換\n puzzle[blank_pos] = puzzle[next_blank_pos];\n puzzle[next_blank_pos] = 0;\n blank_pos = next_blank_pos;\n \n int new_threshold = ida_star(depth + 1, i, threshold);\n \n // 盤面を元に戻す\n blank_pos = by * N + bx;\n puzzle[next_blank_pos] = puzzle[blank_pos];\n puzzle[blank_pos] = 0;\n\n if (new_threshold == 0) return 0; // ゴールが見つかった\n if (new_threshold < min_threshold) {\n min_threshold = new_threshold;\n }\n }\n }\n\n return min_threshold;\n}\n\nint main() {\n for (int i = 0; i < N2; i++) {\n scanf(\"%d\", &puzzle[i]);\n if (puzzle[i] == 0) {\n blank_pos = i;\n }\n }\n\n // 最初のしきい値は初期状態のヒューリスティック値\n int threshold = heuristic();\n\n while (1) {\n int next_threshold = ida_star(0, -1, threshold);\n if (next_threshold == 0) {\n printf(\"%d\\n\", threshold);\n break;\n }\n if (next_threshold > LIMIT) {\n // 制約上、45手以内で解けるはず\n break;\n }\n threshold = next_threshold;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 2984, "score_of_the_acc": -0.0206, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_13_C_10455225", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\nstatic const int N = 4;\nstatic const vector<int> dx = {-1, 0, 1, 0};\nstatic const vector<int> dy = {0, -1, 0, 1};\nstatic const vector<char> dir = {'u', 'l', 'd', 'r'};\nstatic const int LIMIT = 45;\nvector<vector<int>> MDT(N *N, vector<int>(N *N));\n\nstruct Puzzle\n{\n vector<vector<int>> f = vector<vector<int>>(N, vector<int>(N));\n int sx;\n int sy;\n int MD;\n\n bool operator<(const Puzzle &p) const\n {\n int i;\n int j;\n rep(i, N)\n {\n rep(j, N)\n {\n if (f.at(i).at(j) == p.f.at(i).at(j))\n {\n continue;\n }\n return f.at(i).at(j) > p.f.at(i).at(j);\n }\n }\n return false;\n }\n};\n\nvoid makeMDT()\n{\n int i;\n int j;\n\n rep(i, N * N)\n {\n rep(j, N * N)\n {\n MDT.at(i).at(j) = abs(i / N - j / N) + abs(i % N - j % N);\n }\n }\n return;\n}\n\nint getAllMD(Puzzle pz)\n{\n int sum;\n int i;\n int j;\n int tgt;\n\n sum = 0;\n rep(i, N)\n {\n rep(j, N)\n {\n tgt = (i * N + j) + 1;\n if (pz.f.at(i).at(j) == tgt || pz.f.at(i).at(j) == N * N)\n {\n continue;\n }\n sum += MDT.at(tgt - 1).at(pz.f.at(i).at(j) - 1);\n }\n }\n return sum;\n}\n\nbool isSolved(Puzzle s)\n{\n int i;\n int j;\n\n rep(i, N)\n {\n rep(j, N)\n {\n if (s.f.at(i).at(j) != i * N + j + 1)\n {\n return false;\n }\n }\n }\n return true;\n}\n\nbool dfs(Puzzle &state, int limit, int depth, int prev, vector<int> &path)\n{\n Puzzle tmp;\n int r;\n int tx;\n int ty;\n\n if (state.MD == 0)\n {\n return true;\n }\n if (depth + state.MD > limit)\n {\n return false;\n }\n\n rep(r, 4)\n {\n tx = state.sx + dx.at(r);\n ty = state.sy + dy.at(r);\n if (tx < 0 || ty < 0 || tx >= N || ty >= N)\n {\n continue;\n }\n if (abs(prev - r) == 2)\n {\n continue;\n }\n tmp = state;\n state.MD -= MDT.at(tx * N + ty).at(state.f.at(tx).at(ty) - 1);\n state.MD += MDT.at(state.sx * N + state.sy).at(state.f.at(tx).at(ty) - 1);\n swap(state.f.at(tx).at(ty), state.f.at(state.sx).at(state.sy));\n state.sx = tx;\n state.sy = ty;\n if (dfs(state, limit, depth + 1, r, path))\n {\n path.at(depth) = r;\n return true;\n }\n state = tmp;\n }\n return false;\n}\n\nstring iterative_deepening(Puzzle in)\n{\n int limit;\n int i;\n Puzzle state;\n string ans;\n\n in.MD = getAllMD(in);\n for (limit = in.MD; limit <= LIMIT; limit++)\n {\n vector<int> path(limit);\n state = in;\n if (dfs(state, limit, 0, -100, path))\n {\n ans = \"\";\n rep(i, limit)\n {\n ans += dir.at(path.at(i));\n }\n return ans;\n }\n }\n return \"\";\n}\n\nint main()\n{\n int i;\n int j;\n Puzzle in;\n string ans;\n\n makeMDT();\n\n rep(i, N)\n {\n rep(j, N)\n {\n cin >> in.f.at(i).at(j);\n if (in.f.at(i).at(j) == 0)\n {\n in.f.at(i).at(j) = N * N;\n in.sx = i;\n in.sy = j;\n }\n }\n }\n\n ans = iterative_deepening(in);\n cout << ans.size() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 750, "memory_kb": 3584, "score_of_the_acc": -0.3684, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_13_C_10401363", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\n// 目标状态\nconst string target = \"123456789ABCDEF0\";\n\n// 计算曼哈顿距离\nint manhattanDistance(const string& state) {\n int dist = 0;\n for (int i = 0; i < 16; ++i) {\n if (state[i] == '0') continue;\n int targetPos = state[i] - '1';\n int currentRow = i / 4;\n int currentCol = i % 4;\n int targetRow = targetPos / 4;\n int targetCol = targetPos % 4;\n dist += abs(currentRow - targetRow) + abs(currentCol - targetCol);\n }\n return dist;\n}\n\n// 找到空格(数字 0)的位置\nint findZero(const string& state) {\n return state.find('0');\n}\n\n// 交换字符串中两个位置的字符\nstring swapChars(string state, int i, int j) {\n swap(state[i], state[j]);\n return state;\n}\n\n// 节点结构体\nstruct Node {\n string state;\n int g; // 从起始节点到当前节点的实际代价\n int h; // 从当前节点到目标节点的估计代价\n int f; // f = g + h\n\n Node(string s, int _g) : state(s), g(_g) {\n h = manhattanDistance(state);\n f = g + h;\n }\n\n // 重载小于运算符,用于优先队列\n bool operator>(const Node& other) const {\n return f > other.f;\n }\n};\n\n// A* 算法\nint aStar(const string& start) {\n priority_queue<Node, vector<Node>, greater<Node>> pq;\n unordered_set<string> visited;\n\n pq.push(Node(start, 0));\n visited.insert(start);\n\n while (!pq.empty()) {\n Node current = pq.top();\n pq.pop();\n\n if (current.state == target) {\n return current.g;\n }\n\n int zeroPos = findZero(current.state);\n int row = zeroPos / 4;\n int col = zeroPos % 4;\n\n // 尝试四个方向的移动\n int dx[] = {-1, 1, 0, 0};\n int dy[] = {0, 0, -1, 1};\n\n for (int i = 0; i < 4; ++i) {\n int newRow = row + dx[i];\n int newCol = col + dy[i];\n\n if (newRow >= 0 && newRow < 4 && newCol >= 0 && newCol < 4) {\n int newPos = newRow * 4 + newCol;\n string nextState = swapChars(current.state, zeroPos, newPos);\n\n if (visited.find(nextState) == visited.end()) {\n pq.push(Node(nextState, current.g + 1));\n visited.insert(nextState);\n }\n }\n }\n }\n\n return -1; // 理论上不会执行到这里,因为题目保证有解\n}\n\nint main() {\n string start;\n for (int i = 0; i < 16; ++i) {\n int num;\n cin >> num;\n if (num == 0) {\n start += '0';\n } else if (num < 10) {\n start += to_string(num);\n } else {\n start += 'A' + num - 10;\n }\n }\n\n int result = aStar(start);\n cout << result << endl;\n\n return 0;\n}", "accuracy": 0.6428571428571429, "time_ms": 520, "memory_kb": 92756, "score_of_the_acc": -0.5977, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_13_C_10394299", "code_snippet": "#include <iostream>\n#include <queue>\n#include <unordered_map>\n#include <cmath>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nconst int n = 4;\nconst int maxLimit = 45;\nconst vector<int> dr = {0, 1, 0, -1};\nconst vector<int> dc = {1, 0, -1, 0};\n\nstruct Puzzle {\n string board;\n int zeroPos;\n int g;\n\n Puzzle(string b, int zp, int depth) : board(b), zeroPos(zp), g(depth) {}\n\n int getHeuristic() const {\n int h = 0;\n for (int i = 0; i < 16; ++i) {\n if (board[i] == '0') continue;\n int val = board[i] - '1';\n int goalRow = val / 4, goalCol = val % 4;\n int curRow = i / 4, curCol = i % 4;\n h += abs(goalRow - curRow) + abs(goalCol - curCol);\n }\n return h;\n }\n\n bool isGoal() const {\n for (int i = 0; i < 15; ++i)\n if (board[i] != '1' + i) return false;\n return board[15] == '0';\n }\n};\n\n// Custom comparator for priority_queue\nstruct ComparePuzzle {\n bool operator()(const pair<int, Puzzle>& a, const pair<int, Puzzle>& b) const {\n return a.first > b.first; // min-heap by f = g + h\n }\n};\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n string inputBoard = \"\";\n int zeroPos = 0;\n\n for (int i = 0, num; i < 16; ++i) {\n cin >> num;\n inputBoard += static_cast<char>('0' + num);\n if (num == 0) zeroPos = i;\n }\n\n Puzzle start(inputBoard, zeroPos, 0);\n priority_queue<pair<int, Puzzle>, vector<pair<int, Puzzle>>, ComparePuzzle> pq;\n\n unordered_map<string, int> visited;\n int h = start.getHeuristic();\n pq.emplace(h, start);\n visited[start.board] = 0;\n\n while (!pq.empty()) {\n auto [f, cur] = pq.top();\n pq.pop();\n\n if (cur.isGoal()) {\n cout << cur.g << '\\n';\n return 0;\n }\n\n if (cur.g > maxLimit) continue;\n\n int r = cur.zeroPos / 4, c = cur.zeroPos % 4;\n\n for (int i = 0; i < 4; ++i) {\n int nr = r + dr[i], nc = c + dc[i];\n if (nr < 0 || nr >= 4 || nc < 0 || nc >= 4) continue;\n\n int nextPos = nr * 4 + nc;\n string nextBoard = cur.board;\n swap(nextBoard[cur.zeroPos], nextBoard[nextPos]);\n\n int newG = cur.g + 1;\n if (visited.count(nextBoard) && visited[nextBoard] <= newG) continue;\n\n visited[nextBoard] = newG;\n Puzzle next(nextBoard, nextPos, newG);\n int nextH = next.getHeuristic();\n pq.emplace(newG + nextH, next);\n }\n }\n\n cout << -1 << '\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 1330, "memory_kb": 244820, "score_of_the_acc": -1.6085, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_13_C_10394045", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <string>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <set>\n#include <cmath>\n#include <algorithm>\n#include <bitset>\n#include <climits>\n#include <functional>\nusing namespace std;\n\nint n = 4, limit = 0, maxLimit = 45;\n\nvector<int> dr{0, 1, 0, -1}, dc{1, 0, -1, 0};\n\nstruct Puzzle {\n vector<vector<int> > mat;\n pair<int, int> zeroPos;\n\n Puzzle() {\n mat.resize(n, vector<int>(n));\n }\n\n void swapZero(pair<int, int> nextPos) {\n swap(mat[zeroPos.first][zeroPos.second], mat[nextPos.first][nextPos.second]);\n zeroPos = nextPos;\n }\n\n bool isGoal() {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int goal = (i * n + j + 1) % (n * n);\n if (mat[i][j] != goal) return false;\n }\n }\n return true;\n }\n\n int getCost() {\n int cost = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (mat[i][j] == 0) continue;\n int num = mat[i][j] - 1;\n int goali = num / n, goalj = num % n;\n\n cost += (abs(goali - i) + abs(goalj - j));\n }\n }\n\n return cost;\n }\n\n void print() {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n cout << mat[i][j] << \" \";\n }\n cout << endl;\n }\n cout << \"--------\" << endl;\n }\n};\n\nint dfs(Puzzle &cur, pair<int, int> lastPos, int d) {\n if (cur.isGoal()) return d;\n\n // if ((d == 1 || d == 2) && limit == 40) {\n // cur.print();\n // }\n\n pair<int, int> curPos = cur.zeroPos;\n\n for (int i = 0; i < 4; i++) {\n int nextr = curPos.first + dr[i], nextc = curPos.second + dc[i];\n \n if (nextr < 0 || nextr >= n || nextc < 0 || nextc >= n) continue;\n\n pair<int, int> nextPos = {nextr, nextc};\n if (lastPos == nextPos) continue;\n\n cur.swapZero(nextPos);\n\n int cost = cur.getCost();\n \n if (d + cost <= limit) {\n int res = dfs(cur, curPos, d + 1);\n if (res != -1) return res;\n }\n\n cur.swapZero(curPos);\n }\n\n return -1;\n}\n\nint main () {\n Puzzle puzzle;\n\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n cin >> puzzle.mat[i][j];\n if (puzzle.mat[i][j] == 0) {\n puzzle.zeroPos = {i, j};\n }\n }\n }\n\n for (; limit <= maxLimit; limit++) {\n int res = dfs(puzzle, {-1, -1}, 0);\n if (res != -1) {\n cout << res << endl;\n return 0;\n }\n }\n\n cout << -1 << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 240, "memory_kb": 3452, "score_of_the_acc": -0.1049, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_13_C_10394012", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <string>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <set>\n#include <cmath>\n#include <algorithm>\n#include <bitset>\n#include <climits>\n#include <functional>\nusing namespace std;\n\nint n = 4, limit = 0, maxLimit = 45;\n\nvector<int> dr{0, 1, 0, -1}, dc{1, 0, -1, 0};\n\nstruct Puzzle {\n vector<vector<int> > mat;\n pair<int, int> zeroPos;\n\n Puzzle() {\n mat.resize(n, vector<int>(n));\n }\n\n void swapZero(pair<int, int> nextPos) {\n swap(mat[zeroPos.first][zeroPos.second], mat[nextPos.first][nextPos.second]);\n zeroPos = nextPos;\n }\n\n bool isGoal() {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int goal = (i * n + j + 1) % (n * n);\n if (mat[i][j] != goal) return false;\n }\n }\n return true;\n }\n\n int getCost() {\n int cost = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int num = (mat[i][j] + (n * n) - 1) % (n * n);\n\n int goali = num / n, goalj = num % n;\n\n cost += (abs(goali - i) + abs(goalj - j));\n }\n }\n\n return cost;\n }\n};\n\nint dfs(Puzzle &cur, pair<int, int> lastPos, int d) {\n if (cur.isGoal()) return d;\n\n pair<int, int> curPos = cur.zeroPos;\n\n for (int i = 0; i < 4; i++) {\n int nextr = curPos.first + dr[i], nextc = curPos.second + dc[i];\n \n if (nextr < 0 || nextr >= n || nextc < 0 || nextc >= n) continue;\n\n pair<int, int> nextPos = {nextr, nextc};\n if (lastPos == nextPos) continue;\n\n cur.swapZero(nextPos);\n\n int cost = cur.getCost();\n \n if (d + cost <= limit) {\n int res = dfs(cur, curPos, d + 1);\n if (res != -1) return res;\n }\n\n cur.swapZero(curPos);\n }\n\n return -1;\n}\n\nint main () {\n Puzzle puzzle;\n\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n cin >> puzzle.mat[i][j];\n if (puzzle.mat[i][j] == 0) {\n puzzle.zeroPos = {i, j};\n }\n }\n }\n\n for (; limit <= maxLimit; limit++) {\n int res = dfs(puzzle, {-1, -1}, 0);\n if (res != -1) {\n cout << res << endl;\n return 0;\n }\n }\n\n cout << -1 << endl;\n\n return 0;\n}", "accuracy": 0.8571428571428571, "time_ms": 750, "memory_kb": 3456, "score_of_the_acc": -0.3679, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_13_C_10393992", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <string>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <set>\n#include <cmath>\n#include <algorithm>\n#include <bitset>\n#include <climits>\n#include <functional>\nusing namespace std;\n\nint n = 4, limit = 0, maxLimit = 45;\n\nvector<int> dr{0, 1, 0, -1}, dc{1, 0, -1, 0};\n\nstruct Puzzle {\n vector<vector<int> > mat;\n pair<int, int> zeroPos;\n\n Puzzle() {\n mat.resize(n, vector<int>(n));\n }\n\n void swapZero(pair<int, int> nextPos) {\n swap(mat[zeroPos.first][zeroPos.second], mat[nextPos.first][nextPos.second]);\n zeroPos = nextPos;\n }\n\n bool isGoal() {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int goal = (i * n + j + 1) % (n * n);\n if (mat[i][j] != goal) return false;\n }\n }\n return true;\n }\n\n int getCost() {\n int cost = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int num = mat[i][j] - 1;\n\n int goali = num / n, goalj = num % n;\n\n cost += (abs(goali - i) + abs(goalj - j));\n }\n }\n\n return cost;\n }\n};\n\nint dfs(Puzzle &cur, pair<int, int> lastPos, int d) {\n if (cur.isGoal()) return d;\n\n pair<int, int> curPos = cur.zeroPos;\n\n for (int i = 0; i < 4; i++) {\n int nextr = curPos.first + dr[i], nextc = curPos.second + dc[i];\n \n if (nextr < 0 || nextr >= n || nextc < 0 || nextc >= n) continue;\n\n pair<int, int> nextPos = {nextr, nextc};\n if (lastPos == nextPos) continue;\n\n cur.swapZero(nextPos);\n\n int cost = cur.getCost();\n \n if (d + cost <= limit) {\n int res = dfs(cur, curPos, d + 1);\n if (res != -1) return res;\n }\n\n cur.swapZero(curPos);\n }\n\n return -1;\n}\n\nint main () {\n Puzzle puzzle;\n\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n cin >> puzzle.mat[i][j];\n if (puzzle.mat[i][j] == 0) {\n puzzle.zeroPos = {i, j};\n }\n }\n }\n\n for (; limit <= maxLimit; limit++) {\n int res = dfs(puzzle, {-1, -1}, 0);\n if (res != -1) {\n cout << res << endl;\n return 0;\n }\n }\n\n cout << -1 << endl;\n\n return 0;\n}", "accuracy": 0.7142857142857143, "time_ms": 1300, "memory_kb": 3464, "score_of_the_acc": -0.6514, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_13_C_10307826", "code_snippet": "#include<cstdio>\n#include<iostream>\n#include<cmath>\n#include<map>\n#include<queue>\n\nusing namespace std;\n#define N 4\n#define N2 16\n\nstatic const int dx[4] = {0, -1, 0, 1};\nstatic const int dy[4] = {1, 0, -1, 0};\nstatic const char dir[4] = {'r','u','l','d'};\nint MDT[N2][N2];\n\nstruct Puzzle {\n int f[N2], space, MD;\n int cost;\n\n bool operator < ( const Puzzle &p ) const {\n for ( int i = 0; i < N2; i++ ) {\n if ( f[i] == p.f[i] ) continue;\n return f[i] < p.f[i];\n }\n return false;\n }\n};\nstruct State {\n Puzzle puzzle;\n int estimated;\n bool operator < (const State &s) const {\n return estimated > s.estimated;\n }\n};\n\nint getAllMD(Puzzle pz) {\n int sum = 0;\n for ( int i = 0; i < N2; i++ ) {\n if ( pz.f[i] == N2 ) continue;\n sum += MDT[i][pz.f[i] - 1];\n }\n return sum;\n}\n\nint astar(Puzzle s) {\n priority_queue<State> PQ;\n s.MD = getAllMD(s);\n s.cost = 0;\n map<Puzzle, bool> V;\n Puzzle u, v;\n State initial;\n initial.puzzle = s;\n initial.estimated = getAllMD(s);\n PQ.push(initial);\n while ( !PQ.empty() ) {\n State st = PQ.top(); PQ.pop();\n u = st.puzzle;\n\n if ( u.MD == 0 ) return u.cost;\n V[u] = true;\n\n int sx = u.space / N;\n int sy = u.space % N;\n\n for ( int r = 0; r < 4; r++ ) {\n int tx = sx + dx[r];\n int ty = sy + dy[r];\n if ( tx < 0 || ty < 0 || tx >= N || ty >= N ) continue;\n v = u;\n\n v.MD -= MDT[tx * N + ty][v.f[tx * N + ty] - 1];\n v.MD += MDT[sx * N + sy][v.f[tx * N + ty] - 1];\n\n swap(v.f[sx * N + sy], v.f[tx * N + ty]);\n v.space = tx * N + ty;\n if ( !V[v] ) {\n v.cost++;\n State news;\n news.puzzle = v;\n news.estimated = v.cost + v.MD;\n PQ.push(news);\n }\n }\n }\n return -1;\n}\n\nint main() {\n for ( int i = 0; i < N2; i++ )\n for ( int j = 0; j < N2; j++ )\n MDT[i][j] = abs(i / N - j / N) + abs(i % N - j % N);\n\n Puzzle in;\n\n for ( int i = 0; i < N2; i++ ) {\n cin >> in.f[i];\n if ( in.f[i] == 0 ) {\n in.f[i] = N2;\n in.space = i;\n }\n }\n cout << astar(in) << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 1980, "memory_kb": 258956, "score_of_the_acc": -1.9987, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_13_C_10230966", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n#include <queue>\n#include <map>\nusing namespace std;\n\n#define MAX_SIZE (4)\n\nint b[MAX_SIZE][MAX_SIZE];\nint limit;\n\nint dx[] = {-1, 0, 1, 0};\nint dy[] = {0, -1, 0, 1};\n\nint dist() {\n int res = 0, n;\n for(int i = 0; i < MAX_SIZE; i++) {\n for(int j = 0; j < MAX_SIZE; j++) {\n if(b[i][j] == 0) continue;\n n = b[i][j]-1;\n res += abs(n/4-i) + abs(n%4-j);\n }\n }\n return res;\n}\n\nbool check(int depth, int prev, int x, int y) {\n int h = dist();\n if(h+depth > limit) return false;\n if(h == 0) return true; //目標の配置ならば終了\n for(int i = 0; i<4; i++) {\n if(abs(i-prev) == 2) continue;\n int ny = y + dy[i]; //新しい空白の座標\n int nx = x + dx[i];\n if(ny < 0 || nx < 0) continue; //新しい座標が盤面外ならスキップ\n if(ny > 3 || nx > 3) continue;\n swap(b[ny][nx], b[y][x]);\n if(check(depth+1, i, nx, ny)) return true;\n swap(b[ny][nx], b[y][x]);\n }\n return false;\n}\n\n\nint solve(int x, int y) {\n for(limit = 0;; limit++) {\n if(check(0, 99, x, y)) {\n cout << limit << endl;\n return 0;\n }\n }\n}\n\n\nint main(void) {\n int x;\n int y;\n //入力\n for(int i = 0; i < MAX_SIZE; i++) {\n for(int j = 0; j < MAX_SIZE; j++) {\n cin >> b[i][j];\n if(b[i][j] == 0) { //0の場所を記録\n x = j;\n y = i;\n }\n }\n }\n\n solve(x, y);\n\n return 0;\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 3440, "score_of_the_acc": -0.0946, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_13_C_10216256", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define N 4\n#define N2 16\n#define Limit 100\nstatic const int dx[4]={0,-1,0,1};\nstatic const int dy[4]={1,0,-1,0};\nstatic const char dir[4]={'r','u','l','d'};\nint mdt[N2][N2];\nstruct puzzle{\n\tint f[N2],space,md;\n};\npuzzle state;\nint limit,path[Limit];\nint getallmd(puzzle pz){\n\tint sum=0;\n\tfor(int i=0;i<N2;i++){\n\t\tif(pz.f[i]==N2) continue;\n\t\tsum+=mdt[i][pz.f[i]-1];\n\t}\n\treturn sum;\n}\nbool issolved(){\n\tfor(int i=0;i<N2;i++)if(state.f[i]!=i+1) return false;\n\treturn true;\n}\nbool dfs(int depth,int prev){\n\tif(state.md==0) return true;\n\tif(depth+state.md > limit) return false;\n\tint sx=state.space/N;\n\tint sy=state.space%N;\n\tpuzzle tmp;\n\tfor(int r=0;r<4;r++){\n\t\tint tx=sx+dx[r];\n\t\tint ty=sy+dy[r];\n\t\tif(tx<0 || ty<0 || tx>=N || ty>=N ) continue;\n\t\tif(max(prev,r)-min(prev,r)==2) continue;\n\t\ttmp=state;\n\t\tstate.md-=mdt[tx*N+ty][state.f[tx*N+ty]-1];\n\t\tstate.md+=mdt[sx*N+sy][state.f[tx*N+ty]-1];\n\t\tswap(state.f[tx*N+ty],state.f[sx*N+sy]);\n\t\tstate.space=tx*N+ty;\n\t\tif(dfs(depth+1,r)){\n\t\t\tpath[depth]=r;\n\t\t\treturn true;\n\t\t}\n\t\tstate=tmp;\n\t} \n\treturn false;\n}\nstring iterative_deepening(puzzle in){\n\tin.md=getallmd(in);\n\tfor(limit=in.md;limit<=Limit;limit++){\n\t\tstate=in;\n\t\tif(dfs(0,-100)){\n\t\t\tstring ans= \"\";\n\t\t\tfor(int i=0;i<limit;i++) ans+=dir[path[i]];\n\t\t\treturn ans;\n\t\t}\n\t}\n\treturn \"unsolvable\";\n}\nint main(){\n\tfor(int i=0;i<N2;i++){\n\t\tfor(int j=0;j<N2;j++){\n\t\t\tmdt[i][j]=abs(i/N-j/N)+abs(i%N-j%N);\n\t\t}\n\t}\n\tpuzzle in;\n\tfor(int i=0;i<N2;i++){\n\t\tcin>>in.f[i];\n\t\tif(in.f[i]==0){\n\t\t\tin.f[i]=N2;\n\t\t\tin.space=i;\n\t\t}\n\t}\n\tstring ans=iterative_deepening(in);\n\tcout<<ans.size()<<endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3488, "score_of_the_acc": -0.0123, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_13_C_10199949", "code_snippet": "#include <stdio.h>\n#include <stdlib.h>\n#define N 4\n#define true 1\n#define false 0\n\nint dx[4] = {0, -1, 0, 1};\nint dy[4] = {1, 0, -1, 0};\nint limit;\nint t[N][N];\n\nvoid swap(int *x, int *y) {\n int tmp = *x;\n *x = *y;\n *y = tmp;\n}\n\nint getHeuristic() {\n int i, j, sum = 0, x;\n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++) {\n if (t[i][j] == 0) continue; \n x = t[i][j] - 1;\n sum += abs(x / 4 - i) + abs(x % 4 - j);\n }\n }\n return sum;\n}\n\nint dfs(int depth, int prev, int py, int px) {\n int h = getHeuristic();\n if (h == 0) return true; \n if (depth + h > limit) return false;\n\n int i;\n for (i = 0; i < 4; i++) {\n if (abs(i - prev) == 2) continue;\n\n int tx = px + dx[i], ty = py + dy[i];\n if (tx < 0 || ty < 0 || tx >= N || ty >= N) continue; \n\n swap(&t[ty][tx], &t[py][px]); \n if (dfs(depth + 1, i, ty, tx)) return true;\n swap(&t[ty][tx], &t[py][px]); \n }\n return false;\n}\n\nvoid isSolved(int py, int px) {\n for (limit = 0;; limit++) {\n if (dfs(0, 99, py, px)) {\n printf(\"%d\\n\", limit);\n return;\n }\n }\n}\n\nint main() {\n int i, j, px, py;\n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++) {\n scanf(\"%d\", &t[i][j]);\n if (t[i][j] == 0) { \n py = i;\n px = j;\n }\n }\n }\n isSolved(py, px);\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 2980, "score_of_the_acc": -0.0516, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_13_C_10184764", "code_snippet": "// Iterative Deepening C++\n#include<stdio.h>\n#include<iostream>\n#include<cmath>\n#include<string>\n#include<cassert>\n\nusing namespace std;\n\n#define N 4\n#define N2 16\n#define LIMIT 100\nstatic const int dx[4]={0,-1,0,1};\nstatic const int dy[4]={1,0,-1,0};\nstatic const char dir[4]={'r','u','l','d'};\nint MDT[N2][N2];\n\n\nstruct Puzzle{int f[N2],space, MD;};\n\nPuzzle state;\nint limit;/*深さの制限*/\nint path[LIMIT];\n\nint fucking_getALLMD(Puzzle pz){\n int sum=0;\n for(int i=0;i<N2;i++){\n if(pz.f[i]==N2) continue;\n sum+=MDT[i][pz.f[i]-1];\n }\n return sum;\n}\n\nbool fucking_isSolved(){\n for(int i=0;i<N2;i++) if(state.f[i]!=i+1) return false;\n\n return true;\n}\n\nbool fucking_dfs(int depth, int prev){\n if(state.MD==0) return true;\n /*現在の深さにヒューリスティックを足して制限を越えたら枝を刈る*/\n if(depth+state.MD>limit) return false;\n\n int sx=state.space/N;\n int sy=state.space%N;\n Puzzle tmp;\n\n for(int r=0;r<4;r++){\n int tx=sx+dx[r];\n int ty=sy+dy[r];\n if(tx<0||ty<0||tx>=N||ty>=N) continue;\n if(max(prev, r)-min(prev, r)==2) continue;\n tmp=state;\n /*マンハッタン距離の差分を計算しつつ、ピースをスワップ*/\n state.MD-=MDT[tx*N+ty][state.f[tx*N+ty]-1];\n state.MD+=MDT[sx*N+sy][state.f[tx*N+ty]-1];\n swap(state.f[tx*N+ty],state.f[sx*N+sy]);\n state.space=tx*N+ty;\n if(fucking_dfs(depth+1,r)){path[depth]=r; return true;}\n\n state=tmp;\n }\n return false;\n}\n\n\n/*反復深化*/\nstring fucking_iterative_deepening(Puzzle in){\n in.MD=fucking_getALLMD(in); /*初期状態のマンハッタン距離*/\n\n for(limit=in.MD;limit<=LIMIT;limit++){\n state=in;\n if(fucking_dfs(0,-100)){\n string ans=\"\";\n for(int i=0;i<limit;i++)ans+=dir[path[i]];\n return ans;\n }\n }\n return \"unsolvable\";\n}\nint main(){\n for(int i=0;i<N2;i++)\n for(int j=0;j<N2;j++)\n MDT[i][j]=abs(i/N-j/N)+abs(i%N-j%N);\n Puzzle in;\n for(int i=0;i<N2;i++){\n cin>>in.f[i];\n if(in.f[i]==0){\n in.f[i]=N2;\n in.space=i;\n }\n }\n\n string ans = fucking_iterative_deepening(in);\n cout<<ans.size()<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3444, "score_of_the_acc": -0.0121, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_13_C_10179410", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint x[4]={-1,0,1,0};\nint y[4]={0,-1,0,1};\nchar z[4]={'u','l','d','r'};\nvector<vector<int>>mdt(16,vector<int>(16));\n\nstruct pazuru{int a[16],kuhaku,md;};\npazuru genzai;\nint genkai;\nvector<int>miti(101);\n\n\n\nbool seigo(){\n for(int i=0;i<16;i++){\n if(genzai.a[i]!=i+1)return false;\n\n return true;\n }\n\n}\n\nint mdzenbu(pazuru g){\n int sum=0;\n for(int i=0;i<16;i++){\n if(g.a[i]==16)continue;\n sum+=mdt[i][g.a[i]-1];\n }\n return sum;\n\n\n}\n\nbool fukasayusen(int fukasa,int mae){\n if(genzai.md==0)return true;\n if(fukasa+genzai.md>genkai){\n return false;\n }\n\n int lx=genzai.kuhaku/4,ly=genzai.kuhaku%4;\n pazuru itizi;\n\n for(int i=0;i<4;i++){\n int mx=lx+x[i];int my=ly+y[i];\n if(mx<0 or my<0 or mx>=4 or my>=4)continue;\n if(max(mae,i)-min(mae,i)==2)continue;\n\n itizi=genzai;\n genzai.md-=mdt[mx*4+my][genzai.a[mx*4+my]-1];\n genzai.md+=mdt[lx*4+ly][genzai.a[mx*4+my]-1];\n\n swap(genzai.a[mx*4+my],genzai.a[lx*4+ly]);\n genzai.kuhaku=mx*4+my;\n\n if(fukasayusen(fukasa+1,i)){\n miti[fukasa]=i;\n return true;\n }\n genzai=itizi;\n }\n return false;\n\n}\n\nstring hanpukusinka(pazuru pan){\n pan.md=mdzenbu(pan);\n for(genkai=pan.md;genkai<=101;genkai++){\n genzai=pan;\n \n if(fukasayusen(0,-100)){\n string kotae=\"\";\n for(int i=0;i<genkai;i++){\n kotae+=z[miti[i]];\n }\n return kotae;\n }\n }\n return \"unsolvable\";\n}\n\nint main(){\n for(int i=0;i<16;i++){\n for(int j=0;j<16;j++){\n mdt[i][j]=abs(i/4-j/4)+abs(i%4-j%4);\n }\n }\n pazuru pan;\n\n for(int i=0;i<16;i++){\n cin >> pan.a[i];\n if(pan.a[i]==0){\n pan.a[i]=16;\n pan.kuhaku=i;\n }\n }\n string ans=hanpukusinka(pan);\n cout << ans.size() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3444, "score_of_the_acc": -0.0121, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_13_C_10176252", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n// ゴール状態(配列で表す)\nstatic const vector<int> GOAL = {\n 1, 2, 3, 4,\n 5, 6, 7, 8,\n 9, 10,11,12,\n 13,14,15,0\n};\n\n// 4x4 の各マスにおける(行,列)を事前に求めておく\n// 例: index=0 -> (0,0), index=5 -> (1,1) など\n// これによりマンハッタン距離計算が簡単になる\nstatic vector<pair<int,int>> indexToRC(16);\n\n// ゴール位置: タイル番号 n (1~15) が最終的にどこにあるか (row,col)\nstatic vector<pair<int,int>> goalPos(16);\n\n// 空白(0)が動かせる方向をプリセット\n// blankPos によって動かせるパネルは異なるが、\n// row, col ごとに移動可能な方向を持っていてもよい\n// ここでは直接計算してもOKだが、事前に隣接先をテーブル化してもよい\nint dr[4] = { -1, 1, 0, 0 }; // 上 下 左 右\nint dc[4] = { 0, 0, -1, 1 };\n\n// -------------------------------------\n// ヒューリスティック: マンハッタン距離の合計\n// -------------------------------------\nint manhattanDist(const vector<int>& board) {\n int dist = 0;\n for(int i=0; i<16; i++){\n int val = board[i];\n if(val == 0) continue; // 空白はカウントしない\n // タイルvalの現在位置(i)とゴール位置goalPos[val]の差を足す\n auto [r, c] = indexToRC[i];\n auto [gr, gc] = goalPos[val];\n dist += abs(r - gr) + abs(c - gc);\n }\n return dist;\n}\n\n// -------------------------------------\n// IDA*再帰DFS: 現在の深さg, 現在のヒューリスティックh, 閾値threshold\n// をもとに探索して、解を見つければ深さ(手数)を返す。\n// 見つからなければ、\n// - 次に試行すべき( g + h )の最小値(=次のthreshold候補)\n// を返す。\n// -------------------------------------\nint idaSearch(vector<int>& board, int g, int h, int threshold, int prevBlankPos, int& nodesSearched) {\n nodesSearched++;\n\n int f = g + h;\n if(f > threshold) {\n // これ以上探索できないので、この先で最小となる(f= g+h)を戻す\n return f;\n }\n // goal チェック\n if(board == GOAL) {\n // 解が見つかった\n return -1; // 特殊値で「解発見」を表すことにする\n }\n\n // 空白(0)の位置を探す\n int blankPos = 0;\n for(int i=0; i<16; i++){\n if(board[i] == 0){\n blankPos = i;\n break;\n }\n }\n\n int row = blankPos / 4;\n int col = blankPos % 4;\n\n int minNextThreshold = INT_MAX;\n\n // 4方向試す (上,下,左,右)\n for(int k=0; k<4; k++){\n int nr = row + dr[k];\n int nc = col + dc[k];\n // 盤面外はスキップ\n if(nr<0 || nr>=4 || nc<0 || nc>=4) continue;\n\n int nextPos = nr*4 + nc;\n // 「直前の位置にただ戻るだけ」を避けたい場合\n // (prevBlankPos が -1 でなければ)\n if(prevBlankPos == nextPos) {\n // 直前に移動したタイルを元に戻す動きなのでスキップ\n continue;\n }\n\n // board[blankPos] と board[nextPos] を交換 (実際には0とタイルを交換)\n // 交換前のタイル番号を記録\n int tileVal = board[nextPos];\n\n // (ヒューリスティック更新) tileVal の位置が変わることで h がどの程度増減するか\n // 事前に計算してから入れ替えると若干効率が良い\n\n // 現在位置(blankPos) と nextPos の座標を取得\n auto [r0, c0] = indexToRC[blankPos];\n auto [r1, c1] = indexToRC[nextPos];\n // タイル tileVal のゴール位置 (gr, gc)\n auto [gr, gc] = goalPos[tileVal];\n\n // 移動前のマンハッタン距離寄与分\n // = abs(r1 - gr) + abs(c1 - gc)\n int oldCost = abs(r1 - gr) + abs(c1 - gc);\n // 移動後のマンハッタン距離寄与分\n // = abs(r0 - gr) + abs(c0 - gc)\n int newCost = abs(r0 - gr) + abs(c0 - gc);\n\n int deltaH = newCost - oldCost; // 増減分\n\n // タイル交換(実際のboard更新)\n board[blankPos] = tileVal;\n board[nextPos] = 0;\n\n // 再帰探索\n int t = idaSearch(board, g + 1, h + deltaH, threshold, blankPos, nodesSearched);\n\n // 元に戻す\n board[nextPos] = tileVal;\n board[blankPos] = 0;\n\n // t == -1 なら「解を発見した」合図\n if(t == -1) {\n return -1; \n }\n // そうでなければ minNextThreshold を更新 (t は次に試すべき閾値候補)\n if(t < minNextThreshold) {\n minNextThreshold = t;\n }\n }\n\n return minNextThreshold;\n}\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n // indexToRC と goalPos を初期化\n for(int i=0; i<16; i++){\n indexToRC[i] = make_pair(i/4, i%4);\n }\n // タイル n(1~15) があるべきゴール位置を先に求めておく\n // GOAL[i] = n のとき、 n が (i/4, i%4) にある\n for(int i=0; i<16; i++){\n int val = GOAL[i];\n goalPos[val] = indexToRC[i];\n }\n\n // パズルの入力を受け取り\n // board[0..15] に格納\n vector<int> board(16);\n for(int i=0; i<16; i++){\n cin >> board[i];\n }\n\n // まずヒューリスティック h を計算\n int h = manhattanDist(board);\n\n // IDA* の反復深化\n int threshold = h;\n const int LIMIT = 50; // 問題文により45手以内に解けるので、少し余裕持たせる\n\n // 深さ探索の際にノード数カウント(デバッグ用途)\n int nodesSearched = 0;\n\n while(threshold <= LIMIT){\n int t = idaSearch(board, 0, h, threshold, -1, nodesSearched);\n if(t == -1){\n // 解が見つかった => 閾値 threshold が 解の手数\n cout << threshold << \"\\n\";\n return 0;\n }\n threshold = t; // 次のthresholdを更新\n }\n\n // ここに来ることは問題設定上ほぼ無いが、一応\n // 解が見つからなかった場合\n cout << \"-1\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3448, "score_of_the_acc": -0.0018, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_13_C_10174041", "code_snippet": "#include<stdio.h>\n#include<stdlib.h>\n\nint Puzzle[4][4];\nint tmp[4][4];\nint dx[4] = {0, 1, 0, -1};\nint dy[4] = {1, 0, -1, 0};\n\nvoid Empty(int *, int *);\nvoid swap(int *, int *);\nint Cal();\nint DFS(int, int, int, int, int);\n\nint main(){\n int i, j, l;\n int x, y, a;\n\n for(i = 0 ; i < 4 ; i++){\n for(j = 0 ; j < 4 ; j++){\n scanf(\"%d\",&Puzzle[i][j]);\n }\n }\n\n Empty(&x,&y);\n\n for(l = 0 ; l < 100 ; l++){\n for(i = 0 ; i < 4 ; i++){\n for(j = 0 ; j < 4 ; j++){\n\ttmp[i][j] = Puzzle[i][j];\n }\n }\n\n a = DFS(x, y, -1, 0, l);\n if(a != -1){\n printf(\"%d\\n\",a);\n break;\n }\n\n for(i = 0 ; i < 4 ; i++){\n for(j = 0 ; j < 4 ; j++){\n\tPuzzle[i][j] = tmp[i][j];\n }\n }\n \n a = -1;\n if(l == 99) printf(\"%d\\n\",a);\n }\n\n return 0;\n}\n\nvoid Empty(int *x, int *y){\n int i, j;\n\n for(i = 0 ; i < 4 ; i++){\n for(j = 0 ; j < 4 ; j++){\n if(!Puzzle[i][j]){\n\t*x = j;\n\t*y = i;\n\treturn;\n }\n }\n }\n}\n\nvoid swap(int *a, int *b){\n int tmp;\n \n tmp = *a;\n *a = *b;\n *b = tmp;\n}\n\n\nint Cal(){\n int i, a;\n int sum = 0;\n\n for(i = 0 ; i < 16 ; i++){\n a = Puzzle[i/4][i%4];\n if(a){\n a--;\n sum += abs(i/4 - a/4) + abs(i%4 - a%4);\n }\n }\n\n return sum;\n}\n\nint DFS(int x, int y, int p, int dep, int limit){\n int i, h, nx, ny, res;\n\n h = Cal();\n \n if(h == 0) return dep;\n if(dep + h > limit) return -1;\n\n for(i = 0 ; i < 4 ; i++){\n nx = x + dx[i];\n ny = y + dy[i];\n\n if(~p && i == (p+2)%4) continue;\n if(!(0 <= nx && nx < 4 && 0 <= ny && ny < 4)) continue;\n\n swap(&Puzzle[y][x], &Puzzle[ny][nx]);\n res = DFS(nx, ny, i, dep+1, limit);\n if(~res) return res;\n\n swap(&Puzzle[y][x], &Puzzle[ny][nx]);\n }\n\n return -1;\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 2976, "score_of_the_acc": -0.0825, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_13_C_10169166", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <algorithm>\nusing namespace std;\n\nstruct Puzzle {\n vector<int> state;\n int zero_pos;\n int moves;\n int heuristic;\n \n bool operator>(const Puzzle &other) const {\n return (moves + heuristic) > (other.moves + other.heuristic);\n }\n};\n\nconst vector<int> goal = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0};\nconst vector<int> dx = {-1, 1, 0, 0};\nconst vector<int> dy = {0, 0, -1, 1};\n\nint manhattan_distance(const vector<int> &state) {\n int distance = 0;\n for (int i = 0; i < 16; ++i) {\n if (state[i] == 0) continue;\n int target_x = (state[i] - 1) / 4;\n int target_y = (state[i] - 1) % 4;\n int x = i / 4;\n int y = i % 4;\n distance += abs(target_x - x) + abs(target_y - y);\n }\n return distance;\n}\n\nint a_star(vector<int> start) {\n priority_queue<Puzzle, vector<Puzzle>, greater<Puzzle>> pq;\n unordered_map<string, int> visited;\n \n int zero_pos = distance(start.begin(), find(start.begin(), start.end(), 0));\n pq.push({start, zero_pos, 0, manhattan_distance(start)});\n \n while (!pq.empty()) {\n Puzzle current = pq.top(); pq.pop();\n \n if (current.state == goal) return current.moves;\n \n string state_str = \"\";\n for (int num : current.state) state_str += to_string(num);\n if (visited.count(state_str) && visited[state_str] <= current.moves) continue;\n visited[state_str] = current.moves;\n \n int x = current.zero_pos / 4, y = current.zero_pos % 4;\n for (int i = 0; i < 4; ++i) {\n int nx = x + dx[i], ny = y + dy[i];\n if (nx >= 0 && nx < 4 && ny >= 0 && ny < 4) {\n vector<int> new_state = current.state;\n swap(new_state[current.zero_pos], new_state[nx * 4 + ny]);\n int new_heuristic = manhattan_distance(new_state);\n if (new_heuristic + current.moves + 1 <= 45) { // Limit moves to ensure optimal path within 45 steps\n pq.push({new_state, nx * 4 + ny, current.moves + 1, new_heuristic});\n }\n }\n }\n }\n return -1;\n}\n\nint main() {\n vector<int> start(16);\n for (int i = 0; i < 16; ++i) {\n cin >> start[i];\n }\n cout << a_star(start) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 1820, "memory_kb": 152432, "score_of_the_acc": -1.5006, "final_rank": 14 } ]
aoj_ALDS1_14_C_cpp
Pattern Search Find places where a R × C pattern is found within a H × W region. Print top-left coordinates ( i , j ) of sub-regions where the pattern found. The top-left and bottom-right coordinates of the region is (0, 0) and ( H -1, W -1) respectively. Input In the first line, two integers H and W are given. In the following H lines, i -th lines of the region are given. In the next line, two integers R and C are given. In the following R lines, i -th lines of the pattern are given. output For each sub-region found, print a coordinate i and j separated by a space character in a line. Print the coordinates in ascending order of the row numbers ( i ), or the column numbers ( j ) in case of a tie. Constraints 1 ≤ H, W ≤ 1000 1 ≤ R, C ≤ 1000 The input consists of alphabetical characters and digits Sample Input 1 4 5 00010 00101 00010 00100 3 2 10 01 10 Sample Output 1 0 3 1 2
[ { "submission_id": "aoj_ALDS1_14_C_10933201", "code_snippet": "#include<iostream>\n#include<vector>\n#include<string>\nusing namespace std;\nusing ull = unsigned long long;\n#define D1 1000000007\n#define D2 2000000011\n\nint main(){\n\tint H, W;\n\tcin >> H >> W;\n\tvector<string> str(H);\n\tfor(auto& i : str) cin >> i;\n\tint R, C;\n\tcin >> R >> C;\n\tif(R > H || C > W) return 0;\n\tvector<string> pt(R);\n\tfor(auto& i : pt) cin >> i;\n\tvector<ull> ph1(R, 0), ph2(ph1), sh1(R), sh2(R);\n\tull n1 = 1, n2 = 1;\n\tfor(int i = 0; i < C; i++){\n\t\tn1 *= D1, n2 *= D2;\n\t\tph1[0] = ph1[0] * D1 + pt[0][i];\n\t\tph2[0] = ph2[0] * D2 + pt[0][i];\n\t}\n\tfor(int i = 1; i < R; i++){\n\t\tfor(int j = 0; j < C; j++){\n\t\t\tph1[i] = ph1[i] * D1 + pt[i][j];\n\t\t\tph2[i] = ph2[i] * D2 + pt[i][j];\n\t\t}\n\t}\n\t\n\tfor(int k = 0, t1 = H - R + 1, t2 = W - C + 1; k < t1; k++){\n\t\tbool iscur = true;\n\t\tsh1.assign(R, 0);\n\t\tsh2.assign(R, 0);\n\t\tfor(int i = 0; i < R; i++){\n\t\t\tfor(int j = 0; j < C; j++){\n\t\t\t\tsh1[i] = sh1[i] * D1 + str[k + i][j];\n\t\t\t\tsh2[i] = sh2[i] * D2 + str[k + i][j];\n\t\t\t}\n\t\t\tif(sh1[i] != ph1[i] || sh2[i] != ph2[i]) iscur = false; \n\t\t}\n\t\tif(iscur) cout << k << ' ' << 0 << endl;\n\t\tfor(int l = 1; l < t2; l++){\n\t\t\tiscur = true;\n\t\t\tfor(int i = 0; i < R; i++){\n\t\t\t\tsh1[i] = sh1[i] * D1 - str[i + k][l - 1] * n1 + str[i + k][l + C - 1];\n\t\t\t\tsh2[i] = sh2[i] * D2 - str[i + k][l - 1] * n2 + str[i + k][l + C - 1];\n\t\t\t\tif(sh1[i] != ph1[i] || sh2[i] != ph2[i]) iscur = false; \n\t\t\t}\n\t\t\tif(iscur) cout << k << ' ' << l << endl;\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 830, "memory_kb": 7296, "score_of_the_acc": -0.6077, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_14_C_10854016", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\nstring s[1005],t[1005];\nll pre[1005][1005];\nll pre2[1005][1005];\nll mp[1005];\nll mq[1005];\nint n1,m1,n2,m2;\nll p=131,q=233;\nll Q=1e9+7;\nvoid solve(){\n\tmp[0]=mq[0]=1;\n\tfor(int i=1;i<=1000;i++){\n\t\tmp[i]=mp[i-1]*p%Q;\n\t\tmq[i]=mq[i-1]*q%Q;\n\t}\n\tfor(int i=1;i<=n1;i++){\n\t\tfor(int j=1;j<=m1;j++){\n\t\t\tpre[i][j]=(-pre[i-1][j-1]*p*q+pre[i-1][j]*p+pre[i][j-1]*q+s[i-1][j-1])%Q;\n\t\t\tpre[i][j]=(pre[i][j]+Q)%Q;\n\t\t}\n\t}\n\tfor(int i=1;i<=n2;i++){\n\t\tfor(int j=1;j<=m2;j++){\n\t\t\tpre2[i][j]=(-pre2[i-1][j-1]*p*q+pre2[i-1][j]*p+pre2[i][j-1]*q+t[i-1][j-1])%Q;\n\t\t\tpre2[i][j]=(pre2[i][j]+Q)%Q;\n\t\t}\n\t}\n\tll hs=pre2[n2][m2];\n\tfor(int i=1;i<=n1-n2+1;i++){\n\t\tfor(int j=1;j<=m1-m2+1;j++){\n\t\t\tll v=(pre[i+n2-1][j+m2-1]+pre[i-1][j-1]*mp[n2]%Q*mq[m2]%Q-pre[i+n2-1][j-1]*mq[m2]%Q-pre[i-1][j+m2-1]*mp[n2]%Q)%Q;\n\t\t\tv=(v+Q)%Q;\n\t\t\tif(v==hs){\n\t\t\t\tcout<<i-1<<' '<<j-1<<\"\\n\";\n\t\t\t}\n\t\t}\n\t}\t\n}\nint main(){\n//\tfreopen(\"a.txt\",\"r\",stdin);\n\tios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\tcin>>n1>>m1;\n\tfor(int i=0;i<n1;i++)cin>>s[i];\n\tcin>>n2>>m2;\n\tfor(int i=0;i<n2;i++)cin>>t[i];\n\tsolve();\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 21260, "score_of_the_acc": -0.2365, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_14_C_10412191", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n\n#define BASE0 (long long)2549\n#define BASE1 (long long)4283\n#define MOD (long long)1000000007\n\n/*\n* @brief 文字列のハッシュを生成\n* \n* @param [in] vField 元の2次元文字列\n* @param [in] fieldHeight 2次元文字列の高さ\n* @param [in] fieldWidth 2次元文字列の長さ\n* @param [in] powHeight 2次元文字列の高さ分BASE0を累乗した配列\n* @param [in] powWidth 2次元文字列の長さ分BASE1を累乗した配列\n* @returns ハッシュ値を持つ2次元配列\n*/\nstd::vector<std::vector<long long>> MakeHash(const std::vector<std::string>& vField, int fieldHeight, int fieldWidth, const std::vector<long long>& powHeight, const std::vector<long long>& powWidth)\n{\n\tstd::vector<std::vector<long long>> vHashedField(fieldHeight + 1, std::vector<long long>(fieldWidth + 1, 0));\n\n\tfor (int i = 0;i < fieldHeight;i++)\n\t{\n\t\tfor (int j = 0;j < fieldWidth;j++)\n\t\t{\n\t\t\tvHashedField[i + 1][j + 1] = (vField[i][j] * powHeight[i] % MOD * powWidth[j] % MOD + vHashedField[i][j + 1] + vHashedField[i + 1][j] - vHashedField[i][j] + MOD) % MOD;\n\t\t}\n\t}\n\n\treturn vHashedField;\n}\n\n/*\n* @brief 文字フィールドから検索パターンと一致する箇所を出力する\n* \n* @param [in] vHashedField 文字列フィールドのハッシュ値\n* @param [in] vHashedPattern 検索パターンのハッシュ値\n* @param [in] fieldHeight 2次元文字列の高さ\n* @param [in] fieldWidth 2次元文字列の長さ\n* @param [in] fieldHeight 2次元パターンの高さ\n* @param [in] fieldWidth 2次元パターンの長さ\n* @param [in] powHeight 2次元文字列の高さ分BASE0を累乗した配列\n* @param [in] powWidth 2次元文字列の長さ分BASE1を累乗した配列\n*/\nvoid OutputMatchPatternIndex(const std::vector<std::vector<long long>>& vHashedField, const std::vector<std::vector<long long>>& vHashedPattern, int fieldHeight, int fieldWidth, int patternRow, int patternColumn, const std::vector<long long>& powHeight, const std::vector<long long>& powWidth)\n{\n\tint numSearchRow = fieldHeight - patternRow + 1;\n\tint numSearchColumn = fieldWidth - patternColumn + 1;\n\n\tfor (int fri = 0;fri < numSearchRow;fri++)\n\t{\n\t\tfor (int fci = 0;fci < numSearchColumn;fci++)\n\t\t{\n\t\t\tint pr = patternRow, pc = patternColumn;\n\t\t\tlong long hashedFieldValue = (vHashedField[fri + pr][fci + pc] - vHashedField[fri][fci + pc] + MOD - vHashedField[fri + pr][fci] + MOD + vHashedField[fri][fci]) % MOD;\n\t\t\tlong long hashedPatternValue = vHashedPattern[pr][pc] * powHeight[fri] % MOD * powWidth[fci] % MOD;\n\n\t\t\tif (hashedFieldValue == hashedPatternValue)\n\t\t\t{\n\t\t\t\tstd::cout << fri << \" \" << fci << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n\nint main()\n{\n\tint fieldHeight, fieldWidth;\n\tstd::cin >> fieldHeight >> fieldWidth;\n\n\tstd::vector<std::string> vField(fieldHeight);\n\tfor (int i = 0;i < fieldHeight;i++)\n\t{\n\t\tstd::cin >> vField[i];\n\t}\n\t\n\tint patternRow, patternColumn;\n\tstd::cin >> patternRow >> patternColumn;\n\n\tstd::vector<std::string> vPattern(patternRow);\n\tfor (int i = 0;i < patternRow;i++)\n\t{\n\t\tstd::cin >> vPattern[i];\n\t}\n\n\tstd::vector<long long> powHeight(fieldHeight), powWidth(fieldWidth);\n\tpowHeight[0] = 1;\n\tpowWidth[0] = 1;\n\n\tfor (int i = 1;i < fieldHeight;i++)\n\t{\n\t\tpowHeight[i] = (powHeight[i - 1] * BASE0) % MOD;\n\t}\n\n\tfor (int i = 1;i < fieldWidth;i++)\n\t{\n\t\tpowWidth[i] = (powWidth[i - 1] * BASE1) % MOD;\n\t}\n\n\tstd::vector<std::vector<long long>> vHashedField = MakeHash(vField, fieldHeight, fieldWidth, powHeight, powWidth);\n\tstd::vector<std::vector<long long>> vHashedPattern = MakeHash(vPattern, patternRow, patternColumn, powHeight, powWidth);\n\n\tOutputMatchPatternIndex(vHashedField, vHashedPattern, fieldHeight, fieldWidth, patternRow, patternColumn, powHeight, powWidth);\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 22508, "score_of_the_acc": -0.5017, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_14_C_10204061", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#pragma GCC target(\"avx2\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define rep2(i,a,b) for (int i = (int)(a); i < (int)(b); i++)\n#define all(v) v.begin(),v.end()\n#define inc(x,l,r) ((l)<=(x)&&(x)<(r)) \n#define Unique(x) sort(all(x)), x.erase(unique(all(x)), x.end())\n#define pcnt __builtin_popcountll\n#define pb push_back\ntypedef long long ll;\n#define int ll\nusing ld = long double;\n//using ld = __float128;\nusing vi = vector<int>;\nusing vs = vector<string>;\nusing P = pair<int,int>;\nusing vp = vector<P>;\nusing ull = unsigned long long;\ntemplate<typename T1,typename T2> bool chmax(T1 &a, const T2 b) {if (a < b) {a = b; return true;} else return false; }\ntemplate<typename T1,typename T2> bool chmin(T1 &a, const T2 b) {if (a > b) {a = b; return true;} else return false; }\ntemplate<typename T> using priority_queue_greater = priority_queue<T, vector<T>, greater<T>>;\ntemplate<typename T> istream &operator>>(istream& is,vector<T> &v){for(T &in:v)is>>in;return is;}\ntemplate<class... T> void input(T&... a){(cin>> ... >> a);}\n#ifdef LOCAL\ntemplate<typename T> ostream &operator<<(ostream &os,const vector<T> &v){os<<\"\\x1b[32m\";rep(i,v.size())os<<v[i]<<(i+1!=v.size()?\" \":\"\");os<<\"\\x1b[0m\";return os;}\ntemplate<class T> int print(T& a){cout << \"\\x1b[32m\"<< a<< '\\n' << \"\\x1b[0m\";return 0;}\ntemplate<class T,class... Ts> int print(const T&a, const Ts&... b){cout << \"\\x1b[32m\" << a;(cout<<...<<(cout<<' ',b));cout<<'\\n' << \"\\x1b[0m\";return 0;}\n#else\ntemplate<typename T> ostream &operator<<(ostream &os,const vector<T> &v){rep(i,v.size())os<<v[i]<<(i+1!=v.size()?\" \":\"\");return os;}\ntemplate<class T> int print(T& a){cout << a<< '\\n';return 0;}\ntemplate<class T,class... Ts> int print(const T&a, const Ts&... b){cout << a;(cout<<...<<(cout<<' ',b));cout<<'\\n';return 0;}\n#endif\n#define VI(v,n) vi v(n); input(v)\n#define INT(...) int __VA_ARGS__; input(__VA_ARGS__)\nstruct __m___m__ {__m___m__(){cin.tie(0);ios_base::sync_with_stdio(false);cout << fixed << setprecision(20);}} _m_m_;\nint di[]={0,1,0,-1,-1,-1,1,1};\nint dj[]={1,0,-1,0,-1,1,-1,1};\nconst ll INF = 8e18;\n//mint stom(const string &s,int b=10){mint res = 0;for(auto c:s)res *= b,res += c-'0';return res;}\nuint32_t xor128() {\n static uint32_t x = 123456789,y = 362436069,z = 521288629,w = 88675123;\n uint32_t t;\n t = x ^ (x << 11);x = y; y = z; z = w;\n return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));\n}\nll randint(ll mn,ll mx){\n return xor128()%(mx+1-mn)+mn;\n}\nusing ull = unsigned long long;\nconst ull mod = 0x1fffffffffffffff;\nconst ull base1 = chrono::duration_cast<chrono::microseconds>(chrono::system_clock::now().time_since_epoch()).count() %mod;\nconst ull base2 = (base1 + 1123581321)%mod;\nstruct RollingHash2D {\n int H, W;\n vector<vector<ull>> hash;\n vector<ull> pow1, pow2;\n\n inline ull mul(ull a, ull b) const {\n __uint128_t ans = __uint128_t(a) * b;\n ans = (ans >> 61) + (ans & mod);\n if (ans >= mod) ans -= mod;\n return ans;\n }\n RollingHash2D(const vector<vector<ll>>& grid) {\n init(grid);\n }\n RollingHash2D(const vector<string>& grid) {\n H = grid.size();\n W = grid[0].size();\n vector numGrid(H, vector<ll>(W));\n rep(i,H)rep(j,W)numGrid[i][j] = grid[i][j];\n init(numGrid);\n }\n\n void init(const vector<vector<ll>>& grid) {\n H = grid.size();\n W = grid[0].size();\n hash.assign(H + 1, vector<ull>(W + 1, 0));\n pow1.assign(H + 1, 1);\n pow2.assign(W + 1, 1);\n rep(i,H) pow1[i+1] = mul(pow1[i], base1);\n rep(j,W) pow2[j+1] = mul(pow2[j], base2);\n rep(i,H)rep(j,W){\n hash[i+1][j+1] = grid[i][j];\n hash[i+1][j+1] += mul(hash[i+1][j], base2);\n hash[i+1][j+1] %= mod;\n hash[i+1][j+1] += mul(hash[i][j+1], base1);\n hash[i+1][j+1] %= mod;\n hash[i+1][j+1] += mod - mul(hash[i][j], mul(base1, base2));\n hash[i+1][j+1] %= mod;\n }\n }\n\n ull get(int li, int lj, int ri, int rj) {\n ull res = hash[ri][rj];\n res += mod - mul(hash[li][rj], pow1[ri-li]);\n res %= mod;\n res += mod - mul(hash[ri][lj], pow2[rj-lj]);\n res %= mod;\n res += mul(hash[li][lj], mul(pow1[ri-li], pow2[rj-lj]));\n res %= mod;\n return res;\n }\n};\n\nsigned main() {\n INT(h,w);\n vs s(h);cin>>s;\n INT(r,c);\n vs t(r);cin>>t;\n RollingHash2D rs(s), rt(t);\n rep(i,h-r+1)rep(j,w-c+1){\n if(rs.get(i,j,i+r,j+c) == rt.get(0,0,r,c))print(i,j);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 28868, "score_of_the_acc": -0.3451, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_14_C_10126456", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)\ntypedef unsigned long long ull;\nconst int N = 1e3 + 5;\nconst ull p1 = 257, p2 = 1e7 + 7;\n\nstring s1[N], s2[N];\null res, d2[N][N], d1[N][N];\n\nvoid solve() {\n int h1, h2, w1, w2;\n cin >> h1 >> w1;\n rep(i, h1) cin >> s1[i];\n cin >> h2 >> w2;\n rep(i, h2) cin >> s2[i];\n\n for (int i = 0; i < h2; i++) {\n ull t = 0;\n for (int j = 0; j < w2; j++) t = t * p1 + s2[i][j];\n res = res * p2 + t;\n }\n\n ull C = 1;\n for (int i = 0; i < w2; i++) C *= p1;\n for (int i = 0; i < h1; i++) {\n ull key = 0;\n for (int j = 0; j < w1; j++) {\n key = key * p1 + s1[i][j];\n if (j >= w2) key -= s1[i][j - w2] * C;\n d2[i][j] = d1[i][j] = key;\n }\n }\n\n C = 1;\n for (int i = 0; i < h2; i++) C *= p2;\n for (int i = 1; i < h1; i++) {\n for (int j = 0; j < w1; j++) {\n d1[i][j] = d1[i - 1][j] * p2 + d1[i][j];\n if (i >= h2) d1[i][j] -= d2[i - h2][j] * C;\n }\n }\n\n for (int i = h2 - 1; i < h1; i++) {\n for (int j = w2 - 1; j < w1; j++) {\n if (d1[i][j] == res) cout << i - h2 + 1 << \" \" << j - w2 + 1 << endl;\n }\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 21172, "score_of_the_acc": -0.4582, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_14_C_9822868", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nusing ull=unsigned long long;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\nconstexpr ull MOD=(1UL<<61)-1;\null add(ull a,ull b){\n ull res=a+b;\n if(res>=MOD)res-=MOD;\n return res;\n}\null dec(ull a,ull b){return add(a,MOD-b);}\null mul(ull a,ull b){\n __uint128_t t=(__uint128_t)a*(__uint128_t)b;\n t=(t>>61)+(t&MOD);\n if(t>=MOD)return (ull)(t-MOD);\n return (ull)t;\n}\nconstexpr int ma=1000000;\nconstexpr ull base=2191546160808601280UL;\nconstexpr ull baseinv=250865457956280347UL;\narray<ull,ma+1>tab;\narray<ull,ma+1>tabinv;\nint main() {\n std::cin.tie(nullptr);\n std::ios_base::sync_with_stdio(false);\n cout<<fixed<<setprecision(16);\n tab[0]=1UL;tabinv[0]=1UL;\n rep(i,ma){tab[i+1]=mul(tab[i],base);tabinv[i+1]=mul(tabinv[i],baseinv);}\n int H;int W;cin>>H>>W;\n vector<string>S(H);\n rep(i,H)cin>>S[i];\n int R;int C;cin>>R>>C;\n if(R>H||C>W)return 0;\n vector<string>T(R);\n rep(i,R)cin>>T[i];\n vector<vector<ull>>S0(H+1,vector<ull>(W+1));\n rep(i,H){\n rep(j,W)S0[i+1][j+1]=mul((ull)S[i][j],tab[i*C+j]);\n }\n rep(i,H){\n rep(j,W){S0[i+1][j+1]+=S0[i+1][j];if(S0[i+1][j+1]>=MOD)S0[i+1][j+1]-=MOD;}\n }\n rep(i,H){\n rep(j,W){S0[i+1][j+1]+=S0[i][j+1];if(S0[i+1][j+1]>=MOD)S0[i+1][j+1]-=MOD;}\n }\n ull T0=0UL;\n int i0=0;\n rep(i,R){\n rep(j,C){\n T0+=mul((ull)T[i][j],tab[i0]);\n if(T0>=MOD)T0-=MOD;\n i0++;\n }\n }\n rep(i,H-R+1){\n rep(j,W-C+1){\n if(T0==mul(dec(add(S0[i+R][j+C],S0[i][j]),add(S0[i][j+C],S0[i+R][j])),tabinv[i*C+j])){\n\tcout<<i<<' '<<j<<'\\n';\n }\n }\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 29000, "score_of_the_acc": -0.3317, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_14_C_9747237", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\n// 1次元KMP法のための部分一致テーブル (LPS) を構築\nvector<int> computeLPSArray(const string& pattern) {\n int M = pattern.size();\n vector<int> lps(M);\n int length = 0; // 最長の部分一致の長さ\n lps[0] = 0; // 初期値\n\n // パターンの2文字目から末尾までを処理\n int i = 1;\n while (i < M) {\n if (pattern[i] == pattern[length]) {\n length++;\n lps[i] = length;\n i++;\n } else {\n if (length != 0) {\n length = lps[length - 1];\n } else {\n lps[i] = 0;\n i++;\n }\n }\n }\n return lps;\n}\n\n// 2次元フィールドに対するKMP法\nvoid KMP2D(const vector<string>& field, const vector<string>& pattern, int H, int W, int R, int C) {\n // 各行に対して部分一致テーブルを作成 (1次元KMPの前処理)\n vector<vector<int>> lps(R);\n for (int i = 0; i < R; ++i) {\n lps[i] = computeLPSArray(pattern[i]);\n }\n\n // フィールド内でパターンを探索\n for (int i = 0; i <= H - R; ++i) {\n vector<int> match_row(W, 0); // 各列で一致する行数を追跡\n for (int row = 0; row < R; ++row) {\n // 1次元KMP法で行ごとにパターンを探索\n int j = 0; // フィールド内の列位置\n int k = 0; // パターン内の列位置\n while (j < W) {\n if (field[i + row][j] == pattern[row][k]) {\n j++;\n k++;\n if (k == C) {\n match_row[j - C]++; // パターンの全行が一致する候補の開始列\n k = lps[row][k - 1]; // 部分一致情報を利用\n }\n } else {\n if (k != 0) {\n k = lps[row][k - 1];\n } else {\n j++;\n }\n }\n }\n }\n\n // 各列で全行一致するか確認\n for (int col = 0; col <= W - C; ++col) {\n if (match_row[col] == R) {\n // R行すべてで一致するので位置を報告\n cout << i << \" \" << col << endl;\n }\n }\n }\n}\n\nint main() {\n // 入力の読み取り\n int H, W;\n cin >> H >> W;\n vector<string> field(H);\n for (int i = 0; i < H; ++i) {\n cin >> field[i];\n }\n\n int R, C;\n cin >> R >> C;\n vector<string> pattern(R);\n for (int i = 0; i < R; ++i) {\n cin >> pattern[i];\n }\n\n // 2次元KMP法でフィールド内のパターンを探索\n KMP2D(field, pattern, H, W, R, C);\n\n return 0;\n}", "accuracy": 1, "time_ms": 750, "memory_kb": 10984, "score_of_the_acc": -0.6025, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_14_C_9695272", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nconst ulong BASE = 31;\nconst ulong MASK30 = (1ull << 30) -1;\nconst ulong MASK31 = (1ull << 31) -1;\nconst ulong MOD = (1ull << 61) -1;\nconst ulong MASK61 = MOD;\nconst ulong POSITIZER = MOD*4;\n\nulong Pow = 1;\n\nulong convert_int(char c){\n ulong ans;\n if('a' <= c && c <= 'z'){\n ans = c - 'a' + 1;\n }\n else if('A' <= c && c <= 'Z'){\n ans = c - 'A' + 27;\n }\n else{\n ans = c - '0' + 52;\n }\n return ans; \n}\nulong Mul(ulong a,ulong b){\n ulong au = a >> 31;\n ulong bu = b >> 31;\n ulong ad = a & MASK31;\n ulong bd = b & MASK31;\n ulong mid = ad*bu + bd*au;\n ulong midu = mid >> 30;\n ulong midd = mid & MASK30;\n return 2*au*bu + midu + (midd<<31) + ad*bd;\n}\n\nulong CalcMod(ulong x){\n ulong xu = x >> 61;\n ulong xd = x & MASK61;\n ulong res = xu + xd;\n if(res >= MOD){\n res -= MOD;\n }\n return res;\n}\n\nint main(){\n int h,w;\n cin >> h >> w;\n vector<pair<int,int>> ans;\n vector<vector<char>> field(h,vector<char>(w+1));\n for(int i = 0; i < h; i++){\n for(int j = 0; j < w; j++){\n cin >> field[i][j];\n }\n }\n int r,c;\n cin >> r >> c;\n vector<vector<char>> pattern(r,vector<char>(c+1));\n vector<ulong> pattern_key(r);\n for(int i = 0; i < r; i++){\n for(int j = 0; j < c; j++){\n cin >> pattern[i][j];\n }\n }\n for(int i = 0; i < r; i++){\n ulong hash = convert_int(pattern[i][0]);\n for(int j = 1; j < c; j++){\n ulong second_hash = convert_int(pattern[i][j]);\n hash = CalcMod(Mul(hash,BASE) + second_hash);\n }\n pattern_key[i] = hash;\n }\n for(int i = 0; i < c; i++){\n Pow = CalcMod(Mul(Pow,BASE));\n }\n vector<vector<ulong>> Hash(h,vector<ulong>(w+1));\n for(int i = 0; i < h; i++){\n for(int j = 0; j < w; j++){\n ulong c = convert_int(field[i][j]);\n if(j==0) Hash[i][j+1] = c;\n else Hash[i][j+1] = CalcMod(Mul(Hash[i][j],BASE) + c);\n }\n }\n for(int i = 0; i <= h-r; i++){\n for(int j = 0; j <= w-c; j++){\n bool result = true;\n for(int l = 0; l < r; l++){\n ulong search_hash = CalcMod(Hash[i+l][j+c] + POSITIZER - Mul(Hash[i+l][j],Pow));\n if(search_hash!=pattern_key[l]){\n result = false;\n break;\n }\n }\n if(result){\n ans.push_back({i,j});\n }\n }\n }\n for(int i = 0; i < ans.size(); i++){\n cout << ans[i].first << \" \" << ans[i].second << endl;\n }\n}", "accuracy": 1, "time_ms": 1340, "memory_kb": 17832, "score_of_the_acc": -1.161, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_14_C_9655283", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nconst string dl = \"\\n\";\ntypedef unsigned long long ll;\nconst ll B = 1e9 + 7;\n/*\nLet's discuss how string hashing works:\n1. We have a string s of length n.\n2. We have a base B.\n3. We have a prime p.\n4. We have a hash array h of length n.\n\nwe represent the string s as a number in base B, under modulo p.\nthat is the string is letters abcde will look like this:\n\\( a * B^4 + b * B^3 + c * B^2 + d * B^1 + e * B^0 \\) mod p\nso we build the array h as follows (one-based):\n\\( h[1] = s[1] \\)\n\\( h[i] = (h[i-1] * B + s[i]) mod p \\) mod p for all i from 2 to n.\nNow, to get a substring hash, it is easy as getting using prefix sums to get the sum of a range of numbers.\nWe use the following formula to get the hash of a substring from l to r:\n\\( h[l,r] = h[r] - h[l-1] * B^{r-l+1} \\) mod p, that is we divide by the base raised to the power of the length of the substring, that is similar to shifting the number to the right by the length of the substring.\n\nchar(31) =\n\nWith that said, let's read the input, and start coding the solution.\n*/\n\nint main()\n{\n\n ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n ll H, W, R, C;\n cin >> H >> W;\n vector<string> grid(H);\n for (int i = 0; i < H; i++)\n cin >> grid[i];\n\n cin >> R >> C;\n vector<string> pattern(R);\n for (int i = 0; i < R; i++)\n cin >> pattern[i];\n\n if (H < R || W < C)\n {\n return 0;\n }\n\n vector<vector<ll>> grid_hash(H, vector<ll>(W + 1));\n vector<vector<ll>> pattern_hash(R, vector<ll>(C + 1));\n vector<ll> power(W + 1);\n power[0] = 1;\n for (int i = 1; i <= W; i++)\n power[i] = (power[i - 1] * B);\n\n for (int i = 0; i < H; i++)\n {\n for (int j = 0; j < W; j++)\n {\n grid_hash[i][j + 1] = (grid_hash[i][j] * B + grid[i][j]);\n }\n }\n\n for (int i = 0; i < R; i++)\n {\n for (int j = 0; j < C; j++)\n {\n pattern_hash[i][j + 1] = (pattern_hash[i][j] * B + pattern[i][j]);\n }\n }\n\n auto query = [&](int i, int l, int r)\n {\n return (grid_hash[i][r] - grid_hash[i][l - 1] * power[r - l + 1]);\n };\n\n vector<vector<ll>> preCalcQuery(H, vector<ll>(W - C + 1));\n for (int i = 0; i < H; i++)\n {\n for (int j = 0; j <= W - C; j++)\n {\n preCalcQuery[i][j] = query(i, j + 1, j + C);\n }\n }\n for (int i = 0; i <= H - R; i++)\n {\n for (int j = 0; j <= W - C; j++)\n {\n bool found = true;\n for (int k = 0; k < R; k++)\n {\n if (preCalcQuery[i + k][j] != pattern_hash[k][C])\n {\n found = false;\n break;\n }\n }\n if (found)\n cout << i << \" \" << j << dl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 330, "memory_kb": 21284, "score_of_the_acc": -0.4369, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_14_C_9655282", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nconst string dl = \"\\n\";\ntypedef unsigned long long ll;\nconst ll B = 1e9 + 7;\n/*\nLet's discuss how string hashing works:\n1. We have a string s of length n.\n2. We have a base B.\n3. We have a prime p.\n4. We have a hash array h of length n.\n\nwe represent the string s as a number in base B, under modulo p.\nthat is the string is letters abcde will look like this:\n\\( a * B^4 + b * B^3 + c * B^2 + d * B^1 + e * B^0 \\) mod p\nso we build the array h as follows (one-based):\n\\( h[1] = s[1] \\)\n\\( h[i] = (h[i-1] * B + s[i]) mod p \\) mod p for all i from 2 to n.\nNow, to get a substring hash, it is easy as getting using prefix sums to get the sum of a range of numbers.\nWe use the following formula to get the hash of a substring from l to r:\n\\( h[l,r] = h[r] - h[l-1] * B^{r-l+1} \\) mod p, that is we divide by the base raised to the power of the length of the substring, that is similar to shifting the number to the right by the length of the substring.\n\nchar(31) =\n\nWith that said, let's read the input, and start coding the solution.\n*/\n\nint main()\n{\n\n ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n ll H, W, R, C;\n cin >> H >> W;\n vector<string> grid(H);\n for (int i = 0; i < H; i++)\n cin >> grid[i];\n\n cin >> R >> C;\n vector<string> pattern(R);\n for (int i = 0; i < R; i++)\n cin >> pattern[i];\n\n vector<vector<ll>> grid_hash(H, vector<ll>(W + 1));\n vector<vector<ll>> pattern_hash(R, vector<ll>(C + 1));\n vector<ll> power(W + 1);\n power[0] = 1;\n for (int i = 1; i <= W; i++)\n power[i] = (power[i - 1] * B);\n\n for (int i = 0; i < H; i++)\n {\n for (int j = 0; j < W; j++)\n {\n grid_hash[i][j + 1] = (grid_hash[i][j] * B + grid[i][j]);\n }\n }\n\n for (int i = 0; i < R; i++)\n {\n for (int j = 0; j < C; j++)\n {\n pattern_hash[i][j + 1] = (pattern_hash[i][j] * B + pattern[i][j]);\n }\n }\n\n auto query = [&](int i, int l, int r)\n {\n return (grid_hash[i][r] - grid_hash[i][l - 1] * power[r - l + 1]);\n };\n\n vector<vector<ll>> preCalcQuery(H, vector<ll>(W - C + 1));\n for (int i = 0; i < H; i++)\n {\n for (int j = 0; j <= W - C; j++)\n {\n preCalcQuery[i][j] = query(i, j + 1, j + C);\n }\n }\n for (int i = 0; i <= H - R; i++)\n {\n for (int j = 0; j <= W - C; j++)\n {\n bool found = true;\n for (int k = 0; k < R; k++)\n {\n if (preCalcQuery[i + k][j] != pattern_hash[k][C])\n {\n found = false;\n break;\n }\n }\n if (found)\n cout << i << \" \" << j << dl;\n }\n }\n return 0;\n}", "accuracy": 0.8333333333333334, "time_ms": 320, "memory_kb": 21268, "score_of_the_acc": -0.4289, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_14_C_9650038", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef vector<ll> vi;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\n#define FOR(i,l,r) for(ll i=l;i<r;i++)\n#define REP(i,n) FOR(i,0,n)\n#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)\n#define RREP(i,n) RFOR(i,0,n)\n#define ALL(A) A.begin(),A.end()\nll f(char c){\n if('0'<=c&&c<='9')return c-'0';\n if('a'<=c&&c<='z')return 10+c-'a';\n return 36+c-'A';\n}\nint main(){\n int H,W;cin>>H>>W;\n vector<string>S(H);\n REP(i,H)cin>>S[i];\n int h,w;cin>>h>>w;\n vector<string>T(h);\n if(h>H||w>W)return 0;\n REP(i,h)cin>>T[i];\n srand(time(NULL));\n ll base=rand();\n const vi mod={998244353,1000000007,1000000009};\n vvvi P(3,vvi(H,vi(W)));\n vi s={1,1,1};\n REP(i,H)REP(j,W){\n REP(_,3)P[_][i][j]=s[_];\n REP(_,3)s[_]=s[_]*base%mod[_];\n }\n vvvi A(3,vvi(H+1,vi(W+1)));\n REP(_,3)REP(i,H)REP(j,W)A[_][i+1][j+1]=(A[_][i+1][j]+A[_][i][j+1]-A[_][i][j]+f(S[i][j])*P[_][i][j])%mod[_];\n vi hash(3);\n REP(_,3)REP(i,h)REP(j,w){\n hash[_]+=P[_][i][j]*f(T[i][j]);\n hash[_]%=mod[_];\n }\n REP(i,H-h+1)REP(j,W-w+1){\n vi val(3);\n REP(_,3)val[_]=A[_][i+h][j+w]-A[_][i][j+w]-A[_][i+h][j]+A[_][i][j];\n REP(_,3)val[_]=(val[_]%mod[_]+mod[_])%mod[_];\n bool ok=1;\n REP(_,3)if((P[_][i][j]*hash[_]-val[_])%mod[_])ok=0;\n if(ok)cout<<i<<\" \"<<j<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 480, "memory_kb": 61952, "score_of_the_acc": -1.1738, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_14_C_9650031", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef vector<ll> vi;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\n#define FOR(i,l,r) for(ll i=l;i<r;i++)\n#define REP(i,n) FOR(i,0,n)\n#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)\n#define RREP(i,n) RFOR(i,0,n)\n#define ALL(A) A.begin(),A.end()\nll f(char c){\n if('0'<=c&&c<='9')return c-'0';\n if('a'<=c&&c<='z')return 10+c-'a';\n return 36+c-'A';\n}\nint main(){\n int H,W;cin>>H>>W;\n vector<string>S(H);\n REP(i,H)cin>>S[i];\n int h,w;cin>>h>>w;\n vector<string>T(h);\n REP(i,h)cin>>T[i];\n srand(time(NULL));\n ll base=rand();\n const vi mod={998244353,1000000007,1000000009};\n vvvi P(3,vvi(H,vi(W)));\n vi s={1,1,1};\n REP(i,H)REP(j,W){\n REP(_,3)P[_][i][j]=s[_];\n REP(_,3)s[_]=s[_]*base%mod[_];\n }\n vvvi A(3,vvi(H+1,vi(W+1)));\n REP(_,3)REP(i,H)REP(j,W)A[_][i+1][j+1]=(A[_][i+1][j]+A[_][i][j+1]-A[_][i][j]+f(S[i][j])*P[_][i][j])%mod[_];\n vi hash(3);\n REP(_,3)REP(i,h)REP(j,w){\n hash[_]+=P[_][i][j]*f(T[i][j]);\n hash[_]%=mod[_];\n }\n REP(i,H-h+1)REP(j,W-w+1){\n vi val(3);\n REP(_,3)val[_]=A[_][i+h][j+w]-A[_][i][j+w]-A[_][i+h][j]+A[_][i][j];\n REP(_,3)val[_]=(val[_]%mod[_]+mod[_])%mod[_];\n bool ok=1;\n REP(_,3)if((P[_][i][j]*hash[_]-val[_])%mod[_])ok=0;\n if(ok)cout<<i<<\" \"<<j<<endl;\n }\n return 0;\n}", "accuracy": 0.8333333333333334, "time_ms": 480, "memory_kb": 61804, "score_of_the_acc": -1.1715, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_14_C_9614539", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\nusing ull=unsigned int64_t;\n\null M1=1000000007;\null M2=9973;\n\nint main(){\n int h,w,r,c;\n cin >> h >> w;\n vector<string> s(h);\n for(int i=0;i<h;i++) cin >> s[i];\n cin >> r >> c;\n vector<string> t(r);\n for(int i=0;i<r;i++) cin >> t[i];\n \n vector hs(h+1,vector<ull>(w+1,0));\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n hs[i+1][j+1]=hs[i+1][j]*M1+s[i][j];\n }\n for(int j=0;j<w;j++){\n hs[i+1][j+1]+=hs[i][j+1]*M2;\n }\n }\n ull ht=0;\n for(int i=0;i<r;i++){\n ull ht1=0;\n for(int j=0;j<c;j++){\n ht1=ht1*M1+t[i][j];\n }\n ht=ht*M2+ht1;\n }\n \n ull Mr=1,Mc=1;\n for(int i=0;i<r;i++) Mr*=M2;\n for(int j=0;j<c;j++) Mc*=M1;\n \n for(int i=0;i<=h-r;i++){\n for(int j=0;j<=w-c;j++){\n ull h1=hs[i+r][j+c]-hs[i+r][j]*Mc;\n ull h2=hs[i][j+c]-hs[i][j]*Mc;\n ull hss=h1-h2*Mr;\n if( hss==ht) cout << i << \" \" << j << endl;\n }\n }\n \n}", "accuracy": 1, "time_ms": 380, "memory_kb": 14520, "score_of_the_acc": -0.3719, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_14_C_9614534", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\nusing ull=unsigned int64_t;\n\null M1=1000000007;\null M2=998244353;\n\nint main(){\n int h,w,r,c;\n cin >> h >> w;\n vector<string> s(h);\n for(int i=0;i<h;i++) cin >> s[i];\n cin >> r >> c;\n vector<string> t(r);\n for(int i=0;i<r;i++) cin >> t[i];\n \n vector hs(h+1,vector<ull>(w+1,0));\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n hs[i+1][j+1]=hs[i+1][j]*M1+s[i][j];\n }\n for(int j=0;j<w;j++){\n hs[i+1][j+1]+=hs[i][j+1]*M2;\n }\n }\n ull ht=0;\n for(int i=0;i<r;i++){\n ull ht1=0;\n for(int j=0;j<c;j++){\n ht1=ht1*M1+t[i][j];\n }\n ht=ht*M2+ht1;\n }\n \n ull Mr=1,Mc=1;\n for(int i=0;i<r;i++) Mr*=M2;\n for(int j=0;j<c;j++) Mc*=M1;\n \n for(int i=0;i<=h-r;i++){\n for(int j=0;j<=w-c;j++){\n ull h1=hs[i+r][j+c]-hs[i+r][j]*Mc;\n ull h2=hs[i][j+c]-hs[i][j]*Mc;\n ull hss=h1-h2*Mr;\n if( hss==ht) cout << i << \" \" << j << endl;\n }\n }\n \n}", "accuracy": 1, "time_ms": 380, "memory_kb": 14624, "score_of_the_acc": -0.3735, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_14_C_9614522", "code_snippet": "#pragma GCC optimize(\"Ofast\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\nusing ull=unsigned int64_t;\n\n\nstruct slv{\n int h,w,r,c;\n vector<vector<ull>> hs;\n ull M1=1000000007;\n ull M2=998244353;\n ull ht,Mr,Mc;\n \n slv(vector<vector<char>> &s,vector<vector<char>> &t)\n :h(s.size()),w(s[0].size()),r(t.size()),c(t[0].size()),hs(h+1,vector<ull>(w+1,0)){\n\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n hs[i+1][j+1]=hs[i+1][j]*M1+s[i][j];\n }\n for(int j=0;j<w;j++){\n hs[i+1][j+1]+=hs[i][j+1]*M2;\n }\n }\n ht=0;\n for(int i=0;i<r;i++){\n ull ht1=0;\n for(int j=0;j<c;j++){\n ht1=ht1*M1+t[i][j];\n }\n ht=ht*M2+ht1;\n }\n \n Mr=1,Mc=1;\n for(int i=0;i<r;i++) Mr*=M2;\n for(int j=0;j<c;j++) Mc*=M1;\n }\n \n ull get(int i,int j){\n return hs[i+r][j+c]-hs[i+r][j]*Mc+(hs[i][j]*Mc-hs[i][j+c])*Mr;\n }\n\n};\n\nint main(){\n int h,w,r,c;\n cin >> h >> w;\n vector s(h,vector<char>(w));\n for(int i=0;i<h;i++)for(int j=0;j<w;j++) cin >> s[i][j];\n cin >> r >> c;\n vector t(r,vector<char>(c));\n for(int i=0;i<r;i++)for(int j=0;j<c;j++) cin >> t[i][j];\n \n slv sv(s,t);\n ull ht=sv.ht;\n for(int i=0;i<=h-r;i++){\n for(int j=0;j<=w-c;j++){\n ull hss=sv.get(i,j);\n if( hss==ht) cout << i << \" \" << j << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 12888, "score_of_the_acc": -0.3624, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_14_C_9614363", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\ntypedef unsigned long long int ull;\n\ntemplate <ull b1 = 9973, ull b2 = 1000000007>\nstruct rolling_hash2 {\n const int h, w;\n vector<ull> rh, rw;\n vector<vector<ull>> hs;\n template <class T> rolling_hash2(const vector<vector<T>>& a)\n : h(a.size()), w(a[0].size()), rh(h+1), rw(w+1), hs(h+1, vector<ull>(w+1))\n {\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n hs[i+1][j+1] = hs[i+1][j] * b2 + a[i][j];\n }\n for (int j = 0; j < w; ++j) {\n hs[i+1][j+1] += hs[i][j+1] * b1;\n }\n }\n rh[0] = rw[0] = 1;\n for (int i = 0; i < h; ++i) {\n rh[i+1] = rh[i] * b1;\n }\n for (int i = 0; i < w; ++i) {\n rw[i+1] = rw[i] * b2;\n }\n }\n ull get(int i1, int j1, int i2, int j2) {\n assert(0 <= i1 and i1 <= i2 and i2 <= h);\n assert(0 <= j1 and j1 <= j2 and j2 <= w);\n ull u = hs[i2][j2] - hs[i2][j1] * rw[j2 - j1];\n ull d = hs[i1][j2] - hs[i1][j1] * rw[j2 - j1];\n return u - d * rh[i2 - i1];\n }\n};\n\nint main(){\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n int h,w; cin >> h >> w;\n vector<vector<char>> a(h, vector<char>(w));\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n cin >> a[i][j];\n }\n }\n int r,c; cin >> r >> c;\n vector<vector<char>> b(r, vector<char>(c));\n for (int i = 0; i < r; ++i) {\n for (int j = 0; j < c; ++j) {\n cin >> b[i][j];\n }\n }\n rolling_hash2 rha(a), rhb(b);\n ull hsh = rhb.get(0,0,r,c);\n for (int i = 0; i+r <= h; ++i) {\n for (int j = 0; j+c <= w; ++j) {\n if (rha.get(i,j,i+r,j+c) == hsh) {\n cout << i << \" \" << j << \"\\n\";\n }\n }\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 20744, "score_of_the_acc": -0.2055, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_14_C_9614340", "code_snippet": "#pragma GCC optimize(\"Ofast\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\nusing ull=unsigned int64_t;\n\null M1=1000000007;\null M2=998244353;\n\nint main(){\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n int h,w,r,c;\n cin >> h >> w;\n vector s(h,vector<char>(w));\n for(int i=0;i<h;i++)for(int j=0;j<w;j++) cin >> s[i][j];\n cin >> r >> c;\n vector t(r,vector<char>(c));\n for(int i=0;i<r;i++)for(int j=0;j<c;j++) cin >> t[i][j];\n \n vector hs(h+1,vector<ull>(w+1,0));\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n hs[i+1][j+1]=hs[i+1][j]*M1+s[i][j];\n }\n for(int j=0;j<w;j++){\n hs[i+1][j+1]+=hs[i][j+1]*M2;\n }\n }\n ull ht=0;\n for(int i=0;i<r;i++){\n ull ht1=0;\n for(int j=0;j<c;j++){\n ht1=ht1*M1+t[i][j];\n }\n ht=ht*M2+ht1;\n }\n \n ull Mr=1,Mc=1;\n for(int i=0;i<r;i++) Mr*=M2;\n for(int j=0;j<c;j++) Mc*=M1;\n \n for(int i=0;i<=h-r;i++){\n for(int j=0;j<=w-c;j++){\n ull hss=hs[i+r][j+c]-hs[i+r][j]*Mc+(hs[i][j]*Mc-hs[i][j+c])*Mr;\n if( hss==ht) cout << i << \" \" << j << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 370, "memory_kb": 13004, "score_of_the_acc": -0.3411, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_14_C_9614239", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\nusing ull=unsigned int64_t;\n\null M1=1000000007;\null M2=998244353;\n\nint main(){\n int h,w,r,c;\n cin >> h >> w;\n vector s(h,vector<char>(w));\n for(int i=0;i<h;i++)for(int j=0;j<w;j++) cin >> s[i][j];\n cin >> r >> c;\n vector t(r,vector<char>(c));\n for(int i=0;i<r;i++)for(int j=0;j<c;j++) cin >> t[i][j];\n \n vector hs(h+1,vector<ull>(w+1,0));\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n hs[i+1][j+1]=hs[i+1][j]*M1+s[i][j];\n }\n for(int j=0;j<w;j++){\n hs[i+1][j+1]+=hs[i][j+1]*M2;\n }\n }\n ull ht=0;\n for(int i=0;i<r;i++){\n ull ht1=0;\n for(int j=0;j<c;j++){\n ht1=ht1*M1+t[i][j];\n }\n ht=ht*M2+ht1;\n }\n \n ull Mr=1,Mc=1;\n for(int i=0;i<r;i++) Mr*=M2;\n for(int j=0;j<c;j++) Mc*=M1;\n \n for(int i=0;i<=h-r;i++){\n for(int j=0;j<=w-c;j++){\n ull hss=hs[i+r][j+c]-hs[i+r][j]*Mc+(hs[i][j]*Mc-hs[i][j+c])*Mr;\n if( hss==ht) cout << i << \" \" << j << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 12812, "score_of_the_acc": -0.3535, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_14_C_9613740", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\nusing ull=unsigned int64_t;\n\null M1=1000000007;\null M2=998244353;\n\nint main(){\n int h,w,r,c;\n cin >> h >> w;\n vector<string> s(h);\n for(int i=0;i<h;i++) cin >> s[i];\n cin >> r >> c;\n vector<string> t(r);\n for(int i=0;i<r;i++) cin >> t[i];\n \n vector hs(h+1,vector<ull>(w+1,0));\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n hs[i+1][j+1]=hs[i+1][j]*M1+s[i][j];\n }\n for(int j=0;j<w;j++){\n hs[i+1][j+1]+=hs[i][j+1]*M2;\n }\n }\n ull ht=0;\n for(int i=0;i<r;i++){\n ull ht1=0;\n for(int j=0;j<c;j++){\n ht1=ht1*M1+t[i][j];\n }\n ht=ht*M2+ht1;\n }\n \n ull Mr=1,Mc=1;\n for(int i=0;i<r;i++) Mr*=M2;\n for(int j=0;j<c;j++) Mc*=M1;\n \n for(int i=0;i<=h-r;i++){\n for(int j=0;j<=w-c;j++){\n ull hss=hs[i+r][j+c]-hs[i+r][j]*Mc-hs[i][j+c]*Mr+hs[i][j]*Mr*Mc;\n if( hss==ht) cout << i << \" \" << j << endl;\n }\n }\n \n}", "accuracy": 1, "time_ms": 380, "memory_kb": 14544, "score_of_the_acc": -0.3723, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_14_C_9611123", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\n\nclass RollingHash{\n private:\n ll B[5]={114514,1919,810,893,364364};\n ll C[5]={31415,9265,3589,79323,846};\n ll M[5]={1000000007,1000000009,999999937,998244353,2147483647};\n ll Binv[5],Cinv[5];\n \n public:\n vector<string> S;\n vector<vector<ll>> H[5],Hsum[5];\n \n //繰り返し二乗法\n ll BE(long long b,int e,int m){\n ll r=1;\n while(e){\n if(e&1){\n r=(r*b)%M[m];\n }\n b=(b*b)%M[m];\n e >>=1;\n }\n return r;\n }\n\n \n void init(vector<string> cs,int Mcount){ //Mcountは最大5重化まで\n S=cs;\n int n=S.size();\n int m;\n if(n==0){\n m=0;\n }else{\n m=S[0].size();\n }\n\n //逆元\n for(int i=0;i<Mcount;i++){\n Binv[i]=BE(B[i],M[i]-2,i);\n Cinv[i]=BE(C[i],M[i]-2,i);\n }\n \n //本体\n for(int i=0;i<Mcount;i++){\n H[i].resize(n+1);\n for(int j=0;j<n+1;j++){\n H[i][j].assign(m+1,{0});\n }\n ll b=1,c=1;\n for(int j=n-1;j>=0;j--){\n c=1;\n for(int k=m-1;k>=0;k--){\n H[i][j][k]=(((b*c)%M[i])*(ll)S[j][k])%M[i];\n c=(c*C[i])%M[i];\n }\n b=(b*B[i])%M[i];\n }\n }\n \n //累積和\n for(int i=0;i<Mcount;i++){\n Hsum[i].resize(n+1);\n for(int j=0;j<n+1;j++){\n Hsum[i][j].assign(m+1,{0});\n }\n for(int j=0;j<n;j++){\n for(int k=0;k<m;k++){\n Hsum[i][j+1][k+1]=(Hsum[i][j+1][k+1]+H[i][j][k])%M[i];\n Hsum[i][j+1][k+1]=(Hsum[i][j+1][k+1]+Hsum[i][j+1][k])%M[i];\n Hsum[i][j+1][k+1]=(Hsum[i][j+1][k+1]+Hsum[i][j][k+1])%M[i];\n Hsum[i][j+1][k+1]=(Hsum[i][j+1][k+1]-Hsum[i][j][k]+M[i])%M[i];\n }\n }\n }\n }\n \n //計算\n ll get(int l1,int r1,int l2,int r2,int i){\n ll R=(Hsum[i][l2+1][r2+1]-Hsum[i][l1][r2+1]-Hsum[i][l2+1][r1]+Hsum[i][l1][r1])%M[i];\n R=(R+M[i])%M[i];\n R=(R*BE(Binv[i],(S.size())-l2-1,i))%M[i];\n R=(R*BE(Cinv[i],(S[0].size())-r2-1,i))%M[i];\n return R;\n }\n \n};\n\nint main(){\n \n int h,w,r,c;\n cin >> h >> w;\n vector<string> s(h);\n for(int i=0;i<h;i++) cin >> s[i];\n cin >> r >> c;\n vector<string> t(r);\n for(int i=0;i<r;i++) cin >> t[i];\n \n RollingHash rsh;\n rsh.init(s,2);\n RollingHash rth;\n rth.init(t,2);\n ll thash1=rth.get(0,0,r-1,c-1,0),thash2=rth.get(0,0,r-1,c-1,1);\n ll shash1=0,shash2=0;\n for(int i=0;i<=h-r;i++){\n for(int j=0;j<=w-c;j++){\n shash1=rsh.get(i,j,i+r-1,j+c-1,0);\n shash2=rsh.get(i,j,i+r-1,j+c-1,1);\n if((thash1==shash1)&&(thash2==shash2)) cout << i << \" \" << j << endl; \n }\n }\n \n}", "accuracy": 1, "time_ms": 710, "memory_kb": 72728, "score_of_the_acc": -1.5154, "final_rank": 18 } ]
aoj_ALDS1_14_B_cpp
String Search Find places where a string P is found within a text T . Print all indices of T where P found. The indices of T start with 0. Input In the first line, a text T is given. In the second line, a string P is given. Output Print an index of T where P found in a line. Print the indices in ascending order. Constraints 1 ≤ length of T ≤ 1000000 1 ≤ length of P ≤ 10000 The input consists of alphabetical characters and digits Sample Input 1 aabaaa aa Sample Output 1 0 3 4 Sample Input 2 xyzz yz Sample Output 2 1 Sample Input 3 abc xyz Sample Output 3 The output should be empty.
[ { "submission_id": "aoj_ALDS1_14_B_10961094", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\n// 失敗関数fの計算\nvoid compf(string p, int f[])\n{\n\tf[0] = -1;\n\t\n\tfor(int i=1; i<p.size()+1; i++){\n\t\tint j = f[i-1];\t\t\t\t\t// 1文字前のf\n\t\t\n\t\twhile(j>=0 && p[i-1]!=p[j]){\n\t\t\tj = f[j];\n\t\t}\n\t\t\n\t\tf[i] = j+1;\t\t\t\t\t\t// 1文字前と一致した次\n\t}\n}\n\n\nvoid kmp(string p, string t)\n{\n\tint* f = new int[p.size()+1];\t\t// 配列fの動的確保\n\tcompf(p, f);\t\t\t\t\t// 失敗関数fの計算\n\t\n\tint i = 0;\n\tint j = 0;\n\t\n\twhile(true){\n\t\twhile(i<p.size() && j<t.size()){\n\t\t\tif(p[i]==t[j]){\t\t\t\t\t// 文字が一致したら\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse{\t\t\t\t\t\t\t// 一致しなかったら\n\t\t\t\ti = f[i];\n\t\t\t\tif(i==-1){\t\t\t\t\t\t// 次が0番目\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(i==p.size()){\t\t\t\t// 見つかった\n\t\t\tcout << j-i << endl;\n\t\t\ti = f[i];\n\t\t\tif(i==-1){\t\t\t\t\t\t// 次が0番目\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}else{\n\t\t\tdelete[] f;\t\t\t\t\t\t// 配列fの解放\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tstring t;\n\tstring p;\n cin >> t >> p;\n\t\n kmp(p,t);\n\treturn 0;\n}", "accuracy": 1, "time_ms": 680, "memory_kb": 5184, "score_of_the_acc": -0.7185, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_14_B_10947681", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define pii pair < int , int >\n#define fi first\n#define se second\nconst int N = 1e6 + 3;\nconst int mod1 = 1e9 + 7;\nconst int mod2 = 1e9 + 133;\nconst int base = 311;\nstring s, t;\nint n, m;\npii p[N], h[N], ht;\nvoid init() {\n p[0].fi = p[0].se = 1;\n for (int i = 1; i <= n; i++) {\n p[i].fi = (p[i - 1].fi * base) % mod1;\n p[i].se = (p[i - 1].se * base) % mod2;\n }\n for (int i = 1; i <= n; i++) {\n h[i].fi = (h[i - 1].fi * base + s[i]) % mod1;\n h[i].se = (h[i - 1].se * base + s[i]) % mod2;\n }\n for (int i = 1; i <= m; i++) {\n ht.fi = (ht.fi * base + t[i]) % mod1;\n ht.se = (ht.se * base + t[i]) % mod2;\n }\n}\npii get(int l, int r) {\n int get1 = ((h[r].fi - h[l - 1].fi * p[r - l + 1].fi) % mod1 + mod1 * mod1) % mod1;\n int get2 = ((h[r].se - h[l - 1].se * p[r - l + 1].se) % mod2 + mod2 * mod2) % mod2;\n return pii(get1, get2);\n}\nsigned main() {\n ios_base::sync_with_stdio(0);\n cin.tie(0); cout.tie(0);\n // freopen(\"STRING.inp\",\"r\",stdin);\n // freopen(\"STRING.out\",\"w\",stdout);\n\n cin >> s >> t;\n n = s.size();\n m = t.size();\n s = '*' + s;\n t = '*' + t;\n init();\n for (int i = m; i <= n; i++) {\n// cerr << get(i - m + 1, i).fi << \" \" << ht.fi << \"\\n\";\n if (get(i - m + 1, i) == ht) {\n cout << i - m << '\\n';\n }\n }\n// cerr << h[4].fi << \" \" << ht.fi << '\\n';\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 35308, "score_of_the_acc": -1.0408, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_14_B_10943637", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n// 失敗関数fの計算\nvoid compf(string p, int f[])\n{\nf[0] = -1;\nfor(int i=1; i<p.size()+1; i++){ // 1文字多く\nint j = f[i-1];\nwhile(j>=0 && p[i-1]!=p[j]){\nj = f[j];\n}\nf[i] = j+1;\n}\n}\nvoid kmp(string p, string t)\n{\nint* f = new int[p.size()+1]; // 1文字多く\ncompf(p, f);\nint i = 0;\nint j = 0;\nwhile(true){\nwhile(i<p.size() && j<t.size()){\nif(p[i]==t[j]){\ni++;\nj++;\n}\nelse{\ni = f[i];\nif(i==-1){\ni++;\nj++;\n}\n}\n}\nif(i==p.size()){\ncout << j-i << endl;\ni = f[i];\nif(i==-1){\ni++;\nj++;\n}\n}\nelse{\ndelete[] f;\nreturn;\n}\n}\n}\nint main()\n{\nstring T;\nstring P;\ncin >> T;\ncin >> P;\nkmp(P, T);\nreturn 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 5180, "score_of_the_acc": -0.7286, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_14_B_10938770", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\nvoid compf(string p, int f[])\n{\n\tf[0] = -1;\n\tfor(int i=1; i<p.size()+1; i++){ \n\t\tint j = f[i-1];\n\t\twhile(j>=0 && p[i-1]!=p[j]){\n\t\t\tj = f[j];\n\t\t}\n\t\tf[i] = j+1;\n\t}\n}\nvoid kmp(string p, string t){\n\tint* f = new int[p.size()+1];\n\tcompf(p, f);\n\tint i = 0;\n\tint j = 0;\n\twhile(true){\n\t\twhile(i<p.size() && j<t.size()){\n\t\t\tif(p[i]==t[j]){\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ti = f[i];\n\t\t\t\tif(i==-1){\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(i==p.size()){\n\t\t\tcout << j-i << endl;\n\t\t\ti = f[i];\n\t\t\tif(i==-1){\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tdelete[] f;\n\t\t\treturn;\n\t\t}\n\t}\n}\nint main(){\n\tstring T;\n\tstring P;\n\tcin >> T;\n\tcin >> P;\n\tkmp(P, T);\n\treturn 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 5156, "score_of_the_acc": -0.7278, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_14_B_10934999", "code_snippet": "#include<iostream>\n#include<vector>\n#include<string>\n#include<algorithm>\nusing namespace std;\n\nint main(){\n\tstring T, P;\n\tcin >> T >> P;\n\tint tl = T.length(), pl = P.length();\n\tvector<int> B(256, -1), f(pl + 1, 0), G(pl + 1, 0);\n\tfor(int i = 0; i < pl; i++) B[P[i]] = i;\n\tint t = pl + 1;\n\tf[pl] = t;\n\tfor(int i = pl; i > 0; i--){\n\t\twhile(t <= pl && P[i - 1] != P[t - 1]) t = f[t];\n\t\tf[i - 1] = --t;\n\t}\n\tfor(int i = pl; i > 0; i--){\n\t\tt = f[i];\n\t\twhile(t <= pl && P[i - 1] != P[t - 1]){\n\t\t\tif(G[t] == 0) G[t] = t - i;\n\t\t\tt = f[t];\n\t\t}\n\t}\n\tt = f[0];\n\tfor(int i = 0; i < pl; i++){\n\t\tif(G[i] == 0) G[i] = t;\n\t\tif(t == i) t = f[t];\n\t}\n\tint i = 0, j, p = 0, s;\n\twhile(i + pl <= tl){\n\t\tj = pl - 1;\n\t\twhile(j >= p && T[i + j] == P[j]) j--;\n\t\tif(j < p){\n\t\t\tj = -1;\n\t\t\tcout << i << endl;\n\t\t\ts = G[0];\n\t\t}else s = max(G[j + 1], j - B[T[i + j]]);\n\t\tif(j < s) p = pl - s;\n\t\telse p = 0;\n\t\ti += s;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 5428, "score_of_the_acc": -0.4406, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_14_B_10934769", "code_snippet": "#include<iostream>\n#include<vector>\n#include<string>\nusing namespace std;\n\nint main(){\n\tstring T, P;\n\tcin >> T >> P;\n\tvector<int> B(256, -1), f(P.length() + 1, 0), G(P.length() + 1, 0);\n\tfor(int i = 0; i < P.length(); i++){\n\t\tB[P[i]] = i;\n\t} \n\tint t = P.length() + 1;\n\tf[t - 1] = t;\n\tfor(int i = t - 1; i > 0; i--){\n\t\twhile(t <= P.length() && P[i - 1] != P[t - 1]) t = f[t];\n\t\tf[i - 1] = --t;\n\t}\n\tfor(int i = P.length(); i >= 0; i--){\n\t\tt = f[i];\n\t\twhile(t <= P.length() && P[i - 1] != P[t - 1]){\n\t\t\tif(G[t] == 0) G[t] = t - i;\n\t\t\tt = f[t];\n\t\t}\n\t}\n\tt = f[0];\n\tfor(int i = 0; i < P.length(); i++){\n\t\tif(G[i] == 0) G[i] = t;\n\t\tif(t == i) t = f[t];\n\t}\n\tint i = 0, j, s, p = 0;\n\twhile(i + P.length() <= T.length()){\n\t\tj = P.length() - 1;\n\t\twhile(j >= p && T[i + j] == P[j]) j--;\n\t\tif(j < p){\n\t\t\tj = -1;\n\t\t\tcout << i << endl;\n\t\t\ts = G[0];\n\t\t}else{\n\t\t\ts = max(G[j + 1], j - B[T[i + j]]);\n\t\t}\n\t\tif(j < s) p = P.length() - s;\n\t\telse p = 0;\n\t\ti += s;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 5428, "score_of_the_acc": -0.4406, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_14_B_10934029", "code_snippet": "#include<iostream>\n#include<vector>\n#include<string>\nusing namespace std;\n\nint main(){\n\tstring T, P;\n\tcin >> T >> P;\n\tvector<int> tab(P.length() + 1, 0);\n\ttab[0] = -1;\n\tfor(int i = 0, j = -1; i < P.length(); i++){\n\t\twhile(j >= 0 && P[i] != P[j]) j = tab[j];\n\t\ttab[i + 1] = ++j;\n\t}\n\tint i = 0, j = 0;\n\twhile(i + j < T.length()){\n\t\tif(T[i + j] == P[j]){\n\t\t\tj++;\n\t\t\tif(j == P.length()){\n\t\t\t cout << i << endl;\n\t\t\t i = i + j - tab[j];\n\t\t\t j = tab[j];\n\t\t }\n\t\t}else{\n\t\t\ti = i + j - tab[j];\n\t\t\tif(j > 0) j = tab[j];\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 400, "memory_kb": 5428, "score_of_the_acc": -0.4406, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_14_B_10933484", "code_snippet": "// 2025/10/14 Tazoe\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\n// 失敗関数fの計算\nvoid compf(string p, int f[])\n{\n\tf[0] = -1;\n\t\n\tfor(int i=1; i<p.size()+1; i++){\t\t// 1文字多く\n\t\tint j = f[i-1];\n\t\t\n\t\twhile(j>=0 && p[i-1]!=p[j]){\n\t\t\tj = f[j];\n\t\t}\n\t\t\n\t\tf[i] = j+1;\n\t}\n}\n\n\nvoid kmp(string p, string t)\n{\n\tint* f = new int[p.size()+1];\t\t\t// 1文字多く\n\tcompf(p, f);\n\t\n\tint i = 0;\n\tint j = 0;\n\t\n\twhile(true){\n\t\twhile(i<p.size() && j<t.size()){\n\t\t\tif(p[i]==t[j]){\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ti = f[i];\n\t\t\t\tif(i==-1){\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(i==p.size()){\n\t\t\tcout << j-i << endl;\n\t\t\ti = f[i];\n\t\t\tif(i==-1){\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tdelete[] f;\n\t\t\treturn;\n\t\t}\n\t}\n}\n\n\nint main()\n{\n\tstring T;\n\tstring P;\n\t\n\tcin >> T;\n\tcin >> P;\n\t\n\tkmp(P, T);\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 5180, "score_of_the_acc": -0.7286, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_14_B_10933000", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\n#define D1 1000000007\n#define D2 2000000011\n\n\nint main(){\n\tstring T, P;\n\tcin >> T >> P;\n\tif(T.length() < P.length()) return 0;\n\tunsigned long long th1, th2, ph1, ph2, k1 = 1, k2 = 1;\n\tfor(int i = 0; i < P.length(); i++){\n\t\tk1 *= D1;\n\t\tk2 *= D2;\n\t}\n\tth1 = th2 = ph1 = ph2 = 0;\n\tfor(auto i : P){\n\t\tph1 = ph1 * D1 + i;\n\t\tph2 = ph2 * D2 + i;\n\t}\n\tfor(int i = 0; i < P.length(); i++){\n\t\tth1 = th1 * D1 + T[i];\n\t\tth2 = th2 * D2 + T[i];\n\t}\n\tif(th1 == ph1 && th2 == ph2) cout << 0 << endl;\n\tfor(int i = 1, tmp = T.length() - P.length() + 1; i < tmp; i++){\n\t\tth1 = th1 * D1 - T[i - 1] * k1 + T[i + P.length() - 1];\n\t\tth2 = th2 * D2 - T[i - 1] * k2 + T[i + P.length() - 1];\n\t\tif(th1 == ph1 && th2 == ph2) cout << i << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 5428, "score_of_the_acc": -0.4304, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_14_B_10921047", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\nvoid compf(string p, int f[]) {\n f[0] = -1;\n int j = -1;\n for (int i = 1; i < p.size(); i++) {\n while (j >= 0 && p[i] != p[j + 1]) {\n j = f[j];\n }\n if (p[i] == p[j + 1]) {\n j++;\n }\n f[i] = j;\n }\n}\n\nvoid kmp(string p, string t) {\n int m = p.size(), n = t.size();\n int* f = new int[m];\n compf(p, f);\n\n int j = -1;\n for (int i = 0; i < n; i++) {\n while (j >= 0 && t[i] != p[j + 1]) {\n j = f[j];\n }\n if (t[i] == p[j + 1]) {\n j++;\n }\n if (j == m - 1) {\n cout << i - m + 1 << endl;\n j = f[j];\n }\n }\n\n delete[] f;\n}\n\nint main() {\n string t, p;\n cin >> t >> p;\n kmp(p, t);\n return 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 5180, "score_of_the_acc": -0.7286, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_14_B_10921008", "code_snippet": "#include <iostream>\n#include <string>\nusing namespace std;\n\nvoid compf(string p, int f[]) {\n f[0] = -1;\n for (int i = 1; i < p.size(); i++) {\n int j = f[i - 1];\n while (j >= 0 && p[i - 1] != p[j]) {\n j = f[j];\n }\n f[i] = j + 1;\n }\n}\n\nvoid kmp(string p, string t) {\n int* f = new int[p.size()];\n compf(p, f);\n\n int i = 0, j = 0;\n while (j < t.size()) {\n if (p[i] == t[j]) {\n i++;\n j++;\n if (i == p.size()) {\n cout << j - i << endl;\n i = f[i - 1];\n if (i == -1) i = 0;\n }\n } else {\n i = f[i];\n if (i == -1) {\n i = 0;\n j++;\n }\n }\n }\n\n delete[] f;\n}\n\nint main() {\n string t, p;\n cin >> t >> p;\n kmp(p, t);\n return 0;\n}", "accuracy": 0.5277777777777778, "time_ms": 10, "memory_kb": 5152, "score_of_the_acc": -0.0338, "final_rank": 20 }, { "submission_id": "aoj_ALDS1_14_B_10920981", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\n\nvoid compf(string p,int f[]){\n f[0]=-1;\n for(int i=1;i<p.size();i++){\n int j=f[i-1];\n\n while(j>=0&&p[i-1]!=p[j]){\n j=f[j];\n }\n f[i]=j+1;\n }\n}\n\nvoid kmp(string p, string t)\n{\n\tint* f = new int[p.size()];\t\t// 配列fの動的確保\n\tcompf(p, f);\t\t\t\t\t// 失敗関数fの計算\n\t\n\tint i = 0;\n\tint j = 0;\n\t\n\twhile(i<p.size() && j<t.size()){\n\t\tif(p[i]==t[j]){\t\t\t\t\t// 文字が一致したら\n\t\t\ti++;\n\t\t\tj++;\n if(i==p.size()){\n cout << j-i<<endl;\n i = f[i - 1];\n if(i == -1) {\n i = 0;\n }\n }\n\t\t}\n\t\telse{\t\t\t\t\t\t\t// 一致しなかったら\n\t\t\ti = f[i];\n\t\t\tif(i==-1){\t\t\t\t\t\t// 次が0番目\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tdelete[] f;\t\t\t\t\t\t// 配列fの解放\n}\n\n\nint main()\n{\n\tstring t,p;\n cin >> t >> p;\n kmp(p,t);\nreturn 0;\n}", "accuracy": 0.5277777777777778, "time_ms": 10, "memory_kb": 5072, "score_of_the_acc": -0.0313, "final_rank": 19 }, { "submission_id": "aoj_ALDS1_14_B_10920908", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n// 失敗関数を計算する\nvoid compf(string p, vector<int> &f) {\n f.resize(p.size());\n f[0] = 0;\n int j = 0;\n for (int i = 1; i < p.size(); i++) {\n while (j > 0 && p[i] != p[j]) {\n j = f[j - 1];\n }\n if (p[i] == p[j]) {\n j++;\n }\n f[i] = j;\n }\n}\n\n// KMPアルゴリズムで、tの中からpをすべて見つける\nvoid kmp(string p, string t, vector<int> &result) {\n if (p.empty() || t.empty() || t.size() < p.size()) {\n return; // 検索不要な場合はここで終了\n }\n\n vector<int> f;\n compf(p, f);\n\n int i = 0; // パターンpのインデックス\n int j = 0; // テキストtのインデックス\n while (j < t.size()) {\n if (p[i] == t[j]) {\n i++;\n j++;\n }\n\n if (i == p.size()) {\n result.push_back(j - i);\n i = f[i - 1];\n } else if (j < t.size() && p[i] != t[j]) {\n if (i != 0) {\n i = f[i - 1];\n } else {\n j++;\n }\n }\n }\n}\n\nint main() {\n string t, p;\n getline(cin, t);\n getline(cin, p);\n\n vector<int> result;\n kmp(p, t, result);\n\n for (int i = 0; i < result.size(); i++) {\n cout << result[i] << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 11524, "score_of_the_acc": -0.9319, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_14_B_10903955", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\nvector<int> buildLPS(string p) {\n int m = p.size();\n vector<int> lps(m, 0);\n int len = 0;\n for (int i = 1; i < m; ) {\n if (p[i] == p[len]) {\n len++;\n lps[i] = len;\n i++;\n } else {\n if (len != 0) {\n len = lps[len - 1];\n } else {\n lps[i] = 0;\n i++;\n }\n }\n }\n return lps;\n}\n\nvoid stringmatching(string p, string t) {\n int m = p.size();\n int n = t.size();\n vector<int> lps = buildLPS(p);\n int i = 0, j = 0;\n while (i < n) {\n if (p[j] == t[i]) {\n i++; j++;\n }\n if (j == m) {\n cout << i - j << endl;\n j = lps[j - 1];\n } else if (i < n && p[j] != t[i]) {\n if (j != 0) {\n j = lps[j - 1];\n } else {\n i++;\n }\n }\n }\n}\n\nint main() {\n string t, p;\n cin >> t >> p;\n stringmatching(p, t);\n return 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 5132, "score_of_the_acc": -0.7271, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_14_B_10899437", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nll MOD=9007199254740997;\n\nint main(){\n string T,P; cin>>T>>P;\n if(T.size()<P.size()) return 0;\n\n ll pow=1;\n for(int i=0;i<P.size()-1;i++) pow=pow*128%MOD;\n\n ll p=0;\n for(int i=0;i<P.size();i++){\n p*=128;\n p=(p+P[i])%MOD;\n }\n\n ll t=0;\n for(int i=0;i<P.size();i++){\n t*=128;\n t=(t+T[i])%MOD;\n }\n if(p==t) cout<<0<<endl;\n for(int i=P.size();i<T.size();i++){\n t=(t+MOD*128-pow*T[i-P.size()])%MOD;\n t*=128;\n t=(t+T[i])%MOD;\n if(p==t) cout<<i-P.size()+1<<endl;\n }\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 5168, "score_of_the_acc": -0.7384, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_14_B_10892941", "code_snippet": "#pragma region Macros\n#include <bits/stdc++.h>\n\nusing namespace std;\nusing lint = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing int128 = __int128_t;\n#define all(x) (x).begin(), (x).end()\n#define EPS 1e-8\n#define uniqv(v) v.erase(unique(all(v)), v.end())\n#define OVERLOAD_REP(_1, _2, _3, name, ...) name\n#define REP1(i, n) for (auto i = std::decay_t<decltype(n)>{}; (i) != (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\n#define log(x) cout << x << endl\n#define logfixed(x) cout << fixed << setprecision(10) << x << endl;\n#define logy(bool) \\\n if (bool) { \\\n cout << \"Yes\" << endl; \\\n } else { \\\n cout << \"No\" << endl; \\\n }\n\nostream &operator<<(ostream &dest, __int128_t value) {\n ostream::sentry s(dest);\n if (s) {\n __uint128_t tmp = value < 0 ? -value : value;\n char buffer[128];\n char *d = end(buffer);\n do {\n --d;\n *d = \"0123456789\"[tmp % 10];\n tmp /= 10;\n } while (tmp != 0);\n if (value < 0) {\n --d;\n *d = '-';\n }\n int len = end(buffer) - d;\n if (dest.rdbuf()->sputn(d, len) != len) {\n dest.setstate(ios_base::badbit);\n }\n }\n return dest;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v) {\n for (int i = 0; i < (int)v.size(); i++) {\n os << v[i] << (i + 1 != (int)v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const set<T> &set_var) {\n for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {\n os << *itr;\n ++itr;\n if (itr != set_var.end()) os << \" \";\n itr--;\n }\n return os;\n}\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const map<T, U> &map_var) {\n for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {\n os << itr->first << \" -> \" << itr->second << \"\\n\";\n }\n return os;\n}\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const pair<T, U> &pair_var) {\n os << \"(\" << pair_var.first << \", \" << pair_var.second << \")\";\n return os;\n}\n\nvoid out() { cout << '\\n'; }\ntemplate <class T, class... Ts>\nvoid out(const T &a, const Ts &...b) {\n cout << a;\n (cout << ... << (cout << ' ', b));\n cout << '\\n';\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v) {\n for (T &in : v) is >> in;\n return is;\n}\n\ninline void in(void) { return; }\ntemplate <typename First, typename... Rest>\nvoid in(First &first, Rest &...rest) {\n cin >> first;\n in(rest...);\n return;\n}\n\ntemplate <typename T>\nbool chmax(T &a, const T &b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T &b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n\nvector<lint> dx8 = {1, 1, 0, -1, -1, -1, 0, 1};\nvector<lint> dy8 = {0, 1, 1, 1, 0, -1, -1, -1};\nvector<lint> dx4 = {1, 0, -1, 0};\nvector<lint> dy4 = {0, 1, 0, -1};\n\n#pragma endregion\n\nclass RollingHash {\n private:\n int64_t n;\n int64_t mod = (1LL << 61) - 1;\n int64_t base = 58347;\n vector<int64_t> invb;\n vector<int64_t> sum;\n\n __int128_t mod_pow(__int128_t a, int64_t p) {\n __int128_t res = 1;\n while (p) {\n if (p & 1) res = (res * a) % mod;\n a = (a * a) % mod;\n p >>= 1;\n }\n return res;\n }\n\n public:\n RollingHash(const string &s) {\n __int128_t b_p = 1;\n n = int64_t(s.size());\n invb.resize(n + 1);\n sum.resize(n + 1);\n\n for (int i = 0; i < n; i++) {\n int64_t h_i = (b_p * int(s[i])) % mod;\n sum[i + 1] = (sum[i] + h_i) % mod;\n b_p = (b_p * base) % mod;\n }\n invb[n] = mod_pow(b_p, mod - 2);\n for (int i = n - 1; i >= 0; i--) {\n invb[i] = (__int128_t(invb[i + 1]) * base) % mod;\n }\n }\n\n int64_t range_hash(int l, int r) {\n return (__int128_t(sum[r] - sum[l] + mod) * invb[l]) % mod;\n }\n};\n\nint main() {\n cin.tie(0)->sync_with_stdio(0);\n string t, p;\n in(t, p);\n int n = t.size();\n int m = p.size();\n\n if (n < m) return 0;\n\n RollingHash tmp(p);\n int64_t h = tmp.range_hash(0, m);\n\n RollingHash rh(t);\n\n rep(i, n - m + 1) {\n if (rh.range_hash(i, i + m) == h) {\n out(i);\n }\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 20144, "score_of_the_acc": -0.5448, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_14_B_10875697", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vec<vv<T>>;\ntemplate <class T> using pq = priority_queue<T, vector<T>, greater<T>>;\n#define rep(i, r) for(ll i = 0; i < (r); i++)\n#define reps(i, l, r) for(ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for(ll i = (r) - 1; i >= l; i--)\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\ntemplate<typename T>\nbool chmax(T &a, const T& b) { return a < b ? a = b, true : false; }\ntemplate<typename T>\nbool chmin(T &a, const T& b) { return a > b ? a = b, true : false; }\nvl pi(const string &s) {\n\tvl p(sz(s));\n\treps(i, 1, sz(s)) {\n\t\tll g = p[i - 1];\n\t\twhile (g && s[i] != s[g]) g = p[g - 1];\n\t\tp[i] = g + (s[i] == s[g]);\n\t}\n\treturn p;\n}\nvl match(const string &s, const string& pat) {\n\tvl p = pi(pat + '\\0' + s), res;\n\treps(i, sz(p) - sz(s), sz(p))\n\t\tif (p[i] == sz(pat)) res.push_back(i - 2 * sz(pat));\n\treturn res;\n}\nvoid solve() {\n\tstring s, t; cin >> s >> t;\n\tauto mm = match(s, t);\n\trep(i, sz(mm)) cout << mm[i] << endl;\n}\nint main() {\n\tll T = 1;\n\t// cin >> T;\n\twhile (T--) solve();\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 22948, "score_of_the_acc": -1.0122, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_14_B_10851568", "code_snippet": "#include <bits/stdc++.h>\n#define optimizar_io ios_base::sync_with_stdio(0);cin.tie\nusing namespace std;\n\nstring s,t;\n//Saber en que posiciones t es subcadena de s\n//La complejidad de su funcionamiento es O(|s| + |t|)\n\n//Arreglo de la Función de Error. Debemos cuidar que el tamaño sea igual al peor tamaño de T , más 5.\n//Si |T| <= 10⁵ , entonces : \nint FE[1000002];\n\n\n//Calculamos la función de error\nvoid FuncionError(){\t\n\n\t//Ya vimos que para la 0, su Fe es -1\n\tFE[0] = -1;\n\n\t//Vamos ir caracter por caracter\n\tfor(int i = 0; i < t.size();){\n\n\t\t//Tomamos el caracter i para resolver la solución para la posición i+1.\n\n\t\t//Ya que queremos saber para i+1, el anterior es i, por lo tanto nos vamos \n\t\t//a su función de error.\n\t\tint pos = FE[i];\n\n\t\t//Iteramos mientras que la letra siguiente no sea igual a la siguiente de la función\n\t\t//de error. Adicionalmente, si pos se vuelve negativo, o sea -1, deja de moverse\n\t\t//hacia atras.\n\t\twhile(pos >= 0 && t[pos] != t[i])\n\t\t\tpos = FE[pos]; //Usa la función de error para moverse hacia atras\n\n\t\t//Como s[pos] == s[i] , es como si los dos se movieran en el automata.\n\t\t//Y como el prefijo que termina en 'pos' es sufijo del prefijo que termina en i.\n\t\t//Y como s[pos] == s[i], entonces el prefijo que termina en 'pos+1' es sufijo\n\t\t//del que termina en i+1.\n\t\tFE[++i] = ++pos;\n\n\t}\n}\n\n\n//Imprime las posiciones en las que t se encuentra en s.\n//Debimos haber calculado la función de error desde antes de llamar esta función.\nvoid Aparece(){\n\n\t//Ya que no hemos matcheado nada, empezamos en el estado inicial\n\tint pos = 0;\n\n\t//Vamos caracter por caracter\n\tfor(int i = 0; i < s.size(); i++){\n\n\t\t//Buscamos sobre 't' el primer caracter que sea igual al siguiente de 's'\n\t\t//Aplica la misma regla de cuando llegamos a -1, es decir, dejamos de movernos\n\t\t//hacia atrás.\n\t\twhile(pos >= 0 && s[i] != t[pos] )\n\t\t\tpos = FE[pos]; //De nuevo usamos la función de error\n\t\t\n\t\t//Ya que encontramos un caracter igual, o llegamos a -1, avanzamos sobre\n\t\t//el \"autómata\", que en sí es un arreglo\n\t\tpos++;\n\n\t\t//Preguntamos si ya procesamos todos los caracteres de t\n\t\tif(pos == t.size()){\n\t\t\t//Si es así, es porque en i hemos pasados por todos los caracteres\n\t\t\t//Por lo tanto t termina en la posición i.\n\t\t\t//Así, si termina en i , entonces inicio en i - |t| + 1.\n\t\t\tcout << i - t.size() + 1 << '\\n';\n\n\t\t\t//Al estar en el último estado, no habrá nada que acepte el \"autómata\",\n\t\t\t//entonces, eventualmente se moverá con la función de errro. Por lo tanto\n\t\t\t//no hay problema con moverse desde este punto.\n\t\t\tpos = FE[pos];\n\n\t\t}\n\t}\n}\n\nint main()\n{\n\toptimizar_io(0);\n\tcin>>s;\n\tcin>>t;\n\n\tFuncionError();\n\n\tAparece();\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4096, "score_of_the_acc": -0.0306, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_14_B_10827014", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n string t,p;\n cin >> t >> p;\n int n = t.size();\n int m = p.size();\n for(int i = 0; i + m <= n; ++i) {\n if(t.substr(i,m) == p) {\n cout << i << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 990, "memory_kb": 4124, "score_of_the_acc": -1.0009, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_14_B_10826737", "code_snippet": "#line 1 \"/home/y_midori/cp/test/test.test.cpp\"\n#define PROBLEM \"https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_14_B\"\n#line 2 \"template.hpp\"\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3\")\n// #pragma GCC optimize(\"unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\n#ifdef LOCAL\n#include <debug.hpp>\n#else\ntemplate <class T>\nconcept Streamable = requires(ostream os, T &x) { os << x; };\ntemplate <class mint>\nconcept is_modint = requires(mint &x) {\n { x.val() } -> std::convertible_to<int>;\n};\n#define debug(...)\n#endif\ntemplate <Streamable T> void print_one(const T &value) { cout << value; }\ntemplate <is_modint T> void print_one(const T &value) { cout << value.val(); }\nvoid print() { cout << '\\n'; }\ntemplate <class T, class... Ts> void print(const T &a, const Ts &...b) {\n print_one(a);\n ((cout << ' ', print_one(b)), ...);\n cout << '\\n';\n}\ntemplate <ranges::range Iterable>\n requires(!Streamable<Iterable>)\nvoid print(const Iterable &v) {\n for(auto it = v.begin(); it != v.end(); ++it) {\n if(it != v.begin())\n cout << \" \";\n print_one(*it);\n }\n cout << '\\n';\n}\nusing vi = vector<int>;\nusing vii = vector<vector<int>>;\nusing pii = pair<int, int>;\nusing ll = long long;\nusing vl = vector<ll>;\nusing vll = vector<vl>;\nusing pll = pair<ll, ll>;\n#define all(v) begin(v), end(v)\ntemplate <class T> void UNIQUE(T &v) {\n ranges::sort(v);\n v.erase(unique(all(v)), end(v));\n}\ntemplate <typename T> inline bool chmax(T &a, T b) {\n return ((a < b) ? (a = b, true) : (false));\n}\ntemplate <typename T> inline bool chmin(T &a, T b) {\n return ((a > b) ? (a = b, true) : (false));\n}\n// https://trap.jp/post/1224/\ntemplate <class... T> constexpr auto min(T... a) {\n return min(initializer_list<common_type_t<T...>>{a...});\n}\ntemplate <class... T> constexpr auto max(T... a) {\n return max(initializer_list<common_type_t<T...>>{a...});\n}\ntemplate <class... T> void input(T &...a) { (cin >> ... >> a); }\ntemplate <class T> void input(vector<T> &a) {\n for(T &x : a)\n cin >> x;\n}\n#define INT(...) \\\n int __VA_ARGS__; \\\n input(__VA_ARGS__)\n#define LL(...) \\\n long long __VA_ARGS__; \\\n input(__VA_ARGS__)\n#define STR(...) \\\n string __VA_ARGS__; \\\n input(__VA_ARGS__)\n#define REP1_0(n, c) REP1_1(n, c)\n#define REP1_1(n, c) \\\n for(ll REP_COUNTER_##c = 0; REP_COUNTER_##c < (ll)(n); REP_COUNTER_##c++)\n#define REP1(n) REP1_0(n, __COUNTER__)\n#define REP2(i, a) for(ll i = 0; i < (ll)(a); i++)\n#define REP3(i, a, b) for(ll i = (ll)(a); i < (ll)(b); i++)\n#define REP4(i, a, b, c) for(ll i = (ll)(a); i < (ll)(b); i += (ll)(c))\n#define overload4(a, b, c, d, e, ...) e\n#define rep(...) overload4(__VA_ARGS__, REP4, REP3, REP2, REP1)(__VA_ARGS__)\nll inf = 3e18;\nvl dx = {1, -1, 0, 0};\nvl dy = {0, 0, 1, -1};\ntemplate <class T> constexpr T floor(T x, T y) noexcept {\n return x / y - ((x ^ y) < 0 and x % y);\n}\ntemplate <class T> constexpr T ceil(T x, T y) noexcept {\n return x / y + ((x ^ y) >= 0 and x % y);\n}\n// yの符号に関わらず非負で定義 \\bmod:texコマンド\ntemplate <class T> constexpr T bmod(T x, T y) noexcept {\n T m = x % y;\n return (m < 0) ? m + (y > 0 ? y : -y) : m;\n}\ntemplate <std::signed_integral T> constexpr int bit_width(T x) noexcept {\n return std::bit_width((uint64_t)x);\n}\ntemplate <std::signed_integral T> constexpr int popcount(T x) noexcept {\n return std::popcount((uint64_t)x);\n}\nconstexpr bool kth_bit(auto n, auto k) { return (n >> k) & 1; }\n#line 3 \"/home/y_midori/cp/test/test.test.cpp\"\n#include <atcoder/string>\n// knuth\nvector<int> knuth_morris_pratt(const string &&s) {\n int n = ssize(s);\n vector<int> res(n + 1, -1);\n for(int i = 0, j = -1; i < n; ++i) {\n while(j >= 0 and s[j] != s[i]) {\n j = res[j];\n }\n ++j;\n debug(i + 1, n, res.size());\n res[i + 1] = j;\n // res[i + 1] = (i + 1 < n and s[j] == s[i + 1]) ? res[j] : j;\n }\n debug(s);\n debug(res);\n return res;\n}\nvoid solve() {\n STR(t, p);\n auto v = knuth_morris_pratt(p + \"$\" + t);\n v.erase(begin(v), begin(v) + 2 + p.size());\n for(int i = 0; i < t.size(); ++i) {\n if(v[i] == p.size()) {\n print(i - p.size() + 1);\n }\n }\n}\n\nint main() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n solve();\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 9472, "score_of_the_acc": -0.1926, "final_rank": 2 } ]
aoj_DSL_1_B_cpp
Weighted Union Find Trees There is a sequence $A = a_0, a_1, ..., a_{n-1}$. You are given the following information and questions. relate$(x, y, z)$: $a_y$ is greater than $a_x$ by $z$ diff$(x, y)$: report the difference between $a_x$ and $a_y$ $(a_y - a_x)$ Input $n \; q$ $query_1$ $query_2$ : $query_q$ In the first line, $n$ and $q$ are given. Then, $q$ information/questions are given in the following format. 0 $x \; y\; z$ or 1 $x \; y$ where ' 0 ' of the first digit denotes the relate information and ' 1 ' denotes the diff question. Output For each diff question, print the difference between $a_x$ and $a_y$ $(a_y - a_x)$. Constraints $2 \leq n \leq 100,000$ $1 \leq q \leq 200,000$ $0 \leq x, y < n$ $x \ne y$ $0 \leq z \leq 10000$ There are no inconsistency in the given information Sample Input 5 6 0 0 2 5 0 1 2 3 1 0 1 1 1 3 0 1 4 8 1 0 4 Sample Output 2 ? 10
[ { "submission_id": "aoj_DSL_1_B_11052170", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Weighted_UnionFind {\n vector<int> par, rank, siz;\n vector<ll> weight;\n\n Weighted_UnionFind(int N) : par(N,-1), rank(N, 0), siz(N,1), weight(N,0) {}\n \n int root(int x) {\n if (par[x] == -1) return x;\n int r = root(par[x]);\n weight[x] += weight[par[x]];\n return par[x] = r;\n }\n\n ll weight_of(int x) {\n root(x);\n return weight[x];\n }\n\n void relate(int x, int y, ll w) {\n ll wx = weight_of(x), wy = weight_of(y);\n int rx = root(x), ry = root(y);\n if (rx == ry) return;\n\n ll d = w + wx - wy;\n if (rank[rx] < rank[ry]) { swap(rx, ry); d = -d; }\n\n par[ry] = rx;\n weight[ry] = d;\n siz[rx] += siz[ry];\n if (rank[rx] == rank[ry]) rank[rx]++;\n }\n\n ll diff(int x, int y) {\n if (root(x) != root(y)) return LLONG_MAX;\n return weight_of(y) - weight_of(x);\n }\n};\n\nint main() {\n int N, Q;\n cin >> N >> Q;\n\n Weighted_UnionFind w_uf(N);\n for (int qi = 0; qi < Q; qi++) {\n int type; cin >> type;\n if (type == 0) {\n int x, y; ll w;\n cin >> x >> y >> w;\n w_uf.relate(x, y, w); //a[y] > a[x] 差はz\n } else if (type == 1) {\n int x, y;\n cin >> x >> y;\n ll d = w_uf.diff(x, y); //a[y]とa[x]の差を求める\n if (d == LLONG_MAX) cout << \"?\" << endl;\n else cout << d << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4936, "score_of_the_acc": -1.1394, "final_rank": 18 }, { "submission_id": "aoj_DSL_1_B_11021354", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntemplate<class T>\nstruct weighted_uf{\n\tvector<int>a;\n\tvector<T>w;\n\tweighted_uf(int n):a(n,-1),w(n){}\n\tint root(int u){\n\t\tif(a[u]<0)return u;\n\t\tint v=a[u];\n\t\ta[u]=root(a[u]);\n\t\tw[u]+=w[v];\n\t\treturn a[u];\n\t}\n\tbool same(int u,int v){return root(u)==root(v);}\n\tT diff(int u,int v){\n\t\tassert(same(u,v));\n\t\treturn w[v]-w[u];\n\t}\n\tbool unite(int u,int v,T d){\n\t\troot(u),root(v);\n\t\td+=w[u]-w[v];\n\t\tu=root(u),v=root(v);\n\t\tif(u==v){assert(d==0);return 0;}\n\t\tif(a[u]>a[v])swap(u,v),d=-d;\n\t\ta[u]+=a[v];\n\t\tw[v]=d;\n\t\ta[v]=u;\n\t\treturn 1;\n\t}\n};\nint main(){\n\tcin.tie(0)->sync_with_stdio(0);\n\tint n,q;\n\tcin>>n>>q;\n\tweighted_uf<int>uf(n);\n\twhile(q--){\n\t\tint op,u,v;\n\t\tcin>>op>>u>>v;\n\t\tif(op==0){\n\t\t\tint w;\n\t\t\tcin>>w;\n\t\t\tuf.unite(u,v,w);\n\t\t}\n\t\tif(op==1){\n\t\t\tif(uf.root(u)==uf.root(v)){\n\t\t\t\tcout<<uf.diff(u,v)<<'\\n';\n\t\t\t}else{\n\t\t\t\tcout<<'?'<<'\\n';\n\t\t\t}\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3744, "score_of_the_acc": -0.0667, "final_rank": 2 }, { "submission_id": "aoj_DSL_1_B_11009305", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\n#define revrep(i,n) for(int i=(int)(n)-1;i>=0;--i)\nusing namespace std;\nusing ll = long long;\n\nclass WUF {\n\nprivate:\n vector<int> parent;\n vector<int> diff_weight;\n\npublic:\n WUF(int n):parent(n),diff_weight(n){\n iota(parent.begin(),parent.end(),0);\n }\n \n int find(int x){\n if(parent[x]==x) return x;\n \n int r = find(parent[x]);\n diff_weight[x] += diff_weight[parent[x]];\n parent[x] = r;\n return r;\n }\n \n bool same(int x,int y){\n return find(x) == find(y);\n }\n \n bool unite(int x,int y,int z){\n int root_x = find(x);\n int root_y = find(y);\n \n if(root_x!=root_y){\n parent[root_y] = root_x;\n diff_weight[root_y] = z + diff_weight[x] - diff_weight[y];\n return true;\n }else return false;\n }\n \n string diff(int x,int y){\n if(!same(x,y)) return \"?\";\n int ans = diff_weight[y] - diff_weight[x];\n return to_string(ans);\n }\n \n};\n\n\nint main(void){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int n,Q;cin>>n>>Q;\n WUF S(n);\n \n while(Q--){\n int com;cin>>com;\n if(com==0){\n int x,y,z;cin>>x>>y>>z;\n S.unite(x,y,z);\n }else{\n int x,y;cin>>x>>y;\n cout << S.diff(x,y) << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 3880, "score_of_the_acc": -0.5568, "final_rank": 6 }, { "submission_id": "aoj_DSL_1_B_10993797", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* WeightedUnionFind \n\thttps://www.youtube.com/live/ugeZCP6JxqQ?&t=8302\n\n\troot(x): xの根。O(α(n))\n\tsize(x): xを含む集合の要素数。\n\tsame(x,y): xとyが同じ集合にいるか。O(α(n))\n\tmerge(x,y): xとyを同じ集合にする。y->xに重さdの辺を張る。 O(α(n))\n\tgroups(): 「一つの連結成分の頂点番号のリスト」のリスト\n\tdiff(x,y): y->xを返す。\n*/\ntemplate<class T>\nstruct WeightedUF{\n\tint _n;\n\tvi par;\n\tvc<T> dif;\n\tWeightedUF(): _n(0) {}\n\tWeightedUF(int n): _n(n),par(n,-1), dif(n) {}\n\tint root(int x){\n\t\tif(par[x] < 0) return x;\n\t\tint nroot=root(par[x]);\n\t\tdif[x] += dif[par[x]];\n\t\tpar[x] = nroot; //経路圧縮\n\t\treturn nroot;\n\t}\n\tint size(int x){\n\t\treturn -par[root(x)];\n\t}\n\tbool same(int x, int y){\n\t\treturn root(x) == root(y);\n\t}\n\tbool merge(int x, int y, T d){ //merge成功のときtrue\n\t\tint rx=root(x), ry=root(y);\n\t\td += dif[x]-dif[y];\n\t\tif(rx == ry) return d == 0;\n\t\tif(-par[x] < -par[y]){\n\t\t\tswap(rx,ry);\n\t\t\td*=-1;\n\t\t}\n\t\tpar[rx]+=par[ry];\n\t\tpar[ry]=rx;\n\t\tdif[ry]=d;\n\t\treturn true;\n\t}\n\tvvi groups() {\n vi roots(_n), si(_n);\n rep(i,_n){\n roots[i] = root(i);\n si[roots[i]]++;\n }\n vvi result(_n);\n rep(i,_n) result[i].reserve(si[i]);\n rep(i,_n) result[roots[i]].pb(i);\n result.erase(\n remove_if(result.begin(), result.end(), [&](const vi& v) { return v.empty(); }),\n result.end()\n );\n return result;\n }\n\tT diff(int x, int y) {\n\t\tif(!same(x,y)) return numeric_limits<T>::max();\n return dif[y] - dif[x];\n }\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n \tcin.tie(0);\n\tint n,q; cin >> n >> q;\n WeightedUF<ll> uf(n);\n rep(i,q){\n int type; cin >> type;\n if(type==0){\n int x,y; ll z; cin >> x >> y >> z;\n uf.merge(x,y,z);\n } else {\n int x,y; cin >> x >> y;\n if(uf.diff(x,y)==numeric_limits<ll>::max())cout << '?' << endl;\n else cout << uf.diff(x,y) << endl;\n }\n }\n\treturn 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 4772, "score_of_the_acc": -0.7111, "final_rank": 7 }, { "submission_id": "aoj_DSL_1_B_10958621", "code_snippet": "#include <stdio.h>\n#include <cmath>\n#include <algorithm>\n#include <cfloat>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <set>\n#include <map>\n#include <time.h>\ntypedef long long int ll;\ntypedef unsigned long long int ull;\n#define BIG_NUM 2000000000\n#define MOD 1000000007\n#define EPS 0.000000001\nusing namespace std;\n\n\n#define NUM 100005\n\nint height[NUM]; //同じグループに属しているかどうかだけを調べるために使用\nint calc_parent[NUM];\nint relative_weight[NUM]; //自分のボスとの相対的な重さの差を持つ配列\n\nstruct Info{\n\tvoid set(int arg_parent_id,int arg_weight_sum){\n\t\tparent_id = arg_parent_id;\n\t\tweight_sum = arg_weight_sum;\n\t}\n\tint parent_id,weight_sum;\n};\n\nInfo find_parent_and_calc_weight(int id){\n\tif(calc_parent[id] == id){\n\t\tInfo ret;\n\t\tret.set(id,0); //大ボスの相対的重さは必ず0\n\t\treturn ret;\n\t}\n\telse{\n\t\tInfo ret = find_parent_and_calc_weight(calc_parent[id]); //大ボスのidと、自分より上の相対的重さの総和を取得\n\t\tcalc_parent[id] = ret.parent_id;\n\t\trelative_weight[id] += ret.weight_sum; //自分より上の相対的重さを足す\n\t\tret.weight_sum = relative_weight[id];\n\n\t\treturn ret;\n\t}\n}\n\n\n//グループの統合、および相対的重さ木の統合を行う\nvoid unite(int a,int b,int w){\n\n\t//まずは\n\tInfo a_info = find_parent_and_calc_weight(a);\n\tInfo b_info = find_parent_and_calc_weight(b);\n\n\tif(a_info.parent_id == b_info.parent_id)return; //大ボスが同じならreturn\n\n\t//統合処理\n\tif(height[a_info.parent_id] == height[b_info.parent_id]){ //木の高さが同じ場合はaに併合する\n\n\t\trelative_weight[b_info.parent_id] = w-(relative_weight[b]-relative_weight[a]);\n\t\tcalc_parent[b_info.parent_id] = a_info.parent_id;\n\n\t}else if(height[a_info.parent_id] == height[b_info.parent_id]){ //木の高さが高い方に併合する\n\t\trelative_weight[b_info.parent_id] = w-(relative_weight[b]-relative_weight[a]);\n\t\tcalc_parent[b_info.parent_id] = a_info.parent_id;\n\t\theight[a_info.parent_id]++;\n\t}else{\n\n\t\trelative_weight[a_info.parent_id] = (relative_weight[b]-relative_weight[a])-w;\n\t\tcalc_parent[a_info.parent_id] = b_info.parent_id;\n\t}\n}\n\nbool isSame(int a,int b){\n\tInfo left = find_parent_and_calc_weight(a);\n\tInfo right = find_parent_and_calc_weight(b);\n\n\treturn left.parent_id == right.parent_id;\n}\n\nint main(){\n\n\tint N,Q;\n\tscanf(\"%d %d\",&N,&Q);\n\n\tfor(int i = 0; i <= N; i++){\n\t\theight[i] = 0;\n\t\tcalc_parent[i] = i;\n\t\trelative_weight[i] = 0; //初期値は0にしておく\n\t}\n\n\tint command,A,B,value;\n\tfor(int loop = 0; loop < Q; loop++){\n\t\tscanf(\"%d\",&command);\n\n\t\tif(command == 0){\n\t\t\tscanf(\"%d %d %d\",&A,&B,&value);\n\t\t\tunite(A,B,value);\n\t\t}else{\n\t\t\tscanf(\"%d %d\",&A,&B);\n\t\t\tif(!isSame(A,B)){ //★ここでそれぞれの経路圧縮&weight計算が行われる★\n\t\t\t\tprintf(\"?\\n\");\n\t\t\t}else{\n\t\t\t\tprintf(\"%d\\n\",relative_weight[B]-relative_weight[A]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4736, "score_of_the_acc": -0.3048, "final_rank": 4 }, { "submission_id": "aoj_DSL_1_B_10860049", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n//レビューの力を借りたプログラムです\n\nclass DisjointSet {\n vector<int> parent, rank, weight;\n int INT_MAX = 10001;\n\npublic:\n DisjointSet(int n) {\n parent.resize(n);\n rank.resize(n, 0);\n weight.resize(n, 0);\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n }\n\n int findSet(int x) {\n if (parent[x] != x) {\n int orig = parent[x];\n parent[x] = findSet(parent[x]);\n weight[x] += weight[orig];\n }\n return parent[x];\n }\n\n void unionSet(int x, int y, int w) {\n int rootX = findSet(x);\n int rootY = findSet(y);\n if (rootX != rootY) {\n if (rank[rootX] < rank[rootY]) {\n parent[rootX] = rootY;\n weight[rootX] = weight[y] - weight[x] - w;\n } else if (rank[rootX] > rank[rootY]) {\n parent[rootY] = rootX;\n weight[rootY] = weight[x] - weight[y] + w;\n } else {\n parent[rootY] = rootX;\n weight[rootY] = weight[x] - weight[y] + w;\n rank[rootX]++;\n }\n }\n }\n\n int diff(int x, int y) {\n if (findSet(x) == findSet(y)) {\n return weight[y] - weight[x];\n }\n return INT_MAX;\n }\n};\n\nint main() {\n int n, q;\n int INT_MAX = 10001;\n cin >> n >> q;\n DisjointSet ds(n);\n\n for (int i = 0; i < q; i++) {\n int queryType, x, y, z;\n cin >> queryType;\n if (queryType == 0) {\n cin >> x >> y >> z;\n ds.unionSet(x, y, z);\n } else if (queryType == 1) {\n cin >> x >> y;\n int result = ds.diff(x, y);\n if (result == INT_MAX) {\n cout << \"?\" << endl;\n } else {\n cout << result << endl;\n }\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4112, "score_of_the_acc": -0.997, "final_rank": 9 }, { "submission_id": "aoj_DSL_1_B_10848204", "code_snippet": "#include<bits/stdc++.h>\n\n#define N 100010\n\nint a[N],w[N];\n\nint Find(int x){\n\tif(x==a[x])\n\t\treturn x;\n\tint t=Find(a[x]);\n\tw[x]+=w[a[x]];\n\treturn a[x]=t;\n}\n\nvoid Union(int x,int y,int z){\n\tint u=Find(x),v=Find(y);\n if(u==v)\n\t\tassert(w[y]-w[x]==z);\n\telse{\n\t\ta[v]=u;\n\t\tw[v]=w[x]-w[y]+z;\n\t}\n}\n\nint main(){\n\tint n,q;\n\tscanf(\"%d%d\",&n,&q);\n\tfor(int i=1;i<=n;i++)\n\t\ta[i]=i;\n\tfor(int op,x,y,z;q--;){\n\t\tscanf(\"%d%d%d\",&op,&x,&y);\n\t\tx++,y++;\n\t\tif(!op){\n\t\t\tscanf(\"%d\",&z);\n\t\t\tUnion(x,y,z);\n\t\t}\n\t\telse{\n\t\t\tif(Find(x)==Find(y))\n\t\t\t\tprintf(\"%d\\n\",w[y]-w[x]);\n\t\t\telse\n\t\t\t\tputs(\"?\");\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4344, "score_of_the_acc": -0.2371, "final_rank": 3 }, { "submission_id": "aoj_DSL_1_B_10787513", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<n;i++)\nusing ll=long long;\n\nstruct wdsu{\n vector<int> p;\n vector<ll> wd;\n wdsu(int _n):p(_n,-1),wd(_n,0){}\n int root(int x){\n if(p[x]<0) return x;\n int r=root(p[x]);\n wd[x]+=wd[p[x]];\n return p[x]=r;}\n bool same(int x,int y){return root(x)==root(y);}\n int size(int x){return -p[root(x)];}\n void add(int _n=1){rep(i,_n){p.push_back(-1);wd.push_back(0);}}\n ll weight(int x){root(x);return wd[x];}\n void relate(int x,int y,ll w){ //weight(y)はweight(x)よりw大きい\n w=w+weight(x)-weight(y);\n x=root(x),y=root(y);\n if(x==y) return;\n if(p[x]>p[y]){swap(x,y);w=-w;}\n p[x]+=p[y]; p[y]=x; wd[y]=w;}\n ll diff(int x,int y){return weight(y)-weight(x);}\n};\n\nint main(){\n int n,q;cin>>n>>q;\n wdsu d(n);\n while(q--){\n int cmd;cin>>cmd;\n if(cmd==0){\n int x,y;ll z;cin>>x>>y>>z;\n d.relate(x,y,z);\n }\n if(cmd==1){\n int x,y;cin>>x>>y;\n if(!d.same(x,y)) cout<<\"?\\n\";\n else cout<<d.diff(x,y)<<\"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4320, "score_of_the_acc": -1.0329, "final_rank": 13 }, { "submission_id": "aoj_DSL_1_B_10787512", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<n;i++)\nusing ll=long long;\n\nstruct wdsu{\n vector<int> p;\n vector<ll> wd;\n wdsu(int _n=0):p(_n,-1),wd(_n,0){}\n int root(int x){\n if(p[x]<0) return x;\n int r=root(p[x]);\n wd[x]+=wd[p[x]];\n return p[x]=r;}\n bool same(int x,int y){return root(x)==root(y);}\n int size(int x){return -p[root(x)];}\n void add(int _n=1){rep(i,_n){p.push_back(-1);wd.push_back(0);}}\n ll weight(int x){root(x);return wd[x];}\n void relate(int x,int y,ll w){ //weight(y)はweight(x)よりw大きい\n w=w+weight(x)-weight(y);\n x=root(x),y=root(y);\n if(x==y) return;\n if(p[x]>p[y]){swap(x,y);w=-w;}\n p[x]+=p[y]; p[y]=x; wd[y]=w;}\n ll diff(int x,int y){return weight(y)-weight(x);}\n};\n\nint main(){\n int n,q;cin>>n>>q;\n wdsu d;\n d.add(n);\n while(q--){\n int cmd;cin>>cmd;\n if(cmd==0){\n int x,y;ll z;cin>>x>>y>>z;\n d.relate(x,y,z);\n }\n if(cmd==1){\n int x,y;cin>>x>>y;\n if(!d.same(x,y)) cout<<\"?\\n\";\n else cout<<d.diff(x,y)<<\"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4464, "score_of_the_acc": -1.0578, "final_rank": 15 }, { "submission_id": "aoj_DSL_1_B_10787509", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<n;i++)\nusing ll=long long;\n\nstruct wdsu{\n vector<int> p;\n vector<ll> wd;\n wdsu(int _n=0):p(_n,-1),wd(_n,0){}\n int root(int x){\n if(p[x]<0) return x;\n int r=root(p[x]);\n wd[x]+=wd[p[x]];\n return p[x]=r;}\n bool same(int x,int y){return root(x)==root(y);}\n int size(int x){return -p[root(x)];}\n void add(int _n=1){rep(i,_n){p.push_back(-1);wd.push_back(0);}}\n ll weight(int x){root(x);return wd[x];}\n void relate(int x,int y,ll w){ //weight(y)はweight(x)よりw大きい\n w=w+weight(x)-weight(y);\n x=root(x),y=root(y);\n if(x==y) return;\n if(p[x]>p[y]){swap(x,y);w=-w;}\n p[x]+=p[y]; p[y]=x; wd[y]=w;}\n ll diff(int x,int y){return weight(y)-weight(x);}\n};\n\nint main(){\n int n,q;cin>>n>>q;\n wdsu d(n);\n while(q--){\n int cmd;cin>>cmd;\n if(cmd==0){\n int x,y;ll z;cin>>x>>y>>z;\n d.relate(x,y,z);\n }\n if(cmd==1){\n int x,y;cin>>x>>y;\n if(!d.same(x,y)) cout<<\"?\\n\";\n else cout<<d.diff(x,y)<<\"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 4100, "score_of_the_acc": -1.0615, "final_rank": 16 }, { "submission_id": "aoj_DSL_1_B_10787505", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nstruct wdsu{\n vector<int> p;\n vector<ll> wd;\n wdsu(int _n=0):p(_n,-1),wd(_n){}\n int root(int x){\n if(p[x]<0) return x;\n int r=root(p[x]);\n wd[x]+=wd[p[x]];\n return p[x]=r;}\n bool same(int x,int y){return root(x)==root(y);}\n int size(int x){return -p[root(x)];}\n ll weight(int x){root(x);return wd[x];}\n void relate(int x,int y,ll w){ //weight(y)はweight(x)よりw大きい\n w=w+weight(x)-weight(y);\n x=root(x),y=root(y);\n if(x==y) return;\n if(p[x]>p[y]){swap(x,y);w=-w;}\n p[x]+=p[y]; p[y]=x; wd[y]=w;}\n ll diff(int x,int y){return weight(y)-weight(x);}\n};\n\nint main(){\n int n,q;cin>>n>>q;\n wdsu d(n);\n while(q--){\n int cmd;cin>>cmd;\n if(cmd==0){\n int x,y;ll z;cin>>x>>y>>z;\n d.relate(x,y,z);\n }\n if(cmd==1){\n int x,y;cin>>x>>y;\n if(!d.same(x,y)) cout<<\"?\\n\";\n else cout<<d.diff(x,y)<<\"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4140, "score_of_the_acc": -1.0018, "final_rank": 10 }, { "submission_id": "aoj_DSL_1_B_10787502", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nstruct wdsu{\n vector<int> p;\n vector<ll> wd;\n wdsu(int _n=0):p(_n,-1),wd(_n){}\n int root(int x){\n if(p[x]<0) return x;\n int r=root(p[x]);\n wd[x]+=wd[p[x]];\n return p[x]=r;}\n bool same(int x,int y){return root(x)==root(y);}\n ll weight(int x){root(x);return wd[x];}\n void relate(int x,int y,ll w){ //weight(y)はweight(x)よりw大きい\n w=w+weight(x)-weight(y);\n x=root(x),y=root(y);\n if(x==y) return;\n if(p[x]>p[y]){swap(x,y);w=-w;}\n p[x]+=p[y]; p[y]=x; wd[y]=w;}\n ll diff(int x,int y){return weight(y)-weight(x);}\n};\n\nint main(){\n int n,q;cin>>n>>q;\n wdsu d(n);\n while(q--){\n int cmd;cin>>cmd;\n if(cmd==0){\n int x,y;ll z;cin>>x>>y>>z;\n d.relate(x,y,z);\n }\n if(cmd==1){\n int x,y;cin>>x>>y;\n if(!d.same(x,y)) cout<<\"?\\n\";\n else cout<<d.diff(x,y)<<\"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4320, "score_of_the_acc": -1.0329, "final_rank": 13 }, { "submission_id": "aoj_DSL_1_B_10787501", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nstruct wdsu{\n vector<int> p;\n vector<int> wd;\n wdsu(int _n=0):p(_n,-1),wd(_n){}\n int root(int x){\n if(p[x]<0) return x;\n int r=root(p[x]);\n wd[x]+=wd[p[x]];\n return p[x]=r;}\n bool same(int x,int y){return root(x)==root(y);}\n ll weight(int x){root(x);return wd[x];}\n void relate(int x,int y,int w){ //weight(y)はweight(x)よりw大きい\n w=w+weight(x)-weight(y);\n x=root(x),y=root(y);\n if(x==y) return;\n if(p[x]>p[y]){swap(x,y);w=-w;}\n p[x]+=p[y]; p[y]=x; wd[y]=w;}\n ll diff(int x,int y){return weight(y)-weight(x);}\n};\n\nint main(){\n int n,q;cin>>n>>q;\n wdsu d(n);\n while(q--){\n int cmd;cin>>cmd;\n if(cmd==0){\n int x,y,z;cin>>x>>y>>z;\n d.relate(x,y,z);\n }\n if(cmd==1){\n int x,y;cin>>x>>y;\n if(!d.same(x,y)) cout<<\"?\\n\";\n else cout<<d.diff(x,y)<<\"\\n\";\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 3904, "score_of_the_acc": -0.961, "final_rank": 8 }, { "submission_id": "aoj_DSL_1_B_10781962", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n#ifdef LOCAL\n#include <debug.hpp>\n#else\n#define debug(...)\n#endif\n\ntemplate <class T>\nstruct PotentializedUnionFind {\n int n, counter;\n vector<int> data;\n vector<T> potential;\n PotentializedUnionFind(int size) : n(size), counter(size), data(size, -1), potential(size, 0) {}\n int root(int x) {\n if (data[x] < 0) return x;\n int r = root(data[x]);\n potential[x] += potential[data[x]];\n return data[x] = r;\n }\n bool same(int x, int y) { return root(x) == root(y); }\n // U[y] - U[x] = cost\n bool merge(int x, int y, T cost) {\n int rx = root(x), ry = root(y);\n if (rx == ry) return false;\n if (-data[rx] < -data[ry]) swap(x, y), swap(rx, ry), cost = -cost;\n data[rx] += data[ry];\n data[ry] = rx;\n potential[ry] = potential[x] - potential[y] + cost;\n counter--;\n return true;\n }\n T diff(int x, int y) { return potential[y] - potential[x]; }\n int size(int x) { return -data[root(x)]; }\n int size() { return counter; }\n vector<pair<int, T>> group(int x) {\n vector<pair<int, T>> res;\n for (int i = 0; i < n; i++) {\n if (same(x, i)) res.emplace_back(i, potential[i]);\n }\n return res;\n }\n vector<vector<pair<int, T>>> groups() {\n vector<vector<pair<int, T>>> res(n);\n for (int i = 0; i < n; i++) {\n res[root(i)].emplace_back(i, potential[i]);\n }\n res.erase(remove_if(res.begin(), res.end(), [&](const vector<pair<int, T>>& v) { return v.empty(); }), res.end());\n return res;\n }\n};\n\nint main() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(20);\n int N, Q;\n cin >> N >> Q;\n\n PotentializedUnionFind<int> uf(N);\n while (Q--) {\n int t;\n cin >> t;\n if (t == 0) {\n int x, y, z;\n cin >> x >> y >> z;\n uf.merge(x, y, z);\n }\n if (t == 1) {\n int x, y;\n cin >> x >> y;\n if (uf.same(x, y)) {\n cout << uf.diff(x, y) << '\\n';\n } else {\n cout << \"?\\n\";\n }\n }\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4096, "score_of_the_acc": -0.0609, "final_rank": 1 }, { "submission_id": "aoj_DSL_1_B_10781416", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n// #define rep(i,n) for(int i=0;i<(int)n;i++)\n#define rep(i,n) for(ll i=0;i<(ll)n;i++)\n#define vi vector<int>\n#define vl vector<ll>\n#define vd vector<double>\n#define vb vector<bool>\n#define vs vector<string>\n#define vc vector<char>\n#define ull unsigned long long\n#define chmax(a,b) a=max(a,b)\n#define chmin(a,b) a=min(a,b)\n\n\n\nll inf=(1ll<<60);\n\n// ll rui(ll a,ll b){\n// if(b==0)return 1;\n// if(b%2==1) return a*rui(a*a,b/2);\n// return rui(a*a,b/2);\n// }\n\n// ll kai(ll n){\n// if(n==0)return 1;\n// return n*kai(n-1);\n// }\n\n// ll mod=?;\n// ll const mod=998244353ll;\n// ll modrui(ll a,ll b){\n// if(b==0)return 1;\n// if(b%2==1) return a%mod*modrui(a%mod*a%mod,b/2)%mod;\n// return modrui(a%mod*a%mod,b/2)%mod;\n// }\n\n// ll inv(ll x){\n// return modrui(x,mod-2);\n// }\n\n// ll modkai(ll n){\n// ll ret=1;\n// rep(i,n){\n// ret*=i+1;\n// ret%=mod;\n// }\n// return ret;\n// }\n\n\n// void incr(vl &f,ll &n){\n// ll k=f.size();\n// f[k-1]++;\n// ll now=k-1;\n// while (f[now]>=n)\n// {\n// f[now]=0;\n// if(now==0)break;\n// f[now-1]++;\n// now--;\n// }\n// return;\n// }\n\n\n\n\n// weighted unionfind\nstruct WeightedUnionFind {\n vector<ll> par, rank, diff_weight;\n\n WeightedUnionFind(ll n) : par(n), rank(n, 0), diff_weight(n, 0) {\n for (ll i = 0; i < n; i++) par[i] = i;\n }\n\n ll find(ll x) {\n if (par[x] == x) return x;\n ll r = find(par[x]);\n diff_weight[x] += diff_weight[par[x]];\n return par[x] = r;\n }\n\n ll weight(ll x) {\n find(x);\n return diff_weight[x];\n }\n\n bool unite(ll x, ll y, ll w) {// a[y] - a[x] = w\n w += weight(x);\n w -= weight(y);\n x = find(x);\n y = find(y);\n if (x == y) return false;\n if (rank[x] < rank[y]) swap(x, y), w = -w;\n if (rank[x] == rank[y]) rank[x]++;\n par[y] = x;\n diff_weight[y] = w;\n return true;\n }\n\n bool same(ll x, ll y) {\n return find(x) == find(y);\n }\n\n ll diff(ll x, ll y) {// return a[y]-a[x]\n return weight(y) - weight(x);\n }\n};\n\n\n\n\nvoid solve(){\n ll n,q,x,y,z,op;\n cin >> n >> q;\n WeightedUnionFind uf(n);\n while(q--){\n cin >> op;\n if(op==0){\n cin >> x >> y >> z;\n uf.unite(x,y,z);\n }\n else{\n cin >> x >> y;\n if(uf.same(x,y))cout << uf.diff(x,y) << endl;\n else cout << \"?\\n\";\n }\n }\n}\n\n\nint main(){\n ll t=1;\n // cin >> t;\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 5464, "score_of_the_acc": -1.2307, "final_rank": 19 }, { "submission_id": "aoj_DSL_1_B_10781268", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n// #define rep(i,n) for(int i=0;i<(int)n;i++)\n#define rep(i,n) for(ll i=0;i<(ll)n;i++)\n#define vi vector<int>\n#define vl vector<ll>\n#define vd vector<double>\n#define vb vector<bool>\n#define vs vector<string>\n#define vc vector<char>\n#define ull unsigned long long\n#define chmax(a,b) a=max(a,b)\n#define chmin(a,b) a=min(a,b)\n\n\n\nll inf=(1ll<<60);\n\n// ll rui(ll a,ll b){\n// if(b==0)return 1;\n// if(b%2==1) return a*rui(a*a,b/2);\n// return rui(a*a,b/2);\n// }\n\n// ll kai(ll n){\n// if(n==0)return 1;\n// return n*kai(n-1);\n// }\n\n// ll mod=?;\n// ll const mod=998244353ll;\n// ll modrui(ll a,ll b){\n// if(b==0)return 1;\n// if(b%2==1) return a%mod*modrui(a%mod*a%mod,b/2)%mod;\n// return modrui(a%mod*a%mod,b/2)%mod;\n// }\n\n// ll inv(ll x){\n// return modrui(x,mod-2);\n// }\n\n// ll modkai(ll n){\n// ll ret=1;\n// rep(i,n){\n// ret*=i+1;\n// ret%=mod;\n// }\n// return ret;\n// }\n\n\n// void incr(vl &f,ll &n){\n// ll k=f.size();\n// f[k-1]++;\n// ll now=k-1;\n// while (f[now]>=n)\n// {\n// f[now]=0;\n// if(now==0)break;\n// f[now-1]++;\n// now--;\n// }\n// return;\n// }\n\n\n\n\n// weighted unionfind\nstruct WeightedUnionFind {\n vector<ll> par, rank, diff_weight;\n\n WeightedUnionFind(ll n) : par(n), rank(n, 0), diff_weight(n, 0) {\n for (ll i = 0; i < n; i++) par[i] = i;\n }\n\n ll find(ll x) {\n if (par[x] == x) return x;\n ll r = find(par[x]);\n diff_weight[x] += diff_weight[par[x]];\n return par[x] = r;\n }\n\n ll weight(ll x) {\n find(x);\n return diff_weight[x];\n }\n\n bool unite(ll x, ll y, ll w) {// a[x] - a[y] = w\n w += weight(x);\n w -= weight(y);\n x = find(x);\n y = find(y);\n if (x == y) return false;\n if (rank[x] < rank[y]) swap(x, y), w = -w;\n if (rank[x] == rank[y]) rank[x]++;\n par[y] = x;\n diff_weight[y] = w;\n return true;\n }\n\n bool same(ll x, ll y) {\n return find(x) == find(y);\n }\n\n ll diff(ll x, ll y) {// return a[y]-a[x]\n return weight(y) - weight(x);\n }\n};\n\n\n\n\nvoid solve(){\n ll n,q,x,y,z,op;\n cin >> n >> q;\n WeightedUnionFind uf(n);\n while(q--){\n cin >> op;\n if(op==0){\n cin >> x >> y >> z;\n uf.unite(x,y,z);\n }\n else{\n cin >> x >> y;\n if(uf.same(x,y))cout << uf.diff(x,y) << endl;\n else cout << \"?\\n\";\n }\n }\n}\n\n\nint main(){\n ll t=1;\n // cin >> t;\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 5492, "score_of_the_acc": -1.2355, "final_rank": 20 }, { "submission_id": "aoj_DSL_1_B_10754138", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\nusing namespace std;\nusing ll = long long;\nconstexpr ll INF = 1LL << 60;\ntemplate <class Type>\nstruct WeightedUnionFind {\n vector<int> par, size;\n vector<Type> diffWeight;\n\n WeightedUnionFind(int n) : par(n), size(n, 1), diffWeight(n) {\n iota(par.begin(), par.end(), 0);\n }\n\n int root(int x) {\n if (par[x] == x) return x;\n int r = root(par[x]);\n diffWeight[x] += diffWeight[par[x]];\n return par[x] = r;\n }\n\n Type weight(int x) {\n root(x);\n return diffWeight[x];\n }\n\n bool merge(int x, int y, Type w) {\n w += weight(x);\n w -= weight(y);\n x = root(x);\n y = root(y);\n if (x == y) return false;\n if (size[x] < size[y]) {\n swap(x, y);\n w = -w;\n }\n par[y] = x;\n size[x] += size[y];\n diffWeight[y] = w;\n return true;\n }\n\n bool isSame(int x, int y) {\n return root(x) == root(y);\n }\n\n Type diff(int x, int y) {\n return weight(y) - weight(x);\n }\n\n int groupSize(int x) {\n return size[root(x)];\n }\n};\nint main() {\n int n,m;\n cin >>n >> m;\n WeightedUnionFind<int> wuf(n);\n rep(i,m) {\n int t;\n cin >> t;\n if (t == 0) {\n int x,y,d;\n cin >> x >> y >> d;\n wuf.merge(x,y,d);\n\n }\n else {\n int x,y;\n cin >> x >> y;\n if (!wuf.isSame(x,y)) {\n cout << \"?\" << endl;\n continue;\n }\n cout << wuf.diff(x,y) << endl;\n }\n } \n \n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4168, "score_of_the_acc": -1.0066, "final_rank": 11 }, { "submission_id": "aoj_DSL_1_B_10723848", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\n#define pb push_back\n#define fr(a, b) for (int i = a; i < b; i++)\n#define rep(i, a, b) for (int i = a; i < b; i++)\n#define mod 1000000007\n#define inf (1LL << 60)\n#define all(x) (x).begin(), (x).end()\n#define prDouble(x) cout << fixed << setprecision(10) << x\n#define triplet pair<ll, pair<ll, ll>>\n#define goog(tno) cout << \"Case #\" << tno << \": \"\n#define fast_io \\\n ios_base::sync_with_stdio(false); \\\n cin.tie(NULL); \\\n cout.tie(NULL);\n#define read(x) \\\n int x; \\\n cin >> x\nusing namespace std;\n\nstruct WeightedDSU {\n int n, set_size, *parent, *value, *rank;\n vector<vector<int>> graph;\n\n WeightedDSU(int a) {\n n = a;\n set_size = a;\n parent = new int[n];\n value = new int[n];\n rank = new int[n];\n graph.resize(n);\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n rank[i] = 1;\n value[i] = 0;\n }\n }\n\n int find(int a) {\n if (parent[a] != a)\n return parent[a] = find(parent[a]);\n\n return parent[a];\n }\n\n void dfs(int a, int par, int val) {\n value[a] += val;\n\n for (int u : graph[a]) {\n if (u == par)\n continue;\n dfs(u, a, val);\n }\n }\n\n void merge(int a, int b, int wt) {\n int aroot = find(a);\n int broot = find(b);\n\n if (aroot != broot) {\n if (rank[aroot] >= rank[broot]) {\n int val = value[a] - value[b];\n val -= wt;\n dfs(broot, -1, val);\n parent[broot] = aroot;\n rank[aroot] += rank[broot];\n } else {\n int val = value[b] - value[a];\n val += wt;\n dfs(aroot, -1, val);\n parent[aroot] = broot;\n rank[broot] += rank[aroot];\n }\n graph[a].push_back(b);\n graph[b].push_back(a);\n }\n }\n int value1(int x, int y) {\n if (find(x) != find(y)) // Not connected components.\n return 1e9;\n return value[x] - value[y];\n }\n};\n\nint main() {\n fast_io int t = 1;\n // read(t);\n while (t--) {\n // Your code here\n read(n);\n read(q);\n WeightedDSU uf(n);\n\n while (q--) {\n int type;\n cin >> type;\n if (type == 0) {\n int a, b, c;\n cin >> a >> b >> c;\n // edge.push_back({c, {a, b}});\n uf.merge(a, b, c);\n } else {\n int a, b;\n cin >> a >> b;\n int x = uf.value1(a, b);\n if (x == 1e9)\n cout << \"?\" << \"\\n\";\n else\n cout << x << \"\\n\";\n }\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 9528, "score_of_the_acc": -1.1333, "final_rank": 17 }, { "submission_id": "aoj_DSL_1_B_10723796", "code_snippet": "/******************************************************************************\n * Potential-Difference Union-Find\n *\n * Problem statement\n * ---------------------------------------------------------------------------\n * You are given `n` variables (0-indexed) whose integer values are initially\n * unknown. You must process `q` online operations of two kinds:\n *\n * 0 x y z — Add the constraint value[x] − value[y] = z\n * (if x and y are already connected, the equation is guaranteed\n * to be consistent with the previous ones).\n *\n * 1 x y — If x and y belong to the same connected component, output\n * the implied difference value[x] − value[y] .\n * Otherwise output a single question-mark “?”.\n *\n * Input format\n * ---------------------------------------------------------------------------\n * n q\n * q lines, each in one of the formats above.\n *\n * Output\n * ---------------------------------------------------------------------------\n * For every type-1 query, print either the integer difference or “?”.\n *\n * Constraints\n * ---------------------------------------------------------------------------\n * 1 ≤ n, q ≤ 200 000\n * −10⁹ ≤ z ≤ 10⁹\n *\n * Solution outline\n * ---------------------------------------------------------------------------\n * Maintain a weighted Disjoint-Set Union (Union-Find) structure.\n * For each node we store:\n * • parent index\n * • `pot` = value[node] − value[parent]\n *\n * Taking the transitive sum of `pot` fields along the path to the root yields\n * the potential (value) difference with respect to that root.\n * Merging two components while inserting a new equation lets us fix the\n * relative potential between their roots and keeps future queries consistent.\n *\n * The implementation below runs in O((n+q) α(n)) time and O(n) memory.\n ******************************************************************************/\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define F first\n#define S second\n\nstruct WeightedDSU {\n vector<pair<int, long long>> par; // (parent, pot = val - parent_val)\n vector<int> sz;\n\n WeightedDSU(int n = 0) { init(n); }\n\n void init(int n) {\n par.resize(n);\n sz.assign(n, 1);\n for (int i = 0; i < n; ++i)\n par[i] = {i, 0};\n }\n\n // Find root of x, compress path and return (root, potential wrt root)\n pair<int, long long> find(int x) {\n if (par[x].F == x)\n return par[x];\n auto [r, p] = find(par[x].F);\n long long newPot = p + par[x].S;\n return par[x] = {r, newPot};\n }\n\n // Enforce value[x] - value[y] = diff\n void unite(int x, int y, long long diff) {\n auto [rx, px] = find(x);\n auto [ry, py] = find(y);\n if (rx == ry)\n return; // already consistent\n\n // Make ry the larger set’s root\n if (sz[rx] > sz[ry]) {\n swap(rx, ry);\n swap(px, py);\n diff = -diff; // direction changed\n }\n\n // Attach rx under ry and set its pot so that equation holds:\n // value[x] = value[rx] + (px)\n // value[y] = value[ry] + (py)\n // We need: (value[x] - value[y]) == diff\n // → (value[rx] + px) - (value[ry] + py) = diff\n // → value[rx] - value[ry] = diff - (px - py)\n long long pot_rx_to_ry = diff - (px - py);\n par[rx] = {ry, pot_rx_to_ry};\n sz[ry] += sz[rx];\n }\n\n // Query value[x] - value[y]; must be in same component\n long long diff(int x, int y) { return find(x).S - find(y).S; }\n\n bool same(int x, int y) { return find(x).F == find(y).F; }\n};\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n, q;\n if (!(cin >> n >> q))\n return 0;\n\n WeightedDSU dsu(n);\n\n while (q--) {\n int type;\n cin >> type;\n if (type == 0) {\n int x, y;\n long long z;\n cin >> x >> y >> z; // enforce value[x] - value[y] = z\n dsu.unite(y, x, z);\n } else { // type == 1\n int x, y;\n cin >> x >> y;\n if (!dsu.same(x, y))\n cout << \"?\\n\";\n else\n cout << -dsu.diff(x, y) << '\\n';\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 5196, "score_of_the_acc": -0.3177, "final_rank": 5 }, { "submission_id": "aoj_DSL_1_B_10697877", "code_snippet": "/**\n * アルゴリズムイントロダクション章末問題 19-2「深さの決定」\n * (depth-determination problem)\n *\n * find_depth(v):vが属する木におけるvの深さを返す\n * graft(r,v):節点rを節点vの子にする。ただしrは木の根、vはrとは別の木の(根とは限らない)節点\n *\n */\n\n#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define all(x) (x).begin(), (x).end()\nusing ll = long long;\n#ifdef LOCAL\n#include <debug_print.hpp>\n#define debug(...) debug_print::multi_print(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define debug(...) (static_cast<void>(0))\n#endif\n\nclass Dsu {\n public:\n int n;\n vector<int> leader;\n vector<int> parent;\n vector<int> rank;\n // 親ノードとの差分\n vector<int> diff_weight;\n\n Dsu() {}\n Dsu(int n_) : n(n_) {\n leader.resize(n);\n parent.resize(n);\n rank.resize(n);\n diff_weight.resize(n);\n rep(i, n) {\n leader[i] = i;\n parent[i] = i;\n rank[i] = 0;\n diff_weight[i] = 0;\n }\n }\n int get_leader(int x) {\n if (parent[x] == x) return x;\n int root = get_leader(parent[x]);\n diff_weight[x] += diff_weight[parent[x]];\n return parent[x] = root;\n }\n\n // weight(y) - weight(x) = wとなるようにマージする\n void unite(int x, int y, int w) {\n w = w + get_weight(x) - get_weight(y);\n\n int lx = get_leader(x);\n int ly = get_leader(y);\n assert(lx != ly);\n if (rank[lx] == rank[ly]) {\n parent[ly] = lx;\n rank[lx]++;\n diff_weight[ly] = w;\n } else if (rank[lx] > rank[ly]) {\n parent[ly] = lx;\n diff_weight[ly] = w;\n } else {\n parent[lx] = ly;\n diff_weight[lx] = -w;\n }\n }\n\n int get_weight(int x) {\n // マージ後の不整合を経路圧縮しながら解消\n get_leader(x);\n return diff_weight[x];\n }\n\n bool is_same(int x, int y) { return get_leader(x) == get_leader(y); }\n};\n\nvoid test_depth_determination_problem() {\n Dsu dsu(10);\n\n vector<tuple<int, int, int>> query;\n query = {{2, 0, 1}, {1, 0, -1}, {1, 1, -1}, {2, 3, 2},\n {2, 2, 0}, {1, 2, -1}, {1, 3, -1}};\n vector<int> expected = {1, 0, 2, 3};\n\n vector<int> actual;\n rep(qi, query.size()) {\n auto [com, v1, v2] = query[qi];\n if (com == 1) {\n dsu.get_leader(v1);\n actual.push_back(dsu.get_weight(v1));\n } else {\n dsu.unite(v2, v1, 1);\n }\n rep(i, 4) {\n //\n debug(i, dsu.get_weight(i));\n }\n }\n debug(actual);\n assert(expected == actual);\n}\n\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_1_B&lang=ja\nvoid solve_weighted_union_find() {\n int n, q;\n cin >> n >> q;\n Dsu dsu(n);\n\n while (q--) {\n int com;\n cin >> com;\n if (com == 0) {\n int x, y, z;\n cin >> x >> y >> z;\n if (!dsu.is_same(x, y)) {\n dsu.unite(x, y, z);\n }\n } else {\n int x, y;\n cin >> x >> y;\n if (dsu.is_same(x, y)) {\n cout << dsu.get_weight(y) - dsu.get_weight(x) << endl;\n } else {\n cout << \"?\" << endl;\n }\n }\n }\n}\nint main() {\n // test_depth_determination_problem();\n solve_weighted_union_find();\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 4676, "score_of_the_acc": -1.0278, "final_rank": 12 } ]
aoj_DSL_1_A_cpp
Disjoint Set Write a program which manipulates a disjoint set S = {S 1 , S 2 , . . . , S k } . First of all, the program should read an integer n , then make a disjoint set where each element consists of 0, 1, ... n−1 respectively. Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of queries for different operations: unite(x, y) : unites sets that contain x and y , say S x and S y , into a new set. same(x, y) : determine whether x and y are in the same set. Input n q com 1 x 1 y 1 com 2 x 2 y 2 ... com q x q y q In the first line, n and q are given. Then, q queries are given where com represents the type of queries. '0' denotes unite and '1' denotes same operation. Output For each same operation, print 1 if x and y are in the same set, otherwise 0 , in a line. Constraints 1 ≤ n ≤ 10000 1 ≤ q ≤ 100000 x ≠ y Sample Input 5 12 0 1 4 0 2 3 1 1 2 1 3 4 1 1 4 1 3 2 0 1 3 1 2 4 1 3 0 0 0 4 1 0 2 1 3 0 Sample Output 0 0 1 1 1 0 1 1
[ { "submission_id": "aoj_DSL_1_A_11063815", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cstdint>\n\nnamespace uft { // mst.cc で merge 関数を使用するために、名前空間を定義する\n\nuint16_t root(uint16_t idx, std::vector<uint16_t>& parent) {\n if (parent[idx] == idx) { // 親が自分自身の場合\n return idx;\n }\n return (parent[idx] = root(parent[idx], parent)); // 親が自分自身でない場合は、再帰的に root を更新する (経路を圧縮する)\n}\n\nbool same_root(uint16_t i_1, uint16_t i_2, std::vector<uint16_t>& parent) { // i_1 と i_2 が同じグラフに所属するかどうか\n return root(i_1, parent) == root(i_2, parent);\n}\n\nvoid merge(uint16_t i_1, uint16_t i_2, std::vector<uint16_t>& parent) {\n parent[root(i_1, parent)] = root(i_2, parent); // i_1 のルートノードを i_2 のルートノードにする\n}\n}\n\n#ifndef NO_MAIN\n\nuint16_t n; // 要素の数\nuint q; // クエリの数\n\nint main() {\n using namespace uft;\n\n std::cin >> n >> q;\n\n std::vector<uint16_t> parent;\n\n parent.resize(n+1); // n 個の要素のためのメモリを確保する\n\n parent[0] = 0; // 番兵ノード\n\n // n 個のグラフを作成する (すべての要素は、親が自分自身、つまり root であると初期化される)\n for (uint16_t i = 1; i < n+1; ++i) {\n parent[i] = i;\n }\n\n std::vector<uint16_t> qry; // クエリ設定を保存するベクタ\n qry.resize(3); // 要素を 3 つ確保しておく\n\n // 各クエリ順に、グラフの統合、親ノードの同一性の判定を行う\n for (uint i = 0; i < q; ++i) {\n std::cin >> qry[0] >> qry[1] >> qry[2];\n\n if (qry[0] == 0) { // unite クエリの場合\n merge(qry[1], qry[2], parent); // マージする\n } else { // same クエリの場合\n if (same_root(qry[1], qry[2], parent)) {\n std::cout << 1 << \"\\n\";\n } else {\n std::cout << 0 << \"\\n\";\n }\n }\n }\n}\n#endif", "accuracy": 1, "time_ms": 70, "memory_kb": 3584, "score_of_the_acc": -0.732, "final_rank": 18 }, { "submission_id": "aoj_DSL_1_A_11062845", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nvector<int> parent, rankv;\n\nint root(int x) {\n if (parent[x] == x) return x;\n return parent[x] = root(parent[x]);\n}\n\nbool same(int x, int y) {\n return root(x) == root(y);\n}\n\nvoid unite(int a, int b) {\n a = root(a);\n b = root(b);\n if (a == b) return;\n if (rankv[a] < rankv[b]) swap(a, b); //ランクが小さい方を常にbにする\n parent[b] = a;\n if (rankv[a] == rankv[b]) ++rankv[a];\n}\n\nint main() {\n int n, q;\n cin >> n >> q;\n parent.assign(n, 0);\n rankv.assign(n, 0);\n for (int i = 0; i < n; ++i) parent[i] = i;\n\n for (int i = 0; i < q; ++i) {\n int k, x, y;\n cin >> k >> x >> y;\n if (k == 0) {\n unite(x, y);\n } else {\n cout << (same(x, y) ? 1 : 0) << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3524, "score_of_the_acc": -0.6251, "final_rank": 11 }, { "submission_id": "aoj_DSL_1_A_11062814", "code_snippet": "#include <iostream>\nusing namespace std;\n\nint P[10010];\nvoid init(int N){\n for(int i=0; i<N; ++i) P[i] = i;\n}\nint root(int a) {\n if (P[a] == a) return a;\n return (P[a] = root(P[a]));\n}\nbool same(int a, int b) {\n return root(a) == root(b);\n}\nvoid unite(int a, int b) {\n P[root(a)] = root(b);\n}\n\nint main() {\n int n;\n cin >> n;\n init(n);\n\n int q;\n cin >> q;\n for(int i=0; i<q; ++i) {\n int com, x, y;\n cin >> com >> x >> y;\n if (com==0) unite(x, y);\n else cout << same(x, y) << endl;\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3456, "score_of_the_acc": -0.5985, "final_rank": 6 }, { "submission_id": "aoj_DSL_1_A_11062799", "code_snippet": "#include <iostream>\n#include <cassert>\n#include <vector>\nusing namespace std;\n\nclass unionfind{\npublic:\n unionfind(int n): n_(n) {\n parent_.resize(n);\n size_.resize(n);\n for(int i=0; i<n; i++){\n parent_[i] = i;\n size_[i] = 1;\n }\n }\n int root(int i){\n if(parent_[i] == i) return i;\n parent_[i] = root(parent_[i]);\n return parent_[i];\n }\n void unite(int i, int j){\n int p = root(i);\n int q = root(j);\n if(p==q) return;\n if(size_[p]>size_[q]){\n parent_[q] = p;\n size_[p] += size_[q];\n }else{\n parent_[p] = q;\n size_[q] += size_[p];\n }\n }\n bool is_same(int i, int j){\n return root(i) == root(j);\n }\nprivate:\n int n_;\n vector<int> parent_;\n vector<int> size_;\n};\n\nint main(){\n int n,q;\n cin >> n >> q;\n\n unionfind uf(n+5);\n int com,x,y;\n for(int i=0; i<q; i++){\n cin >> com >> x >> y;\n if(com == 0){\n uf.unite(x,y);\n }else{\n cout << (int)uf.is_same(x,y) << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3500, "score_of_the_acc": -0.6157, "final_rank": 8 }, { "submission_id": "aoj_DSL_1_A_11062633", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <cctype>\n#include <cstdarg>\n#include <cstddef>\n#include <cstdint>\n#include <cstdbool>\n#include <cstdint>\nusing namespace std;\n\nint P[10010]; // 0 から 10000 までの頂点を取り扱い可能 \nvoid init(int N) { // 初期化 はじめは全ての頂点はバラバラ \n for (int i=0; i<=N; ++i) P[i] = i; \n} \nint root(int a) { // a の root(代表元) を求める \n if (P[a] == a) return a; // a は root \n return (P[a] = root(P[a])); // a の親の root を求め,a の親とする \n} \nbool is_same_set(int a, int b) { // a と b が同じグループに属するか? \n return root(a) == root(b); \n} \nvoid unite(int a, int b) { // a と b を同一グループにまとめる \n P[root(a)] = root(b); \n}\n\nint main() {\n int n, q;\n cin >> n >> q;\n init(n);\n for (int i = 0; i < q; i++) {\n int com, x, y;\n cin >> com >> x >> y;\n if (com == 0) {\n unite(x, y);\n } else {\n cout << (is_same_set(x, y) ? 1 : 0) << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3476, "score_of_the_acc": -0.6897, "final_rank": 14 }, { "submission_id": "aoj_DSL_1_A_11060588", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cstdint>\n\nuint16_t n; // 要素の数\nuint q; // クエリの数\n\nnamespace uft { // mst.cc で merge 関数を使用するために、名前空間を定義する\nstd::vector<uint16_t> parent; // 親のノードの値を積んだベクタ\n\nuint16_t root(uint16_t idx) {\n if (parent[idx] == idx) { // 親が自分自身の場合\n return idx;\n }\n return (parent[idx] = root(parent[idx])); // 親が自分自身でない場合は、再帰的に root を更新する (経路を圧縮する)\n}\n\nbool same_root(uint16_t i_1, uint16_t i_2) { // i_1 と i_2 が同じグラフに所属するかどうか\n return root(i_1) == root(i_2);\n}\n\nvoid merge(uint16_t i_1, uint16_t i_2) {\n parent[root(i_1)] = root(i_2); // i_1 のルートノードを i_2 のルートノードにする\n}\n}\n\n#ifndef NO_MAIN\nint main() {\n using namespace uft;\n\n std::cin >> n >> q;\n\n parent.resize(n+1); // n 個の要素のためのメモリを確保する\n\n parent[0] = 0; // 番兵ノード\n\n // n 個のグラフを作成する (すべての要素は、親が自分自身、つまり root であると初期化される)\n for (uint16_t i = 1; i < n+1; ++i) {\n parent[i] = i;\n }\n\n std::vector<uint16_t> qry; // クエリ設定を保存するベクタ\n qry.resize(3); // 要素を 3 つ確保しておく\n\n // 各クエリ順に、グラフの統合、親ノードの同一性の判定を行う\n for (uint i = 0; i < q; ++i) {\n std::cin >> qry[0] >> qry[1] >> qry[2];\n\n if (qry[0] == 0) { // unite クエリの場合\n merge(qry[1], qry[2]); // マージする\n } else { // same クエリの場合\n if (same_root(qry[1], qry[2])) {\n std::cout << 1 << \"\\n\"; \n } else {\n std::cout << 0 << \"\\n\";\n }\n }\n }\n}\n#endif", "accuracy": 1, "time_ms": 60, "memory_kb": 3460, "score_of_the_acc": -0.6001, "final_rank": 7 }, { "submission_id": "aoj_DSL_1_A_11060586", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cstdint>\n\nuint16_t n; // 要素の数\nuint q; // クエリの数\n\nnamespace uft { // mst.cc で merge 関数を使用するために、名前空間を定義する\nstd::vector<uint16_t> parent; // 親のノードの値を積んだベクタ\n\nuint16_t root(uint16_t idx) {\n if (parent[idx] == idx) { // 親が自分自身の場合\n return idx;\n }\n return (parent[idx] = root(parent[idx])); // 親が自分自身でない場合は、再帰的に root を更新する (経路を圧縮する)\n}\n\nbool same_root(uint16_t i_1, uint16_t i_2) { // i_1 と i_2 が同じグラフに所属するかどうか\n return root(i_1) == root(i_2);\n}\n\nvoid merge(uint16_t i_1, uint16_t i_2) {\n parent[root(i_1)] = root(i_2); // i_1 のルートノードを i_2 のルートノードにする\n}\n}\nint main() {\n using namespace uft;\n\n std::cin >> n >> q;\n\n parent.resize(n+1); // n 個の要素のためのメモリを確保する\n\n parent[0] = 0; // 番兵ノード\n\n // n 個のグラフを作成する (すべての要素は、親が自分自身、つまり root であると初期化される)\n for (uint16_t i = 1; i < n+1; ++i) {\n parent[i] = i;\n }\n\n std::vector<uint16_t> qry; // クエリ設定を保存するベクタ\n qry.resize(3); // 要素を 3 つ確保しておく\n\n // 各クエリ順に、グラフの統合、親ノードの同一性の判定を行う\n for (uint i = 0; i < q; ++i) {\n std::cin >> qry[0] >> qry[1] >> qry[2];\n\n if (qry[0] == 0) { // unite クエリの場合\n merge(qry[1], qry[2]); // マージする\n } else { // same クエリの場合\n if (same_root(qry[1], qry[2])) {\n std::cout << 1 << \"\\n\"; \n } else {\n std::cout << 0 << \"\\n\";\n }\n }\n }\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3460, "score_of_the_acc": -0.6834, "final_rank": 13 }, { "submission_id": "aoj_DSL_1_A_11060574", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cstdint>\n\nuint16_t n; // 要素の数\nuint q; // クエリの数\n\nstd::vector<uint16_t> parent; // 親のノードの値を積んだベクタ\n\nuint16_t root(uint16_t idx) {\n if (parent[idx] == idx) { // 親が自分自身の場合\n return idx;\n }\n return (parent[idx] = root(parent[idx])); // 親が自分自身でない場合は、再帰的に root を更新する (経路を圧縮する)\n}\n\nbool same_root(uint16_t i_1, uint16_t i_2) { // i_1 と i_2 が同じグラフに所属するかどうか\n return root(i_1) == root(i_2);\n}\n\nvoid merge(uint16_t i_1, uint16_t i_2) {\n parent[root(i_1)] = root(i_2); // i_1 のルートノードを i_2 のルートノードにする\n}\n\nint main() {\n std::cin >> n >> q;\n\n parent.resize(n+1); // n 個の要素のためのメモリを確保する\n\n parent[0] = 0; // 番兵ノード\n\n // n 個のグラフを作成する (すべての要素は、親が自分自身、つまり root であると初期化される)\n for (uint16_t i = 1; i < n+1; ++i) {\n parent[i] = i;\n }\n\n std::vector<uint16_t> qry; // クエリ設定を保存するベクタ\n qry.resize(3); // 要素を 3 つ確保しておく\n\n // 各クエリ順に、グラフの統合、親ノードの同一性の判定を行う\n for (uint i = 0; i < q; ++i) {\n std::cin >> qry[0] >> qry[1] >> qry[2];\n\n if (qry[0] == 0) { // unite クエリの場合\n merge(qry[1], qry[2]); // マージする\n } else { // same クエリの場合\n if (same_root(qry[1], qry[2])) {\n std::cout << 1 << \"\\n\"; \n } else {\n std::cout << 0 << \"\\n\";\n }\n }\n }\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3504, "score_of_the_acc": -0.7006, "final_rank": 16 }, { "submission_id": "aoj_DSL_1_A_11058553", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define v vector\nusing vi = v<int>;\nusing vl = v<ll>;\nusing vs = v<string>;\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)\n#define rRep(i, n) for (ll i = (ll)(n); i >= 0; i--)\n#define all(vec) vec.begin(), vec.end()\n#define rAll(vec) vec.rbegin(), vec.rend()\n// 昇順(小さい→大きい)\n#define vSort(vec) sort(all(vec))\n#define rSort(vec) sort(rAll(vec))\n// sortしてから使う\n#define uni(vec) vec.erase(unique(all(vec)), vec.end());\n\n// ここから追加\nconst int intMax = INT_MAX;\nconst ll llMax = LONG_LONG_MAX;\nconst ll INF = 1e18;\ntemplate<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }\ntemplate <typename T> T gcd(T a, T b) {if (b == 0) return a; else return gcd(b, a % b);}\ntemplate <typename T> inline T lcm(T a, T b) { return (a / gcd(a, b) * b); }\n#define coutFloat(N) cout << fixed << setprecision(N)\n\nstruct UnionFind {\n vector<int> par, rank, siz;\n\n // 構造体の初期化\n UnionFind(int n) : par(n,-1), rank(n,0), siz(n,1) { }\n\n // 根を求める\n int root(int x) {\n if (par[x]==-1) return x; // x が根の場合は x を返す\n else return par[x] = root(par[x]); // 経路圧縮\n }\n\n // x と y が同じグループに属するか (= 根が一致するか)\n bool issame(int x, int y) {\n return root(x)==root(y);\n }\n\n // x を含むグループと y を含むグループを併合する\n bool unite(int x, int y) {\n int rx = root(x), ry = root(y); // x 側と y 側の根を取得する\n if (rx==ry) return false; // すでに同じグループのときは何もしない\n // union by rank\n if (rank[rx]<rank[ry]) swap(rx, ry); // ry 側の rank が小さくなるようにする\n par[ry] = rx; // ry を rx の子とする\n if (rank[rx]==rank[ry]) rank[rx]++; // rx 側の rank を調整する\n siz[rx] += siz[ry]; // rx 側の siz を調整する\n return true;\n }\n\n // x を含む根付き木のサイズを求める\n int size(int x) {\n return siz[root(x)];\n }\n};\n\nint main() {\n int N, Q; cin >> N >> Q;\n\n UnionFind uf = UnionFind(N);\n rep(_, Q) {\n int cmd, x, y; cin >> cmd >> x >> y;\n if (cmd == 0) {\n // unite\n uf.unite(x, y);\n } else {\n cout << (int)(uf.issame(x, y)) << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3560, "score_of_the_acc": -0.6392, "final_rank": 12 }, { "submission_id": "aoj_DSL_1_A_11051859", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct UnionFind {\n vector<int> par, rank, siz;\n UnionFind(int N) : par(N,-1), rank(N,1), siz(N,1) {}\n\n int root(int x) {\n if (par[x] == -1) return x;\n else return par[x] = root(par[x]);\n }\n\n void unite(int x, int y) {\n int rx = root(x), ry = root(y);\n if (rx == ry) return;\n if (rank[rx] < rank[ry]) swap(rx, ry);\n\n par[ry] = rx;\n siz[rx] += siz[ry];\n if (rank[rx] == rank[ry]) rank[rx]++;\n }\n};\n\nint main() {\n int N, Q;\n cin >> N >> Q;\n\n UnionFind uf(N);\n for (int qi = 0; qi < Q; qi++) {\n int type; cin >> type;\n if (type == 0) {\n int x, y;\n cin >> x >> y;\n uf.unite(x, y);\n } else if (type == 1) {\n int x, y;\n cin >> x >> y;\n if (uf.root(x) == uf.root(y)) cout << 1 << endl;\n else cout << 0 << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3512, "score_of_the_acc": -0.6204, "final_rank": 10 }, { "submission_id": "aoj_DSL_1_A_11031450", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e6;\nint n, q;\nint par[N];\nint area[N];\n\nint getpar(int u) {\n if (par[u] == u)\n return u;\n\n return par[u] = getpar(par[u]);\n}\n\nvoid merge(int u, int v) {\n int pu = getpar(u), pv = getpar(v);\n\n if (pu == pv)\n return;\n\n if (area[pu] < area[pv])\n swap(pu, pv); // pu > pv\n\n area[pu] += area[pv];\n par[pv] = pu;\n}\n\nbool connected(int u, int v) { return getpar(u) == getpar(v); }\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n cin >> n >> q;\n\n fill(area, area + n, 1);\n iota(par, par + n, 0);\n\n while (q--) {\n int a, b;\n char t;\n cin >> t >> a >> b;\n\n if (t == '0') {\n merge(a, b);\n } else {\n cout << connected(a, b) << '\\n';\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5544, "score_of_the_acc": -1, "final_rank": 19 }, { "submission_id": "aoj_DSL_1_A_11021333", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nstruct union_find{\n\tvector<int>d;\n\tunion_find(int n):d(n,-1){}\n\tint root(int u){return d[u]<0?u:d[u]=root(d[u]);}\n\tbool unite(int u,int v){\n\t\tu=root(u),v=root(v);\n\t\tif(u==v)return 0;\n\t\tif(d[u]>d[v])swap(u,v);\n\t\td[u]+=d[v];\n\t\td[v]=u;\n\t\treturn 1;\n\t}\n};\nint main(){\n\tcin.tie(0)->sync_with_stdio(0);\n\tint n,q;\n\tcin>>n>>q;\n\tunion_find uf(n);\n\twhile(q--){\n\t\tint op,u,v;\n\t\tcin>>op>>u>>v;\n\t\tif(op==0){\n\t\t\tuf.unite(u,v);\n\t\t}\n\t\tif(op==1){\n\t\t\tcout<<(uf.root(u)==uf.root(v))<<'\\n';\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3480, "score_of_the_acc": -0.1912, "final_rank": 2 }, { "submission_id": "aoj_DSL_1_A_11009192", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\n#define revrep(i,n) for(int i=(int)(n)-1;i>=0;--i)\nusing namespace std;\nusing ll = long long;\n\nclass UnionFind {\n\nprivate:\n vector<int> parent;\n vector<int> sz;\n\npublic:\n UnionFind(int n):parent(n),sz(n,1){\n iota(parent.begin(),parent.end(),0);\n }\n \n int find(int x){\n if(parent[x]==x){ return x;}\n return find(parent[x]);\n }\n \n bool same(int x,int y){\n return (find(x) == find(y));\n }\n \n bool unite(int x,int y){\n int root_x = find(x);\n int root_y = find(y);\n if(root_x!=root_y){\n if(root_x<root_y) swap(root_x,root_y);\n parent[root_y] = root_x;\n sz[root_x] += sz[root_y];\n return true;\n }\n return false;\n }\n \n int size(int x){ return sz[find(x)];}\n};\n\n\nint main(void){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int n,Q;cin>>n>>Q;\n UnionFind S(n);\n \n while(Q--){\n int com;cin>>com;\n if(com==0){\n int x,y;cin>>x>>y;\n S.unite(x,y);\n }else{\n int x,y;cin>>x>>y;\n cout << S.same(x,y) << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 3500, "score_of_the_acc": -1.1991, "final_rank": 20 }, { "submission_id": "aoj_DSL_1_A_10993016", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* UnionFind\n root(x): xの根。O(α(n))\n size(x): x を含む集合の要素数。\n same(x, y): x と y が同じ集合にいるか。O(α(n))\n merge(x, y): x と y を同じ集合にする。 O(α(n))\n*/\nstruct UF{\n vi par;\n UF() {}\n UF(int n): par(n,-1){}\n int root(int x){\n if(par[x] < 0) return x;\n return par[x] = root(par[x]); //経路圧縮\n }\n int size(int x){\n return -par[root(x)];\n }\n bool same(int x, int y){\n return root(x) == root(y);\n }\n bool merge(int x, int y){\n int rx = root(x), ry = root(y);\n if(rx == ry) return false;\n if(-par[rx]<-par[ry]) swap(rx,ry);\n par[rx] += par[ry];\n par[ry] = rx;\n return true;\n }\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n \tcin.tie(0);\n\tint n,q; cin >> n >> q;\n UF uf(n);\n rep(i,q){\n int type; cin >> type;\n if(type==0){\n int s,t; cin >> s >> t;\n uf.merge(s,t);\n } else {\n int s,t; cin >> s >> t;\n cout << (uf.same(s,t)? 1 : 0) << endl;\n }\n }\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3480, "score_of_the_acc": -0.3579, "final_rank": 4 }, { "submission_id": "aoj_DSL_1_A_10974240", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, a, n) for (int i = a; i < n; ++i)\n#define rrep(i, a, n) for (int i = n - 1; i >= a; --i)\nusing ll = long long;\nusing ld = long double;\nusing pl = pair<ll, ll>;\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing vp = vector<pl>;\nusing vvp = vector<vp>;\nusing vb = vector<bool>;\nusing vvb = vector<vb>;\nusing vs = vector<string>;\nusing vc = vector<char>;\nusing vvc = vector<vc>;\nconst int mod = 1000000007;\nconst ll hashh = 2147483647;\n\n#ifndef ATCODER_DSU_HPP\n#define ATCODER_DSU_HPP 1\n\n#include <algorithm>\n#include <cassert>\n#include <vector>\n\nnamespace atcoder\n{\n\n // Implement (union by size) + (path compression)\n // Reference:\n // Zvi Galil and Giuseppe F. Italiano,\n // Data structures and algorithms for disjoint set union problems\n struct dsu\n {\n public:\n dsu() : _n(0) {}\n explicit dsu(int n) : _n(n), parent_or_size(n, -1) {}\n\n int merge(int a, int b)\n {\n assert(0 <= a && a < _n);\n assert(0 <= b && b < _n);\n int x = leader(a), y = leader(b);\n if (x == y)\n return x;\n if (-parent_or_size[x] < -parent_or_size[y])\n std::swap(x, y);\n parent_or_size[x] += parent_or_size[y];\n parent_or_size[y] = x;\n return x;\n }\n\n bool same(int a, int b)\n {\n assert(0 <= a && a < _n);\n assert(0 <= b && b < _n);\n return leader(a) == leader(b);\n }\n\n int leader(int a)\n {\n assert(0 <= a && a < _n);\n return _leader(a);\n }\n\n int size(int a)\n {\n assert(0 <= a && a < _n);\n return -parent_or_size[leader(a)];\n }\n\n std::vector<std::vector<int>> groups()\n {\n std::vector<int> leader_buf(_n), group_size(_n);\n for (int i = 0; i < _n; i++)\n {\n leader_buf[i] = leader(i);\n group_size[leader_buf[i]]++;\n }\n std::vector<std::vector<int>> result(_n);\n for (int i = 0; i < _n; i++)\n {\n result[i].reserve(group_size[i]);\n }\n for (int i = 0; i < _n; i++)\n {\n result[leader_buf[i]].push_back(i);\n }\n result.erase(\n std::remove_if(result.begin(), result.end(),\n [&](const std::vector<int> &v)\n { return v.empty(); }),\n result.end());\n return result;\n }\n\n private:\n int _n;\n // root node: -1 * component size\n // otherwise: parent\n std::vector<int> parent_or_size;\n\n int _leader(int a)\n {\n if (parent_or_size[a] < 0)\n return a;\n return parent_or_size[a] = _leader(parent_or_size[a]);\n }\n };\n\n} // namespace atcoder\n\n#endif // ATCODER_DSU_HPP\n\nusing namespace atcoder;\n\n// main\nint main()\n{\n ll n, q;\n cin >> n >> q;\n dsu d(n);\n rep(i, 0, q)\n {\n ll c, x, y;\n cin >> c >> x >> y;\n if (c == 0)\n {\n d.merge(x, y);\n }\n else\n {\n if (d.same(x, y))\n {\n cout << 1 << endl;\n }\n else\n {\n cout << 0 << endl;\n }\n }\n }\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3480, "score_of_the_acc": -0.6912, "final_rank": 15 }, { "submission_id": "aoj_DSL_1_A_10959968", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n\n\n\n\n\nclass UnionFind {\n public:\n int par[100009];\n int siz[100009];\n\n void init(int N) {\n for(int i = 0; i < N; i++) par[i] = -1;\n for(int i = 0; i < N; i++) siz[i] = 1;\n }\n\n int root(int v) {\n if(par[v] == -1) return v;\n return root(par[v]);\n }\n\n void unite(int v, int u) {\n int RootV = root(v), RootU = root(u);\n\n if(root(u) == root(v)) return;\n\n if(siz[RootV] > siz[RootU]) {\n par[RootU] = RootV;\n siz[RootV] += siz[RootU];\n } else {\n par[RootV] = RootU;\n siz[RootU] += siz[RootV];\n }\n }\n\n bool same(int v, int u) {\n return root(v) == root(u);\n }\n};\n\n\n\n\n\n\n\nint main() {\n int n, q; cin >> n >> q;\n UnionFind UF;\n UF.init(n);\n\n for(int i = 0; i < q; i++) {\n int cmd; cin >> cmd;\n int x, y; cin >> x >> y;\n if(cmd == 0) {\n UF.unite(x, y);\n } else {\n if(UF.same(x, y)) cout << 1 << endl;\n else cout << 0 << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3452, "score_of_the_acc": -0.5969, "final_rank": 5 }, { "submission_id": "aoj_DSL_1_A_10954501", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n\n\n\n\n\nclass UnionFind {\n public:\n int par[10009];\n int siz[10009];\n\n void init(int n) {\n for(int i = 0; i < n; i++) par[i] = -1;\n for(int i = 0; i < n; i++) siz[i] = 1;\n }\n\n int root(int x) {\n if(par[x] == -1) return x;\n return root(par[x]);\n }\n\n void unite(int v, int u) {\n int rootV = root(v);\n int rootU = root(u);\n\n if(rootV == rootU) return;\n if(siz[rootV] < siz[rootU]) {\n par[rootV] = rootU;\n siz[rootU] += siz[rootV];\n } else {\n par[rootU] = rootV;\n siz[rootV] += siz[rootU];\n }\n }\n\n bool same(int v, int u) {\n return root(v) == root(u);\n }\n};\n\n\n\n\n\n\n\nint main() {\n int n, q; cin >> n >> q;\n UnionFind UF;\n UF.init(n);\n\n for(int i = 0; i < q; i++) {\n int x, u, v; cin >> x >> u >> v;\n if(x == 0) UF.unite(u, v);\n else {\n if(UF.same(u, v)) cout << 1 << endl;\n else cout << 0 << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3512, "score_of_the_acc": -0.7038, "final_rank": 17 }, { "submission_id": "aoj_DSL_1_A_10954150", "code_snippet": "#include <cstdio>\n#include <vector>\nusing namespace std;\nclass DisjointSet{\n public:\n vector<int> p,rank;\n DisjointSet(){}//构造函数,这样可以构建无参数类,下面也是,构造函数名字必须和类名一样\n DisjointSet(int size){\n p.resize(size,0);\n rank.resize(size,0);\n for(int i=0;i<size;i++){\n makeset(i);\n }\n }\n void makeset(int i){\n p[i]=i;\n rank[i]=0;//初始化所有元素指向自己\n }\n bool same(int a,int b){\n return findset(a)==findset(b);\n }\n void unite(int a,int b){\n link(findset(a),findset(b));\n }\n void link(int a,int b){\n if(rank[a]>rank[b]){\n p[b]=a;\n }else{\n p[a]=b;\n if(rank[a]==rank[b]){\n rank[b]++;\n }\n }\n }\n int findset(int a){\n if(a!=p[a]){\n p[a]=findset(p[a]);//实现路径压缩\n }\n return p[a];\n }\n};\nint main(){\n int n,q;\n scanf(\"%d %d\",&n,&q);\n DisjointSet ds=DisjointSet(n);\n for(int i=0;i<q;i++){\n int c,x,y;\n scanf(\"%d %d %d\",&c,&x,&y);\n if(c==0){\n ds.unite(x,y);\n }else if(c==1){\n if(ds.same(x,y)){\n printf(\"1\\n\");\n }else printf(\"0\\n\");\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2992, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DSL_1_A_10914507", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, s, e) for (int i = (int)(s); i < (int)(e); ++i)\n\nstruct UnionFind {\n\tvector<int> par;\n\tint group;\n\tUnionFind(int N) : par(N, -1), group(N) {}\n\t\n\tint root(int x) {\n\t\tif (par[x] < 0) return x;\n\t\telse return par[x] = root(par[x]);\n\t}\n\t\n\tbool merge(int x, int y) {\n\t\tif ((x = root(x)) == (y = root(y))) return false;\n\t\tif (par[x] > par[y]) swap(x, y);\n\t\tpar[x] += par[y];\n\t\tpar[y] = x;\n\t\t--group;\n\t\treturn true;\n\t}\n\t\n\tbool same(int x, int y) {\n\t\treturn root(x) == root(y);\n\t}\n\t\n\tint size(int x) {\n\t\treturn -par[root(x)];\n\t}\n};\n\nint main() {\n\tcin.tie(nullptr);\n\tios_base::sync_with_stdio(false);\n\t\n\tint N, Q;\n\tcin >> N >> Q;\n\t\n\tUnionFind uf(N);\n\trep(query, 0, Q) {\n\t\tint t, x, y;\n\t\tcin >> t >> x >> y;\n\t\t\n\t\tif (t == 0) {\n\t\t\tuf.merge(x, y);\n\t\t} else {\n\t\t\tcout << (uf.same(x, y) ? 1 : 0) << '\\n';\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3480, "score_of_the_acc": -0.1912, "final_rank": 2 }, { "submission_id": "aoj_DSL_1_A_10901183", "code_snippet": "#include <iostream>\n#include <vector>\n\nclass disjointSets {\npublic:\n std::vector<int> p, rank;\n\n // default constructor\n disjointSets() {}\n\n // constructor with size\n disjointSets(int size) {\n p.resize(size, 0);\n rank.resize(size, 0);\n for (int i = 0; i < size; i++) makeSet(i);\n }\n\n bool isSame(int x, int y) {\n return findSet(x) == findSet(y);\n }\n\n void uniteSets(int x, int y) {\n link(findSet(x), findSet(y));\n }\n\nprivate:\n void makeSet(int x) {\n p[x] = x;\n rank[x] = 0;\n }\n\n void link(int x, int y) {\n if (rank[x] > rank[y]) {\n p[y] = x;\n } else {\n p[x] = y;\n if (rank[x] == rank[y]) rank[y]++;\n }\n }\n\n int findSet(int x) {\n if (x != p[x]) {\n p[x] = findSet(p[x]); // path compression\n }\n return p[x];\n }\n};\n\nint main() {\n int n, q;\n std::cin >> n >> q;\n\n disjointSets ds(n);\n\n int com, x, y;\n for (int i = 0; i < q; i++) {\n std::cin >> com >> x >> y;\n if (com == 0) {\n ds.uniteSets(x, y); // unite\n } else if (com == 1) { // same\n if (ds.isSame(x, y))\n std::cout << 1 << std::endl;\n else\n std::cout << 0 << std::endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3504, "score_of_the_acc": -0.6173, "final_rank": 9 } ]
aoj_DSL_2_A_cpp
Range Minimum Query (RMQ) Write a program which manipulates a sequence A = { a 0 , a 1 , . . . , a n-1 } with the following operations: find(s, t) : report the minimum element in a s , a s+1 , . . . ,a t . update(i, x) : change a i to x . Note that the initial values of a i ( i = 0, 1, . . . , n−1 ) are 2 31 -1. Input n q com 0 x 0 y 0 com 1 x 1 y 1 ... com q−1 x q−1 y q−1 In the first line, n (the number of elements in A ) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(x i , y i ) and '1' denotes find(x i , y i ) . Output For each find operation, print the minimum element. Constraints 1 ≤ n ≤ 100000 1 ≤ q ≤ 100000 If com i is 0, then 0 ≤ x i < n , 0 ≤ y i < 2 31 -1 . If com i is 1, then 0 ≤ x i < n , 0 ≤ y i < n . Sample Input 1 3 5 0 0 1 0 1 2 0 2 3 1 0 2 1 1 2 Sample Output 1 1 2 Sample Input 2 1 3 1 0 0 0 0 5 1 0 0 Sample Output 2 2147483647 5
[ { "submission_id": "aoj_DSL_2_A_11066373", "code_snippet": "#ifndef ATCODER_INTERNAL_BITOP_HPP\n#define ATCODER_INTERNAL_BITOP_HPP 1\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\n#if __cplusplus >= 202002L\n#include <bit>\n#endif\n\nnamespace atcoder {\n\nnamespace internal {\n\n#if __cplusplus >= 202002L\n\nusing std::bit_ceil;\n\n#else\n\n// @return same with std::bit::bit_ceil\nunsigned int bit_ceil(unsigned int n) {\n unsigned int x = 1;\n while (x < (unsigned int)(n)) x *= 2;\n return x;\n}\n\n#endif\n\n// @param n `1 <= n`\n// @return same with std::bit::countr_zero\nint countr_zero(unsigned int n) {\n#ifdef _MSC_VER\n unsigned long index;\n _BitScanForward(&index, n);\n return index;\n#else\n return __builtin_ctz(n);\n#endif\n}\n\n// @param n `1 <= n`\n// @return same with std::bit::countr_zero\nconstexpr int countr_zero_constexpr(unsigned int n) {\n int x = 0;\n while (!(n & (1 << x))) x++;\n return x;\n}\n\n} // namespace internal\n\n} // namespace atcoder\n\n#endif // ATCODER_INTERNAL_BITOP_HPP\n\n#ifndef ATCODER_SEGTREE_HPP\n#define ATCODER_SEGTREE_HPP 1\n\n#include <algorithm>\n#include <cassert>\n#include <functional>\n#include <vector>\n\nnamespace atcoder {\n\n#if __cplusplus >= 201703L\n\ntemplate <class S, auto op, auto e>\nstruct segtree {\n static_assert(std::is_convertible_v<decltype(op), std::function<S(S, S)>>,\n \"op must work as S(S, S)\");\n static_assert(std::is_convertible_v<decltype(e), std::function<S()>>,\n \"e must work as S()\");\n\n#else\n\ntemplate <class S, S (*op)(S, S), S (*e)()>\nstruct segtree {\n\n#endif\n\n public:\n segtree() : segtree(0) {}\n explicit segtree(int n) : segtree(std::vector<S>(n, e())) {}\n explicit segtree(const std::vector<S>& v) : _n(int(v.size())) {\n size = (int)internal::bit_ceil((unsigned int)(_n));\n log = internal::countr_zero((unsigned int)size);\n d = std::vector<S>(2 * size, e());\n for (int i = 0; i < _n; i++) d[size + i] = v[i];\n for (int i = size - 1; i >= 1; i--) {\n update(i);\n }\n }\n\n void set(int p, S x) {\n assert(0 <= p && p < _n);\n p += size;\n d[p] = x;\n for (int i = 1; i <= log; i++) update(p >> i);\n }\n\n S get(int p) const {\n assert(0 <= p && p < _n);\n return d[p + size];\n }\n\n S prod(int l, int r) const {\n assert(0 <= l && l <= r && r <= _n);\n S sml = e(), smr = e();\n l += size;\n r += size;\n\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++]);\n if (r & 1) smr = op(d[--r], smr);\n l >>= 1;\n r >>= 1;\n }\n return op(sml, smr);\n }\n\n S all_prod() const { return d[1]; }\n\n template <bool (*f)(S)>\n int max_right(int l) const {\n return max_right(l, [](S x) { return f(x); });\n }\n template <class F>\n int max_right(int l, F f) const {\n assert(0 <= l && l <= _n);\n assert(f(e()));\n if (l == _n) return _n;\n l += size;\n S sm = e();\n do {\n while (l % 2 == 0) l >>= 1;\n if (!f(op(sm, d[l]))) {\n while (l < size) {\n l = (2 * l);\n if (f(op(sm, d[l]))) {\n sm = op(sm, d[l]);\n l++;\n }\n }\n return l - size;\n }\n sm = op(sm, d[l]);\n l++;\n } while ((l & -l) != l);\n return _n;\n }\n\n template <bool (*f)(S)>\n int min_left(int r) const {\n return min_left(r, [](S x) { return f(x); });\n }\n template <class F>\n int min_left(int r, F f) const {\n assert(0 <= r && r <= _n);\n assert(f(e()));\n if (r == 0) return 0;\n r += size;\n S sm = e();\n do {\n r--;\n while (r > 1 && (r % 2)) r >>= 1;\n if (!f(op(d[r], sm))) {\n while (r < size) {\n r = (2 * r + 1);\n if (f(op(d[r], sm))) {\n sm = op(d[r], sm);\n r--;\n }\n }\n return r + 1 - size;\n }\n sm = op(d[r], sm);\n } while ((r & -r) != r);\n return 0;\n }\n\n private:\n int _n, size, log;\n std::vector<S> d;\n\n void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }\n};\n\n} // namespace atcoder\n\n#endif // ATCODER_SEGTREE_HPP\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nusing namespace atcoder;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < n; ++i)\n\nusing S = int;\nint op(int a, int b) { return min(a, b); }\nint e() { return INT_MAX; }\nint main() {\n int n, q;\n cin >> n >> q;\n\n segtree<S, op, e> seg(n);\n rep(i, q) {\n int com, x, y;\n cin >> com >> x >> y;\n if (com == 0) {\n seg.set(x, y);\n } else {\n int ans = seg.prod(x, y + 1);\n cout << ans << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4396, "score_of_the_acc": -0.8194, "final_rank": 13 }, { "submission_id": "aoj_DSL_2_A_11066368", "code_snippet": "#include <bits/stdc++.h>\n#ifndef ATCODER_INTERNAL_BITOP_HPP\n#define ATCODER_INTERNAL_BITOP_HPP 1\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\n#if __cplusplus >= 202002L\n#include <bit>\n#endif\n\nnamespace atcoder {\n\nnamespace internal {\n\n#if __cplusplus >= 202002L\n\nusing std::bit_ceil;\n\n#else\n\n// @return same with std::bit::bit_ceil\nunsigned int bit_ceil(unsigned int n) {\n unsigned int x = 1;\n while (x < (unsigned int)(n)) x *= 2;\n return x;\n}\n\n#endif\n\n// @param n `1 <= n`\n// @return same with std::bit::countr_zero\nint countr_zero(unsigned int n) {\n#ifdef _MSC_VER\n unsigned long index;\n _BitScanForward(&index, n);\n return index;\n#else\n return __builtin_ctz(n);\n#endif\n}\n\n// @param n `1 <= n`\n// @return same with std::bit::countr_zero\nconstexpr int countr_zero_constexpr(unsigned int n) {\n int x = 0;\n while (!(n & (1 << x))) x++;\n return x;\n}\n\n} // namespace internal\n\n} // namespace atcoder\n\n#endif // ATCODER_INTERNAL_BITOP_HPP\n\nnamespace atcoder {\n\n#if __cplusplus >= 201703L\n\ntemplate <class S, auto op, auto e>\nstruct segtree {\n static_assert(std::is_convertible_v<decltype(op), std::function<S(S, S)>>,\n \"op must work as S(S, S)\");\n static_assert(std::is_convertible_v<decltype(e), std::function<S()>>,\n \"e must work as S()\");\n\n#else\n\ntemplate <class S, S (*op)(S, S), S (*e)()>\nstruct segtree {\n\n#endif\n\n public:\n segtree() : segtree(0) {}\n explicit segtree(int n) : segtree(std::vector<S>(n, e())) {}\n explicit segtree(const std::vector<S>& v) : _n(int(v.size())) {\n size = (int)internal::bit_ceil((unsigned int)(_n));\n log = internal::countr_zero((unsigned int)size);\n d = std::vector<S>(2 * size, e());\n for (int i = 0; i < _n; i++) d[size + i] = v[i];\n for (int i = size - 1; i >= 1; i--) {\n update(i);\n }\n }\n\n void set(int p, S x) {\n assert(0 <= p && p < _n);\n p += size;\n d[p] = x;\n for (int i = 1; i <= log; i++) update(p >> i);\n }\n\n S get(int p) const {\n assert(0 <= p && p < _n);\n return d[p + size];\n }\n\n S prod(int l, int r) const {\n assert(0 <= l && l <= r && r <= _n);\n S sml = e(), smr = e();\n l += size;\n r += size;\n\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++]);\n if (r & 1) smr = op(d[--r], smr);\n l >>= 1;\n r >>= 1;\n }\n return op(sml, smr);\n }\n\n S all_prod() const { return d[1]; }\n\n template <bool (*f)(S)>\n int max_right(int l) const {\n return max_right(l, [](S x) { return f(x); });\n }\n template <class F>\n int max_right(int l, F f) const {\n assert(0 <= l && l <= _n);\n assert(f(e()));\n if (l == _n) return _n;\n l += size;\n S sm = e();\n do {\n while (l % 2 == 0) l >>= 1;\n if (!f(op(sm, d[l]))) {\n while (l < size) {\n l = (2 * l);\n if (f(op(sm, d[l]))) {\n sm = op(sm, d[l]);\n l++;\n }\n }\n return l - size;\n }\n sm = op(sm, d[l]);\n l++;\n } while ((l & -l) != l);\n return _n;\n }\n\n template <bool (*f)(S)>\n int min_left(int r) const {\n return min_left(r, [](S x) { return f(x); });\n }\n template <class F>\n int min_left(int r, F f) const {\n assert(0 <= r && r <= _n);\n assert(f(e()));\n if (r == 0) return 0;\n r += size;\n S sm = e();\n do {\n r--;\n while (r > 1 && (r % 2)) r >>= 1;\n if (!f(op(d[r], sm))) {\n while (r < size) {\n r = (2 * r + 1);\n if (f(op(d[r], sm))) {\n sm = op(d[r], sm);\n r--;\n }\n }\n return r + 1 - size;\n }\n sm = op(d[r], sm);\n } while ((r & -r) != r);\n return 0;\n }\n\n private:\n int _n, size, log;\n std::vector<S> d;\n\n void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }\n};\n\n} // namespace atcoder\n\nusing namespace std;\nusing namespace atcoder;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < n; ++i)\n\nusing S = int;\nint op(int a, int b) { return min(a, b); }\nint e() { return INT_MAX; }\nint main() {\n int n, q;\n cin >> n >> q;\n\n segtree<S, op, e> seg(n);\n rep(i, q) {\n int com, x, y;\n cin >> com >> x >> y;\n if (com == 0) {\n seg.set(x, y);\n } else {\n int ans = seg.prod(x, y + 1);\n cout << ans << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4308, "score_of_the_acc": -0.8076, "final_rank": 12 }, { "submission_id": "aoj_DSL_2_A_11065645", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n#define ERASE(vec,s,e) vec.erase(vec.begin()+s, vec.begin()+e)\n#define ALL(v) (v).begin(), (v).end()\n#define CIN(v,n) for(int i=0; i<(n); i++) cin >> v[i]\n\nint n;\nint sz=1;\nvector<int> tree;\nconst int INF=2147483647;\n\nvoid update(int index,int num){\n index+=sz;\n tree[index]=num;\n while(index>1){\n index/=2;\n tree[index]=min(tree[2*index],tree[2*index+1]);\n }\n return;\n}\n\nint query(int l,int r){\n int res=INF;\n l+=sz;\n r+=sz;\n while(l<r){\n if(l&1){\n res=min(res,tree[l]);\n l++;\n }\n if(r&1){\n r--;\n res=min(res,tree[r]);\n }\n l/=2;\n r/=2;\n }\n return res;\n}\n\nint main(){\n int q;\n cin>>n>>q;\n while(sz<n)sz*=2;\n tree.resize(2*sz,INF);\n int com,x,y;\n for(int i=0;i<q;i++){\n cin>>com>>x>>y;\n if(com==0){\n update(x,y);\n }\n else{\n cout<<query(x,y+1)<<endl;\n }\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4084, "score_of_the_acc": -0.7778, "final_rank": 11 }, { "submission_id": "aoj_DSL_2_A_11061659", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define oke cout << \"Yes\" << '\\n';\n#define dame cout << \"No\" << '\\n';\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\nusing Hai2 = vector<vector<ll>>;\nusing HaiW = vector<vector<pair<ll,ll>>>;\nusing HaiB = vector<vector<bool>>;\nusing Hai3 = vector<vector<vector<ll>>>;\n\n//0インデックスで関数に入れる\nstruct segment{\n vector<ll>seg;\n ll seg_size=1;\n ll seg_syokiti=(1<<31)-1;\n\n void init(ll N){\n while(N>seg_size){\n seg_size*=2;\n }\n seg.resize(seg_size*2);\n rep(i,seg_size*2){\n seg[i]=seg_syokiti;\n }\n }\n\n void update(ll X,ll Y){\n X+=seg_size;\n seg[X]=Y;\n\n ll f=X/2;\n while(f>0){\n seg[f]=min(seg[f*2],seg[f*2+1]);\n f/=2;\n }\n }\n\n ll query(ll l,ll r){\n return naka_query(0,seg_size-1,l,r,1);\n }\n //a以上b以下 L=0 R=seg_size-1 v=1で関数に入れる\n ll naka_query(ll L,ll R,ll a,ll b,ll v){\n if(a<=L && R<=b) return seg[v];\n\n //ここも変える\n if(b<L || R<a) return seg_syokiti;\n\n ll T=0;\n ll mid=(L+R)/2;\n T=min(naka_query(L,mid,a,b,v*2),naka_query(mid+1,R,a,b,v*2+1));\n\n return T;\n }\n};\n\n\nint main() {\n\tcout << fixed << setprecision(15);\n ll N,Q;\n cin>>N>>Q;\n segment E;\n E.init(N);\n\n rep(i,Q){\n ll q,l; \n cin>>q>>l;\n if(q==0){\n ll x;\n cin>>x;\n E.update(l,x);\n }else{\n ll r;\n cin>>r;\n cout<<E.query(l,r)<<endl;\n }\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5200, "score_of_the_acc": -0.9265, "final_rank": 18 }, { "submission_id": "aoj_DSL_2_A_11060582", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i,a,x) for(int i=a;i<(int)x;i++)\n//セグメント木\nvector<ll> seg_data;\n//nを2のべき乗に直した値(nとごちゃごちゃになりがちなので注意)\nint n_;\n//初期値\nll inf = pow(2,31)-1;\n//seg木の初期化\nvoid segset(int n){\n n_=1;\n while(n_<n){\n n_ *= 2;\n }\n int size = n_*2;\n seg_data.resize(size);\n rep(i,0,size){\n seg_data[i] = inf;\n }\n}\n//index番目をxに変更する関数\nvoid updata(int index,ll x){\n //1番目の値はseg木ではn番目よりn_-1をする\n index += n_-1;\n seg_data[index] = x;\n //更新\n while(index > 0){\n index = (index-1)/2; \n seg_data[index] = min(seg_data[2*index+1],seg_data[2*index+2]);\n }\n}\n\n//[l,r) lからr未満の最小値を求めるRMQ\nll query(int l,int r,int index,int left,int right){\n\n ll res=pow(2,31)-1;\n\n if(l>=right or r<=left){\n return res;\n }\n\n if(l <= left and r >= right){\n return seg_data[index];\n }\n\n int value_1 = query(l,r,2*index+1,left,(left+right)/2);\n int value_2 = query(l,r,2*index+2,(left+right)/2,right);\n\n\n\n return min(value_1,value_2);\n}\n\n\n\nint main(){\n int n,q;\n cin >> n >> q;\n segset(n);\n \n rep(i,0,q){\n int b;\n cin >> b;\n if(b==0){\n int p;\n ll x;\n cin >> p >> x;\n updata(p,x);\n }\n if(b==1){\n int l,r;\n cin >> l >> r;\n ll ans=query(l,r+1,0,0,n_);\n cout << ans << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5156, "score_of_the_acc": -0.9206, "final_rank": 15 }, { "submission_id": "aoj_DSL_2_A_11059763", "code_snippet": "#include <bits/stdc++.h>\n#include <bit>\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing i128 = __int128_t;\nusing u128 = __uint128_t;\nusing pii = pair<int, int>;\nusing pic = pair<int, char>;\nusing pci = pair<char, int>;\nusing pll = pair<ll, ll>;\nusing pllc = pair<ll, char>;\n#define rep(i, a, n) for (int i = a; i < (n); i++)\n\ntemplate <class T, class U>\nstruct PairHash {\n static inline size_t hash_combine(size_t seed, size_t v) noexcept {\n // boost::hash_combine と同等の混合\n return seed ^ (v + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2));\n }\n size_t operator()(const pair<T,U>& p) const noexcept {\n size_t h1 = std::hash<T>{}(p.first);\n size_t h2 = std::hash<U>{}(p.second);\n return hash_combine(h1, h2);\n }\n};\n\npll operator+(const pll& a, const pll& b) {\n return {a.first + b.first, a.second + b.second};\n}\n\npll operator-(const pll& a, const pll& b) {\n return {a.first - b.first, a.second - b.second};\n}\n\npll operator-(const pll& a) {\n return {-a.first, -a.second};\n}\n\n// ===== プロトタイプ宣言 =====\nint solve();\n\n// ===== main関数 =====\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n return solve();\n}\n\n\nvoid prvec(vector<string> V) {\n for (const auto& v : V)\n cout << v << endl;\n}\n\nvoid prvec(vector<bool> V) {\n for (const auto& v : V)\n cout << boolalpha << setw(5) << setfill(' ') << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(vector<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(list<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(unordered_set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(multiset<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T1>\nvoid prvec(deque<T1> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\nvoid prvec(set<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, pair<T2, T3>> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : {\" << v.first << \" \" << v.second << \"}\" << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, vector<pair<T2, T3>>> V) {\n for (const auto& [k, v] : V) {\n cout << k << \" : \" ;\n for (const auto& [a, b] : v)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n }\n}\n\nvoid prvec(map<int, bool> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : \" << boolalpha << v << endl;\n}\n\nvoid prvec(map<string, pii> V) {\n for (const auto& [k, v] : V) \n cout << k << \" : \" << v.first << \" \" << v.second << endl;\n}\n\ntemplate <typename T>\nvoid prvec(map<pii, T> V) {\n for (const auto& [k, v] : V) \n cout << \"{\" << k.first << \", \" << k.second << \"}: \" << v << endl;\n}\n\nvoid prvec(map<int, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, stack<int>> V) {\n for (const auto& [k, stk] : V) {\n cout << k << \" : \";\n stack<int> stk2 = stk;\n while (!stk2.empty()) {\n int v = stk2.top(); stk2.pop();\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(vector<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<string, string>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, double>> V) {\n for (const auto& [a, b] : V)\n cout << fixed << setprecision(15) << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<char, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, char>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(unordered_map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(set<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, vector<int>>> V) {\n for (const auto& [a, vec] : V) {\n cout << a << \" : \";\n for (const auto& v : vec) cout << v << \" \";\n cout << endl;\n }\n}\n\nvoid prvec(vector<pair<int, set<int>>> V) {\n for (const auto& [a, st] : V) {\n cout << a << \" : \";\n for (const auto& v : st) cout << v << \" \";\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(vector<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(set<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\nvoid prvec(vector<tuple<T1, T2, T3, T4>> V) {\n for (const auto& [a, b, c, d] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \", \" << d << \"}, \";\n cout << endl;\n}\n\ntemplate<typename T, typename... Args>\nvoid prvec(std::priority_queue<T, Args...> pq) {\n while (!pq.empty()) {\n auto [f, s] = pq.top();\n cout << \"{\" << f << \", \" << s << \"}, \";\n pq.pop();\n }\n cout << \"\\n\";\n}\n\nclass UnionFind {\n private :\n vector<int> parent;\n vector<int> sz;\n vector<int> edge_count;\n \n public :\n UnionFind(int n) : parent(n), sz(n, 1), edge_count(n, 0) {\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n \n int find(int x) {\n if (parent[x] == x) return x;\n return parent[x] = find(parent[x]);\n }\n \n bool unite(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX == rootY) {\n \tedge_count[rootX]++;\n \treturn false; // cycle検出\n }\n \n if (sz[rootX] < sz[rootY]) swap(rootX, rootY);\n parent[rootY] = rootX;\n sz[rootX] += sz[rootY];\n edge_count[rootX] += edge_count[rootY] + 1;\n return true;\n }\n \n int getSize(int x) {\n return sz[find(x)];\n }\n \n int getEdges(int x) {\n \treturn edge_count[find(x)];\n }\n \n bool same(int x, int y) {\n return find(x) == find(y);\n }\n \n // 頂点数を new_n まで増やす (new_n <= 現在のサイズなら何もしない)\n void ensureSize(int new_n) {\n int old_n = parent.size();\n if (new_n <= old_n) return;\n parent.resize(new_n);\n sz.resize(new_n, 1);\n edge_count.resize(new_n, 0);\n // 新しく追加された i (old_n <= i < new_n) をルート+サイズ1に初期化\n for (int i = old_n; i < new_n; i++) {\n parent[i] = i;\n // sz[i] は resize の第二引数で 1 になっている\n }\n }\n \n // 頂点を1つ追加して、そのインデックスを返す\n int addVertex() {\n int idx = parent.size();\n parent.push_back(idx);\n sz.push_back(1);\n edge_count.push_back(0);\n return idx;\n } \n};\n\ntemplate <class Abel>\n// 重み付きUnionFindの定義\nstruct WeightedUnionFind {\n vector<int> parent, size;\n vector<Abel> diff_weight;\n\n WeightedUnionFind(int n)\n : parent(n), size(n, 1), diff_weight(n, Abel{}) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) {\n if (parent[x] == x) return x;\n int r = find(parent[x]);\n diff_weight[x] = diff_weight[x] + diff_weight[parent[x]];\n return parent[x] = r;\n }\n\n Abel weight(int x) {\n find(x);\n return diff_weight[x];\n }\n\n bool unite(int u, int v, Abel w) {\n Abel wu = weight(u), wv = weight(v);\n int ru = find(u), rv = find(v);\n if (ru == rv) {\n return (wv - wu == w); // すでに矛盾ないかチェック\n }\n\n Abel dw = w + wu - wv;\n\n // union by size(大きいほうに小さいほうをつける)\n if (size[ru] < size[rv]) {\n swap(ru, rv);\n swap(u, v);\n dw = -dw;\n }\n\n parent[rv] = ru;\n diff_weight[rv] = dw;\n size[ru] += size[rv];\n return true;\n }\n\n bool same(int x, int y) {\n return find(x) == find(y);\n }\n\n Abel diff(int x, int y) {\n return weight(y) - weight(x);\n }\n};\n\nstruct DSURollback {\n int n;\n vector<int> parent, sz;\n\n // 変更履歴: (結合された子root, 併合前の親rootのサイズ)\n // 子root = -1 は「何も結合しなかった(uniteで同根)」の印\n vector<pair<int,int>> hist;\n\n DSURollback(int n=0): n(n), parent(n), sz(n,1) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) const {\n // パス圧縮しない\n while (parent[x] != x) x = parent[x];\n return x;\n }\n\n bool unite(int x, int y) {\n x = find(x); y = find(y);\n if (x == y) { \n hist.emplace_back(-1, 0); // ダミー (巻き戻し整合用)\n return false; \n }\n if (sz[x] < sz[y]) swap(x, y); // x に y をくっつける(サイズ併合)\n\n // 履歴に「y が x にぶら下がる前の x のサイズ」を記録\n hist.emplace_back(y, sz[x]);\n\n parent[y] = x;\n sz[x] += sz[y];\n return true;\n }\n\n // 直前の unite を 1 回取り消す\n void rollback() {\n auto [y, old_szx] = hist.back(); hist.pop_back();\n if (y == -1) return; // 何もしていない unite の取消\n int x = parent[y];\n // 親子関係とサイズを元に戻す\n parent[y] = y;\n sz[x] = old_szx;\n }\n\n // スナップショット(この位置まで戻せる)\n int snapshot() const { return (int)hist.size(); }\n\n // 指定スナップショットへ戻す(複数回分まとめて取り消し)\n void rollback_to(int snap) {\n while ((int)hist.size() > snap) rollback();\n }\n\n bool same(int a, int b) { return find(a) == find(b); }\n int size(int x) { return sz[find(x)]; }\n};\n\ntemplate<class S, class Op, class E>\nstruct SegTree {\n int n0 = 0; // 元の配列の長さ\n int n = 1; // セグ木内部のサイズ(2べき)\n std::vector<S> d;\n\n Op op{}; // 区間結合\n E e{}; // 単位元\n\n SegTree() = default;\n explicit SegTree(int n_) { init(n_); }\n explicit SegTree(const std::vector<S>& a) { init(a); }\n\n // 要素数 n_ で初期化(全部 e())\n void init(int n_) {\n n0 = n_;\n n = 1;\n while (n < n_) n <<= 1;\n d.assign(2 * n, e());\n }\n\n // 初期配列 a から構築\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n0; i++) d[n + i] = a[i];\n for (int i = n - 1; i >= 1; i--) {\n d[i] = op(d[i << 1], d[i << 1 | 1]);\n }\n }\n\n // 点代入: A[pos] = val\n void point_set(int pos, const S& val) {\n int k = pos + n;\n d[k] = val;\n for (k >>= 1; k; k >>= 1) {\n d[k] = op(d[k << 1], d[k << 1 | 1]);\n }\n }\n\n // 点取得\n S get(int pos) const {\n return d[pos + n];\n }\n\n // 区間 [l, r) を畳み込み(LazySegTree に合わせて prod という名前に)\n S prod(int l, int r) const {\n S L = e(), R = e();\n for (l += n, r += n; l < r; l >>= 1, r >>= 1) {\n if (l & 1) L = op(L, d[l++]);\n if (r & 1) R = op(d[--r], R);\n }\n return op(L, R);\n }\n\n // 全体\n S all_prod() const {\n return d[1];\n }\n};\n\n// 区間和\nstruct OpSum {\n ll operator()(ll a, ll b) const { return a + b; }\n};\n\n// 単位元(0)\nstruct ESum {\n ll operator()() const { return 0LL; }\n};\n\n// usage: RSQ(SegTreeSum)\n // int n = 10;\n // SegTree<ll, OpSum, ESum> seg(n);\n \n // // A[i] = i をセット\n // for (int i = 0; i < n; i++) seg.point_set(i, i);\n\n // // [l, r) の和\n // ll s = seg.prod(2, 7);\n\n// 区間最大\nstruct OpMax {\n ll operator()(ll a, ll b) const { return std::max(a, b); }\n};\n\nstruct EMax {\n static constexpr ll NEG_INF = (ll)-4e18;\n ll operator()() const { return NEG_INF; }\n};\n// usage: RMaxQ(SegTree)\n// SegTree<ll, OpMax, EMax> seg_max(n);\n\n// 区間最小\nstruct OpMin {\n ll operator()(ll a, ll b) const { return std::min(a, b); }\n};\n\nstruct EMin {\n static constexpr ll INF = (ll)4e18;\n ll operator()() const { return INF; }\n};\n// usage: RMinQ(SeegTree)\n// SegTree<ll, OpMin, EMin> seg_min(n);\n\n// SegTreeMinArg\nstruct MinArgNode {\n long long val;\n int idx;\n};\n\n// 区間最小 & argmin\nstruct OpMinArg {\n MinArgNode operator()(const MinArgNode& a, const MinArgNode& b) const {\n if (a.val != b.val) return (a.val < b.val ? a : b);\n if (a.idx == -1) return b;\n if (b.idx == -1) return a;\n return (a.idx < b.idx ? a : b); // tie: 小さい idx\n }\n};\n\nstruct EMinArg {\n static constexpr long long INF = (long long)4e18;\n MinArgNode operator()() const { return MinArgNode{INF, -1}; }\n};\n// usage: SegTreeMinArg\n// int n = 10;\n// SegTree<MinArgNode, OpMinArg, EMinArg> seg_minarg(n);\n\n// // 値だけ代入する糖衣\n// auto point_set_val = [&](int pos, long long v) {\n// seg_minarg.point_set(pos, MinArgNode{v, pos});\n// };\n\n// point_set_val(3, 5);\n// point_set_val(7, 2);\n\n// MinArgNode res = seg_minarg.prod(0, n); // 全区間の最小 & その位置\n\n// ==============================\n// Generic Lazy Segment Tree\n// S: ノード型(例: {val, len})\n// F: 遅延(写像)型(例: 加算値)\n// 必要な関数: \n// op(S,S)->S : 区間結合(モノイド演算)\n// e()->S : Sの単位元\n// mapping(F,S)->S : SにFを適用\n// composition(Fnew, Fold)->F: 遅延の合成(先にFold→後でFnewがかかる形になるよう定義)\n// id()->F : Fの単位元\n// ==============================\ntemplate<\n class S, class F,\n class Op, class E,\n class Mapping, class Composition, class Id\n>\nstruct LazySegTree {\n int n = 0, size = 1, logn = 0;\n\n // ここで中の演算子たちをデフォルト初期化\n Op op{};\n E e{};\n Mapping mapping{};\n Composition composition{};\n Id id{};\n\n std::vector<S> d;\n std::vector<F> lz;\n\n LazySegTree() = default;\n explicit LazySegTree(int n_) { init(n_); }\n explicit LazySegTree(const std::vector<S>& a) { init(a); }\n\n void init(int n_) {\n n = n_;\n logn = 0;\n size = 1;\n while (size < n) size <<= 1, ++logn;\n d.assign(2 * size, e()); // E::operator() で単位元\n lz.assign(size, id()); // Id::operator() で遅延の単位元\n }\n\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n; i++) d[size + i] = a[i];\n for (int i = size - 1; i >= 1; i--) pull(i);\n }\n\n void set_point(int p, const S& x) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n d[p] = x;\n for (int i = 1; i <= logn; i++) pull(p >> i);\n }\n\n S get_point(int p) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n return d[p];\n }\n\n // 区間 [l, r) に f を適用\n void apply(int l, int r, const F& f) {\n if (l >= r) return;\n l += size; r += size;\n int l0 = l, r0 = r;\n for (int i = logn; i >= 1; i--) {\n if (((l0 >> i) << i) != l0) push(l0 >> i);\n if (((r0 >> i) << i) != r0) push((r0 - 1) >> i);\n }\n while (l < r) {\n if (l & 1) all_apply(l++, f);\n if (r & 1) all_apply(--r, f);\n l >>= 1; r >>= 1;\n }\n for (int i = 1; i <= logn; i++) {\n if (((l0 >> i) << i) != l0) pull(l0 >> i);\n if (((r0 >> i) << i) != r0) pull((r0 - 1) >> i);\n }\n }\n\n // 区間 [l, r) を畳み込み\n S prod(int l, int r) {\n if (l >= r) return e();\n l += size; r += size;\n for (int i = logn; i >= 1; i--) {\n if (((l >> i) << i) != l) push(l >> i);\n if (((r >> i) << i) != r) push((r - 1) >> i);\n }\n S sml = e(), smr = e();\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++]);\n if (r & 1) smr = op(d[--r], smr);\n l >>= 1; r >>= 1;\n }\n return op(sml, smr);\n }\n\n // 全体\n S all_prod() const { return d[1]; }\n\nprivate:\n void pull(int k) { d[k] = op(d[2*k], d[2*k+1]); }\n\n void all_apply(int k, const F& f) {\n d[k] = mapping(f, d[k]);\n if (k < size) lz[k] = composition(f, lz[k]);\n }\n\n void push(int k) {\n if (lz[k] != id()) { // F 型同士の比較(例: long long)\n all_apply(2*k, lz[k]);\n all_apply(2*k+1, lz[k]);\n lz[k] = id();\n }\n }\n};\n\n// ==============================\n// ここから具体インスタンス例\n// 共通ノード型(lenを持たせることで sum/max の両方に対応)\n// ==============================\nstruct Node {\n long long val; // 区間の値(和 or 最大)\n int len; // その区間の長さ(sumでのみ使用)\n};\n\n// -------- Range Add + Range Sum 用の関数群 --------\nstruct OpSumlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{a.val + b.val, a.len + b.len};\n }\n};\nstruct ESumlazy {\n Node operator()() const { return Node{0LL, 0}; } // 単位元\n};\nstruct MappingAddToSum {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add * 1LL * s.len, s.len};\n }\n};\nstruct ComposeAdd {\n long long operator()(long long fnew, long long fold) const {\n return fnew + fold;\n }\n};\nstruct IdAdd {\n long long operator()() const { return 0LL; }\n};\n\n// Range Add + Range Max\nstatic constexpr long long NEG_INF = -(1LL<<60);\nstruct OpMaxlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{std::max(a.val, b.val), a.len + b.len};\n }\n};\nstruct EMaxlazy {\n Node operator()() const { return Node{NEG_INF, 0}; }\n};\nstruct MappingAddToMax {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add, s.len};\n }\n};\n\n// ==============================\n// 使用例1: Range Add + Range Sum\n// ==============================\nvoid example_sum() {\n int n = 8;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpSumlazy, ESumlazy,\n MappingAddToSum, ComposeAdd, IdAdd>\n seg(init); // ← もう functor を渡さなくてよい\n\n seg.apply(2, 6, 5); // [2, 6) に +5\n std::cout << seg.all_prod().val << \"\\n\"; // 20\n std::cout << seg.prod(3, 5).val << \"\\n\"; // 10\n}\n\n// ==============================\n// 使用例2: Range Add + Range Max\n// ==============================\nvoid example_max() {\n int n = 10;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpMaxlazy, EMaxlazy,\n MappingAddToMax, ComposeAdd, IdAdd>\n seg(init); // ここも functor いらない\n\n seg.apply(2, 5, 1);\n seg.apply(4, 9, 3);\n std::cout << seg.all_prod().val << \"\\n\";\n}\n\n// 1-indexed Fenwick Tree (Binary Indexed Tree)\ntemplate <class T>\nstruct Fenwick {\n int n;\n vector<T> bit;\n\n Fenwick() : n(0) {}\n explicit Fenwick(int n) : n(n), bit(n + 1, T{}) {}\n\n // a[idx] += delta\n void add(int idx, T delta) {\n for (; idx <= n; idx += idx & -idx) bit[idx] += delta;\n }\n\n // prefix sum: a[1] + ... + a[idx]\n T sum(int idx) const {\n T s{};\n for (; idx > 0; idx -= idx & -idx) s += bit[idx];\n return s;\n }\n\n // range sum: a[l] + ... + a[r]\n T range_sum(int l, int r) const {\n if (l > r) return T{};\n return sum(r) - sum(l - 1);\n }\n\n // ---- ここから先は「順序統計」をやりたい人向けのオプション ----\n // すべての要素が「非負の整数」である前提で、\n // 最小の idx を返す: sum(idx) >= t (tは1..sum(n))\n // T が整数型のときのみ有効化\n template <class U = T, std::enable_if_t<std::is_integral_v<U>, int> = 0>\n int kth(U t) const {\n // 前提: すべての add が非負、bitの総和 >= t\n int idx = 0;\n U acc = 0;\n int step = 1;\n while ((step << 1) <= n) step <<= 1; // n以下の最大2冪\n for (int p = step; p; p >>= 1) {\n int nx = idx + p;\n if (nx <= n && acc + (U)bit[nx] < t) {\n acc += (U)bit[nx];\n idx = nx;\n }\n }\n return idx + 1; // 1-indexed\n }\n};\n \n// ===== 素数判定を行う =====\nstruct MillerRabin64 {\n static inline ull mul_mod(ull a, ull b, ull mod) {\n return (ull)((u128)a * b % mod);\n }\n static inline ull pow_mod(ull a, ull e, ull mod) {\n ull r = 1 % mod;\n a %= mod;\n while (e) {\n if (e & 1) r = mul_mod(r, a, mod);\n a = mul_mod(a, a, mod);\n e >>= 1;\n }\n return r;\n }\n static bool isPrime(ull n) {\n if (n < 2) return false;\n // 小さい素数で先に弾く\n static const ull smalls[] = {2,3,5,7,11,13,17,19,23,29,31,37};\n for (ull p : smalls) {\n if (n == p) return true;\n if (n % p == 0) return n == p;\n }\n // n-1 = d * 2^s2\n ull d = n - 1, s2 = 0;\n while (!(d & 1)) d >>= 1, ++s2;\n\n auto witness = [&](ull a) -> bool {\n if (!(a % n)) return false;\n ull x = pow_mod(a, d, n);\n if (x == 1 || x == n - 1) return false;\n for (ull i = 1; i < s2; i++) {\n x = mul_mod(x, x, n);\n if (x == n - 1) return false;\n }\n return true; // 合成数の証人\n };\n\n // 64bit 決定的基底\n static const ull bases[] = {\n 2ULL, 325ULL, 9375ULL, 28178ULL,\n 450775ULL, 9780504ULL, 1795265022ULL\n };\n for (ull a : bases) {\n if (!(a % n)) continue;\n if (witness(a)) return false;\n }\n return true;\n }\n};\nusing MR64 = MillerRabin64;\n\n// modint: mod計算をintを扱うように扱える構造体\n// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a#8-modint\ntemplate<int MOD> struct Fp {\n ll val;\n constexpr Fp(ll v = 0) noexcept : val(v % MOD) {\n if (val < 0) val += MOD;\n }\n constexpr int getmod() { return MOD; }\n constexpr Fp operator - () const noexcept {\n return val ? MOD - val : 0;\n }\n constexpr Fp operator + (const Fp& r) const noexcept { return Fp(*this) += r;}\n constexpr Fp operator - (const Fp& r) const noexcept { return Fp(*this) -= r;}\n constexpr Fp operator * (const Fp& r) const noexcept { return Fp(*this) *= r;}\n constexpr Fp operator / (const Fp& r) const noexcept { return Fp(*this) /= r;}\n constexpr Fp& operator += (const Fp& r) noexcept {\n val += r.val;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n constexpr Fp& operator -= (const Fp& r) noexcept {\n val -= r.val;\n if (val < 0) val += MOD;\n return *this;\n }\n constexpr Fp& operator *= (const Fp& r) noexcept {\n val = val * r.val % MOD;\n return *this;\n }\n constexpr Fp& operator /= (const Fp& r) noexcept {\n return *this *= modpow(r, MOD - 2);\n }\n // 前置 ++x\n constexpr Fp& operator++() noexcept {\n val++;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n\n // 後置 x++\n constexpr Fp operator++(int) noexcept {\n Fp tmp = *this;\n ++(*this);\n return tmp;\n }\n\n // 前置 --x\n constexpr Fp& operator--() noexcept {\n val--;\n if (val < 0) val += MOD;\n return *this;\n }\n\n // 後置 x--\n constexpr Fp operator--(int) noexcept {\n Fp tmp = *this;\n --(*this);\n return tmp;\n }\n constexpr bool operator == (const Fp& r) const noexcept {\n return this->val == r.val;\n }\n constexpr bool operator != (const Fp& r) const noexcept {\n return this->val != r.val;\n }\n constexpr bool operator < (const Fp& r) const noexcept { return this->val < r.val;}\n constexpr bool operator <= (const Fp& r) const noexcept { return this->val <= r.val;}\n constexpr bool operator > (const Fp& r) const noexcept { return this->val > r.val;}\n constexpr bool operator >= (const Fp& r) const noexcept { return this->val >= r.val;}\n friend constexpr ostream& operator << (ostream &os, const Fp<MOD>& x) {\n return os << x.val;\n }\n friend constexpr istream& operator >> (istream &is, Fp<MOD>& x) {\n ll v;\n is >> v;\n x = Fp<MOD>(v);\n return is;\n }\n friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, ll n) noexcept {\n if (n == 0) return 1;\n auto t = modpow(a, n / 2);\n t = t * t;\n if (n & 1) t = t * a;\n return t;\n }\n};\nusing mint = Fp<998244353>;\n\nint solve() {\n int n, q;\n cin >> n >> q;\n \n int size = 1;\n while (size < n) size <<= 1;\n const int SEG_LEN = size;\n const ll INF = (1LL << 31) - 1;\n vector<ll> seg_tree(SEG_LEN * 2, INF);\n \n auto update = [&](int idx, ll x) -> void {\n idx += SEG_LEN;\n seg_tree[idx] = x;\n while (true) {\n idx /= 2;\n if (idx == 0) break;\n seg_tree[idx] = min(seg_tree[idx * 2], seg_tree[idx * 2 + 1]);\n }\n };\n \n auto find_main = [&](auto&& self, int ql, int qr, int sl, int sr, int pos) -> ll {\n // 範囲外\n if (sr <= ql || sl >= qr) return INF;\n // 完全に含まれる\n if (ql <= sl && sr <= qr) return seg_tree[pos];\n // 部分的に含まれる-> 子を検索\n int m = (sl + sr) >> 1;\n ll left = self(self, ql, qr, sl, m, pos * 2);\n ll right = self(self, ql, qr, m, sr, pos * 2 + 1);\n return std::min(left, right);\n };\n \n auto find = [&](int l, int r) -> ll {\n return find_main(find_main, l, r, 0, SEG_LEN, 1) ;\n };\n \n while (q--) {\n int com; ll x, y; cin >> com >> x >> y;\n \n if (com == 0) update(x, y);\n else cout << find(x, y + 1) << \"\\n\";\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5480, "score_of_the_acc": -0.2971, "final_rank": 2 }, { "submission_id": "aoj_DSL_2_A_11059681", "code_snippet": "#include <bits/stdc++.h>\n#include <bit>\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing i128 = __int128_t;\nusing u128 = __uint128_t;\nusing pii = pair<int, int>;\nusing pic = pair<int, char>;\nusing pci = pair<char, int>;\nusing pll = pair<ll, ll>;\nusing pllc = pair<ll, char>;\n#define rep(i, a, n) for (int i = a; i < (n); i++)\n\ntemplate <class T, class U>\nstruct PairHash {\n static inline size_t hash_combine(size_t seed, size_t v) noexcept {\n // boost::hash_combine と同等の混合\n return seed ^ (v + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2));\n }\n size_t operator()(const pair<T,U>& p) const noexcept {\n size_t h1 = std::hash<T>{}(p.first);\n size_t h2 = std::hash<U>{}(p.second);\n return hash_combine(h1, h2);\n }\n};\n\npll operator+(const pll& a, const pll& b) {\n return {a.first + b.first, a.second + b.second};\n}\n\npll operator-(const pll& a, const pll& b) {\n return {a.first - b.first, a.second - b.second};\n}\n\npll operator-(const pll& a) {\n return {-a.first, -a.second};\n}\n\n// ===== プロトタイプ宣言 =====\nint solve();\n\n// ===== main関数 =====\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n return solve();\n}\n\n\nvoid prvec(vector<string> V) {\n for (const auto& v : V)\n cout << v << endl;\n}\n\nvoid prvec(vector<bool> V) {\n for (const auto& v : V)\n cout << boolalpha << setw(5) << setfill(' ') << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(vector<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(list<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(unordered_set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(multiset<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T1>\nvoid prvec(deque<T1> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\nvoid prvec(set<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, pair<T2, T3>> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : {\" << v.first << \" \" << v.second << \"}\" << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, vector<pair<T2, T3>>> V) {\n for (const auto& [k, v] : V) {\n cout << k << \" : \" ;\n for (const auto& [a, b] : v)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n }\n}\n\nvoid prvec(map<int, bool> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : \" << boolalpha << v << endl;\n}\n\nvoid prvec(map<string, pii> V) {\n for (const auto& [k, v] : V) \n cout << k << \" : \" << v.first << \" \" << v.second << endl;\n}\n\ntemplate <typename T>\nvoid prvec(map<pii, T> V) {\n for (const auto& [k, v] : V) \n cout << \"{\" << k.first << \", \" << k.second << \"}: \" << v << endl;\n}\n\nvoid prvec(map<int, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, stack<int>> V) {\n for (const auto& [k, stk] : V) {\n cout << k << \" : \";\n stack<int> stk2 = stk;\n while (!stk2.empty()) {\n int v = stk2.top(); stk2.pop();\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(vector<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<string, string>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, double>> V) {\n for (const auto& [a, b] : V)\n cout << fixed << setprecision(15) << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<char, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, char>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(unordered_map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(set<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, vector<int>>> V) {\n for (const auto& [a, vec] : V) {\n cout << a << \" : \";\n for (const auto& v : vec) cout << v << \" \";\n cout << endl;\n }\n}\n\nvoid prvec(vector<pair<int, set<int>>> V) {\n for (const auto& [a, st] : V) {\n cout << a << \" : \";\n for (const auto& v : st) cout << v << \" \";\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(vector<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(set<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\nvoid prvec(vector<tuple<T1, T2, T3, T4>> V) {\n for (const auto& [a, b, c, d] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \", \" << d << \"}, \";\n cout << endl;\n}\n\ntemplate<typename T, typename... Args>\nvoid prvec(std::priority_queue<T, Args...> pq) {\n while (!pq.empty()) {\n auto [f, s] = pq.top();\n cout << \"{\" << f << \", \" << s << \"}, \";\n pq.pop();\n }\n cout << \"\\n\";\n}\n\nclass UnionFind {\n private :\n vector<int> parent;\n vector<int> sz;\n vector<int> edge_count;\n \n public :\n UnionFind(int n) : parent(n), sz(n, 1), edge_count(n, 0) {\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n \n int find(int x) {\n if (parent[x] == x) return x;\n return parent[x] = find(parent[x]);\n }\n \n bool unite(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX == rootY) {\n \tedge_count[rootX]++;\n \treturn false; // cycle検出\n }\n \n if (sz[rootX] < sz[rootY]) swap(rootX, rootY);\n parent[rootY] = rootX;\n sz[rootX] += sz[rootY];\n edge_count[rootX] += edge_count[rootY] + 1;\n return true;\n }\n \n int getSize(int x) {\n return sz[find(x)];\n }\n \n int getEdges(int x) {\n \treturn edge_count[find(x)];\n }\n \n bool same(int x, int y) {\n return find(x) == find(y);\n }\n \n // 頂点数を new_n まで増やす (new_n <= 現在のサイズなら何もしない)\n void ensureSize(int new_n) {\n int old_n = parent.size();\n if (new_n <= old_n) return;\n parent.resize(new_n);\n sz.resize(new_n, 1);\n edge_count.resize(new_n, 0);\n // 新しく追加された i (old_n <= i < new_n) をルート+サイズ1に初期化\n for (int i = old_n; i < new_n; i++) {\n parent[i] = i;\n // sz[i] は resize の第二引数で 1 になっている\n }\n }\n \n // 頂点を1つ追加して、そのインデックスを返す\n int addVertex() {\n int idx = parent.size();\n parent.push_back(idx);\n sz.push_back(1);\n edge_count.push_back(0);\n return idx;\n } \n};\n\ntemplate <class Abel>\n// 重み付きUnionFindの定義\nstruct WeightedUnionFind {\n vector<int> parent, size;\n vector<Abel> diff_weight;\n\n WeightedUnionFind(int n)\n : parent(n), size(n, 1), diff_weight(n, Abel{}) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) {\n if (parent[x] == x) return x;\n int r = find(parent[x]);\n diff_weight[x] = diff_weight[x] + diff_weight[parent[x]];\n return parent[x] = r;\n }\n\n Abel weight(int x) {\n find(x);\n return diff_weight[x];\n }\n\n bool unite(int u, int v, Abel w) {\n Abel wu = weight(u), wv = weight(v);\n int ru = find(u), rv = find(v);\n if (ru == rv) {\n return (wv - wu == w); // すでに矛盾ないかチェック\n }\n\n Abel dw = w + wu - wv;\n\n // union by size(大きいほうに小さいほうをつける)\n if (size[ru] < size[rv]) {\n swap(ru, rv);\n swap(u, v);\n dw = -dw;\n }\n\n parent[rv] = ru;\n diff_weight[rv] = dw;\n size[ru] += size[rv];\n return true;\n }\n\n bool same(int x, int y) {\n return find(x) == find(y);\n }\n\n Abel diff(int x, int y) {\n return weight(y) - weight(x);\n }\n};\n\nstruct DSURollback {\n int n;\n vector<int> parent, sz;\n\n // 変更履歴: (結合された子root, 併合前の親rootのサイズ)\n // 子root = -1 は「何も結合しなかった(uniteで同根)」の印\n vector<pair<int,int>> hist;\n\n DSURollback(int n=0): n(n), parent(n), sz(n,1) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) const {\n // パス圧縮しない\n while (parent[x] != x) x = parent[x];\n return x;\n }\n\n bool unite(int x, int y) {\n x = find(x); y = find(y);\n if (x == y) { \n hist.emplace_back(-1, 0); // ダミー (巻き戻し整合用)\n return false; \n }\n if (sz[x] < sz[y]) swap(x, y); // x に y をくっつける(サイズ併合)\n\n // 履歴に「y が x にぶら下がる前の x のサイズ」を記録\n hist.emplace_back(y, sz[x]);\n\n parent[y] = x;\n sz[x] += sz[y];\n return true;\n }\n\n // 直前の unite を 1 回取り消す\n void rollback() {\n auto [y, old_szx] = hist.back(); hist.pop_back();\n if (y == -1) return; // 何もしていない unite の取消\n int x = parent[y];\n // 親子関係とサイズを元に戻す\n parent[y] = y;\n sz[x] = old_szx;\n }\n\n // スナップショット(この位置まで戻せる)\n int snapshot() const { return (int)hist.size(); }\n\n // 指定スナップショットへ戻す(複数回分まとめて取り消し)\n void rollback_to(int snap) {\n while ((int)hist.size() > snap) rollback();\n }\n\n bool same(int a, int b) { return find(a) == find(b); }\n int size(int x) { return sz[find(x)]; }\n};\n\ntemplate<class S, class Op, class E>\nstruct SegTree {\n int n0 = 0; // 元の配列の長さ\n int n = 1; // セグ木内部のサイズ(2べき)\n std::vector<S> d;\n\n Op op{}; // 区間結合\n E e{}; // 単位元\n\n SegTree() = default;\n explicit SegTree(int n_) { init(n_); }\n explicit SegTree(const std::vector<S>& a) { init(a); }\n\n // 要素数 n_ で初期化(全部 e())\n void init(int n_) {\n n0 = n_;\n n = 1;\n while (n < n_) n <<= 1;\n d.assign(2 * n, e());\n }\n\n // 初期配列 a から構築\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n0; i++) d[n + i] = a[i];\n for (int i = n - 1; i >= 1; i--) {\n d[i] = op(d[i << 1], d[i << 1 | 1]);\n }\n }\n\n // 点代入: A[pos] = val\n void point_set(int pos, const S& val) {\n int k = pos + n;\n d[k] = val;\n for (k >>= 1; k; k >>= 1) {\n d[k] = op(d[k << 1], d[k << 1 | 1]);\n }\n }\n\n // 点取得\n S get(int pos) const {\n return d[pos + n];\n }\n\n // 区間 [l, r) を畳み込み(LazySegTree に合わせて prod という名前に)\n S prod(int l, int r) const {\n S L = e(), R = e();\n for (l += n, r += n; l < r; l >>= 1, r >>= 1) {\n if (l & 1) L = op(L, d[l++]);\n if (r & 1) R = op(d[--r], R);\n }\n return op(L, R);\n }\n\n // 全体\n S all_prod() const {\n return d[1];\n }\n};\n\n// 区間和\nstruct OpSum {\n ll operator()(ll a, ll b) const { return a + b; }\n};\n\n// 単位元(0)\nstruct ESum {\n ll operator()() const { return 0LL; }\n};\n\n// usage: RSQ(SegTreeSum)\n // int n = 10;\n // SegTree<ll, OpSum, ESum> seg(n);\n \n // // A[i] = i をセット\n // for (int i = 0; i < n; i++) seg.point_set(i, i);\n\n // // [l, r) の和\n // ll s = seg.prod(2, 7);\n\n// 区間最大\nstruct OpMax {\n ll operator()(ll a, ll b) const { return std::max(a, b); }\n};\n\nstruct EMax {\n static constexpr ll NEG_INF = (ll)-4e18;\n ll operator()() const { return NEG_INF; }\n};\n// usage: RMaxQ(SegTree)\n// SegTree<ll, OpMax, EMax> seg_max(n);\n\n// 区間最小\nstruct OpMin {\n ll operator()(ll a, ll b) const { return std::min(a, b); }\n};\n\nstruct EMin {\n static constexpr ll INF = (ll)4e18;\n ll operator()() const { return INF; }\n};\n// usage: RMinQ(SeegTree)\n// SegTree<ll, OpMin, EMin> seg_min(n);\n\n// SegTreeMinArg\nstruct MinArgNode {\n long long val;\n int idx;\n};\n\n// 区間最小 & argmin\nstruct OpMinArg {\n MinArgNode operator()(const MinArgNode& a, const MinArgNode& b) const {\n if (a.val != b.val) return (a.val < b.val ? a : b);\n if (a.idx == -1) return b;\n if (b.idx == -1) return a;\n return (a.idx < b.idx ? a : b); // tie: 小さい idx\n }\n};\n\nstruct EMinArg {\n static constexpr long long INF = (long long)4e18;\n MinArgNode operator()() const { return MinArgNode{INF, -1}; }\n};\n// usage: SegTreeMinArg\n// int n = 10;\n// SegTree<MinArgNode, OpMinArg, EMinArg> seg_minarg(n);\n\n// // 値だけ代入する糖衣\n// auto point_set_val = [&](int pos, long long v) {\n// seg_minarg.point_set(pos, MinArgNode{v, pos});\n// };\n\n// point_set_val(3, 5);\n// point_set_val(7, 2);\n\n// MinArgNode res = seg_minarg.prod(0, n); // 全区間の最小 & その位置\n\n// ==============================\n// Generic Lazy Segment Tree\n// S: ノード型(例: {val, len})\n// F: 遅延(写像)型(例: 加算値)\n// 必要な関数: \n// op(S,S)->S : 区間結合(モノイド演算)\n// e()->S : Sの単位元\n// mapping(F,S)->S : SにFを適用\n// composition(Fnew, Fold)->F: 遅延の合成(先にFold→後でFnewがかかる形になるよう定義)\n// id()->F : Fの単位元\n// ==============================\ntemplate<\n class S, class F,\n class Op, class E,\n class Mapping, class Composition, class Id\n>\nstruct LazySegTree {\n int n = 0, size = 1, logn = 0;\n\n // ここで中の演算子たちをデフォルト初期化\n Op op{};\n E e{};\n Mapping mapping{};\n Composition composition{};\n Id id{};\n\n std::vector<S> d;\n std::vector<F> lz;\n\n LazySegTree() = default;\n explicit LazySegTree(int n_) { init(n_); }\n explicit LazySegTree(const std::vector<S>& a) { init(a); }\n\n void init(int n_) {\n n = n_;\n logn = 0;\n size = 1;\n while (size < n) size <<= 1, ++logn;\n d.assign(2 * size, e()); // E::operator() で単位元\n lz.assign(size, id()); // Id::operator() で遅延の単位元\n }\n\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n; i++) d[size + i] = a[i];\n for (int i = size - 1; i >= 1; i--) pull(i);\n }\n\n void set_point(int p, const S& x) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n d[p] = x;\n for (int i = 1; i <= logn; i++) pull(p >> i);\n }\n\n S get_point(int p) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n return d[p];\n }\n\n // 区間 [l, r) に f を適用\n void apply(int l, int r, const F& f) {\n if (l >= r) return;\n l += size; r += size;\n int l0 = l, r0 = r;\n for (int i = logn; i >= 1; i--) {\n if (((l0 >> i) << i) != l0) push(l0 >> i);\n if (((r0 >> i) << i) != r0) push((r0 - 1) >> i);\n }\n while (l < r) {\n if (l & 1) all_apply(l++, f);\n if (r & 1) all_apply(--r, f);\n l >>= 1; r >>= 1;\n }\n for (int i = 1; i <= logn; i++) {\n if (((l0 >> i) << i) != l0) pull(l0 >> i);\n if (((r0 >> i) << i) != r0) pull((r0 - 1) >> i);\n }\n }\n\n // 区間 [l, r) を畳み込み\n S prod(int l, int r) {\n if (l >= r) return e();\n l += size; r += size;\n for (int i = logn; i >= 1; i--) {\n if (((l >> i) << i) != l) push(l >> i);\n if (((r >> i) << i) != r) push((r - 1) >> i);\n }\n S sml = e(), smr = e();\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++]);\n if (r & 1) smr = op(d[--r], smr);\n l >>= 1; r >>= 1;\n }\n return op(sml, smr);\n }\n\n // 全体\n S all_prod() const { return d[1]; }\n\nprivate:\n void pull(int k) { d[k] = op(d[2*k], d[2*k+1]); }\n\n void all_apply(int k, const F& f) {\n d[k] = mapping(f, d[k]);\n if (k < size) lz[k] = composition(f, lz[k]);\n }\n\n void push(int k) {\n if (lz[k] != id()) { // F 型同士の比較(例: long long)\n all_apply(2*k, lz[k]);\n all_apply(2*k+1, lz[k]);\n lz[k] = id();\n }\n }\n};\n\n// ==============================\n// ここから具体インスタンス例\n// 共通ノード型(lenを持たせることで sum/max の両方に対応)\n// ==============================\nstruct Node {\n long long val; // 区間の値(和 or 最大)\n int len; // その区間の長さ(sumでのみ使用)\n};\n\n// -------- Range Add + Range Sum 用の関数群 --------\nstruct OpSumlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{a.val + b.val, a.len + b.len};\n }\n};\nstruct ESumlazy {\n Node operator()() const { return Node{0LL, 0}; } // 単位元\n};\nstruct MappingAddToSum {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add * 1LL * s.len, s.len};\n }\n};\nstruct ComposeAdd {\n long long operator()(long long fnew, long long fold) const {\n return fnew + fold;\n }\n};\nstruct IdAdd {\n long long operator()() const { return 0LL; }\n};\n\n// Range Add + Range Max\nstatic constexpr long long NEG_INF = -(1LL<<60);\nstruct OpMaxlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{std::max(a.val, b.val), a.len + b.len};\n }\n};\nstruct EMaxlazy {\n Node operator()() const { return Node{NEG_INF, 0}; }\n};\nstruct MappingAddToMax {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add, s.len};\n }\n};\n\n// ==============================\n// 使用例1: Range Add + Range Sum\n// ==============================\nvoid example_sum() {\n int n = 8;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpSumlazy, ESumlazy,\n MappingAddToSum, ComposeAdd, IdAdd>\n seg(init); // ← もう functor を渡さなくてよい\n\n seg.apply(2, 6, 5); // [2, 6) に +5\n std::cout << seg.all_prod().val << \"\\n\"; // 20\n std::cout << seg.prod(3, 5).val << \"\\n\"; // 10\n}\n\n// ==============================\n// 使用例2: Range Add + Range Max\n// ==============================\nvoid example_max() {\n int n = 10;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpMaxlazy, EMaxlazy,\n MappingAddToMax, ComposeAdd, IdAdd>\n seg(init); // ここも functor いらない\n\n seg.apply(2, 5, 1);\n seg.apply(4, 9, 3);\n std::cout << seg.all_prod().val << \"\\n\";\n}\n\n// 1-indexed Fenwick Tree (Binary Indexed Tree)\ntemplate <class T>\nstruct Fenwick {\n int n;\n vector<T> bit;\n\n Fenwick() : n(0) {}\n explicit Fenwick(int n) : n(n), bit(n + 1, T{}) {}\n\n // a[idx] += delta\n void add(int idx, T delta) {\n for (; idx <= n; idx += idx & -idx) bit[idx] += delta;\n }\n\n // prefix sum: a[1] + ... + a[idx]\n T sum(int idx) const {\n T s{};\n for (; idx > 0; idx -= idx & -idx) s += bit[idx];\n return s;\n }\n\n // range sum: a[l] + ... + a[r]\n T range_sum(int l, int r) const {\n if (l > r) return T{};\n return sum(r) - sum(l - 1);\n }\n\n // ---- ここから先は「順序統計」をやりたい人向けのオプション ----\n // すべての要素が「非負の整数」である前提で、\n // 最小の idx を返す: sum(idx) >= t (tは1..sum(n))\n // T が整数型のときのみ有効化\n template <class U = T, std::enable_if_t<std::is_integral_v<U>, int> = 0>\n int kth(U t) const {\n // 前提: すべての add が非負、bitの総和 >= t\n int idx = 0;\n U acc = 0;\n int step = 1;\n while ((step << 1) <= n) step <<= 1; // n以下の最大2冪\n for (int p = step; p; p >>= 1) {\n int nx = idx + p;\n if (nx <= n && acc + (U)bit[nx] < t) {\n acc += (U)bit[nx];\n idx = nx;\n }\n }\n return idx + 1; // 1-indexed\n }\n};\n \n// ===== 素数判定を行う =====\nstruct MillerRabin64 {\n static inline ull mul_mod(ull a, ull b, ull mod) {\n return (ull)((u128)a * b % mod);\n }\n static inline ull pow_mod(ull a, ull e, ull mod) {\n ull r = 1 % mod;\n a %= mod;\n while (e) {\n if (e & 1) r = mul_mod(r, a, mod);\n a = mul_mod(a, a, mod);\n e >>= 1;\n }\n return r;\n }\n static bool isPrime(ull n) {\n if (n < 2) return false;\n // 小さい素数で先に弾く\n static const ull smalls[] = {2,3,5,7,11,13,17,19,23,29,31,37};\n for (ull p : smalls) {\n if (n == p) return true;\n if (n % p == 0) return n == p;\n }\n // n-1 = d * 2^s2\n ull d = n - 1, s2 = 0;\n while (!(d & 1)) d >>= 1, ++s2;\n\n auto witness = [&](ull a) -> bool {\n if (!(a % n)) return false;\n ull x = pow_mod(a, d, n);\n if (x == 1 || x == n - 1) return false;\n for (ull i = 1; i < s2; i++) {\n x = mul_mod(x, x, n);\n if (x == n - 1) return false;\n }\n return true; // 合成数の証人\n };\n\n // 64bit 決定的基底\n static const ull bases[] = {\n 2ULL, 325ULL, 9375ULL, 28178ULL,\n 450775ULL, 9780504ULL, 1795265022ULL\n };\n for (ull a : bases) {\n if (!(a % n)) continue;\n if (witness(a)) return false;\n }\n return true;\n }\n};\nusing MR64 = MillerRabin64;\n\n// modint: mod計算をintを扱うように扱える構造体\n// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a#8-modint\ntemplate<int MOD> struct Fp {\n ll val;\n constexpr Fp(ll v = 0) noexcept : val(v % MOD) {\n if (val < 0) val += MOD;\n }\n constexpr int getmod() { return MOD; }\n constexpr Fp operator - () const noexcept {\n return val ? MOD - val : 0;\n }\n constexpr Fp operator + (const Fp& r) const noexcept { return Fp(*this) += r;}\n constexpr Fp operator - (const Fp& r) const noexcept { return Fp(*this) -= r;}\n constexpr Fp operator * (const Fp& r) const noexcept { return Fp(*this) *= r;}\n constexpr Fp operator / (const Fp& r) const noexcept { return Fp(*this) /= r;}\n constexpr Fp& operator += (const Fp& r) noexcept {\n val += r.val;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n constexpr Fp& operator -= (const Fp& r) noexcept {\n val -= r.val;\n if (val < 0) val += MOD;\n return *this;\n }\n constexpr Fp& operator *= (const Fp& r) noexcept {\n val = val * r.val % MOD;\n return *this;\n }\n constexpr Fp& operator /= (const Fp& r) noexcept {\n return *this *= modpow(r, MOD - 2);\n }\n // 前置 ++x\n constexpr Fp& operator++() noexcept {\n val++;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n\n // 後置 x++\n constexpr Fp operator++(int) noexcept {\n Fp tmp = *this;\n ++(*this);\n return tmp;\n }\n\n // 前置 --x\n constexpr Fp& operator--() noexcept {\n val--;\n if (val < 0) val += MOD;\n return *this;\n }\n\n // 後置 x--\n constexpr Fp operator--(int) noexcept {\n Fp tmp = *this;\n --(*this);\n return tmp;\n }\n constexpr bool operator == (const Fp& r) const noexcept {\n return this->val == r.val;\n }\n constexpr bool operator != (const Fp& r) const noexcept {\n return this->val != r.val;\n }\n constexpr bool operator < (const Fp& r) const noexcept { return this->val < r.val;}\n constexpr bool operator <= (const Fp& r) const noexcept { return this->val <= r.val;}\n constexpr bool operator > (const Fp& r) const noexcept { return this->val > r.val;}\n constexpr bool operator >= (const Fp& r) const noexcept { return this->val >= r.val;}\n friend constexpr ostream& operator << (ostream &os, const Fp<MOD>& x) {\n return os << x.val;\n }\n friend constexpr istream& operator >> (istream &is, Fp<MOD>& x) {\n ll v;\n is >> v;\n x = Fp<MOD>(v);\n return is;\n }\n friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, ll n) noexcept {\n if (n == 0) return 1;\n auto t = modpow(a, n / 2);\n t = t * t;\n if (n & 1) t = t * a;\n return t;\n }\n};\nusing mint = Fp<998244353>;\n\nint solve() {\n int n, q;\n cin >> n >> q;\n \n int size = 1;\n while (size < n) size <<= 1;\n const int SEG_LEN = size;\n const ll INF = (1LL << 31) - 1;\n vector<ll> seg_tree(SEG_LEN * 2, INF);\n \n auto update = [&](int idx, ll x) -> void {\n idx += SEG_LEN;\n seg_tree[idx] = x;\n while (true) {\n idx /= 2;\n if (idx == 0) break;\n seg_tree[idx] = min(seg_tree[idx * 2], seg_tree[idx * 2 + 1]);\n }\n };\n \n auto find = [&](int l, int r) -> ll {\n l += SEG_LEN;\n r += SEG_LEN;\n ll res = INF;\n while (l < r) {\n if (l & 1) res = min(res, seg_tree[l]), l++;\n l /= 2;\n if (r & 1) res = min(res, seg_tree[r - 1]), r--;\n r /= 2;\n }\n return res;\n };\n \n while (q--) {\n int com; ll x, y; cin >> com >> x >> y;\n \n if (com == 0) update(x, y);\n else cout << find(x, y + 1) << \"\\n\";\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5480, "score_of_the_acc": -0.186, "final_rank": 1 }, { "submission_id": "aoj_DSL_2_A_11059662", "code_snippet": "#include <bits/stdc++.h>\n#include <bit>\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing i128 = __int128_t;\nusing u128 = __uint128_t;\nusing pii = pair<int, int>;\nusing pic = pair<int, char>;\nusing pci = pair<char, int>;\nusing pll = pair<ll, ll>;\nusing pllc = pair<ll, char>;\n#define rep(i, a, n) for (int i = a; i < (n); i++)\n\ntemplate <class T, class U>\nstruct PairHash {\n static inline size_t hash_combine(size_t seed, size_t v) noexcept {\n // boost::hash_combine と同等の混合\n return seed ^ (v + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2));\n }\n size_t operator()(const pair<T,U>& p) const noexcept {\n size_t h1 = std::hash<T>{}(p.first);\n size_t h2 = std::hash<U>{}(p.second);\n return hash_combine(h1, h2);\n }\n};\n\npll operator+(const pll& a, const pll& b) {\n return {a.first + b.first, a.second + b.second};\n}\n\npll operator-(const pll& a, const pll& b) {\n return {a.first - b.first, a.second - b.second};\n}\n\npll operator-(const pll& a) {\n return {-a.first, -a.second};\n}\n\n// ===== プロトタイプ宣言 =====\nint solve();\n\n// ===== main関数 =====\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n return solve();\n}\n\n\nvoid prvec(vector<string> V) {\n for (const auto& v : V)\n cout << v << endl;\n}\n\nvoid prvec(vector<bool> V) {\n for (const auto& v : V)\n cout << boolalpha << setw(5) << setfill(' ') << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(vector<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(list<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(unordered_set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(multiset<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T1>\nvoid prvec(deque<T1> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\nvoid prvec(set<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, pair<T2, T3>> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : {\" << v.first << \" \" << v.second << \"}\" << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, vector<pair<T2, T3>>> V) {\n for (const auto& [k, v] : V) {\n cout << k << \" : \" ;\n for (const auto& [a, b] : v)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n }\n}\n\nvoid prvec(map<int, bool> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : \" << boolalpha << v << endl;\n}\n\nvoid prvec(map<string, pii> V) {\n for (const auto& [k, v] : V) \n cout << k << \" : \" << v.first << \" \" << v.second << endl;\n}\n\ntemplate <typename T>\nvoid prvec(map<pii, T> V) {\n for (const auto& [k, v] : V) \n cout << \"{\" << k.first << \", \" << k.second << \"}: \" << v << endl;\n}\n\nvoid prvec(map<int, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, stack<int>> V) {\n for (const auto& [k, stk] : V) {\n cout << k << \" : \";\n stack<int> stk2 = stk;\n while (!stk2.empty()) {\n int v = stk2.top(); stk2.pop();\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(vector<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<string, string>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, double>> V) {\n for (const auto& [a, b] : V)\n cout << fixed << setprecision(15) << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<char, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, char>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(unordered_map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(set<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, vector<int>>> V) {\n for (const auto& [a, vec] : V) {\n cout << a << \" : \";\n for (const auto& v : vec) cout << v << \" \";\n cout << endl;\n }\n}\n\nvoid prvec(vector<pair<int, set<int>>> V) {\n for (const auto& [a, st] : V) {\n cout << a << \" : \";\n for (const auto& v : st) cout << v << \" \";\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(vector<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(set<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\nvoid prvec(vector<tuple<T1, T2, T3, T4>> V) {\n for (const auto& [a, b, c, d] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \", \" << d << \"}, \";\n cout << endl;\n}\n\ntemplate<typename T, typename... Args>\nvoid prvec(std::priority_queue<T, Args...> pq) {\n while (!pq.empty()) {\n auto [f, s] = pq.top();\n cout << \"{\" << f << \", \" << s << \"}, \";\n pq.pop();\n }\n cout << \"\\n\";\n}\n\nclass UnionFind {\n private :\n vector<int> parent;\n vector<int> sz;\n vector<int> edge_count;\n \n public :\n UnionFind(int n) : parent(n), sz(n, 1), edge_count(n, 0) {\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n \n int find(int x) {\n if (parent[x] == x) return x;\n return parent[x] = find(parent[x]);\n }\n \n bool unite(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX == rootY) {\n \tedge_count[rootX]++;\n \treturn false; // cycle検出\n }\n \n if (sz[rootX] < sz[rootY]) swap(rootX, rootY);\n parent[rootY] = rootX;\n sz[rootX] += sz[rootY];\n edge_count[rootX] += edge_count[rootY] + 1;\n return true;\n }\n \n int getSize(int x) {\n return sz[find(x)];\n }\n \n int getEdges(int x) {\n \treturn edge_count[find(x)];\n }\n \n bool same(int x, int y) {\n return find(x) == find(y);\n }\n \n // 頂点数を new_n まで増やす (new_n <= 現在のサイズなら何もしない)\n void ensureSize(int new_n) {\n int old_n = parent.size();\n if (new_n <= old_n) return;\n parent.resize(new_n);\n sz.resize(new_n, 1);\n edge_count.resize(new_n, 0);\n // 新しく追加された i (old_n <= i < new_n) をルート+サイズ1に初期化\n for (int i = old_n; i < new_n; i++) {\n parent[i] = i;\n // sz[i] は resize の第二引数で 1 になっている\n }\n }\n \n // 頂点を1つ追加して、そのインデックスを返す\n int addVertex() {\n int idx = parent.size();\n parent.push_back(idx);\n sz.push_back(1);\n edge_count.push_back(0);\n return idx;\n } \n};\n\ntemplate <class Abel>\n// 重み付きUnionFindの定義\nstruct WeightedUnionFind {\n vector<int> parent, size;\n vector<Abel> diff_weight;\n\n WeightedUnionFind(int n)\n : parent(n), size(n, 1), diff_weight(n, Abel{}) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) {\n if (parent[x] == x) return x;\n int r = find(parent[x]);\n diff_weight[x] = diff_weight[x] + diff_weight[parent[x]];\n return parent[x] = r;\n }\n\n Abel weight(int x) {\n find(x);\n return diff_weight[x];\n }\n\n bool unite(int u, int v, Abel w) {\n Abel wu = weight(u), wv = weight(v);\n int ru = find(u), rv = find(v);\n if (ru == rv) {\n return (wv - wu == w); // すでに矛盾ないかチェック\n }\n\n Abel dw = w + wu - wv;\n\n // union by size(大きいほうに小さいほうをつける)\n if (size[ru] < size[rv]) {\n swap(ru, rv);\n swap(u, v);\n dw = -dw;\n }\n\n parent[rv] = ru;\n diff_weight[rv] = dw;\n size[ru] += size[rv];\n return true;\n }\n\n bool same(int x, int y) {\n return find(x) == find(y);\n }\n\n Abel diff(int x, int y) {\n return weight(y) - weight(x);\n }\n};\n\nstruct DSURollback {\n int n;\n vector<int> parent, sz;\n\n // 変更履歴: (結合された子root, 併合前の親rootのサイズ)\n // 子root = -1 は「何も結合しなかった(uniteで同根)」の印\n vector<pair<int,int>> hist;\n\n DSURollback(int n=0): n(n), parent(n), sz(n,1) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) const {\n // パス圧縮しない\n while (parent[x] != x) x = parent[x];\n return x;\n }\n\n bool unite(int x, int y) {\n x = find(x); y = find(y);\n if (x == y) { \n hist.emplace_back(-1, 0); // ダミー (巻き戻し整合用)\n return false; \n }\n if (sz[x] < sz[y]) swap(x, y); // x に y をくっつける(サイズ併合)\n\n // 履歴に「y が x にぶら下がる前の x のサイズ」を記録\n hist.emplace_back(y, sz[x]);\n\n parent[y] = x;\n sz[x] += sz[y];\n return true;\n }\n\n // 直前の unite を 1 回取り消す\n void rollback() {\n auto [y, old_szx] = hist.back(); hist.pop_back();\n if (y == -1) return; // 何もしていない unite の取消\n int x = parent[y];\n // 親子関係とサイズを元に戻す\n parent[y] = y;\n sz[x] = old_szx;\n }\n\n // スナップショット(この位置まで戻せる)\n int snapshot() const { return (int)hist.size(); }\n\n // 指定スナップショットへ戻す(複数回分まとめて取り消し)\n void rollback_to(int snap) {\n while ((int)hist.size() > snap) rollback();\n }\n\n bool same(int a, int b) { return find(a) == find(b); }\n int size(int x) { return sz[find(x)]; }\n};\n\ntemplate<class S, class Op, class E>\nstruct SegTree {\n int n0 = 0; // 元の配列の長さ\n int n = 1; // セグ木内部のサイズ(2べき)\n std::vector<S> d;\n\n Op op{}; // 区間結合\n E e{}; // 単位元\n\n SegTree() = default;\n explicit SegTree(int n_) { init(n_); }\n explicit SegTree(const std::vector<S>& a) { init(a); }\n\n // 要素数 n_ で初期化(全部 e())\n void init(int n_) {\n n0 = n_;\n n = 1;\n while (n < n_) n <<= 1;\n d.assign(2 * n, e());\n }\n\n // 初期配列 a から構築\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n0; i++) d[n + i] = a[i];\n for (int i = n - 1; i >= 1; i--) {\n d[i] = op(d[i << 1], d[i << 1 | 1]);\n }\n }\n\n // 点代入: A[pos] = val\n void point_set(int pos, const S& val) {\n int k = pos + n;\n d[k] = val;\n for (k >>= 1; k; k >>= 1) {\n d[k] = op(d[k << 1], d[k << 1 | 1]);\n }\n }\n\n // 点取得\n S get(int pos) const {\n return d[pos + n];\n }\n\n // 区間 [l, r) を畳み込み(LazySegTree に合わせて prod という名前に)\n S prod(int l, int r) const {\n S L = e(), R = e();\n for (l += n, r += n; l < r; l >>= 1, r >>= 1) {\n if (l & 1) L = op(L, d[l++]);\n if (r & 1) R = op(d[--r], R);\n }\n return op(L, R);\n }\n\n // 全体\n S all_prod() const {\n return d[1];\n }\n};\n\n// 区間和\nstruct OpSum {\n ll operator()(ll a, ll b) const { return a + b; }\n};\n\n// 単位元(0)\nstruct ESum {\n ll operator()() const { return 0LL; }\n};\n\n// usage: RSQ(SegTreeSum)\n // int n = 10;\n // SegTree<ll, OpSum, ESum> seg(n);\n \n // // A[i] = i をセット\n // for (int i = 0; i < n; i++) seg.point_set(i, i);\n\n // // [l, r) の和\n // ll s = seg.prod(2, 7);\n\n// 区間最大\nstruct OpMax {\n ll operator()(ll a, ll b) const { return std::max(a, b); }\n};\n\nstruct EMax {\n static constexpr ll NEG_INF = (ll)-4e18;\n ll operator()() const { return NEG_INF; }\n};\n// usage: RMaxQ(SegTree)\n// SegTree<ll, OpMax, EMax> seg_max(n);\n\n// 区間最小\nstruct OpMin {\n ll operator()(ll a, ll b) const { return std::min(a, b); }\n};\n\nstruct EMin {\n static constexpr ll INF = (ll)4e18;\n ll operator()() const { return INF; }\n};\n// usage: RMinQ(SeegTree)\n// SegTree<ll, OpMin, EMin> seg_min(n);\n\n// SegTreeMinArg\nstruct MinArgNode {\n long long val;\n int idx;\n};\n\n// 区間最小 & argmin\nstruct OpMinArg {\n MinArgNode operator()(const MinArgNode& a, const MinArgNode& b) const {\n if (a.val != b.val) return (a.val < b.val ? a : b);\n if (a.idx == -1) return b;\n if (b.idx == -1) return a;\n return (a.idx < b.idx ? a : b); // tie: 小さい idx\n }\n};\n\nstruct EMinArg {\n static constexpr long long INF = (long long)4e18;\n MinArgNode operator()() const { return MinArgNode{INF, -1}; }\n};\n// usage: SegTreeMinArg\n// int n = 10;\n// SegTree<MinArgNode, OpMinArg, EMinArg> seg_minarg(n);\n\n// // 値だけ代入する糖衣\n// auto point_set_val = [&](int pos, long long v) {\n// seg_minarg.point_set(pos, MinArgNode{v, pos});\n// };\n\n// point_set_val(3, 5);\n// point_set_val(7, 2);\n\n// MinArgNode res = seg_minarg.prod(0, n); // 全区間の最小 & その位置\n\n// ==============================\n// Generic Lazy Segment Tree\n// S: ノード型(例: {val, len})\n// F: 遅延(写像)型(例: 加算値)\n// 必要な関数: \n// op(S,S)->S : 区間結合(モノイド演算)\n// e()->S : Sの単位元\n// mapping(F,S)->S : SにFを適用\n// composition(Fnew, Fold)->F: 遅延の合成(先にFold→後でFnewがかかる形になるよう定義)\n// id()->F : Fの単位元\n// ==============================\ntemplate<\n class S, class F,\n class Op, class E,\n class Mapping, class Composition, class Id\n>\nstruct LazySegTree {\n int n = 0, size = 1, logn = 0;\n\n // ここで中の演算子たちをデフォルト初期化\n Op op{};\n E e{};\n Mapping mapping{};\n Composition composition{};\n Id id{};\n\n std::vector<S> d;\n std::vector<F> lz;\n\n LazySegTree() = default;\n explicit LazySegTree(int n_) { init(n_); }\n explicit LazySegTree(const std::vector<S>& a) { init(a); }\n\n void init(int n_) {\n n = n_;\n logn = 0;\n size = 1;\n while (size < n) size <<= 1, ++logn;\n d.assign(2 * size, e()); // E::operator() で単位元\n lz.assign(size, id()); // Id::operator() で遅延の単位元\n }\n\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n; i++) d[size + i] = a[i];\n for (int i = size - 1; i >= 1; i--) pull(i);\n }\n\n void set_point(int p, const S& x) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n d[p] = x;\n for (int i = 1; i <= logn; i++) pull(p >> i);\n }\n\n S get_point(int p) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n return d[p];\n }\n\n // 区間 [l, r) に f を適用\n void apply(int l, int r, const F& f) {\n if (l >= r) return;\n l += size; r += size;\n int l0 = l, r0 = r;\n for (int i = logn; i >= 1; i--) {\n if (((l0 >> i) << i) != l0) push(l0 >> i);\n if (((r0 >> i) << i) != r0) push((r0 - 1) >> i);\n }\n while (l < r) {\n if (l & 1) all_apply(l++, f);\n if (r & 1) all_apply(--r, f);\n l >>= 1; r >>= 1;\n }\n for (int i = 1; i <= logn; i++) {\n if (((l0 >> i) << i) != l0) pull(l0 >> i);\n if (((r0 >> i) << i) != r0) pull((r0 - 1) >> i);\n }\n }\n\n // 区間 [l, r) を畳み込み\n S prod(int l, int r) {\n if (l >= r) return e();\n l += size; r += size;\n for (int i = logn; i >= 1; i--) {\n if (((l >> i) << i) != l) push(l >> i);\n if (((r >> i) << i) != r) push((r - 1) >> i);\n }\n S sml = e(), smr = e();\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++]);\n if (r & 1) smr = op(d[--r], smr);\n l >>= 1; r >>= 1;\n }\n return op(sml, smr);\n }\n\n // 全体\n S all_prod() const { return d[1]; }\n\nprivate:\n void pull(int k) { d[k] = op(d[2*k], d[2*k+1]); }\n\n void all_apply(int k, const F& f) {\n d[k] = mapping(f, d[k]);\n if (k < size) lz[k] = composition(f, lz[k]);\n }\n\n void push(int k) {\n if (lz[k] != id()) { // F 型同士の比較(例: long long)\n all_apply(2*k, lz[k]);\n all_apply(2*k+1, lz[k]);\n lz[k] = id();\n }\n }\n};\n\n// ==============================\n// ここから具体インスタンス例\n// 共通ノード型(lenを持たせることで sum/max の両方に対応)\n// ==============================\nstruct Node {\n long long val; // 区間の値(和 or 最大)\n int len; // その区間の長さ(sumでのみ使用)\n};\n\n// -------- Range Add + Range Sum 用の関数群 --------\nstruct OpSumlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{a.val + b.val, a.len + b.len};\n }\n};\nstruct ESumlazy {\n Node operator()() const { return Node{0LL, 0}; } // 単位元\n};\nstruct MappingAddToSum {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add * 1LL * s.len, s.len};\n }\n};\nstruct ComposeAdd {\n long long operator()(long long fnew, long long fold) const {\n return fnew + fold;\n }\n};\nstruct IdAdd {\n long long operator()() const { return 0LL; }\n};\n\n// Range Add + Range Max\nstatic constexpr long long NEG_INF = -(1LL<<60);\nstruct OpMaxlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{std::max(a.val, b.val), a.len + b.len};\n }\n};\nstruct EMaxlazy {\n Node operator()() const { return Node{NEG_INF, 0}; }\n};\nstruct MappingAddToMax {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add, s.len};\n }\n};\n\n// ==============================\n// 使用例1: Range Add + Range Sum\n// ==============================\nvoid example_sum() {\n int n = 8;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpSumlazy, ESumlazy,\n MappingAddToSum, ComposeAdd, IdAdd>\n seg(init); // ← もう functor を渡さなくてよい\n\n seg.apply(2, 6, 5); // [2, 6) に +5\n std::cout << seg.all_prod().val << \"\\n\"; // 20\n std::cout << seg.prod(3, 5).val << \"\\n\"; // 10\n}\n\n// ==============================\n// 使用例2: Range Add + Range Max\n// ==============================\nvoid example_max() {\n int n = 10;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpMaxlazy, EMaxlazy,\n MappingAddToMax, ComposeAdd, IdAdd>\n seg(init); // ここも functor いらない\n\n seg.apply(2, 5, 1);\n seg.apply(4, 9, 3);\n std::cout << seg.all_prod().val << \"\\n\";\n}\n\n// 1-indexed Fenwick Tree (Binary Indexed Tree)\ntemplate <class T>\nstruct Fenwick {\n int n;\n vector<T> bit;\n\n Fenwick() : n(0) {}\n explicit Fenwick(int n) : n(n), bit(n + 1, T{}) {}\n\n // a[idx] += delta\n void add(int idx, T delta) {\n for (; idx <= n; idx += idx & -idx) bit[idx] += delta;\n }\n\n // prefix sum: a[1] + ... + a[idx]\n T sum(int idx) const {\n T s{};\n for (; idx > 0; idx -= idx & -idx) s += bit[idx];\n return s;\n }\n\n // range sum: a[l] + ... + a[r]\n T range_sum(int l, int r) const {\n if (l > r) return T{};\n return sum(r) - sum(l - 1);\n }\n\n // ---- ここから先は「順序統計」をやりたい人向けのオプション ----\n // すべての要素が「非負の整数」である前提で、\n // 最小の idx を返す: sum(idx) >= t (tは1..sum(n))\n // T が整数型のときのみ有効化\n template <class U = T, std::enable_if_t<std::is_integral_v<U>, int> = 0>\n int kth(U t) const {\n // 前提: すべての add が非負、bitの総和 >= t\n int idx = 0;\n U acc = 0;\n int step = 1;\n while ((step << 1) <= n) step <<= 1; // n以下の最大2冪\n for (int p = step; p; p >>= 1) {\n int nx = idx + p;\n if (nx <= n && acc + (U)bit[nx] < t) {\n acc += (U)bit[nx];\n idx = nx;\n }\n }\n return idx + 1; // 1-indexed\n }\n};\n \n// ===== 素数判定を行う =====\nstruct MillerRabin64 {\n static inline ull mul_mod(ull a, ull b, ull mod) {\n return (ull)((u128)a * b % mod);\n }\n static inline ull pow_mod(ull a, ull e, ull mod) {\n ull r = 1 % mod;\n a %= mod;\n while (e) {\n if (e & 1) r = mul_mod(r, a, mod);\n a = mul_mod(a, a, mod);\n e >>= 1;\n }\n return r;\n }\n static bool isPrime(ull n) {\n if (n < 2) return false;\n // 小さい素数で先に弾く\n static const ull smalls[] = {2,3,5,7,11,13,17,19,23,29,31,37};\n for (ull p : smalls) {\n if (n == p) return true;\n if (n % p == 0) return n == p;\n }\n // n-1 = d * 2^s2\n ull d = n - 1, s2 = 0;\n while (!(d & 1)) d >>= 1, ++s2;\n\n auto witness = [&](ull a) -> bool {\n if (!(a % n)) return false;\n ull x = pow_mod(a, d, n);\n if (x == 1 || x == n - 1) return false;\n for (ull i = 1; i < s2; i++) {\n x = mul_mod(x, x, n);\n if (x == n - 1) return false;\n }\n return true; // 合成数の証人\n };\n\n // 64bit 決定的基底\n static const ull bases[] = {\n 2ULL, 325ULL, 9375ULL, 28178ULL,\n 450775ULL, 9780504ULL, 1795265022ULL\n };\n for (ull a : bases) {\n if (!(a % n)) continue;\n if (witness(a)) return false;\n }\n return true;\n }\n};\nusing MR64 = MillerRabin64;\n\n// modint: mod計算をintを扱うように扱える構造体\n// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a#8-modint\ntemplate<int MOD> struct Fp {\n ll val;\n constexpr Fp(ll v = 0) noexcept : val(v % MOD) {\n if (val < 0) val += MOD;\n }\n constexpr int getmod() { return MOD; }\n constexpr Fp operator - () const noexcept {\n return val ? MOD - val : 0;\n }\n constexpr Fp operator + (const Fp& r) const noexcept { return Fp(*this) += r;}\n constexpr Fp operator - (const Fp& r) const noexcept { return Fp(*this) -= r;}\n constexpr Fp operator * (const Fp& r) const noexcept { return Fp(*this) *= r;}\n constexpr Fp operator / (const Fp& r) const noexcept { return Fp(*this) /= r;}\n constexpr Fp& operator += (const Fp& r) noexcept {\n val += r.val;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n constexpr Fp& operator -= (const Fp& r) noexcept {\n val -= r.val;\n if (val < 0) val += MOD;\n return *this;\n }\n constexpr Fp& operator *= (const Fp& r) noexcept {\n val = val * r.val % MOD;\n return *this;\n }\n constexpr Fp& operator /= (const Fp& r) noexcept {\n return *this *= modpow(r, MOD - 2);\n }\n // 前置 ++x\n constexpr Fp& operator++() noexcept {\n val++;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n\n // 後置 x++\n constexpr Fp operator++(int) noexcept {\n Fp tmp = *this;\n ++(*this);\n return tmp;\n }\n\n // 前置 --x\n constexpr Fp& operator--() noexcept {\n val--;\n if (val < 0) val += MOD;\n return *this;\n }\n\n // 後置 x--\n constexpr Fp operator--(int) noexcept {\n Fp tmp = *this;\n --(*this);\n return tmp;\n }\n constexpr bool operator == (const Fp& r) const noexcept {\n return this->val == r.val;\n }\n constexpr bool operator != (const Fp& r) const noexcept {\n return this->val != r.val;\n }\n constexpr bool operator < (const Fp& r) const noexcept { return this->val < r.val;}\n constexpr bool operator <= (const Fp& r) const noexcept { return this->val <= r.val;}\n constexpr bool operator > (const Fp& r) const noexcept { return this->val > r.val;}\n constexpr bool operator >= (const Fp& r) const noexcept { return this->val >= r.val;}\n friend constexpr ostream& operator << (ostream &os, const Fp<MOD>& x) {\n return os << x.val;\n }\n friend constexpr istream& operator >> (istream &is, Fp<MOD>& x) {\n ll v;\n is >> v;\n x = Fp<MOD>(v);\n return is;\n }\n friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, ll n) noexcept {\n if (n == 0) return 1;\n auto t = modpow(a, n / 2);\n t = t * t;\n if (n & 1) t = t * a;\n return t;\n }\n};\nusing mint = Fp<998244353>;\n\nint solve() {\n int n, q;\n cin >> n >> q;\n \n const int SEG_LEN = n * 2 + 5;\n const ll INF = (1LL << 31) - 1;\n vector<ll> seg_tree(SEG_LEN * 2, INF);\n \n auto update = [&](int idx, ll x) -> void {\n idx += SEG_LEN;\n seg_tree[idx] = x;\n while (true) {\n idx /= 2;\n if (idx == 0) break;\n seg_tree[idx] = min(seg_tree[idx * 2], seg_tree[idx * 2 + 1]);\n }\n };\n \n auto find = [&](int l, int r) -> ll {\n l += SEG_LEN;\n r += SEG_LEN;\n ll res = INF;\n while (l < r) {\n if (l & 1) res = min(res, seg_tree[l]), l++;\n l /= 2;\n if (r & 1) res = min(res, seg_tree[r - 1]), r--;\n r /= 2;\n }\n return res;\n };\n \n while (q--) {\n int com; ll x, y; cin >> com >> x >> y;\n \n if (com == 0) update(x, y);\n else cout << find(x, y + 1) << \"\\n\";\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6556, "score_of_the_acc": -0.3294, "final_rank": 4 }, { "submission_id": "aoj_DSL_2_A_11056954", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define oke cout << \"Yes\" << '\\n';\n#define dame cout << \"No\" << '\\n';\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\nusing Hai2 = vector<vector<ll>>;\nusing HaiW = vector<vector<pair<ll,ll>>>;\nusing HaiB = vector<vector<bool>>;\nusing Hai3 = vector<vector<vector<ll>>>;\n\n//0インデックスで関数に入れる\nvector<ll>seg;\nll v=1;\n\nvoid init(ll N){\n while(N>v){\n v*=2;\n }\n seg.resize(v*2);\n rep(i,v*2){\n seg[i]=(1<<31)-1;\n }\n}\n\nvoid update(ll X,ll Y){\n X+=v;\n seg[X]=Y;\n\n ll f=X/2;\n while(f>0){\n seg[f]=min(seg[f*2],seg[f*2+1]);\n f/=2;\n }\n}\n\n//a以上b以下 L=0 R=V-1 v=1で関数に入れる\nll query(ll L,ll R,ll a,ll b,ll v){\n if(a<=L && R<=b) return seg[v];\n\n if(b<L || R<a) return (1<<31)-1;\n\n ll T=0;\n ll mid=(L+R)/2;\n T=min(query(L,mid,a,b,v*2),query(mid+1,R,a,b,v*2+1));\n\n return T;\n}\n\nint main() {\n\tcout << fixed << setprecision(15);\n ll N,Q;\n cin>>N>>Q;\n init(N);\n rep(i,Q){\n int q;\n cin>>q;\n if(q==0){\n ll t,x;\n cin>>t>>x;\n update(t,x);\n }else{\n ll s,t;\n cin>>s>>t;\n cout<<query(0,v-1,s,t,1)<<endl;\n }\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5164, "score_of_the_acc": -0.9217, "final_rank": 16 }, { "submission_id": "aoj_DSL_2_A_11052939", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (1LL << 31) - 1; // 初期値は 2^31-1\n\nstruct SegmentTree {\n int SEG_LEN;\n vector<ll> tree;\n\n SegmentTree(int size) {\n SEG_LEN = 1;\n while (SEG_LEN < size) SEG_LEN <<= 1;\n tree.assign(2*SEG_LEN, INF);\n }\n\n void update(int index, ll x) {\n index += SEG_LEN;\n tree[index] = x;\n while (index > 1) {\n index >>= 1;\n tree[index] = min(tree[index*2], tree[index*2+1]);\n }\n }\n\n //[l, r]の最小値を取得\n ll query(int l, int r) {\n l += SEG_LEN;\n r += SEG_LEN + 1; //閉区間 [l,r]に対応\n\n ll result = INF;\n while (l < r) {\n if (l & 1) result = min(result, tree[l++]);\n if (r & 1) result = min(result, tree[--r]);\n l >>= 1;\n r >>= 1;\n }\n return result;\n }\n};\n\nint main() {\n int N, Q;\n cin >> N >> Q;\n\n SegmentTree seg(N);\n for (int qi = 0; qi < Q; qi++) {\n int type; cin >> type;\n if (type == 0) {\n int index; ll x;\n cin >> index >> x;\n seg.update(index, x);\n } else if (type == 1) {\n int s, t;\n cin >> s >> t;\n ll result = seg.query(s, t);\n cout << result << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5180, "score_of_the_acc": -0.9238, "final_rank": 17 }, { "submission_id": "aoj_DSL_2_A_11047993", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n\n//最小全域木\nll Kruskal(const WeightedGraph &G) {\n return 0;\n}\n\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n, sz;\n vector<long long> node;\n\n SegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, INF);\n }\n SegTree(vector<long long> a) {\n sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = min(node[2*i+1], node[2*i+2]);\n }\n //[a,b)における最小値\n long long getmin(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return INF;\n if(a <= l and r <= b) return node[k];\n\n long long vl = getmin(a, b, 2*k+1, l, (l+r)/2);\n long long vr = getmin(a, b, 2*k+2, (l+r)/2, r);\n return min(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = min(node[2*i+1], node[2*i+2]);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int getminindex(int a, int b, long long x, int l = 0, int r = -1) {\n return 0;\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n lazy.resize(2*n-1, 0);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = node[2*i+1] + node[2*i+2];\n }\n\n void eval(int k, int l, int r) {\n if(lazy[k] != 0) {\n node[k] += lazy[k];\n\n if(r - l > 1) {\n lazy[2*k+1] += lazy[k]/2;\n lazy[2*k+2] += lazy[k]/2;\n }\n\n lazy[k] = 0;\n }\n }\n //区間[a,b)に値xを加算\n void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n \n eval(k, l, r);\n\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] += (r-l)*x;\n eval(k, l, r);\n }else {\n add(a, b, x, 2*k+1, l, (l+r)/2);\n add(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = node[2*k+1] + node[2*k+2];\n }\n }\n //区間[a,b)の和を取得\n ll getsum(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return 0;\n\n eval(k, l, r);\n if(a <= l and r <= b) return node[k];\n ll vl = getsum(a, b, 2*k+1, l, (l+r)/2);\n ll vr = getsum(a, b, 2*k+2, (l+r)/2, r);\n return vl + vr;\n }\n};\n//平方分割\nstruct Backet {\n vector<ll> array;\n vector<ll> backet;\n int N, M;\n\n Backet(vector<ll> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n //a_i + ... + a_j\n void add(int i, ll x) {\n array[i] += x;\n backet[i/M] += x;\n }\n ll getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n ll s = 0;\n if(l > r) {\n REP(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n REP(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, Q; cin >> N >> Q;\n vll A(N, 2147483647);\n SegTree seg(A);\n while(Q--) {\n int com, x, y; cin >> com >> x >> y;\n if(com == 0) {\n seg.update(x, y);\n }else {\n cout << seg.getmin(x, y+1) << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 6748, "score_of_the_acc": -1.2439, "final_rank": 19 }, { "submission_id": "aoj_DSL_2_A_11040902", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass segmentTree{\n int n;\n vector<int> data;\n int ie=INT_MAX;\n \n public:\n segmentTree(int _n) : n(1) {\n while(n<_n) n<<=1;\n data.assign(2*n,ie);\n }\n \n void update(int i,int x){\n i+=n;\n data[i]=x;\n while(i>0){\n i=(i-1)/2;\n data[i]=min(data[i*2+1],data[i*2+2]);\n }\n }\n\n int find(int i){\n return find(i,i);\n }\n\n int find(int l,int r){\n int L=l+n,R=r+n+1;\n int res=ie;\n while(L<R){\n if((L&1)==0){\n if(res>data[L]){\n res=data[L];\n }\n L++;\n }\n if((R&1)==0){\n R--;\n if(res>data[R]){\n res=data[R];\n }\n }\n L>>=1;\n R>>=1;\n }\n return res;\n }\n};\n\nint main(){\n int N,Q;\n cin>>N>>Q;\n segmentTree seg(N);\n while(Q--){\n int type;\n cin>>type;\n if(type==0){\n int x,y;\n cin>>x>>y;\n seg.update(x,y);\n }else if(type==1){\n int x,y;\n cin>>x>>y;\n cout<<seg.find(x,y)<<\"\\n\";\n }else assert(false);\n }\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4352, "score_of_the_acc": -0.4802, "final_rank": 5 }, { "submission_id": "aoj_DSL_2_A_11032310", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\n#define rep(i,n,m) for(int i=(int)(n);i < (int)(m); i++)\n#define repm(i,n,m) for(int i=(int)(n);i >= (int)(m); i--)\n// #define _GLIBCXX_DEBUG\nusing namespace std;\n\n/*\nfa: 値の更新をする際に操作を指定する関数 || ラムダ式で関数を作る || 例: RSQ -> auto fa = [](int &x1, int &x2){ return x1 + x2; }; \nfx: クエリでやる操作を指定する関数 || ラムダ式で関数を作る || 例: RMQ -> auto fx = [](int &x1, int &x2){ return min(x1, x2); }; \nex: fx の 単位元 || 例: RMQ -> int ex = numeric_limit<int>::max();, RSQ -> int ex = 0;\n*/\n\ntemplate<class X>\nstruct SegTree{\n using FX = function<X(X, X)>;\n int n;\n FX fx, fa;\n const X ex;\n vector<X> dat;\n\n SegTree(int n_, FX fa_, FX fx_, X ex_) : n(), fa(fa_), fx(fx_), ex(ex_), dat(n_ * 4, ex){\n int x = 1;\n while(x < n_){\n x *= 2;\n }\n n = x;\n }\n\n void set(int i, X val){\n dat[i + n - 1] = val;\n }\n void build(){\n for(int i = n - 2; i >= 0; i--){\n dat[i] = fx(dat[2 * i + 1], dat[2 * i + 2]);\n }\n }\n\n void update(int i, X val){ // 0-index\n i += n - 1;\n dat[i] = fa(dat[i], val);\n while(i > 0){\n i = (i - 1) / 2;\n dat[i] = fx(dat[2 * i + 1], dat[2 * i + 2]);\n }\n }\n\n X query(int a, int b){ // 0-index\n return query_sub(a, b, 0, 0, n);\n }\n X query_sub(int a, int b, int k, int l, int r){ // a,b :探索範囲の指定 || k:今調べている dat の idx || l,r: dat[k]の示す範囲\n if(r <= a or b <= l){\n return ex;\n }\n else if(a <= l and r <= b){\n return dat[k];\n }\n else{\n X vl = query_sub(a, b, k * 2 + 1, l, (l + r) / 2);\n X vr = query_sub(a, b, k * 2 + 2, (l + r) / 2, r);\n return fx(vl, vr);\n }\n }\n};\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n\n int n,q;\n cin >> n >> q;\n\n auto fa = [](int x1, int x2){ return x2; };\n auto fx = [](int x1, int x2){ return min(x1, x2); };\n int ex = numeric_limits<int>::max();\n SegTree<int> RMQ(n, fa, fx, ex);\n\n while(q--){\n int op;\n cin >> op;\n\n if(op == 0){\n int x,y;\n cin >> x >> y;\n RMQ.update(x, y);\n }\n\n if(op == 1){\n int x,y;\n cin >> x >> y;\n cout << RMQ.query(x, y + 1) << '\\n';\n }\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 4664, "score_of_the_acc": -0.2995, "final_rank": 3 }, { "submission_id": "aoj_DSL_2_A_11026636", "code_snippet": "/*\n\t平方分割\n*/\n#include<iostream>\n#include<vector>\n#include<cmath>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\n\tint n, q, s;\n\tcin >> n >> q;\n\ts = sqrt(n);\n\tlong st = (1L << 31) - 1;\n\tvector<long> a(n, st), mnum((n + s - 1) / s, st);\n\tlong com, x, y;\n\twhile (q--) {\n\t\tcin >> com >> x >> y;\n\t\tif (com) {\n\t\t\tlong m = st;\n\t\t\tif (x == y) m = a[x];\n\t\t\telse if (x / s == y / s) {\n\t\t\t\tfor (int i = x; i <= y; i++) m = min(m, a[i]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (int i = x / s + 1, j = y / s; i < j; i++) m = min(m, mnum[i]);\n\t\t\t\tfor (int i = x, j = (x / s + 1) * s; i < j; i++) m = min(m, a[i]);\n\t\t\t\tfor (int i = y, j = y / s * s; i >= j; i--) m = min(m, a[i]);\n\t\t\t}\n\t\t\tcout << m << endl;\n\t\t}\n\t\telse {\n\t\t\tif (mnum[x / s] == a[x]) mnum[x / s] = st;\n\t\t\ta[x] = y;\n\t\t\tfor (int i = x / s * s, j = i + s; i < j; i++) mnum[x / s] = min(mnum[x / s], a[i]);\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 4096, "score_of_the_acc": -0.6683, "final_rank": 8 }, { "submission_id": "aoj_DSL_2_A_11013841", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct lseg {\n using T = int; // セグ木の型\n using S = int; // 遅延評価の型\n T id = 1e9; // 初期値\n S lid = 0; // 遅延評価の初期値\n T f(T x, T y) { return min(x, y); } // 使用する計算\n T f2(T x, S y) { return x + y; } // 遅延評価を適用する関数\n S f3(S x, S y) { return x + y; } // 遅延評価をマージする関数\n vector<T> data;\n vector<S> lazy;\n int size;\n // 要素数を指定して構築\n lseg(int n) {\n for (size = 1; size < n; size <<= 1);\n data.resize(2 * size, id);\n lazy.resize(2 * size, lid);\n }\n // 配列を与えて構築(なくてもいい)\n lseg(const vector<T> &n) : lseg(n.size()) {\n for (int i = 0; i < n.size(); i++) data[size + i] = n[i];\n for (int i = size - 1; i >= 1; i--) data[i] = f(data[i << 1], data[i << 1 | 1]);\n }\n // 遅延評価を伝搬\n void eval(int k) {\n if (lazy[k] != lid) {\n data[k] = f2(data[k], lazy[k]);\n if (k < size) {\n lazy[k << 1] = f3(lazy[k << 1], lazy[k]);\n lazy[k << 1 | 1] = f3(lazy[k << 1 | 1], lazy[k]);\n }\n lazy[k] = lid;\n }\n }\n // 再帰型のクエリ\n T query(int l, int r, int k = 1, int a = 0, int b = -1) {\n if (b < 0) b = size;\n if (r <= a || b <= l) return id;\n eval(k);\n if (l <= a && b <= r) return data[k];\n return f(query(l, r, k << 1, a, (a + b) / 2), query(l, r, k << 1 | 1, (a + b) / 2, b));\n }\n // ある地点の値を更新する\n void set(int l, int r, S v, int k = 1, int a = 0, int b = -1) {\n if (b < 0) b = size;\n if (r <= a || b <= l) return;\n eval(k);\n if (l <= a && b <= r) {\n lazy[k] = f3(lazy[k], v);\n eval(k);\n } else {\n set(l, r, v, k << 1, a, (a + b) / 2);\n set(l, r, v, k << 1 | 1, (a + b) / 2, b);\n data[k] = f(data[k << 1], data[k << 1 | 1]);\n }\n }\n // ある地点の値を取得する\n T get(int k, int os = -1) {\n if (os < 0) k += size;\n if (k != 1) get(k >> 1, 0);\n eval(k);\n return data[k];\n }\n};\n\nstruct seg {\n using T = int; // セグ木の型\n T id = INT_MAX; // 初期値\n T f(T x, T y) { return min(x, y); } // 使用する計算\n vector<T> data;\n int size;\n // 要素数を指定して構築\n seg(int n) {\n for (size = 1; size < n; size <<= 1);\n data.resize(2 * size, id);\n }\n // 配列を与えて構築(なくてもいい)\n seg(const vector<T> &n) : seg(n.size()) {\n for (int i = 0; i < n.size(); i++) data[size + i] = n[i];\n for (int i = size - 1; i >= 1; i--) data[i] = f(data[i << 1], data[i << 1 | 1]);\n }\n // 再帰型のクエリ\n T query(int l, int r, int k = 1, int a = 0, int b = -1) {\n if (b < 0) b = size;\n if (r <= a || b <= l) return id;\n if (l <= a && b <= r) return data[k];\n return f(query(l, r, k << 1, a, (a + b) / 2), query(l, r, k << 1 | 1, (a + b) / 2, b));\n }\n // ある地点の値を更新する\n void set(int k, T x) {\n k += size;\n data[k] = x;\n while (k > 1) {\n k >>= 1;\n data[k] = f(data[k << 1], data[k << 1 | 1]);\n }\n }\n // ある地点の値を取得する\n T get(int k) { return data[k + size]; }\n // 二分探索(sumセグ木用)\n int lower_bound(T v, int k = 1) {\n if (data[k] < v) return -1;\n if (k > size) return k;\n if (data[k << 1] >= v)\n return lower_bound(v, k << 1);\n else\n return lower_bound(v - data[k << 1], k << 1 | 1);\n }\n};\n\n/*\n遅セグについて\n\n<区間加算 / minセグ木>\nusing T = int;\nusing S = int;\nT id = INT_MAX;\nS lid = 0;\nT f(T x, T y) { return min(x, y); }\nT f2(T x, S y) { return x + y; }\nS f3(S x, S y) { return x + y; }\n\n<区間加算 / maxセグ木>\nusing T = int;\nusing S = int;\nT id = INT_MIN;\nS lid = 0;\nT f(T x, T y) { return max(x, y); }\nT f2(T x, S y) { return x + y; }\nS f3(S x, S y) { return x + y; }\n\n<区間加算 / sumセグ木>\nstruct T {\n int v, sz;\n};\nusing S = int;\nT id = {0, 0};\nS lid = 0;\nT f(T x, T y) { return {x.v + y.v, x.sz + y.sz}; }\nT f2(T x, S y) { return {x.v + y * x.sz, x.sz}; }\nS f3(S x, S y) { return x + y; }\n\n<区間変更 / minセグ木>\nusing T = int;\nusing S = int;\nT id = INT_MAX;\nS lid = INT_MAX;\nT f(T x, T y) { return min(x, y); }\nT f2(T x, S y) { return y == lid ? x : y; }\nS f3(S x, S y) { return y == lid ? x : y; }\n\n<区間変更 / maxセグ木>\nusing T = int;\nusing S = int;\nT id = INT_MIN;\nS lid = INT_MIN;\nT f(T x, T y) { return max(x, y); }\nT f2(T x, S y) { return y == lid ? x : y; }\nS f3(S x, S y) { return y == lid ? x : y; }\n\n<区間変更 / sumセグ木>\nstruct T {\n int v, sz;\n};\nusing S = int;\nT id = {0, 0};\nS lid = INT_MAX;\nT f(T x, T y) { return {x.v + y.v, x.sz + y.sz}; }\nT f2(T x, S y) {\n if (y != lid) x.v = y * x.sz;\n return x;\n}\nS f3(S x, S y) { return y == lid ? x : y; }\n\n*/\n\nint main() {\n int n, q;\n cin >> n >> q;\n seg sg(n);\n while (q--) {\n int x, y, z;\n cin >> x >> y >> z;\n if (x == 0)\n sg.set(y, z);\n else\n cout << sg.query(y, z + 1) << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 4176, "score_of_the_acc": -0.9011, "final_rank": 14 }, { "submission_id": "aoj_DSL_2_A_11009090", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i, from, to) for (int i = from; i < (to); ++i)\n#define all(x) x.begin(), x.end()\n#define sz(x) (int)(x).size()\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n\n/**\n * Author: Simon Lindholm\n * Date: 2015-09-12\n * License: CC0\n * Source: me\n * Description: When you need to dynamically allocate many objects and don't care about freeing them.\n * \"new X\" otherwise has an overhead of something like 0.05us + 16 bytes per allocation.\n * Status: tested\n */\n\n// Either globally or in a single class:\nstatic char buf[450 << 20];\nvoid* operator new(size_t s) {\n\tstatic size_t i = sizeof buf;\n\tassert(s < i);\n\treturn (void*)&buf[i -= s];\n}\nvoid operator delete(void*) {}\n\n/**\n * Author: Simon Lindholm\n * Date: 2016-10-08\n * License: CC0\n * Source: me\n * Description: Segment tree with ability to add or set values of large intervals, and compute max of intervals.\n * Can be changed to other things.\n * Use with a bump allocator for better performance, and SmallPtr or implicit indices to save memory.\n * Time: O(\\log N).\n * Usage: Node* tr = new Node(v, 0, sz(v));\n * Status: stress-tested a bit\n */\n\nconst int inf = INT_MAX;\nstruct Node {\n\tNode *l = 0, *r = 0;\n\tint lo, hi, mset = inf, madd = 0, val = inf;\n\tNode(int lo,int hi):lo(lo),hi(hi){} // Large interval of -inf\n\tNode(vi& v, int lo, int hi) : lo(lo), hi(hi) {\n\t\tif (lo + 1 < hi) {\n\t\t\tint mid = lo + (hi - lo)/2;\n\t\t\tl = new Node(v, lo, mid); r = new Node(v, mid, hi);\n\t\t\tval = min(l->val, r->val);\n\t\t}\n\t\telse val = v[lo];\n\t}\n\tint query(int L, int R) {\n\t\tif (R <= lo || hi <= L) return inf;\n\t\tif (L <= lo && hi <= R) return val;\n\t\tpush();\n\t\treturn min(l->query(L, R), r->query(L, R));\n\t}\n\tvoid set(int L, int R, int x) {\n\t\tif (R <= lo || hi <= L) return;\n\t\tif (L <= lo && hi <= R) mset = val = x, madd = 0;\n\t\telse {\n\t\t\tpush(), l->set(L, R, x), r->set(L, R, x);\n\t\t\tval = min(l->val, r->val);\n\t\t}\n\t}\n\tvoid add(int L, int R, int x) {\n\t\tif (R <= lo || hi <= L) return;\n\t\tif (L <= lo && hi <= R) {\n\t\t\tif (mset != inf) mset += x;\n\t\t\telse madd += x;\n\t\t\tval += x;\n\t\t}\n\t\telse {\n\t\t\tpush(), l->add(L, R, x), r->add(L, R, x);\n\t\t\tval = min(l->val, r->val);\n\t\t}\n\t}\n\tvoid push() {\n\t\tif (!l) {\n\t\t\tint mid = lo + (hi - lo)/2;\n\t\t\tl = new Node(lo, mid); r = new Node(mid, hi);\n\t\t}\n\t\tif (mset != inf)\n\t\t\tl->set(lo,hi,mset), r->set(lo,hi,mset), mset = inf;\n\t\telse if (madd)\n\t\t\tl->add(lo,hi,madd), r->add(lo,hi,madd), madd = 0;\n\t}\n};\nint main() {\n\tint n, q;\n\tcin >> n >> q;\n\tvector<int> a(n, (1LL << 31) - 1);\n\tNode seg(a, 0, sz(a));\n\twhile (q--) {\n\t\tint op, x, y;\n\t\tcin >> op >> x >> y;\n\t\tif (op == 0) {\n\t\t\tseg.set(x, x + 1, y);\n\t\t} else {\n\t\t\tcout << seg.query(x, y + 1) << '\\n';\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 11588, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_DSL_2_A_10992961", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\ntemplate <class S, S (*op)(S, S), S (*e)()>\nstruct segtree {\n int _n,size=1,log=0;\n vc<S> d; //1-indexed\n\tsegtree(): segtree(0){}\n segtree(int n): segtree(vc<S>(n,e())){}\n\tsegtree(const vc<S> &v): _n(sz(v)){\n while(_n>size) size<<=1, log++;\n\t\td.assign(2*size,e());\n\t\trep(i,_n) d[size+i]=v[i];\n\t\tpre(i,1,size) update(i);\n }\n\tvoid update(int k) { d[k]=op(d[2*k], d[2*k+1]); }\n void set(int p, S x){\n\t\tassert(0 <= p && p < _n);\n\t\tp+=size;\n\t\td[p]=x;\n\t\trep(i,1,log+1) update(p>>i);\n\t}\n\tS get(int p) const { \n\t\tassert(0 <= p && p < _n);\n\t\treturn d[p+size];\n\t}\n\tS prod(int l, int r) const {\n\t\tassert(0 <= l && l <= r && r <= _n);\n\t\tS sml=e(), smr=e();\n\t\tl+=size; r+=size;\n\t\twhile(l<r){\n\t\t\tif(l&1) sml=op(sml,d[l++]);\n\t\t\tif(r&1) smr=op(d[--r],smr);\n\t\t\tl>>=1; r>>=1;\n\t\t}\n\t\treturn op(sml,smr);\n\t}\n\tS all_prod() const { return d[1]; }\n\t\n\ttemplate <bool (*f)(S)> int max_right(int l, int r) const {\n return min(r, max_right(l, [](S x) { return f(x); }));\n }\n\ttemplate <bool (*f)(S)> int max_right(int l) const {\n return max_right(l, [](S x) { return f(x); });\n }\n\ttemplate <class F> int max_right(int l, int r, F f) const {\n\t\treturn min(r, max_right<F>(l, f));\n }\n template <class F> int max_right(int l, F f) const {\n\t\tassert(0 <= l && l <= _n);\n assert(f(e()));\n if (l == _n) return _n;\n l += size;\n S sm = e();\n do {\n while (l % 2 == 0) l >>= 1;\n if (!f(op(sm, d[l]))) {\n while (l < size) {\n l = (2 * l);\n if (f(op(sm, d[l]))) {\n sm = op(sm, d[l]);\n l++;\n }\n }\n return l - size;\n }\n sm = op(sm, d[l]);\n l++;\n } while ((l & -l) != l);\n return _n;\n }\n\n\ttemplate <bool (*f)(S)> int min_left(int l, int r) const {\n return max(l, min_left(r, [](S x) { return f(x); }));\n }\n template <bool (*f)(S)> int min_left(int r) const {\n return min_left(r, [](S x) { return f(x); });\n }\n\ttemplate <class F> int min_left(int l, int r, F f) const {\n\t\treturn max(l, min_left<F>(r, f));\n\t}\n template <class F> int min_left(int r, F f) const {\n\t\tassert(0 <= r && r <= _n);\n assert(f(e()));\n if (r == 0) return 0;\n r += size;\n S sm = e();\n do {\n r--;\n while (r > 1 && (r % 2)) r >>= 1;\n if (!f(op(d[r], sm))) {\n while (r < size) {\n r = (2 * r + 1);\n if (f(op(d[r], sm))) {\n sm = op(d[r], sm);\n r--;\n }\n }\n return r + 1 - size;\n }\n sm = op(d[r], sm);\n } while ((r & -r) != r);\n return 0;\n }\n inline S operator[](int i) { return get(i); }\n /* debug */\n void print() {\n cerr << \"print: \";\n rep(i,_n){\n cerr << (*this)[i];\n if(i!=_n) cerr << \" \";\n }\n cerr << endl;\n }\n};\n\nusing S=ll;\nS op(S a, S b) { return min(a, b); }\nS e() { return infl; }\n\nint main(){\t\n\tios::sync_with_stdio(false);\n \tcin.tie(0);\n\tint n,q; cin >> n >> q;\n vll a(n,(1LL<<31)-1);\n\tsegtree<S,op,e> seg(a);\n\n rep(i,q){\n int type; cin >> type;\n if(type==0){\n int s,x; cin >> s >> x;\n seg.set(s,x);\n } else {\n int s,t; cin >> s >> t;\n cout << seg.prod(s,t+1) << endl;\n }\n }\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5792, "score_of_the_acc": -0.6721, "final_rank": 10 }, { "submission_id": "aoj_DSL_2_A_10940702", "code_snippet": "#include<iostream>\n#include<vector>\n#include<functional>\nusing namespace std;\n\ntemplate<typename T>\nclass Seg_tree{\n\tint n;\n\tT st;\n\tvector<T> node;\n\tfunction<T(T, T)> func;\npublic:\n\tSeg_tree(int N, function<T(T, T)> f, T m = 0): st(m), func(f){\n\t\tn = 1; \n\t\twhile(n < N) n *= 2;\n\t\tnode = vector<T>(2 * n - 1, st);\n\t}\n\t\n\tvoid set(int x, T y){\n\t\tx += n - 1;\n\t\tnode[x] = y;\n\t\twhile(x > 0){\n\t\t\tx = (x - 1) / 2;\n\t\t\tnode[x] = func(node[2 * x + 1], node[2 * x + 2]);\n\t\t}\n\t}\n\t\n\tT solve(int l, int r){\n\t\tl += n - 1, r += n - 1;\n\t\tT vl = st, vr = st;\n\t\twhile(l < r){\n\t\t\tif(l % 2 == 0){\n\t\t\t\tvl = func(vl, node[l]);\n\t\t\t\tl++;\n\t\t\t}\n\t\t\tl /= 2;\n\t\t\tif(r % 2 == 0){\n\t\t\t\tr--;\n\t\t\t\tvr = func(vr, node[r]);\n\t\t\t}\n\t\t\tr /= 2;\n\t\t}\n\t\treturn func(vl, vr);\n\t}\n};\n\nint main(){\n\tint n, q;\n\tcin >> n >> q;\n\tSeg_tree<long long> st(n, [](long long a, long long b){ return (a < b) ? a : b;}, (1LL << 31) - 1);\n\tlong long com, x, y;\n\twhile(q--){\n\t\tcin >> com >> x >> y;\n\t\tif(com) cout << st.solve(x, y + 1) << endl;\n\t\telse st.set(x, y);\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5456, "score_of_the_acc": -0.6273, "final_rank": 6 }, { "submission_id": "aoj_DSL_2_A_10937801", "code_snippet": "#include<iostream>\n#include<vector>\n#include<functional>\nusing namespace std;\n\ntemplate<typename T>\nclass Seg_tree{\n\tint n;\n\tT st;\n\tvector<T> node;\n\tfunction<T(T, T)> func;\npublic:\n\tSeg_tree(int N, function<T(T, T)> f, T m = 0): func(f), st(m){\n\t\tn = 1;\n\t\twhile(n < N) n *= 2;\n\t\tnode = vector<T>(2 * n - 1, st);\n\t}\n\t\n\tvoid set(int x, T y){\n\t\tx += n - 1;\n\t\tnode[x] = y;\n\t\twhile(x > 0){\n\t\t x = (x - 1) / 2;\n\t\t\tnode[x] = func(node[2 * x + 1], node[2 * x + 2]);\n\t\t}\n\t}\n\t\n\tT solve(int l, int r){\n\t\tl += n - 1, r += n - 1;\n\t\tT vl = st, vr = st;\n\t\twhile(l < r){\n\t\t\tif(l % 2 == 0) {vl = func(vl, node[l]), l++;}\n\t\t\tl /= 2;\n\t\t\tif(r % 2 == 0) {r--, vr = func(vr, node[r]);}\n\t\t\tr /= 2;\n\t\t}\n\t\treturn func(vl, vr);\n\t}\n\t\n\t//void putv() { for(int i = n - 1; i < 2 * n - 1; i++) cout << node[i] << endl;}\n};\n\nint main(){\n\tint n, q;\n\tcin >> n >> q;\n\tSeg_tree<long long> st(n, [](long long a, long long b){ return (a < b) ? a : b;}, (1LL << 31) - 1);\n\tlong long com, x, y;\n\twhile(q--){\n\t\tcin >> com >> x >> y;\n\t\tif(com) cout << st.solve(x, y + 1) << endl;\n\t\telse st.set(x, y);\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5456, "score_of_the_acc": -0.6273, "final_rank": 6 }, { "submission_id": "aoj_DSL_2_A_10935303", "code_snippet": "#include<iostream>\n#include<vector>\n#include<cmath>\n#include<algorithm>\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n\tint n, q, s;\n\tcin >> n >> q;\n\ts = sqrt(n);\n\tlong st = (1L << 31) - 1;\n\tvector<long> a(n, st), mnum(s + 1, st);\n\tlong com, x, y;\n\twhile(q--){\n\t\tcin >> com >> x >> y;\n\t\tif(com){\n\t\t\tlong m = st;\n\t\t\tif(x == y) m = a[x];\n\t\t\telse if(x / s == y / s){\n\t\t\t\tfor(int i = x; i <= y; i++) m = min(m, a[i]);\n\t\t\t}else{\n\t\t\t\tfor(int i = x / s + 1, j = y / s; i < j; i++) m = min(m, mnum[i]);\n\t\t\t\tfor(int i = x, j = (x / s + 1) * s; i < j; i++) m = min(m, a[i]);\n\t\t\t\tfor(int i = y, j = y / s * s; i >= j; i--) m = min(m, a[i]);\n\t\t\t}\n\t\t\tcout << m << endl;\n\t\t}else{\n\t\t\tif(mnum[x / s] == a[x]) mnum[x / s] = st;\n\t\t\ta[x] = y;\n\t\t\tfor(int i = x / s * s, j = i + s; i < j; i++) mnum[x / s] = min(mnum[x / s], a[i]);\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 4096, "score_of_the_acc": -0.6683, "final_rank": 8 } ]
aoj_ALDS1_14_D_cpp
String Search Determine whether a text T includes a pattern P . Your program should answer for given queries consisting of P_i . Input In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively. Output For each question, print 1 if the text includes P_i , or print 0 otherwise. Constraints 1 ≤ length of T ≤ 1000000 1 ≤ length of P_i ≤ 1000 1 ≤ Q ≤ 10000 The input consists of alphabetical characters and digits Sample Input 1 aabaaa 4 aa ba bb xyz Sample Output 1 1 1 0 0
[ { "submission_id": "aoj_ALDS1_14_D_10853897", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)\n#define REP(i,n) FOR(i,0,n)\n#define ALL(a) a.begin(), a.end()\n#define MS(m,v) memset(m,v,sizeof(m))\ntypedef long long ll;\ntypedef long double ld;\ntypedef vector<int> vi;\ntypedef vector<string> vs;\ntypedef pair<int, int> pii;\nconst int MOD = 1e9 + 7;\ntemplate<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }\ntemplate<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }\ntemplate<class T>\nistream& operator >> (istream& is, vector<T>& v)\n{\n\tfor (auto &i : v) is >> i;\n\treturn is;\n}\ntemplate<class T>\nostream& operator<<(ostream& os, vector<T>& v)\n{\n\tconst string delimiter = \"\\n\";\n\tREP(i, v.size())\n\t{\n\t\tos << v[i];\n\t\tif (i != v.size() - 1) os << delimiter;\n\t}\n\treturn os;\n}\n/*--------------------template--------------------*/\n\ntypedef vector<int> SuffixArray;\nint n, k;\nvi rnk, tmp;\n\nbool comp_sa(const int i, const int j)\n{\n\tif (rnk[i] != rnk[j]) return rnk[i] < rnk[j];\n\telse\n\t{\n\t\tint ri = i + k <= n ? rnk[i + k] : -1;\n\t\tint rj = j + k <= n ? rnk[j + k] : -1;\n\t\treturn ri < rj;\n\t}\n}\n\nSuffixArray construct_sa(const string& s)\n{\n\tn = s.size();\n\tSuffixArray sa(n + 1);\n\trnk.resize(n + 1), tmp.resize(n + 1);\n\tREP(i, n + 1)\n\t{\n\t\tsa[i] = i;\n\t\tif (i == n) rnk[i] = -1;\n\t\telse rnk[i] = s[i];\n\t}\n\tfor (k = 1; k <= n; k *= 2)\n\t{\n\t\tsort(ALL(sa), comp_sa);\n\t\ttmp[sa[0]] = 0;\n\t\tREP(i, n) tmp[sa[i + 1]] = tmp[sa[i]] + (comp_sa(sa[i], sa[i + 1]) ? 1 : 0);\n\t\trnk = tmp;\n\t}\n\treturn sa;\n}\n\nbool search(const string& s, const string& t, const SuffixArray& sa)\n{\n\tint l = 0, r = s.size();\n\twhile (r - l > 1)\n\t{\n\t\tint mid = (r + l) / 2;\n\t\tif (s.compare(sa[mid], t.size(), t) < 0) l = mid;\n\t\telse r = mid;\n\t}\n\treturn s.compare(sa[r], t.size(), t) == 0;\n}\n\nint lower_bound(const string& s, const string& t, const SuffixArray& sa)\n{\n\tint l = 0, r = s.size() + 1;\n\twhile (r - l > 1)\n\t{\n\t\tint mid = (r + l) / 2;\n\t\tif (s.compare(sa[mid], t.size(), t) < 0) l = mid;\n\t\telse r = mid;\n\t}\n\treturn r;\n}\n\nint upper_bound(const string& s, const string& t, const SuffixArray& sa)\n{\n\tint l = 0, r = s.size() + 1;\n\twhile (r - l > 1)\n\t{\n\t\tint mid = (r + l) / 2;\n\t\tif (s.compare(sa[mid], t.size(), t) <= 0) l = mid;\n\t\telse r = mid;\n\t}\n\treturn r;\n}\n\n\nint main()\n{\n\tcin.sync_with_stdio(false); cout << fixed << setprecision(10);\n\tstring s; cin >> s;\n\tint q; cin >> q;\n\tSuffixArray sa = construct_sa(s);\n\twhile (q--)\n\t{\n\t\tstring t; cin >> t;\n\t\tif (search(s, t, sa)) cout << 1 << endl;\n\t\telse cout << 0 << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 1060, "memory_kb": 15752, "score_of_the_acc": -1, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_14_D_10308549", "code_snippet": "// competitive-verifier: PROBLEM https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_14_D\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cassert>\n#include <numeric>\n#include <vector>\nnamespace internal {\nstd::vector<int> sa_naive(const std::vector<int> &s) {\n int n = int(s.size());\n std::vector<int> sa(n);\n std::iota(sa.begin(), sa.end(), 0);\n std::sort(sa.begin(), sa.end(), [&](int l, int r) {\n if (l == r) return false;\n while (l < n && r < n) {\n if (s[l] != s[r]) return s[l] < s[r];\n ++l, ++r;\n }\n return l == n;\n });\n return sa;\n}\nstd::vector<int> sa_doubling(const std::vector<int> &s) {\n int n = int(s.size());\n std::vector<int> sa(n), rnk = s, tmp(n);\n std::iota(sa.begin(), sa.end(), 0);\n for (int k = 1; k < n; k *= 2) {\n auto cmp = [&](int x, int y) {\n if (rnk[x] != rnk[y]) return rnk[x] < rnk[y];\n int rx = x + k < n ? rnk[x + k] : -1;\n int ry = y + k < n ? rnk[y + k] : -1;\n return rx < ry;\n };\n std::sort(sa.begin(), sa.end(), cmp);\n tmp[sa[0]] = 0;\n for (int i = 1; i < n; ++i) tmp[sa[i]] = tmp[sa[i - 1]] + (cmp(sa[i - 1], sa[i]) ? 1 : 0);\n std::swap(tmp, rnk);\n }\n return sa;\n}\ntemplate <int THRESHOLD_NAIVE = 10, int THRESHOLD_DOUBLING = 40>\nstd::vector<int> sa_is(const std::vector<int> &s, int upper) {\n int n = int(s.size());\n if (n == 0) return {};\n if (n == 1) return {0};\n if (n == 2) {\n if (s[0] < s[1]) return {0, 1};\n else return {1, 0};\n }\n if (n < THRESHOLD_NAIVE) return sa_naive(s);\n if (n < THRESHOLD_DOUBLING) return sa_doubling(s);\n std::vector<int> sa(n);\n std::vector<bool> ls(n);\n for (int i = n - 2; i >= 0; i--) ls[i] = (s[i] == s[i + 1]) ? ls[i + 1] : (s[i] < s[i + 1]);\n std::vector<int> sum_l(upper + 1), sum_s(upper + 1);\n for (int i = 0; i < n; ++i) {\n if (!ls[i]) ++sum_s[s[i]];\n else ++sum_l[s[i] + 1];\n }\n for (int i = 0; i <= upper; ++i) {\n sum_s[i] += sum_l[i];\n if (i < upper) sum_l[i + 1] += sum_s[i];\n }\n auto induce = [&](const std::vector<int> &lms) {\n std::fill(sa.begin(), sa.end(), -1);\n std::vector<int> buf(upper + 1);\n std::copy(sum_s.begin(), sum_s.end(), buf.begin());\n for (auto d : lms) {\n if (d == n) continue;\n sa[buf[s[d]]++] = d;\n }\n std::copy(sum_l.begin(), sum_l.end(), buf.begin());\n sa[buf[s[n - 1]]++] = n - 1;\n for (int i = 0; i < n; ++i) {\n int v = sa[i];\n if (v >= 1 && !ls[v - 1]) sa[buf[s[v - 1]]++] = v - 1;\n }\n std::copy(sum_l.begin(), sum_l.end(), buf.begin());\n for (int i = n - 1; i >= 0; i--) {\n int v = sa[i];\n if (v >= 1 && ls[v - 1]) sa[--buf[s[v - 1] + 1]] = v - 1;\n }\n };\n std::vector<int> lms_map(n + 1, -1);\n int m = 0;\n for (int i = 1; i < n; ++i) {\n if (!ls[i - 1] && ls[i]) lms_map[i] = m++;\n }\n std::vector<int> lms;\n lms.reserve(m);\n for (int i = 1; i < n; ++i) {\n if (!ls[i - 1] && ls[i]) lms.emplace_back(i);\n }\n induce(lms);\n if (m) {\n std::vector<int> sorted_lms;\n sorted_lms.reserve(m);\n for (int v : sa) {\n if (lms_map[v] != -1) sorted_lms.emplace_back(v);\n }\n std::vector<int> rec_s(m);\n int rec_upper = 0;\n rec_s[lms_map[sorted_lms[0]]] = 0;\n for (int i = 1; i < m; ++i) {\n int l = sorted_lms[i - 1], r = sorted_lms[i];\n int end_l = (lms_map[l] + 1 < m) ? lms[lms_map[l] + 1] : n;\n int end_r = (lms_map[r] + 1 < m) ? lms[lms_map[r] + 1] : n;\n bool same = true;\n if (end_l - l != end_r - r) {\n same = false;\n } else {\n while (l < end_l) {\n if (s[l] != s[r]) break;\n ++l, ++r;\n }\n if (l == n || s[l] != s[r]) same = false;\n }\n if (!same) ++rec_upper;\n rec_s[lms_map[sorted_lms[i]]] = rec_upper;\n }\n auto rec_sa = sa_is<THRESHOLD_NAIVE, THRESHOLD_DOUBLING>(rec_s, rec_upper);\n for (int i = 0; i < m; ++i) sorted_lms[i] = lms[rec_sa[i]];\n induce(sorted_lms);\n }\n return sa;\n}\n} // namespace internal\n/**\n * @brief Suffix Array\n *\n * @param s 配列\n * @param upper 最大値\n * @return std::vector<int>\n */\nstd::vector<int> suffix_array(const std::vector<int> &s, int upper) {\n assert(0 <= upper);\n for (int d : s) assert(0 <= d && d <= upper);\n auto sa = internal::sa_is(s, upper);\n return sa;\n}\n/**\n * @brief Suffix Array\n *\n * @tparam T 配列の型\n * @param s 配列\n * @retval std::vector<int> Suffix Array\n */\ntemplate <class T>\nstd::vector<int> suffix_array(const std::vector<T> &s) {\n int n = int(s.size());\n std::vector<int> idx(n);\n std::iota(idx.begin(), idx.end(), 0);\n std::sort(idx.begin(), idx.end(), [&](int l, int r) { return s[l] < s[r]; });\n std::vector<int> s2(n);\n int now = 0;\n for (int i = 0; i < n; ++i) {\n if (i && s[idx[i - 1]] != s[idx[i]]) ++now;\n s2[idx[i]] = now;\n }\n return internal::sa_is(s2, now);\n}\n/**\n * @brief Suffix Array\n *\n * @param s 文字列\n * @retval std::vector<int> Suffix Array\n */\nstd::vector<int> suffix_array(const std::string &s) {\n int n = int(s.size());\n std::vector<int> s2(n);\n for (int i = 0; i < n; ++i) s2[i] = s[i];\n return internal::sa_is(s2, 255);\n}\ntemplate <class T>\nstd::vector<int> lcp_array(const std::vector<T> &s, const std::vector<int> &sa) {\n int n = int(s.size());\n assert(n >= 1);\n std::vector<int> rnk(n);\n for (int i = 0; i < n; ++i) { rnk[sa[i]] = i; }\n std::vector<int> lcp(n - 1);\n int h = 0;\n for (int i = 0; i < n; ++i) {\n if (h > 0) --h;\n if (rnk[i] == 0) continue;\n int j = sa[rnk[i] - 1];\n for (; j + h < n && i + h < n; ++h) {\n if (s[j + h] != s[i + h]) break;\n }\n lcp[rnk[i] - 1] = h;\n }\n return lcp;\n}\nstd::vector<int> lcp_array(const std::string &s, const std::vector<int> &sa) {\n int n = int(s.size());\n std::vector<int> s2(n);\n for (int i = 0; i < n; ++i) { s2[i] = s[i]; }\n return lcp_array(s2, sa);\n}\nint main(void) {\n std::string s;\n std::cin >> s;\n int n = s.size();\n auto v = suffix_array(s);\n int q;\n std::cin >> q;\n while (q--) {\n std::string t;\n std::cin >> t;\n int l = -1, r = n - 1;\n while (r - l > 1) {\n int m = (l + r) / 2;\n if (s.substr(v[m], t.size()) < t)\n l = m;\n else\n r = m;\n }\n std::cout << (s.substr(v[r], t.size()) == t) << '\\n';\n }\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 28668, "score_of_the_acc": -0.9556, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_14_D_10308534", "code_snippet": "// competitive-verifier: PROBLEM https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_14_D\n#include <iostream>\n#include <string>\n#include <cmath>\n#include <cstdint>\n#include <numeric>\n/// @brief めぐる式二分探索\ntemplate <class T, class F>\nstd::int64_t meguru_binary_search(T ok, T ng, F check) {\n while (std::abs(ok - ng) > 1) {\n T mid = std::midpoint(ok, ng);\n (check(mid) ? ok : ng) = mid;\n }\n return ok;\n}\n#include <array>\n#include <bit>\n#include <cassert>\n#include <vector>\n/// @brief スパーステーブル\ntemplate <class M>\nstruct sparse_table {\n private:\n using T = typename M::value_type;\n public:\n sparse_table() = default;\n sparse_table(const std::vector<T> &v) : _size(v.size()), data() {\n int b = std::max(1, std::countr_zero(std::bit_ceil<unsigned>(_size)));\n data.emplace_back(v);\n for (int i = 1; i < b; ++i) data.emplace_back(_size + 1 - (1 << i));\n for (int i = 1; i < b; ++i) {\n for (int j = 0; j + (1 << i) <= _size; ++j) {\n data[i][j] = M::op(data[i - 1][j], data[i - 1][j + (1 << (i - 1))]);\n }\n }\n }\n T prod(int l, int r) const {\n assert(0 <= l && l <= r && r <= _size);\n if (l == r) return M::id();\n if (l + 1 == r) return data[0][l];\n int b = 31 - std::countl_zero<unsigned>(r - l - 1);\n return M::op(data[b][l], data[b][r - (1 << b)]);\n }\n private:\n int _size;\n std::vector<std::vector<T>> data;\n};\nnamespace internal {\ntemplate <class T, int N>\nstruct fixed_stack {\n constexpr fixed_stack() : _size(), _data() {}\n constexpr T top() const { return _data[_size - 1]; }\n constexpr bool empty() const { return _size == 0; }\n constexpr int size() const { return _size; }\n constexpr void emplace(const T &e) { _data[_size++] = e; }\n constexpr void emplace(T &&e) { _data[_size++] = e; }\n constexpr void pop() { --_size; }\n constexpr void clear() { _size = 0; }\n private:\n int _size;\n std::array<T, N> _data;\n};\n} // namespace internal\n/**\n * @brief 線形 Sparse Table\n *\n * @tparam M\n */\ntemplate <class M>\nstruct linear_sparse_table {\n private:\n using T = M::value_type;\n static constexpr int W = 64;\n public:\n linear_sparse_table() = default;\n linear_sparse_table(const std::vector<T> &v) : _size(v.size()), data(v) {\n int n = v.size();\n int b = n / W;\n internal::fixed_stack<int, W + 1> st;\n std::vector<T> u(b);\n word_data.resize(b + (n > b * W));\n for (int i = 0; i < b; ++i) {\n T m = M::id();\n std::uint64_t bit = 0;\n std::vector<std::uint64_t> bits(W);\n for (int j = 0; j < W; ++j) {\n m = M::op(m, v[i * W + j]);\n while (!st.empty() && M::op(v[i * W + st.top()], v[i * W + j]) == v[i * W + j]) {\n bit ^= std::uint64_t(1) << st.top();\n st.pop();\n }\n bits[j] = bit;\n bit |= std::uint64_t(1) << j;\n st.emplace(j);\n }\n u[i] = m;\n word_data[i] = bits;\n st.clear();\n }\n if (n > b * W) {\n std::uint64_t bit = 0;\n std::vector<std::uint64_t> bits(n - b * W);\n for (int j = 0; j < n - b * W; ++j) {\n while (!st.empty() && M::op(v[b * W + st.top()], v[b * W + j]) == v[b * W + j]) {\n bit ^= std::uint64_t(1) << st.top();\n st.pop();\n }\n bits[j] = bit;\n bit |= std::uint64_t(1) << j;\n st.emplace(j);\n }\n word_data[b] = bits;\n }\n block_table = sparse_table<M>(u);\n }\n const T &operator[](int k) const { return data[k]; }\n T prod(int l, int r) const {\n assert(0 <= l && l < r && r <= _size);\n int lb = (l + W - 1) / W, rb = r / W;\n if (lb > rb) return word_prod(l, r);\n T res = (lb == rb ? M::id() : block_table.prod(lb, rb));\n if (l < lb * W) res = M::op(res, word_prod(l, lb * W));\n if (rb * W < r) res = M::op(res, word_prod(rb * W, r));\n return res;\n }\n private:\n int _size;\n std::vector<T> data;\n sparse_table<M> block_table;\n std::vector<std::vector<std::uint64_t>> word_data;\n T word_prod(int l, int r) const {\n if (l == r) return M::id();\n int b = l / W;\n int lw = l - b * W, rw = r - b * W;\n if ((word_data[b][rw - 1] >> lw) == 0ul) return data[r - 1];\n return data[l + std::countr_zero(word_data[b][rw - 1] >> lw)];\n }\n};\n#include <algorithm>\n#include <limits>\n#include <utility>\ntemplate <class T>\nstruct Add {\n using value_type = T;\n static constexpr T id() { return T(); }\n static constexpr T op(const T &lhs, const T &rhs) { return lhs + rhs; }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return lhs + rhs;\n }\n};\ntemplate <class T>\nstruct Mul {\n using value_type = T;\n static constexpr T id() { return T(1); }\n static constexpr T op(const T &lhs, const T &rhs) { return lhs * rhs; }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return lhs * rhs;\n }\n};\ntemplate <class T>\nstruct And {\n using value_type = T;\n static constexpr T id() { return std::numeric_limits<T>::max(); }\n static constexpr T op(const T &lhs, const T &rhs) { return lhs & rhs; }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return lhs & rhs;\n }\n};\ntemplate <class T>\nstruct Or {\n using value_type = T;\n static constexpr T id() { return T(); }\n static constexpr T op(const T &lhs, const T &rhs) { return lhs | rhs; }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return lhs | rhs;\n }\n};\ntemplate <class T>\nstruct Xor {\n using value_type = T;\n static constexpr T id() { return T(); }\n static constexpr T op(const T &lhs, const T &rhs) { return lhs ^ rhs; }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return lhs ^ rhs;\n }\n};\ntemplate <class T>\nstruct Min {\n using value_type = T;\n static constexpr T id() { return std::numeric_limits<T>::max(); }\n static constexpr T op(const T &lhs, const T &rhs) { return std::min(lhs, rhs); }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return std::min((U)lhs, rhs);\n }\n};\ntemplate <class T>\nstruct Max {\n using value_type = T;\n static constexpr T id() { return std::numeric_limits<T>::lowest(); }\n static constexpr T op(const T &lhs, const T &rhs) { return std::max(lhs, rhs); }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return std::max((U)lhs, rhs);\n }\n};\ntemplate <class T>\nstruct Gcd {\n using value_type = T;\n static constexpr T id() { return std::numeric_limits<T>::max(); }\n static constexpr T op(const T &lhs, const T &rhs) {\n return lhs == Gcd::id() ? rhs : (rhs == Gcd::id() ? lhs : std::gcd(lhs, rhs));\n }\n};\ntemplate <class T>\nstruct Lcm {\n using value_type = T;\n static constexpr T id() { return std::numeric_limits<T>::max(); }\n static constexpr T op(const T &lhs, const T &rhs) {\n return lhs == Lcm::id() ? rhs : (rhs == Lcm::id() ? lhs : std::lcm(lhs, rhs));\n }\n};\ntemplate <class T>\nstruct Update {\n using value_type = T;\n static constexpr T id() { return std::numeric_limits<T>::max(); }\n static constexpr T op(const T &lhs, const T &rhs) { return lhs == Update::id() ? rhs : lhs; }\n template <class U>\n static constexpr U f(T lhs, U rhs) {\n return lhs == Update::id() ? rhs : lhs;\n }\n};\ntemplate <class T>\nstruct Affine {\n using P = std::pair<T, T>;\n using value_type = P;\n static constexpr P id() { return P(1, 0); }\n static constexpr P op(P lhs, P rhs) {\n return {lhs.first * rhs.first, lhs.first * rhs.second + lhs.second};\n }\n};\ntemplate <class M>\nstruct Rev {\n using T = typename M::value_type;\n using value_type = T;\n static constexpr T id() { return M::id(); }\n static constexpr T op(T lhs, T rhs) { return M::op(rhs, lhs); }\n};\nnamespace internal {\nstd::vector<int> sa_naive(const std::vector<int> &s) {\n int n = int(s.size());\n std::vector<int> sa(n);\n std::iota(sa.begin(), sa.end(), 0);\n std::sort(sa.begin(), sa.end(), [&](int l, int r) {\n if (l == r) return false;\n while (l < n && r < n) {\n if (s[l] != s[r]) return s[l] < s[r];\n ++l, ++r;\n }\n return l == n;\n });\n return sa;\n}\nstd::vector<int> sa_doubling(const std::vector<int> &s) {\n int n = int(s.size());\n std::vector<int> sa(n), rnk = s, tmp(n);\n std::iota(sa.begin(), sa.end(), 0);\n for (int k = 1; k < n; k *= 2) {\n auto cmp = [&](int x, int y) {\n if (rnk[x] != rnk[y]) return rnk[x] < rnk[y];\n int rx = x + k < n ? rnk[x + k] : -1;\n int ry = y + k < n ? rnk[y + k] : -1;\n return rx < ry;\n };\n std::sort(sa.begin(), sa.end(), cmp);\n tmp[sa[0]] = 0;\n for (int i = 1; i < n; ++i) tmp[sa[i]] = tmp[sa[i - 1]] + (cmp(sa[i - 1], sa[i]) ? 1 : 0);\n std::swap(tmp, rnk);\n }\n return sa;\n}\ntemplate <int THRESHOLD_NAIVE = 10, int THRESHOLD_DOUBLING = 40>\nstd::vector<int> sa_is(const std::vector<int> &s, int upper) {\n int n = int(s.size());\n if (n == 0) return {};\n if (n == 1) return {0};\n if (n == 2) {\n if (s[0] < s[1]) return {0, 1};\n else return {1, 0};\n }\n if (n < THRESHOLD_NAIVE) return sa_naive(s);\n if (n < THRESHOLD_DOUBLING) return sa_doubling(s);\n std::vector<int> sa(n);\n std::vector<bool> ls(n);\n for (int i = n - 2; i >= 0; i--) ls[i] = (s[i] == s[i + 1]) ? ls[i + 1] : (s[i] < s[i + 1]);\n std::vector<int> sum_l(upper + 1), sum_s(upper + 1);\n for (int i = 0; i < n; ++i) {\n if (!ls[i]) ++sum_s[s[i]];\n else ++sum_l[s[i] + 1];\n }\n for (int i = 0; i <= upper; ++i) {\n sum_s[i] += sum_l[i];\n if (i < upper) sum_l[i + 1] += sum_s[i];\n }\n auto induce = [&](const std::vector<int> &lms) {\n std::fill(sa.begin(), sa.end(), -1);\n std::vector<int> buf(upper + 1);\n std::copy(sum_s.begin(), sum_s.end(), buf.begin());\n for (auto d : lms) {\n if (d == n) continue;\n sa[buf[s[d]]++] = d;\n }\n std::copy(sum_l.begin(), sum_l.end(), buf.begin());\n sa[buf[s[n - 1]]++] = n - 1;\n for (int i = 0; i < n; ++i) {\n int v = sa[i];\n if (v >= 1 && !ls[v - 1]) sa[buf[s[v - 1]]++] = v - 1;\n }\n std::copy(sum_l.begin(), sum_l.end(), buf.begin());\n for (int i = n - 1; i >= 0; i--) {\n int v = sa[i];\n if (v >= 1 && ls[v - 1]) sa[--buf[s[v - 1] + 1]] = v - 1;\n }\n };\n std::vector<int> lms_map(n + 1, -1);\n int m = 0;\n for (int i = 1; i < n; ++i) {\n if (!ls[i - 1] && ls[i]) lms_map[i] = m++;\n }\n std::vector<int> lms;\n lms.reserve(m);\n for (int i = 1; i < n; ++i) {\n if (!ls[i - 1] && ls[i]) lms.emplace_back(i);\n }\n induce(lms);\n if (m) {\n std::vector<int> sorted_lms;\n sorted_lms.reserve(m);\n for (int v : sa) {\n if (lms_map[v] != -1) sorted_lms.emplace_back(v);\n }\n std::vector<int> rec_s(m);\n int rec_upper = 0;\n rec_s[lms_map[sorted_lms[0]]] = 0;\n for (int i = 1; i < m; ++i) {\n int l = sorted_lms[i - 1], r = sorted_lms[i];\n int end_l = (lms_map[l] + 1 < m) ? lms[lms_map[l] + 1] : n;\n int end_r = (lms_map[r] + 1 < m) ? lms[lms_map[r] + 1] : n;\n bool same = true;\n if (end_l - l != end_r - r) {\n same = false;\n } else {\n while (l < end_l) {\n if (s[l] != s[r]) break;\n ++l, ++r;\n }\n if (l == n || s[l] != s[r]) same = false;\n }\n if (!same) ++rec_upper;\n rec_s[lms_map[sorted_lms[i]]] = rec_upper;\n }\n auto rec_sa = sa_is<THRESHOLD_NAIVE, THRESHOLD_DOUBLING>(rec_s, rec_upper);\n for (int i = 0; i < m; ++i) sorted_lms[i] = lms[rec_sa[i]];\n induce(sorted_lms);\n }\n return sa;\n}\n} // namespace internal\n/**\n * @brief Suffix Array\n *\n * @param s 配列\n * @param upper 最大値\n * @return std::vector<int>\n */\nstd::vector<int> suffix_array(const std::vector<int> &s, int upper) {\n assert(0 <= upper);\n for (int d : s) assert(0 <= d && d <= upper);\n auto sa = internal::sa_is(s, upper);\n return sa;\n}\n/**\n * @brief Suffix Array\n *\n * @tparam T 配列の型\n * @param s 配列\n * @retval std::vector<int> Suffix Array\n */\ntemplate <class T>\nstd::vector<int> suffix_array(const std::vector<T> &s) {\n int n = int(s.size());\n std::vector<int> idx(n);\n std::iota(idx.begin(), idx.end(), 0);\n std::sort(idx.begin(), idx.end(), [&](int l, int r) { return s[l] < s[r]; });\n std::vector<int> s2(n);\n int now = 0;\n for (int i = 0; i < n; ++i) {\n if (i && s[idx[i - 1]] != s[idx[i]]) ++now;\n s2[idx[i]] = now;\n }\n return internal::sa_is(s2, now);\n}\n/**\n * @brief Suffix Array\n *\n * @param s 文字列\n * @retval std::vector<int> Suffix Array\n */\nstd::vector<int> suffix_array(const std::string &s) {\n int n = int(s.size());\n std::vector<int> s2(n);\n for (int i = 0; i < n; ++i) s2[i] = s[i];\n return internal::sa_is(s2, 255);\n}\ntemplate <class T>\nstd::vector<int> lcp_array(const std::vector<T> &s, const std::vector<int> &sa) {\n int n = int(s.size());\n assert(n >= 1);\n std::vector<int> rnk(n);\n for (int i = 0; i < n; ++i) { rnk[sa[i]] = i; }\n std::vector<int> lcp(n - 1);\n int h = 0;\n for (int i = 0; i < n; ++i) {\n if (h > 0) --h;\n if (rnk[i] == 0) continue;\n int j = sa[rnk[i] - 1];\n for (; j + h < n && i + h < n; ++h) {\n if (s[j + h] != s[i + h]) break;\n }\n lcp[rnk[i] - 1] = h;\n }\n return lcp;\n}\nstd::vector<int> lcp_array(const std::string &s, const std::vector<int> &sa) {\n int n = int(s.size());\n std::vector<int> s2(n);\n for (int i = 0; i < n; ++i) { s2[i] = s[i]; }\n return lcp_array(s2, sa);\n}\nint main(void) {\n std::string s;\n std::cin >> s;\n int n = s.size();\n auto v = suffix_array(s);\n auto lcp = lcp_array(s, v);\n lcp.emplace(lcp.begin(), 0);\n linear_sparse_table<Min<int>> st(lcp);\n int q;\n std::cin >> q;\n while (q--) {\n std::string t;\n std::cin >> t;\n int l = 0, x = 0;\n auto f = [&](int m) {\n if (st.prod(l, m + 1) > x) {\n l = m + 1;\n return false;\n }\n if (st.prod(l, m + 1) == x) {\n for (int i = x; i < (int)t.size(); ++i) {\n if (v[m] + i == (int)s.size() || s[v[m] + i] < t[i]) {\n x = i;\n l = m + 1;\n return false;\n } else if (s[v[m] + i] > t[i]) {\n return true;\n }\n }\n }\n return true;\n };\n int ans = meguru_binary_search(n - 1, -1, f);\n std::cout << (s.substr(v[ans], t.size()) == t) << '\\n';\n }\n return 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 29268, "score_of_the_acc": -1.0215, "final_rank": 3 } ]
aoj_DSL_2_B_cpp
Range Sum Query Write a program which manipulates a sequence A = { a 1 , a 2 , . . . , a n } with the following operations: add(i, x) : add x to a i . getSum(s, t) : print the sum of a s , a s+1 ,...,a t . Note that the initial values of a i ( i = 1, 2, . . . , n ) are 0. Input n q com 1 x 1 y 1 com 2 x 2 y 2 ... com q x q y q In the first line, n (the number of elements in A ) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes add(x i , y i ) and '1' denotes getSum(x i , y i ) . Output For each getSum operation, print the sum in a line. Constraints 1 ≤ n ≤ 100000 1 ≤ q ≤ 100000 If com i is 0, then 1 ≤ x i ≤ n , 0 ≤ y i ≤ 1000 . If com i is 1, then 1 ≤ x i ≤ n , 1 ≤ y i ≤ n . Sample Input 1 3 5 0 1 1 0 2 2 0 3 3 1 1 2 1 2 2 Sample Output 1 3 2
[ { "submission_id": "aoj_DSL_2_B_11059888", "code_snippet": "#include <bits/stdc++.h>\n#include <bit>\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing i128 = __int128_t;\nusing u128 = __uint128_t;\nusing pii = pair<int, int>;\nusing pic = pair<int, char>;\nusing pci = pair<char, int>;\nusing pll = pair<ll, ll>;\nusing pllc = pair<ll, char>;\n#define rep(i, a, n) for (int i = a; i < (n); i++)\n\ntemplate <class T, class U>\nstruct PairHash {\n static inline size_t hash_combine(size_t seed, size_t v) noexcept {\n // boost::hash_combine と同等の混合\n return seed ^ (v + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2));\n }\n size_t operator()(const pair<T,U>& p) const noexcept {\n size_t h1 = std::hash<T>{}(p.first);\n size_t h2 = std::hash<U>{}(p.second);\n return hash_combine(h1, h2);\n }\n};\n\npll operator+(const pll& a, const pll& b) {\n return {a.first + b.first, a.second + b.second};\n}\n\npll operator-(const pll& a, const pll& b) {\n return {a.first - b.first, a.second - b.second};\n}\n\npll operator-(const pll& a) {\n return {-a.first, -a.second};\n}\n\n// ===== プロトタイプ宣言 =====\nint solve();\n\n// ===== main関数 =====\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n return solve();\n}\n\n\nvoid prvec(vector<string> V) {\n for (const auto& v : V)\n cout << v << endl;\n}\n\nvoid prvec(vector<bool> V) {\n for (const auto& v : V)\n cout << boolalpha << setw(5) << setfill(' ') << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(vector<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(list<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(unordered_set<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T>\nvoid prvec(multiset<T> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\ntemplate <typename T1>\nvoid prvec(deque<T1> V) {\n for (const auto& v : V)\n cout << v << \" \";\n cout << endl;\n}\n\nvoid prvec(set<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(deque<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pii> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pll> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, pair<T2, T3>> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : {\" << v.first << \" \" << v.second << \"}\" << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(map<T1, vector<pair<T2, T3>>> V) {\n for (const auto& [k, v] : V) {\n cout << k << \" : \" ;\n for (const auto& [a, b] : v)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n }\n}\n\nvoid prvec(map<int, bool> V) {\n for (const auto& [k, v] : V)\n cout << k << \" : \" << boolalpha << v << endl;\n}\n\nvoid prvec(map<string, pii> V) {\n for (const auto& [k, v] : V) \n cout << k << \" : \" << v.first << \" \" << v.second << endl;\n}\n\ntemplate <typename T>\nvoid prvec(map<pii, T> V) {\n for (const auto& [k, v] : V) \n cout << \"{\" << k.first << \", \" << k.second << \"}: \" << v << endl;\n}\n\nvoid prvec(map<int, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<int>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& v : vec) {\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<char, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, vector<pii>> V) {\n for (const auto& [k, vec] : V) {\n cout << k << \" : \";\n for (const auto& [a, b] : vec) {\n cout << \"{\" << a << \", \" << b << \"}, \";\n }\n cout << endl;\n }\n}\n\nvoid prvec(map<int, stack<int>> V) {\n for (const auto& [k, stk] : V) {\n cout << k << \" : \";\n stack<int> stk2 = stk;\n while (!stk2.empty()) {\n int v = stk2.top(); stk2.pop();\n cout << v << \" \";\n }\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(vector<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<string, string>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<double, double>> V) {\n for (const auto& [a, b] : V)\n cout << fixed << setprecision(15) << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<char, int>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, char>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(unordered_map<T1, T2> V) {\n for (const auto& [k, v] : V)\n cout << \"{\" << k << \": \" << v << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2>\nvoid prvec(set<pair<T1, T2>> V) {\n for (const auto& [a, b] : V)\n cout << \"{\" << a << \", \" << b << \"}, \";\n cout << endl;\n}\n\nvoid prvec(vector<pair<int, vector<int>>> V) {\n for (const auto& [a, vec] : V) {\n cout << a << \" : \";\n for (const auto& v : vec) cout << v << \" \";\n cout << endl;\n }\n}\n\nvoid prvec(vector<pair<int, set<int>>> V) {\n for (const auto& [a, st] : V) {\n cout << a << \" : \";\n for (const auto& v : st) cout << v << \" \";\n cout << endl;\n }\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(vector<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3>\nvoid prvec(set<tuple<T1, T2, T3>> V) {\n for (const auto& [a, b, c] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \"}, \";\n cout << endl;\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\nvoid prvec(vector<tuple<T1, T2, T3, T4>> V) {\n for (const auto& [a, b, c, d] : V)\n cout << \"{\" << a << \", \" << b << \", \" << c << \", \" << d << \"}, \";\n cout << endl;\n}\n\ntemplate<typename T, typename... Args>\nvoid prvec(std::priority_queue<T, Args...> pq) {\n while (!pq.empty()) {\n auto [f, s] = pq.top();\n cout << \"{\" << f << \", \" << s << \"}, \";\n pq.pop();\n }\n cout << \"\\n\";\n}\n\nclass UnionFind {\n private :\n vector<int> parent;\n vector<int> sz;\n vector<int> edge_count;\n \n public :\n UnionFind(int n) : parent(n), sz(n, 1), edge_count(n, 0) {\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n \n int find(int x) {\n if (parent[x] == x) return x;\n return parent[x] = find(parent[x]);\n }\n \n bool unite(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX == rootY) {\n \tedge_count[rootX]++;\n \treturn false; // cycle検出\n }\n \n if (sz[rootX] < sz[rootY]) swap(rootX, rootY);\n parent[rootY] = rootX;\n sz[rootX] += sz[rootY];\n edge_count[rootX] += edge_count[rootY] + 1;\n return true;\n }\n \n int getSize(int x) {\n return sz[find(x)];\n }\n \n int getEdges(int x) {\n \treturn edge_count[find(x)];\n }\n \n bool same(int x, int y) {\n return find(x) == find(y);\n }\n \n // 頂点数を new_n まで増やす (new_n <= 現在のサイズなら何もしない)\n void ensureSize(int new_n) {\n int old_n = parent.size();\n if (new_n <= old_n) return;\n parent.resize(new_n);\n sz.resize(new_n, 1);\n edge_count.resize(new_n, 0);\n // 新しく追加された i (old_n <= i < new_n) をルート+サイズ1に初期化\n for (int i = old_n; i < new_n; i++) {\n parent[i] = i;\n // sz[i] は resize の第二引数で 1 になっている\n }\n }\n \n // 頂点を1つ追加して、そのインデックスを返す\n int addVertex() {\n int idx = parent.size();\n parent.push_back(idx);\n sz.push_back(1);\n edge_count.push_back(0);\n return idx;\n } \n};\n\ntemplate <class Abel>\n// 重み付きUnionFindの定義\nstruct WeightedUnionFind {\n vector<int> parent, size;\n vector<Abel> diff_weight;\n\n WeightedUnionFind(int n)\n : parent(n), size(n, 1), diff_weight(n, Abel{}) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) {\n if (parent[x] == x) return x;\n int r = find(parent[x]);\n diff_weight[x] = diff_weight[x] + diff_weight[parent[x]];\n return parent[x] = r;\n }\n\n Abel weight(int x) {\n find(x);\n return diff_weight[x];\n }\n\n bool unite(int u, int v, Abel w) {\n Abel wu = weight(u), wv = weight(v);\n int ru = find(u), rv = find(v);\n if (ru == rv) {\n return (wv - wu == w); // すでに矛盾ないかチェック\n }\n\n Abel dw = w + wu - wv;\n\n // union by size(大きいほうに小さいほうをつける)\n if (size[ru] < size[rv]) {\n swap(ru, rv);\n swap(u, v);\n dw = -dw;\n }\n\n parent[rv] = ru;\n diff_weight[rv] = dw;\n size[ru] += size[rv];\n return true;\n }\n\n bool same(int x, int y) {\n return find(x) == find(y);\n }\n\n Abel diff(int x, int y) {\n return weight(y) - weight(x);\n }\n};\n\nstruct DSURollback {\n int n;\n vector<int> parent, sz;\n\n // 変更履歴: (結合された子root, 併合前の親rootのサイズ)\n // 子root = -1 は「何も結合しなかった(uniteで同根)」の印\n vector<pair<int,int>> hist;\n\n DSURollback(int n=0): n(n), parent(n), sz(n,1) {\n iota(parent.begin(), parent.end(), 0);\n }\n\n int find(int x) const {\n // パス圧縮しない\n while (parent[x] != x) x = parent[x];\n return x;\n }\n\n bool unite(int x, int y) {\n x = find(x); y = find(y);\n if (x == y) { \n hist.emplace_back(-1, 0); // ダミー (巻き戻し整合用)\n return false; \n }\n if (sz[x] < sz[y]) swap(x, y); // x に y をくっつける(サイズ併合)\n\n // 履歴に「y が x にぶら下がる前の x のサイズ」を記録\n hist.emplace_back(y, sz[x]);\n\n parent[y] = x;\n sz[x] += sz[y];\n return true;\n }\n\n // 直前の unite を 1 回取り消す\n void rollback() {\n auto [y, old_szx] = hist.back(); hist.pop_back();\n if (y == -1) return; // 何もしていない unite の取消\n int x = parent[y];\n // 親子関係とサイズを元に戻す\n parent[y] = y;\n sz[x] = old_szx;\n }\n\n // スナップショット(この位置まで戻せる)\n int snapshot() const { return (int)hist.size(); }\n\n // 指定スナップショットへ戻す(複数回分まとめて取り消し)\n void rollback_to(int snap) {\n while ((int)hist.size() > snap) rollback();\n }\n\n bool same(int a, int b) { return find(a) == find(b); }\n int size(int x) { return sz[find(x)]; }\n};\n\ntemplate<class S, class Op, class E>\nstruct SegTree {\n int n0 = 0; // 元の配列の長さ\n int n = 1; // セグ木内部のサイズ(2べき)\n std::vector<S> d;\n\n Op op{}; // 区間結合\n E e{}; // 単位元\n\n SegTree() = default;\n explicit SegTree(int n_) { init(n_); }\n explicit SegTree(const std::vector<S>& a) { init(a); }\n\n // 要素数 n_ で初期化(全部 e())\n void init(int n_) {\n n0 = n_;\n n = 1;\n while (n < n_) n <<= 1;\n d.assign(2 * n, e());\n }\n\n // 初期配列 a から構築\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n0; i++) d[n + i] = a[i];\n for (int i = n - 1; i >= 1; i--) {\n d[i] = op(d[i << 1], d[i << 1 | 1]);\n }\n }\n\n // 点代入: A[pos] = val\n void point_set(int pos, const S& val) {\n int k = pos + n;\n d[k] = val;\n for (k >>= 1; k; k >>= 1) {\n d[k] = op(d[k << 1], d[k << 1 | 1]);\n }\n }\n\n // 点取得\n S get(int pos) const {\n return d[pos + n];\n }\n\n // 区間 [l, r) を畳み込み(LazySegTree に合わせて prod という名前に)\n S prod(int l, int r) const {\n S L = e(), R = e();\n for (l += n, r += n; l < r; l >>= 1, r >>= 1) {\n if (l & 1) L = op(L, d[l++]);\n if (r & 1) R = op(d[--r], R);\n }\n return op(L, R);\n }\n\n // 全体\n S all_prod() const {\n return d[1];\n }\n};\n\n// 区間和\nstruct OpSum {\n ll operator()(ll a, ll b) const { return a + b; }\n};\n\n// 単位元(0)\nstruct ESum {\n ll operator()() const { return 0LL; }\n};\n\n// usage: RSQ(SegTreeSum)\n // int n = 10;\n // SegTree<ll, OpSum, ESum> seg(n);\n \n // // A[i] = i をセット\n // for (int i = 0; i < n; i++) seg.point_set(i, i);\n\n // // [l, r) の和\n // ll s = seg.prod(2, 7);\n\n// 区間最大\nstruct OpMax {\n ll operator()(ll a, ll b) const { return std::max(a, b); }\n};\n\nstruct EMax {\n static constexpr ll NEG_INF = (ll)-4e18;\n ll operator()() const { return NEG_INF; }\n};\n// usage: RMaxQ(SegTree)\n// SegTree<ll, OpMax, EMax> seg_max(n);\n\n// 区間最小\nstruct OpMin {\n ll operator()(ll a, ll b) const { return std::min(a, b); }\n};\n\nstruct EMin {\n static constexpr ll INF = (ll)4e18;\n ll operator()() const { return INF; }\n};\n// usage: RMinQ(SeegTree)\n// SegTree<ll, OpMin, EMin> seg_min(n);\n\n// SegTreeMinArg\nstruct MinArgNode {\n long long val;\n int idx;\n};\n\n// 区間最小 & argmin\nstruct OpMinArg {\n MinArgNode operator()(const MinArgNode& a, const MinArgNode& b) const {\n if (a.val != b.val) return (a.val < b.val ? a : b);\n if (a.idx == -1) return b;\n if (b.idx == -1) return a;\n return (a.idx < b.idx ? a : b); // tie: 小さい idx\n }\n};\n\nstruct EMinArg {\n static constexpr long long INF = (long long)4e18;\n MinArgNode operator()() const { return MinArgNode{INF, -1}; }\n};\n// usage: SegTreeMinArg\n// int n = 10;\n// SegTree<MinArgNode, OpMinArg, EMinArg> seg_minarg(n);\n\n// // 値だけ代入する糖衣\n// auto point_set_val = [&](int pos, long long v) {\n// seg_minarg.point_set(pos, MinArgNode{v, pos});\n// };\n\n// point_set_val(3, 5);\n// point_set_val(7, 2);\n\n// MinArgNode res = seg_minarg.prod(0, n); // 全区間の最小 & その位置\n\n// ==============================\n// Generic Lazy Segment Tree\n// S: ノード型(例: {val, len})\n// F: 遅延(写像)型(例: 加算値)\n// 必要な関数: \n// op(S,S)->S : 区間結合(モノイド演算)\n// e()->S : Sの単位元\n// mapping(F,S)->S : SにFを適用\n// composition(Fnew, Fold)->F: 遅延の合成(先にFold→後でFnewがかかる形になるよう定義)\n// id()->F : Fの単位元\n// ==============================\ntemplate<\n class S, class F,\n class Op, class E,\n class Mapping, class Composition, class Id\n>\nstruct LazySegTree {\n int n = 0, size = 1, logn = 0;\n\n // ここで中の演算子たちをデフォルト初期化\n Op op{};\n E e{};\n Mapping mapping{};\n Composition composition{};\n Id id{};\n\n std::vector<S> d;\n std::vector<F> lz;\n\n LazySegTree() = default;\n explicit LazySegTree(int n_) { init(n_); }\n explicit LazySegTree(const std::vector<S>& a) { init(a); }\n\n void init(int n_) {\n n = n_;\n logn = 0;\n size = 1;\n while (size < n) size <<= 1, ++logn;\n d.assign(2 * size, e()); // E::operator() で単位元\n lz.assign(size, id()); // Id::operator() で遅延の単位元\n }\n\n void init(const std::vector<S>& a) {\n init((int)a.size());\n for (int i = 0; i < n; i++) d[size + i] = a[i];\n for (int i = size - 1; i >= 1; i--) pull(i);\n }\n\n void set_point(int p, const S& x) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n d[p] = x;\n for (int i = 1; i <= logn; i++) pull(p >> i);\n }\n\n S get_point(int p) {\n p += size;\n for (int i = logn; i >= 1; i--) push(p >> i);\n return d[p];\n }\n\n // 区間 [l, r) に f を適用\n void apply(int l, int r, const F& f) {\n if (l >= r) return;\n l += size; r += size;\n int l0 = l, r0 = r;\n for (int i = logn; i >= 1; i--) {\n if (((l0 >> i) << i) != l0) push(l0 >> i);\n if (((r0 >> i) << i) != r0) push((r0 - 1) >> i);\n }\n while (l < r) {\n if (l & 1) all_apply(l++, f);\n if (r & 1) all_apply(--r, f);\n l >>= 1; r >>= 1;\n }\n for (int i = 1; i <= logn; i++) {\n if (((l0 >> i) << i) != l0) pull(l0 >> i);\n if (((r0 >> i) << i) != r0) pull((r0 - 1) >> i);\n }\n }\n\n // 区間 [l, r) を畳み込み\n S prod(int l, int r) {\n if (l >= r) return e();\n l += size; r += size;\n for (int i = logn; i >= 1; i--) {\n if (((l >> i) << i) != l) push(l >> i);\n if (((r >> i) << i) != r) push((r - 1) >> i);\n }\n S sml = e(), smr = e();\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++]);\n if (r & 1) smr = op(d[--r], smr);\n l >>= 1; r >>= 1;\n }\n return op(sml, smr);\n }\n\n // 全体\n S all_prod() const { return d[1]; }\n\nprivate:\n void pull(int k) { d[k] = op(d[2*k], d[2*k+1]); }\n\n void all_apply(int k, const F& f) {\n d[k] = mapping(f, d[k]);\n if (k < size) lz[k] = composition(f, lz[k]);\n }\n\n void push(int k) {\n if (lz[k] != id()) { // F 型同士の比較(例: long long)\n all_apply(2*k, lz[k]);\n all_apply(2*k+1, lz[k]);\n lz[k] = id();\n }\n }\n};\n\n// ==============================\n// ここから具体インスタンス例\n// 共通ノード型(lenを持たせることで sum/max の両方に対応)\n// ==============================\nstruct Node {\n long long val; // 区間の値(和 or 最大)\n int len; // その区間の長さ(sumでのみ使用)\n};\n\n// -------- Range Add + Range Sum 用の関数群 --------\nstruct OpSumlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{a.val + b.val, a.len + b.len};\n }\n};\nstruct ESumlazy {\n Node operator()() const { return Node{0LL, 0}; } // 単位元\n};\nstruct MappingAddToSum {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add * 1LL * s.len, s.len};\n }\n};\nstruct ComposeAdd {\n long long operator()(long long fnew, long long fold) const {\n return fnew + fold;\n }\n};\nstruct IdAdd {\n long long operator()() const { return 0LL; }\n};\n\n// Range Add + Range Max\nstatic constexpr long long NEG_INF = -(1LL<<60);\nstruct OpMaxlazy {\n Node operator()(const Node& a, const Node& b) const {\n return Node{std::max(a.val, b.val), a.len + b.len};\n }\n};\nstruct EMaxlazy {\n Node operator()() const { return Node{NEG_INF, 0}; }\n};\nstruct MappingAddToMax {\n Node operator()(long long add, const Node& s) const {\n return Node{s.val + add, s.len};\n }\n};\n\n// ==============================\n// 使用例1: Range Add + Range Sum\n// ==============================\nvoid example_sum() {\n int n = 8;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpSumlazy, ESumlazy,\n MappingAddToSum, ComposeAdd, IdAdd>\n seg(init); // ← もう functor を渡さなくてよい\n\n seg.apply(2, 6, 5); // [2, 6) に +5\n std::cout << seg.all_prod().val << \"\\n\"; // 20\n std::cout << seg.prod(3, 5).val << \"\\n\"; // 10\n}\n\n// ==============================\n// 使用例2: Range Add + Range Max\n// ==============================\nvoid example_max() {\n int n = 10;\n std::vector<Node> init(n, Node{0, 1});\n\n LazySegTree<Node, long long,\n OpMaxlazy, EMaxlazy,\n MappingAddToMax, ComposeAdd, IdAdd>\n seg(init); // ここも functor いらない\n\n seg.apply(2, 5, 1);\n seg.apply(4, 9, 3);\n std::cout << seg.all_prod().val << \"\\n\";\n}\n\n// 1-indexed Fenwick Tree (Binary Indexed Tree)\ntemplate <class T>\nstruct Fenwick {\n int n;\n vector<T> bit;\n\n Fenwick() : n(0) {}\n explicit Fenwick(int n) : n(n), bit(n + 1, T{}) {}\n\n // a[idx] += delta\n void add(int idx, T delta) {\n for (; idx <= n; idx += idx & -idx) bit[idx] += delta;\n }\n\n // prefix sum: a[1] + ... + a[idx]\n T sum(int idx) const {\n T s{};\n for (; idx > 0; idx -= idx & -idx) s += bit[idx];\n return s;\n }\n\n // range sum: a[l] + ... + a[r]\n T range_sum(int l, int r) const {\n if (l > r) return T{};\n return sum(r) - sum(l - 1);\n }\n\n // ---- ここから先は「順序統計」をやりたい人向けのオプション ----\n // すべての要素が「非負の整数」である前提で、\n // 最小の idx を返す: sum(idx) >= t (tは1..sum(n))\n // T が整数型のときのみ有効化\n template <class U = T, std::enable_if_t<std::is_integral_v<U>, int> = 0>\n int kth(U t) const {\n // 前提: すべての add が非負、bitの総和 >= t\n int idx = 0;\n U acc = 0;\n int step = 1;\n while ((step << 1) <= n) step <<= 1; // n以下の最大2冪\n for (int p = step; p; p >>= 1) {\n int nx = idx + p;\n if (nx <= n && acc + (U)bit[nx] < t) {\n acc += (U)bit[nx];\n idx = nx;\n }\n }\n return idx + 1; // 1-indexed\n }\n};\n \n// ===== 素数判定を行う =====\nstruct MillerRabin64 {\n static inline ull mul_mod(ull a, ull b, ull mod) {\n return (ull)((u128)a * b % mod);\n }\n static inline ull pow_mod(ull a, ull e, ull mod) {\n ull r = 1 % mod;\n a %= mod;\n while (e) {\n if (e & 1) r = mul_mod(r, a, mod);\n a = mul_mod(a, a, mod);\n e >>= 1;\n }\n return r;\n }\n static bool isPrime(ull n) {\n if (n < 2) return false;\n // 小さい素数で先に弾く\n static const ull smalls[] = {2,3,5,7,11,13,17,19,23,29,31,37};\n for (ull p : smalls) {\n if (n == p) return true;\n if (n % p == 0) return n == p;\n }\n // n-1 = d * 2^s2\n ull d = n - 1, s2 = 0;\n while (!(d & 1)) d >>= 1, ++s2;\n\n auto witness = [&](ull a) -> bool {\n if (!(a % n)) return false;\n ull x = pow_mod(a, d, n);\n if (x == 1 || x == n - 1) return false;\n for (ull i = 1; i < s2; i++) {\n x = mul_mod(x, x, n);\n if (x == n - 1) return false;\n }\n return true; // 合成数の証人\n };\n\n // 64bit 決定的基底\n static const ull bases[] = {\n 2ULL, 325ULL, 9375ULL, 28178ULL,\n 450775ULL, 9780504ULL, 1795265022ULL\n };\n for (ull a : bases) {\n if (!(a % n)) continue;\n if (witness(a)) return false;\n }\n return true;\n }\n};\nusing MR64 = MillerRabin64;\n\n// modint: mod計算をintを扱うように扱える構造体\n// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a#8-modint\ntemplate<int MOD> struct Fp {\n ll val;\n constexpr Fp(ll v = 0) noexcept : val(v % MOD) {\n if (val < 0) val += MOD;\n }\n constexpr int getmod() { return MOD; }\n constexpr Fp operator - () const noexcept {\n return val ? MOD - val : 0;\n }\n constexpr Fp operator + (const Fp& r) const noexcept { return Fp(*this) += r;}\n constexpr Fp operator - (const Fp& r) const noexcept { return Fp(*this) -= r;}\n constexpr Fp operator * (const Fp& r) const noexcept { return Fp(*this) *= r;}\n constexpr Fp operator / (const Fp& r) const noexcept { return Fp(*this) /= r;}\n constexpr Fp& operator += (const Fp& r) noexcept {\n val += r.val;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n constexpr Fp& operator -= (const Fp& r) noexcept {\n val -= r.val;\n if (val < 0) val += MOD;\n return *this;\n }\n constexpr Fp& operator *= (const Fp& r) noexcept {\n val = val * r.val % MOD;\n return *this;\n }\n constexpr Fp& operator /= (const Fp& r) noexcept {\n return *this *= modpow(r, MOD - 2);\n }\n // 前置 ++x\n constexpr Fp& operator++() noexcept {\n val++;\n if (val >= MOD) val -= MOD;\n return *this;\n }\n\n // 後置 x++\n constexpr Fp operator++(int) noexcept {\n Fp tmp = *this;\n ++(*this);\n return tmp;\n }\n\n // 前置 --x\n constexpr Fp& operator--() noexcept {\n val--;\n if (val < 0) val += MOD;\n return *this;\n }\n\n // 後置 x--\n constexpr Fp operator--(int) noexcept {\n Fp tmp = *this;\n --(*this);\n return tmp;\n }\n constexpr bool operator == (const Fp& r) const noexcept {\n return this->val == r.val;\n }\n constexpr bool operator != (const Fp& r) const noexcept {\n return this->val != r.val;\n }\n constexpr bool operator < (const Fp& r) const noexcept { return this->val < r.val;}\n constexpr bool operator <= (const Fp& r) const noexcept { return this->val <= r.val;}\n constexpr bool operator > (const Fp& r) const noexcept { return this->val > r.val;}\n constexpr bool operator >= (const Fp& r) const noexcept { return this->val >= r.val;}\n friend constexpr ostream& operator << (ostream &os, const Fp<MOD>& x) {\n return os << x.val;\n }\n friend constexpr istream& operator >> (istream &is, Fp<MOD>& x) {\n ll v;\n is >> v;\n x = Fp<MOD>(v);\n return is;\n }\n friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, ll n) noexcept {\n if (n == 0) return 1;\n auto t = modpow(a, n / 2);\n t = t * t;\n if (n & 1) t = t * a;\n return t;\n }\n};\nusing mint = Fp<998244353>;\n\nint solve() {\n int n, q;\n cin >> n >> q;\n \n int size = 1;\n while (size < n) size <<= 1;\n const int SEG_LEN = size;\n vector<ll> seg_tree(SEG_LEN * 2, 0);\n \n auto add = [&](int idx, ll x) -> void {\n idx += SEG_LEN - 1;\n seg_tree[idx] += x;\n for (idx >>= 1; idx >= 1; idx >>= 1) {\n seg_tree[idx] = seg_tree[idx * 2] + seg_tree[idx * 2 + 1];\n }\n };\n \n auto sum_main = [&](auto&& self, int ql, int qr, int sl, int sr, int pos) -> ll {\n // 範囲外\n if (sr <= ql || sl >= qr) return 0;\n // 完全に含まれる\n if (ql <= sl && sr <= qr) return seg_tree[pos];\n // 部分的に含まれる-> 子を検索\n int m = (sl + sr) >> 1;\n ll left = self(self, ql, qr, sl, m, pos * 2);\n ll right = self(self, ql, qr, m, sr, pos * 2 + 1);\n return left + right;\n };\n \n auto getSum = [&](int l, int r) -> ll {\n return sum_main(sum_main, l, r, 1, SEG_LEN + 1, 1) ;\n };\n \n while (q--) {\n int com; ll x, y; cin >> com >> x >> y;\n \n if (com == 0) add(x, y);\n else cout << getSum(x, y + 1) << \"\\n\";\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5476, "score_of_the_acc": -0.5113, "final_rank": 3 }, { "submission_id": "aoj_DSL_2_B_11052969", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct SegmentTree {\n int SEG_LEN;\n vector<ll> tree;\n\n SegmentTree(int size) {\n SEG_LEN = 1;\n while (SEG_LEN < size) SEG_LEN <<= 1;\n tree.assign(2*SEG_LEN, 0);\n }\n\n void update(int index, ll x) {\n index += SEG_LEN;\n tree[index] += x;\n while (index > 1) {\n index >>= 1;\n tree[index] = tree[index*2] + tree[index*2+1];\n }\n }\n\n //[l, r]の最小値を取得\n ll query(int l, int r) {\n l += SEG_LEN;\n r += SEG_LEN + 1; //閉区間 [l,r]に対応\n\n ll result = 0;\n while (l < r) {\n if (l & 1) result += tree[l++];\n if (r & 1) result += tree[--r];\n l >>= 1;\n r >>= 1;\n }\n return result;\n }\n};\n\nint main() {\n int N, Q;\n cin >> N >> Q;\n\n SegmentTree seg(N);\n for (int qi = 0; qi < Q; qi++) {\n int type; cin >> type;\n if (type == 0) {\n int index; ll x;\n cin >> index >> x;\n seg.update(index, x);\n } else if (type == 1) {\n int s, t;\n cin >> s >> t;\n ll result = seg.query(s, t);\n cout << result << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5040, "score_of_the_acc": -1.0506, "final_rank": 17 }, { "submission_id": "aoj_DSL_2_B_11047775", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n;\n vector<long long> node;\n\n SegTree(vector<long long> a) {\n int sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = min(node[2*i+1], node[2*i+2]);\n }\n\n long long getmin(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return INF;\n if(a <= l and r <= b) return node[k];\n\n long long vl = getmin(a, b, 2*k+1, l, (l+r)/2);\n long long vr = getmin(a, b, 2*k+2, (l+r)/2, r);\n return min(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = min(node[2*i+1], node[2*i+2]);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n lazy.resize(2*n-1, 0);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = node[2*i+1] + node[2*i+2];\n }\n\n void eval(int k, int l, int r) {\n if(lazy[k] != 0) {\n node[k] += lazy[k];\n\n if(r - l > 1) {\n lazy[2*k+1] += lazy[k]/2;\n lazy[2*k+2] += lazy[k]/2;\n }\n\n lazy[k] = 0;\n }\n }\n //区間[a,b)に値xを加算\n void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n \n eval(k, l, r);\n\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] += (r-l)*x;\n eval(k, l, r);\n }else {\n add(a, b, x, 2*k+1, l, (l+r)/2);\n add(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = node[2*k+1] + node[2*k+2];\n }\n }\n //区間[a,b)の和を取得\n ll getsum(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return 0;\n\n eval(k, l, r);\n if(a <= l and r <= b) return node[k];\n ll vl = getsum(a, b, 2*k+1, l, (l+r)/2);\n ll vr = getsum(a, b, 2*k+2, (l+r)/2, r);\n return vl + vr;\n }\n};\n\ntemplate<typename T> struct Backet {\n vector<T> array;\n vector<T> backet;\n int N, M;\n\n Backet(vector<T> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n //a_i + ... + a_j\n void add(int i, T x) {\n array[i] += x;\n backet[i/M] += x;\n }\n T getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n T s = 0;\n if(l > r) {\n REP(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n REP(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, Q; cin >> N >> Q;\n vi A(N, 0);\n Backet<int> B(A);\n while(Q--) {\n int com, x, y; cin >> com >> x >> y;\n if(com == 0) {\n x--;\n B.add(x, y);\n }else {\n x--, y--;\n cout << B.getsum(x, y) << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4152, "score_of_the_acc": -1.0009, "final_rank": 16 }, { "submission_id": "aoj_DSL_2_B_11047721", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//BIT, 1-indexedに注意!!!!\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n;\n vector<long long> node;\n\n SegTree(vector<long long> a) {\n int sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = min(node[2*i+1], node[2*i+2]);\n }\n\n long long getmin(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return INF;\n if(a <= l and r <= b) return node[k];\n\n long long vl = getmin(a, b, 2*k+1, l, (l+r)/2);\n long long vr = getmin(a, b, 2*k+2, (l+r)/2, r);\n return min(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = min(node[2*i+1], node[2*i+2]);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n lazy.resize(2*n-1, 0);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = node[2*i+1] + node[2*i+2];\n }\n\n void eval(int k, int l, int r) {\n if(lazy[k] != 0) {\n node[k] += lazy[k];\n\n if(r - l > 1) {\n lazy[2*k+1] += lazy[k]/2;\n lazy[2*k+2] += lazy[k]/2;\n }\n\n lazy[k] = 0;\n }\n }\n //区間[a,b)に値xを加算\n void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n \n eval(k, l, r);\n\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] += (r-l)*x;\n eval(k, l, r);\n }else {\n add(a, b, x, 2*k+1, l, (l+r)/2);\n add(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = node[2*k+1] + node[2*k+2];\n }\n }\n //区間[a,b)の和を取得\n ll getsum(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return 0;\n\n eval(k, l, r);\n if(a <= l and r <= b) return node[k];\n ll vl = getsum(a, b, 2*k+1, l, (l+r)/2);\n ll vr = getsum(a, b, 2*k+2, (l+r)/2, r);\n return vl + vr;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, Q; cin >> N >> Q;\n BIT tree(N);\n while(Q--) {\n int com, x, y; cin >> com >> x >> y;\n if(com == 0) {\n x--;\n tree.add(x, y);\n }else {\n x--; y--;\n cout << tree.sum(x, y) << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3892, "score_of_the_acc": -0.8247, "final_rank": 10 }, { "submission_id": "aoj_DSL_2_B_11047251", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//BIT, 1-indexedに注意!!!!\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n+1, 0), n(_n) {}\n\n //a_1 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i > 0) {\n s += array[i];\n i -= i & -i;\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i <= n) {\n array[i] += x;\n i += i & -i;\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n;\n vector<long long> node;\n\n SegTree(vector<long long> a) {\n int sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = min(node[2*i+1], node[2*i+2]);\n }\n\n long long getmin(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return INF;\n if(a <= l and r <= b) return node[k];\n\n long long vl = getmin(a, b, 2*k+1, l, (l+r)/2);\n long long vr = getmin(a, b, 2*k+2, (l+r)/2, r);\n return min(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = min(node[2*i+1], node[2*i+2]);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n lazy.resize(2*n-1, 0);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = node[2*i+1] + node[2*i+2];\n }\n\n void eval(int k, int l, int r) {\n if(lazy[k] != 0) {\n node[k] += lazy[k];\n\n if(r - l > 1) {\n lazy[2*k+1] += lazy[k]/2;\n lazy[2*k+2] += lazy[k]/2;\n }\n\n lazy[k] = 0;\n }\n }\n //区間[a,b)に値xを加算\n void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n \n eval(k, l, r);\n\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] += (r-l)*x;\n eval(k, l, r);\n }else {\n add(a, b, x, 2*k+1, l, (l+r)/2);\n add(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = node[2*k+1] + node[2*k+2];\n }\n }\n //区間[a,b)の和を取得\n ll getsum(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return 0;\n\n eval(k, l, r);\n if(a <= l and r <= b) return node[k];\n ll vl = getsum(a, b, 2*k+1, l, (l+r)/2);\n ll vr = getsum(a, b, 2*k+2, (l+r)/2, r);\n return vl + vr;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, Q; cin >> N >> Q;\n int M = ceil(sqrt(N));\n vi A(N, 0), B((N+M-1)/M, 0);\n while(Q--) {\n int com, x, y; cin >> com >> x >> y;\n if(com == 0) {\n x--;\n A[x] += y;\n B[x/M] += y;\n }else {\n x--, y--;\n int l = x/M, r = y/M, ans = 0;\n l++;\n if(l <= r) {\n rep(i,x,l*M) ans += A[i];\n rep(i,l,r) ans += B[i];\n rep(i,r*M,y+1) ans += A[i];\n }else {\n rep(i,x,y+1) ans += A[i];\n }\n cout << ans << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 3512, "score_of_the_acc": -0.875, "final_rank": 12 }, { "submission_id": "aoj_DSL_2_B_11047189", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//BIT, 1-indexedに注意!!!!\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n+1, 0), n(_n) {}\n\n //a_1 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i > 0) {\n s += array[i];\n i -= i & -i;\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i <= n) {\n array[i] += x;\n i += i & -i;\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n;\n vector<long long> node;\n\n SegTree(vector<long long> a) {\n int sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = min(node[2*i+1], node[2*i+2]);\n }\n\n long long getmin(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return INF;\n if(a <= l and r <= b) return node[k];\n\n long long vl = getmin(a, b, 2*k+1, l, (l+r)/2);\n long long vr = getmin(a, b, 2*k+2, (l+r)/2, r);\n return min(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = min(node[2*i+1], node[2*i+2]);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n lazy.resize(2*n-1, 0);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = node[2*i+1] + node[2*i+2];\n }\n\n void eval(int k, int l, int r) {\n if(lazy[k] != 0) {\n node[k] += lazy[k];\n\n if(r - l > 1) {\n lazy[2*k+1] += lazy[k]/2;\n lazy[2*k+2] += lazy[k]/2;\n }\n\n lazy[k] = 0;\n }\n }\n //区間[a,b)に値xを加算\n void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n \n eval(k, l, r);\n\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] += (r-l)*x;\n eval(k, l, r);\n }else {\n add(a, b, x, 2*k+1, l, (l+r)/2);\n add(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = node[2*k+1] + node[2*k+2];\n }\n }\n //区間[a,b)の和を取得\n ll getsum(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return 0;\n\n eval(k, l, r);\n if(a <= l and r <= b) return node[k];\n ll vl = getsum(a, b, 2*k+1, l, (l+r)/2);\n ll vr = getsum(a, b, 2*k+2, (l+r)/2, r);\n return vl + vr;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, Q; cin >> N >> Q;\n BIT tree(N);\n while(Q--) {\n int com, x, y; cin >> com >> x >> y;\n if(com == 0) {\n tree.add(x, y);\n }\n if(com == 1) {\n cout << tree.sum(x, y) << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3888, "score_of_the_acc": -0.824, "final_rank": 9 }, { "submission_id": "aoj_DSL_2_B_11047176", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//BIT, 1-indexedに注意!!!!\ntemplate<typename T> struct BIT {\n vector<T> array;\n const int n;\n\n BIT(int _n) : array(_n+1, 0), n(_n) {}\n\n T sum(int i) {\n T s = 0;\n while(i > 0) {\n s += array[i];\n i -= i & -i;\n }\n return s;\n }\n T sum(int i, int j) {\n T ans_i = sum(i-1);\n T ans_j = sum(j);\n return ans_j - ans_i;\n }\n void add(int i, T x) {\n while(i <= n) {\n array[i] += x;\n i += i & -i;\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n;\n vector<long long> node;\n\n SegTree(vector<long long> a) {\n int sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = min(node[2*i+1], node[2*i+2]);\n }\n\n long long getmin(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return INF;\n if(a <= l and r <= b) return node[k];\n\n long long vl = getmin(a, b, 2*k+1, l, (l+r)/2);\n long long vr = getmin(a, b, 2*k+2, (l+r)/2, r);\n return min(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = min(node[2*i+1], node[2*i+2]);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1);\n lazy.resize(2*n-1, 0);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = node[2*i+1] + node[2*i+2];\n }\n\n void eval(int k, int l, int r) {\n if(lazy[k] != 0) {\n node[k] += lazy[k];\n\n if(r - l > 1) {\n lazy[2*k+1] += lazy[k]/2;\n lazy[2*k+2] += lazy[k]/2;\n }\n\n lazy[k] = 0;\n }\n }\n //区間[a,b)に値xを加算\n void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n \n eval(k, l, r);\n\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] += (r-l)*x;\n eval(k, l, r);\n }else {\n add(a, b, x, 2*k+1, l, (l+r)/2);\n add(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = node[2*k+1] + node[2*k+2];\n }\n }\n //区間[a,b)の和を取得\n ll getsum(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return 0;\n\n eval(k, l, r);\n if(a <= l and r <= b) return node[k];\n ll vl = getsum(a, b, 2*k+1, l, (l+r)/2);\n ll vr = getsum(a, b, 2*k+2, (l+r)/2, r);\n return vl + vr;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, Q; cin >> N >> Q;\n vll A(N, 0);\n LazySegTree seg(A);\n while(Q--) {\n int com, x, y; cin >> com >> x >> y;\n if(com == 0) {\n x--;\n seg.add(x, x+1, y);\n }\n if(com == 1) {\n x--, y--;\n cout << seg.getsum(x, y+1) << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 8596, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_DSL_2_B_11032355", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\n#define rep(i,n,m) for(int i=(int)(n);i < (int)(m); i++)\n#define repm(i,n,m) for(int i=(int)(n);i >= (int)(m); i--)\n// #define _GLIBCXX_DEBUG\nusing namespace std;\n\n/*\nfa: 値の更新をする際に操作を指定する関数 || ラムダ式で関数を作る || 例: RSQ -> auto fa = [](int &x1, int &x2){ return x1 + x2; }; \nfx: クエリでやる操作を指定する関数 || ラムダ式で関数を作る || 例: RMQ -> auto fx = [](int &x1, int &x2){ return min(x1, x2); }; \nex: fx の 単位元 || 例: RMQ -> int ex = numeric_limit<int>::max();, RSQ -> int ex = 0;\n\ntips: 関数の引数に & つけるとバグる\n*/\n\ntemplate<class X>\nstruct SegTree{\n using FX = function<X(X, X)>;\n int n;\n FX fx, fa;\n const X ex;\n vector<X> dat;\n\n SegTree(int n_, FX fa_, FX fx_, X ex_) : n(), fa(fa_), fx(fx_), ex(ex_){\n int x = 1;\n while(x < n_){\n x *= 2;\n }\n n = x;\n dat.resize(2 * n - 1, ex_);\n }\n\n void set(int i, X val){\n dat[i + n - 1] = val;\n }\n void build(){\n for(int i = n - 2; i >= 0; i--){\n dat[i] = fx(dat[2 * i + 1], dat[2 * i + 2]);\n }\n }\n\n void update(int i, X val){ // 0-index\n i += n - 1;\n dat[i] = fa(dat[i], val);\n while(i > 0){\n i = (i - 1) / 2;\n dat[i] = fx(dat[2 * i + 1], dat[2 * i + 2]);\n }\n }\n\n X query(int a, int b){ // 0-index\n return query_sub(a, b, 0, 0, n);\n }\n X query_sub(int a, int b, int k, int l, int r){ // a,b :探索範囲の指定 || k:今調べている dat の idx || l,r: dat[k]の示す範囲\n if(r <= a or b <= l){\n return ex;\n }\n else if(a <= l and r <= b){\n return dat[k];\n }\n else{\n X vl = query_sub(a, b, k * 2 + 1, l, (l + r) / 2);\n X vr = query_sub(a, b, k * 2 + 2, (l + r) / 2, r);\n return fx(vl, vr);\n }\n }\n};\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n\n int n,q;\n cin >> n >> q;\n\n /*\n auto fa = [](int x1, int x2){ return x2; };\n auto fx = [](int x1, int x2){ return min(x1, x2); };\n int ex = numeric_limits<int>::max();\n SegTree<int> RMQ(n, fa, fx, ex);\n */\n\n auto fa = [](int x1, int x2){ return x1 + x2; };\n auto fx = [](int x1, int x2){ return x1 + x2; };\n int ex = 0;\n SegTree<int> RSQ(n, fa, fx, ex);\n\n while(q--){\n int op;\n cin >> op;\n\n if(op == 0){\n int x,y;\n cin >> x >> y;\n x--;\n RSQ.update(x, y);\n }\n\n if(op == 1){\n int x,y;\n cin >> x >> y;\n x--; y--;\n cout << RSQ.query(x, y + 1) << '\\n';\n }\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 4148, "score_of_the_acc": -0.3751, "final_rank": 2 }, { "submission_id": "aoj_DSL_2_B_10992973", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\ntemplate <class S, S (*op)(S, S), S (*e)()>\nstruct segtree {\n int _n,size=1,log=0;\n vc<S> d; //1-indexed\n\tsegtree(): segtree(0){}\n segtree(int n): segtree(vc<S>(n,e())){}\n\tsegtree(const vc<S> &v): _n(sz(v)){\n while(_n>size) size<<=1, log++;\n\t\td.assign(2*size,e());\n\t\trep(i,_n) d[size+i]=v[i];\n\t\tpre(i,1,size) update(i);\n }\n\tvoid update(int k) { d[k]=op(d[2*k], d[2*k+1]); }\n void set(int p, S x){\n\t\tassert(0 <= p && p < _n);\n\t\tp+=size;\n\t\td[p]=x;\n\t\trep(i,1,log+1) update(p>>i);\n\t}\n\tS get(int p) const { \n\t\tassert(0 <= p && p < _n);\n\t\treturn d[p+size];\n\t}\n\tS prod(int l, int r) const {\n\t\tassert(0 <= l && l <= r && r <= _n);\n\t\tS sml=e(), smr=e();\n\t\tl+=size; r+=size;\n\t\twhile(l<r){\n\t\t\tif(l&1) sml=op(sml,d[l++]);\n\t\t\tif(r&1) smr=op(d[--r],smr);\n\t\t\tl>>=1; r>>=1;\n\t\t}\n\t\treturn op(sml,smr);\n\t}\n\tS all_prod() const { return d[1]; }\n\t\n\ttemplate <bool (*f)(S)> int max_right(int l, int r) const {\n return min(r, max_right(l, [](S x) { return f(x); }));\n }\n\ttemplate <bool (*f)(S)> int max_right(int l) const {\n return max_right(l, [](S x) { return f(x); });\n }\n\ttemplate <class F> int max_right(int l, int r, F f) const {\n\t\treturn min(r, max_right<F>(l, f));\n }\n template <class F> int max_right(int l, F f) const {\n\t\tassert(0 <= l && l <= _n);\n assert(f(e()));\n if (l == _n) return _n;\n l += size;\n S sm = e();\n do {\n while (l % 2 == 0) l >>= 1;\n if (!f(op(sm, d[l]))) {\n while (l < size) {\n l = (2 * l);\n if (f(op(sm, d[l]))) {\n sm = op(sm, d[l]);\n l++;\n }\n }\n return l - size;\n }\n sm = op(sm, d[l]);\n l++;\n } while ((l & -l) != l);\n return _n;\n }\n\n\ttemplate <bool (*f)(S)> int min_left(int l, int r) const {\n return max(l, min_left(r, [](S x) { return f(x); }));\n }\n template <bool (*f)(S)> int min_left(int r) const {\n return min_left(r, [](S x) { return f(x); });\n }\n\ttemplate <class F> int min_left(int l, int r, F f) const {\n\t\treturn max(l, min_left<F>(r, f));\n\t}\n template <class F> int min_left(int r, F f) const {\n\t\tassert(0 <= r && r <= _n);\n assert(f(e()));\n if (r == 0) return 0;\n r += size;\n S sm = e();\n do {\n r--;\n while (r > 1 && (r % 2)) r >>= 1;\n if (!f(op(d[r], sm))) {\n while (r < size) {\n r = (2 * r + 1);\n if (f(op(d[r], sm))) {\n sm = op(d[r], sm);\n r--;\n }\n }\n return r + 1 - size;\n }\n sm = op(d[r], sm);\n } while ((r & -r) != r);\n return 0;\n }\n inline S operator[](int i) { return get(i); }\n /* debug */\n void print() {\n cerr << \"print: \";\n rep(i,_n){\n cerr << (*this)[i];\n if(i!=_n) cerr << \" \";\n }\n cerr << endl;\n }\n};\n\nusing S=ll;\nS op(S a, S b) { return a+b; }\nS e() { return 0; }\n\nint main(){\t\n\tios::sync_with_stdio(false);\n \tcin.tie(0);\n\tint n,q; cin >> n >> q;\n vll a(n);\n\tsegtree<S,op,e> seg(a);\n\n rep(i,q){\n int type; cin >> type;\n if(type==0){\n int s,x; cin >> s >> x; s--;\n seg.set(s,seg[s]+x);\n } else {\n int s,t; cin >> s >> t; s--;\n cout << seg.prod(s,t) << endl;\n }\n }\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5828, "score_of_the_acc": -0.9555, "final_rank": 14 }, { "submission_id": "aoj_DSL_2_B_10992849", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\ntemplate <class S, S (*op)(S, S), S (*e)()>\nstruct segtree {\n int _n,size=1,log=0;\n vc<S> d; //1-indexed\n\tsegtree(): segtree(0){}\n segtree(int n): segtree(vc<S>(n,e())){}\n\tsegtree(const vc<S> &v): _n(sz(v)){\n while(_n>size) size<<=1, log++;\n\t\td.assign(2*size,e());\n\t\trep(i,_n) d[size+i]=v[i];\n\t\tpre(i,1,size) update(i);\n }\n\tvoid update(int k) { d[k]=op(d[2*k], d[2*k+1]); }\n void set(int p, S x){\n\t\tassert(0 <= p && p < _n);\n\t\tp+=size;\n\t\td[p]=x;\n\t\trep(i,1,log+1) update(p>>i);\n\t}\n\tS get(int p) const { \n\t\tassert(0 <= p && p < _n);\n\t\treturn d[p+size];\n\t}\n\tS prod(int l, int r) const {\n\t\tassert(0 <= l && l <= r && r <= _n);\n\t\tS sml=e(), smr=e();\n\t\tl+=size; r+=size;\n\t\twhile(l<r){\n\t\t\tif(l&1) sml=op(sml,d[l++]);\n\t\t\tif(r&1) smr=op(d[--r],smr);\n\t\t\tl>>=1; r>>=1;\n\t\t}\n\t\treturn op(sml,smr);\n\t}\n\tS all_prod() const { return d[1]; }\n\t\n\ttemplate <bool (*f)(S)> int max_right(int l, int r) const {\n return min(r, max_right(l, [](S x) { return f(x); }));\n }\n\ttemplate <bool (*f)(S)> int max_right(int l) const {\n return max_right(l, [](S x) { return f(x); });\n }\n\ttemplate <class F> int max_right(int l, int r, F f) const {\n\t\treturn min(r, max_right<F>(l, f));\n }\n template <class F> int max_right(int l, F f) const {\n\t\tassert(0 <= l && l <= _n);\n assert(f(e()));\n if (l == _n) return _n;\n l += size;\n S sm = e();\n do {\n while (l % 2 == 0) l >>= 1;\n if (!f(op(sm, d[l]))) {\n while (l < size) {\n l = (2 * l);\n if (f(op(sm, d[l]))) {\n sm = op(sm, d[l]);\n l++;\n }\n }\n return l - size;\n }\n sm = op(sm, d[l]);\n l++;\n } while ((l & -l) != l);\n return _n;\n }\n\n\ttemplate <bool (*f)(S)> int min_left(int l, int r) const {\n return max(l, min_left(r, [](S x) { return f(x); }));\n }\n template <bool (*f)(S)> int min_left(int r) const {\n return min_left(r, [](S x) { return f(x); });\n }\n\ttemplate <class F> int min_left(int l, int r, F f) const {\n\t\treturn max(l, min_left<F>(r, f));\n\t}\n template <class F> int min_left(int r, F f) const {\n\t\tassert(0 <= r && r <= _n);\n assert(f(e()));\n if (r == 0) return 0;\n r += size;\n S sm = e();\n do {\n r--;\n while (r > 1 && (r % 2)) r >>= 1;\n if (!f(op(d[r], sm))) {\n while (r < size) {\n r = (2 * r + 1);\n if (f(op(d[r], sm))) {\n sm = op(d[r], sm);\n r--;\n }\n }\n return r + 1 - size;\n }\n sm = op(d[r], sm);\n } while ((r & -r) != r);\n return 0;\n }\n inline S operator[](int i) { return get(i); }\n /* debug */\n void print() {\n cerr << \"print: \";\n rep(i,_n){\n cerr << (*this)[i];\n if(i!=_n) cerr << \" \";\n }\n cerr << endl;\n }\n};\n\nusing S=ll;\nS op(S a, S b) { return a+b; }\nS e() { return 0; }\n\nint main(){\t\n\tios::sync_with_stdio(false);\n \tcin.tie(0);\n\tint n,q; cin >> n >> q;\n\tsegtree<S,op,e> seg(n);\n\n\trep(i,q){\n\t\tint t; cin >> t;\n\t\tif(t==0){\n\t\t\tint x; ll v; cin >> x >> v; x--;\n\t\t\tseg.set(x,seg[x]+v);\n\t\t} else {\n\t\t\tint s,t; cin >> s >> t; s--;\n\t\t\tcout << seg.prod(s,t) << \"\\n\";\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5976, "score_of_the_acc": -0.6097, "final_rank": 7 }, { "submission_id": "aoj_DSL_2_B_10985210", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint a[1<<17];\nint main(){\n int n,q;\n cin >> n >> q;\n auto add=[&](int x,int d){\n for(int i=x;i<(1<<17);i=(i|(i+1)))a[i]+=d; \n };\n auto suma=[&](int x){\n //1-indexed\n int ans=0;\n for(int i=x;i>0;i=(i&(i-1)))ans+=a[i-1];\n return ans;\n };\n auto sumb=[&](int l,int r){\n //1-indeded\n return suma(r)-suma(l-1) ;\n };\n while(q--){\n int com,x,y;\n cin >> com >> x >> y;\n if(com==0){\n add(x-1,y);\n }else{\n cout << sumb(x,y) << \"\\n\";\n }\n }\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3968, "score_of_the_acc": -0.5897, "final_rank": 6 }, { "submission_id": "aoj_DSL_2_B_10985174", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 1;\nint v[140000];\n\nvoid add(int i, int x) {\n for(int t = i; t < N; t |= (t + 1)) v[t] += x;\n}\n\nint sum(int i) {\n int ans = 0;\n for(int t = i; t > 0; t &= (t - 1)) ans += v[t - 1];\n return ans;\n}\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n \n int n, q;\n cin >> n >> q;\n while(N < n) N <<= 1;\n \n while(q--) {\n int cmd;\n cin >> cmd;\n \n if(cmd == 0) {\n int i, x;\n cin >> i >> x;\n --i;\n \n add(i, x);\n }\n \n if(cmd == 1) {\n int s, t;\n cin >> s >> t;\n --s;\n \n cout << sum(t) - sum(s) << endl;\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3812, "score_of_the_acc": -0.559, "final_rank": 5 }, { "submission_id": "aoj_DSL_2_B_10940751", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\n\ntemplate<typename T>\nclass BIT{\n\tint n;\n\tvector<T> node;\npublic:\n\tBIT(int N): n(N){ node = vector<T>(n + 1, 0);}\n\t\n\tvoid add(int x, T y){\n\t\twhile(x <= n){\n\t\t\tnode[x] += y;\n\t\t\tx += x & (-x);\n\t\t}\n\t}\n\t\n\tT sum(int i){\n\t\tT s = 0;\n\t\twhile(i > 0){\n\t\t\ts += node[i];\n\t\t\ti -= i & (-i);\n\t\t}\n\t\treturn s;\n\t}\n\t\n\tT solve(int l, int r){\n\t\treturn sum(r) - sum(l - 1);\n\t}\n};\n\nint main(){\n\tint n, q;\n\tcin >> n >> q;\n\tBIT<int> bt(n);\n\tint com, x, y;\n\twhile(q--){\n\t\tcin >> com >> x >> y;\n\t\tif(com) cout << bt.solve(x, y) << endl;\n\t\telse bt.add(x, y);\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3712, "score_of_the_acc": -0.5393, "final_rank": 4 }, { "submission_id": "aoj_DSL_2_B_10937833", "code_snippet": "#include<iostream>\n#include<vector>\n#include<functional>\nusing namespace std;\n\ntemplate<typename T>\nclass Seg_tree{\n\tint n;\n\tT st;\n\tvector<T> node;\n\tfunction<T(T, T)> func;\npublic:\n\tSeg_tree(int N, function<T(T, T)> f, T m = 0): func(f), st(m){\n\t\tn = 1;\n\t\twhile(n < N) n *= 2;\n\t\tnode = vector<T>(2 * n - 1, st);\n\t}\n\t\n\tvoid set(int x, T y){\n\t\tx += n - 1;\n\t\tnode[x] += y;\n\t\twhile(x > 0){\n\t\t x = (x - 1) / 2;\n\t\t\tnode[x] = func(node[2 * x + 1], node[2 * x + 2]);\n\t\t}\n\t}\n\t\n\tT solve(int l, int r){\n\t\tl += n - 1, r += n - 1;\n\t\tT vl = st, vr = st;\n\t\twhile(l < r){\n\t\t\tif(l % 2 == 0) {vl = func(vl, node[l]), l++;}\n\t\t\tl /= 2;\n\t\t\tif(r % 2 == 0) {r--, vr = func(vr, node[r]);}\n\t\t\tr /= 2;\n\t\t}\n\t\treturn func(vl, vr);\n\t}\n\t\n\t//void putv() { for(int i = n - 1; i < 2 * n - 1; i++) cout << node[i] << endl;}\n};\n\nint main(){\n\tint n, q;\n\tcin >> n >> q;\n\tSeg_tree<long long> st(n, [](long long a, long long b){ return a + b;});\n\tlong long com, x, y;\n\twhile(q--){\n\t\tcin >> com >> x >> y;\n\t\tif(com) cout << st.solve(x - 1, y) << endl;\n\t\telse st.set(x - 1, y);\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5456, "score_of_the_acc": -0.8824, "final_rank": 13 }, { "submission_id": "aoj_DSL_2_B_10928478", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nint main(){\n ll n,q; cin>>n>>q;\n vector<ll> A(n+1,0);\n\n for(int i=0;i<q;i++){\n int com; cin>>com;\n if(com==0){\n ll i,x; cin>>i>>x;\n while(i<=n){\n A[i]+=x;\n i+=i&-i;\n }\n }\n if(com==1){\n ll s,t; cin>>s>>t; s--;\n ll ssum=0,tsum=0;\n while(s>0){\n ssum+=A[s];\n s-=s&-s;\n }\n while(t>0){\n tsum+=A[t];\n t-=t&-t;\n }\n cout<<tsum-ssum<<endl;;\n }\n }\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3860, "score_of_the_acc": -0.8185, "final_rank": 8 }, { "submission_id": "aoj_DSL_2_B_10924037", "code_snippet": "#include <iostream>\n#include <vector>\n\nint n;\n\nvoid add(int i, int x, std::vector<long long> &segTree) {\n i += n; // 0-indexed to leaf\n segTree[i] += x;\n while (i > 1) { // update parents\n i /= 2;\n segTree[i] = segTree[2*i] + segTree[2*i + 1];\n }\n}\n\nlong long getSum(int s, int t, std::vector<long long> &segTree) {\n long long res = 0;\n s += n;\n t += n;\n while (s <= t) {\n if (s % 2 == 1) res += segTree[s++];\n if (t % 2 == 0) res += segTree[t--];\n s /= 2;\n t /= 2;\n }\n return res;\n}\n\nint main() {\n int q;\n std::cin >> n >> q;\n\n std::vector<long long> segTree(2 * n, 0);\n\n for (int i = 0; i < q; ++i) {\n int com, x, y;\n std::cin >> com >> x >> y;\n if (com == 0) add(x, y, segTree); // 0-indexed\n else std::cout << getSum(x, y, segTree) << '\\n';\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4556, "score_of_the_acc": -1.0804, "final_rank": 19 }, { "submission_id": "aoj_DSL_2_B_10914567", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, s, e) for (int i = (int)(s); i < (int)(e); ++i)\n\ntemplate<typename T>\nstruct FenwickTree {\n\tvector<T> data;\n\tFenwickTree(int size) : data(size + 1, 0) {}\n\t\n\tvoid add(int k, T x) {\n\t\tfor (++k; k < data.size(); k += k & -k) data[k] += x;\n\t}\n\t\n\tT sum(int k) { // [0, a]\n\t\tif (k < 0) return 0;\n\t\tT res = 0;\n\t\tfor (++k; k > 0; k -= k & -k) res += data[k];\n\t\treturn res;\n\t}\n\t\n\tT sum(int l, int r) { // [l, r]\n\t\treturn sum(r) - sum(l - 1);\n\t}\n};\n\nint main() {\n\tcin.tie(nullptr);\n\tios_base::sync_with_stdio(false);\n\t\n\tint N, Q;\n\tcin >> N >> Q;\n\t\n\tFenwickTree<ll> BIT(N);\n\t\n\trep(query, 0, Q) {\n\t\tint t, x, y;\n\t\tcin >> t >> x >> y;\n\t\t\n\t\tif (t == 0) {\n\t\t\t--x;\n\t\t\tBIT.add(x, y);\n\t\t} else {\n\t\t\t--x, --y;\n\t\t\tcout << BIT.sum(x, y) << '\\n';\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3856, "score_of_the_acc": -0.0677, "final_rank": 1 }, { "submission_id": "aoj_DSL_2_B_10888134", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing Graph = vector<vector<int>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(int i = a; i < b; i++)\n#define all(v) v.begin(), v.end()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define inf 1070000000\n#define INF 4500000000000000000\n#define MOD 998244353\n//#define MOD 1000000007\n#define pi 3.14159265358979\n\ntemplate<class T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<class T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\n\n//xのn乗\nll llpow(ll x, ll n) {\n ll ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\nll modpow(ll x, ll n, ll mod) {\n ll ans = 1;\n while(n > 0) {\n if(n & 1) ans = ans * x % mod;\n x = x * x % mod;\n n >>= 1;\n }\n return ans;\n}\n//mod pでのaの逆元\nll inverse(ll a, ll p) {\n return modpow(a, p-2, p);\n}\n//nの階乗\nll fact(ll n) {\n if(n == 0) return 1;\n else return n * fact(n-1);\n}\nll modfact(ll n, ll mod) {\n if(n == 0) return 1;\n else return (n * modfact(n-1, mod)) % mod;\n}\n//nCr=n!/r!(n-r)! mod p\nll comb(ll n, ll r, ll mod) {\n ll a = modfact(n, mod), b = modfact(r, mod), c = modfact(n-r, mod);\n b = inverse(b, mod); c = inverse(c, mod);\n return (((a*b)%mod)*c)%mod;\n}\n\n//1+2+...+n = n(n+1)/2\nll triangle(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n//素数判定\nbool is_prime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\n//左回転\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\ndouble dist(ll a, ll b, ll x, ll y) {\n return sqrt((a-x)*(a-x) + (b-y)*(b-y));\n}\nint man(int a, int b, int x, int y) {\n return abs(a-x) + abs(b-y);\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n rep(i,0,H) rep(j,0,W) dist[i][j] = inf;\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvoid floyd(vector<vector<ll>> &G) {\n int N = G.size();\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(G[i][j] > G[i][k] + G[k][j]) {\n G[i][j] = G[i][k] + G[k][j];\n }\n }\n }\n }\n}\n\n//Union-Find\nvector<int> par(0);\nint root(int x) {\n if(par[x] == x) {\n return x;\n }else {\n return par[x] = root(par[x]);\n }\n}\nbool same(int x, int y) {\n return root(x) == root(y);\n}\nvoid unite(int x, int y) {\n x = root(x);\n y = root(y);\n if(x == y) return;\n par[x] = y;\n}\n\nvoid solve() {\n}\n\nint main() {\n int N, Q, tmp = 1; cin >> N >> Q;\n while(tmp < N) tmp *= 2;\n vector<ll> A(2*tmp, 0);\n\n while(Q--) {\n int com; cin >> com;\n if(com == 0) {\n int i; ll x; cin >> i >> x; i--;\n int p = tmp + i;\n A[p] += x;\n while(p != 1) {\n A[p/2] += x;\n p /= 2;\n }\n }\n if(com == 1) {\n int s, t; cin >> s >> t; s--, t--;\n int p = tmp + s, q = tmp + t;\n\n if(p == q) {\n cout << A[p] << \"\\n\";\n continue;\n }\n\n ll ans = 0;\n while(p/2 != q/2) {\n if(p % 2 == 1) ans -= A[p-1];\n p /= 2;\n\n if(q % 2 == 0) ans -= A[q+1];\n q /= 2;\n }\n\n cout << A[p/2] + ans << \"\\n\";\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5096, "score_of_the_acc": -1.0616, "final_rank": 18 }, { "submission_id": "aoj_DSL_2_B_10887933", "code_snippet": "#define _GLGBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n\nint n, q, tree_length = 1;\nvector<int> segment_tree;\n\nint segment_tree_build(int node) {\n int left = 2 * node, right = 2 * node + 1;\n\n if (left < tree_length) {\n return segment_tree.at(node) = segment_tree_build(left) + segment_tree_build(right);\n } else\n return segment_tree.at(node);\n}\n\nvoid segment_tree_add(int x, int y) {\n x = tree_length / 2 + x;\n\n segment_tree.at(x) += y;\n\n while (true) {\n x /= 2;\n\n if (x)\n segment_tree.at(x) = segment_tree.at(x * 2) + segment_tree.at(x * 2 + 1);\n else\n break;\n }\n}\n\nint segment_tree_get_sum(int x, int y, int l = 1, int r = tree_length / 2, int pos = 1) {\n int res = 0;\n\n if (y <= l || r <= x)\n return 0;\n \n if (x <= l && r <= y) {\n return segment_tree[pos];\n }\n\n return res += segment_tree_get_sum(x, y, l, (l + r) / 2, pos * 2) + segment_tree_get_sum(x, y, (l + r) / 2, r, pos * 2 + 1);\n}\n\nint main()\n{\n cin >> n >> q;\n\n if (n == 1)\n segment_tree.push_back(0);\n else {\n while(2 * n > tree_length)\n tree_length *= 2;\n\n segment_tree.resize(tree_length);\n\n for (int i = tree_length / 2; i < tree_length; i++)\n segment_tree.at(i) = 0;\n\n segment_tree_build(1);\n }\n\n for (int j = 0; j < q; j++) {\n int com, x, y;\n cin >> com >> x >> y;\n\n if (com == 0) {\n if (n == 1)\n segment_tree.at(--x) += y;\n else\n segment_tree_add(--x, y);\n } else {\n if (n == 1)\n cout << segment_tree.at(--x) << '\\n';\n else\n cout << segment_tree_get_sum(--x, y, 0, tree_length / 2, 1) << '\\n';\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 4120, "score_of_the_acc": -0.9946, "final_rank": 15 }, { "submission_id": "aoj_DSL_2_B_10885716", "code_snippet": "#define _GLGBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n\nint n, q, tree_length = 1;\nvector<int> segment_tree;\n\nint segment_tree_build(int node) {\n int left = 2 * node, right = 2 * node + 1;\n\n if (left < tree_length) {\n return segment_tree.at(node) = segment_tree_build(left) + segment_tree_build(right);\n } else\n return segment_tree.at(node);\n}\n\nvoid segment_tree_add(int x, int y) {\n x = tree_length / 2 + x;\n\n segment_tree.at(x) += y;\n\n while (true) {\n x /= 2;\n\n if (x)\n segment_tree.at(x) = segment_tree.at(x * 2) + segment_tree.at(x * 2 + 1);\n else\n break;\n }\n}\n\nint segment_tree_getSum(int x, int y) {\n int res = 0;\n\n x = tree_length / 2 + x;\n y = tree_length / 2 + y;\n\n while (x < y) {\n if (x % 2)\n res += segment_tree.at(x++);\n\n x /= 2;\n\n if (y % 2) \n res += segment_tree.at(--y);\n \n y /= 2;\n }\n\n return res;\n}\n\nint main()\n{\n cin >> n >> q;\n\n if (n == 1)\n segment_tree.push_back(0);\n else {\n while(2 * n > tree_length)\n tree_length *= 2;\n\n segment_tree.resize(tree_length);\n\n for (int i = tree_length / 2; i < tree_length; i++)\n segment_tree.at(i) = 0;\n\n segment_tree_build(1);\n }\n\n for (int j = 0; j < q; j++) {\n int com, x, y;\n cin >> com >> x >> y;\n\n if (com == 0) {\n if (n == 1)\n segment_tree.at(--x) += y;\n else\n segment_tree_add(--x, y);\n } else {\n if (n == 1)\n cout << segment_tree.at(--x) << '\\n';\n else\n cout << segment_tree_getSum(--x, y) << '\\n';\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 4144, "score_of_the_acc": -0.8743, "final_rank": 11 } ]
aoj_DSL_2_C_cpp
Range Search (kD Tree) The range search problem consists of a set of attributed records S to determine which records from S intersect with a given range. For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set. Input n x 0 y 0 x 1 y 1 : x n-1 y n-1 q sx 0 tx 0 sy 0 ty 0 sx 1 tx 1 sy 1 ty 1 : sx q-1 tx q-1 sy q-1 ty q-1 The first integer n is the number of points. In the following n lines, the coordinate of the i -th point is given by two integers x i and y i . The next integer q is the number of queries. In the following q lines, each query is given by four integers, sx i , tx i , sy i , ty i . Output For each query, report IDs of points such that sx i ≤ x ≤ tx i and sy i ≤ y ≤ ty i . The IDs should be reported in ascending order. Print an ID in a line, and print a blank line at the end of output for the each query. Constraints 0 ≤ n ≤ 500,000 0 ≤ q ≤ 20,000 -1,000,000,000 ≤ x , y , sx , tx , sy , ty ≤ 1,000,000,000 sx ≤ tx sy ≤ ty For each query, the number of points which are within the range is less than or equal to 100. Sample Input 1 6 2 1 2 2 4 2 6 2 3 3 5 4 2 2 4 0 4 4 10 2 5 Sample Output 1 0 1 2 4 2 3 5
[ { "submission_id": "aoj_DSL_2_C_11053254", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n int x, y, idx;\n};\n\nstruct KDNode {\n Point p;\n KDNode *left, *right;\n int minX, maxX, minY, maxY;\n\n KDNode() : left(nullptr), right(nullptr) {}\n};\n\nbool cmpX(const Point &a, const Point &b) { return a.x < b.x; }\nbool cmpY(const Point &a, const Point &b) { return a.y < b.y; }\n\nKDNode* build(vector<Point>::iterator begin, vector<Point>::iterator end, int depth) {\n if (begin >= end) return nullptr;\n int n = end - begin;\n int axis = depth % 2;\n\n auto mid = begin + n / 2;\n if (axis == 0) nth_element(begin, mid, end, cmpX);\n else nth_element(begin, mid, end, cmpY);\n\n KDNode* node = new KDNode();\n node->p = *mid;\n node->left = build(begin, mid, depth+1);\n node->right = build(mid+1, end, depth+1);\n\n // 範囲の情報を更新\n node->minX = node->maxX = node->p.x;\n node->minY = node->maxY = node->p.y;\n if (node->left) {\n node->minX = min(node->minX, node->left->minX);\n node->maxX = max(node->maxX, node->left->maxX);\n node->minY = min(node->minY, node->left->minY);\n node->maxY = max(node->maxY, node->left->maxY);\n }\n if (node->right) {\n node->minX = min(node->minX, node->right->minX);\n node->maxX = max(node->maxX, node->right->maxX);\n node->minY = min(node->minY, node->right->minY);\n node->maxY = max(node->maxY, node->right->maxY);\n }\n\n return node;\n}\n\n// 範囲クエリ\nvoid rangeQuery(KDNode* node, int sx, int tx, int sy, int ty, vector<int>& ans) {\n if (!node) return;\n if (node->maxX < sx || node->minX > tx || node->maxY < sy || node->minY > ty) return;\n\n if (sx <= node->p.x && node->p.x <= tx && sy <= node->p.y && node->p.y <= ty) ans.push_back(node->p.idx);\n rangeQuery(node->left, sx, tx, sy, ty, ans);\n rangeQuery(node->right, sx, tx, sy, ty, ans);\n}\n\nint main() {\n int n;\n cin >> n;\n vector<Point> pts(n);\n for (int i = 0; i < n; i++) {\n cin >> pts[i].x >> pts[i].y;\n pts[i].idx = i;\n }\n\n KDNode* root = build(pts.begin(), pts.end(), 0);\n\n int q; cin >> q;\n for (int qi = 0; qi < q; qi++) {\n int sx, tx, sy, ty;\n cin >> sx >> tx >> sy >> ty;\n vector<int> ans;\n rangeQuery(root, sx, tx, sy, ty, ans);\n sort(ans.begin(), ans.end());\n for (int id : ans) cout << id << endl;\n cout << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 830, "memory_kb": 39384, "score_of_the_acc": -1.312, "final_rank": 12 }, { "submission_id": "aoj_DSL_2_C_10994206", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n\n/*\n KDTree\n k次元探索用の二分探索木\n find(sx,tx,sy,ty): sx<=x<=tx,sy<=y<=tyに含まれる点を列挙\n*/\n\nstruct Point {\n int x, y;\n int id;\n};\n\nstruct KDTree {\n struct Node {\n int ind;\n int l;\n int r;\n Node(int _ind): ind(_ind), l(-1), r(-1) {}\n };\n int _n;\n vc<Point> ps;\n vc<Node> tree;\n KDTree(const vc<Point>& _ps): _n(sz(_ps)){\n ps = _ps;\n tree.reserve(_n); \n makeKDTree(0, _n);\n }\n int makeKDTree(int l, int r, int depth=0) {\n if (l >= r) return -1; \n int axis = depth % 2;\n int mid = (l + r) / 2;\n if (axis == 0) { //x分割\n nth_element(ps.bg+l, ps.bg+mid, ps.bg+r, [](const Point& a, const Point& b) { return a.x < b.x; });\n } else { //y分割\n nth_element(ps.bg+l, ps.bg+mid, ps.bg+r, [](const Point& a, const Point& b) { return a.y < b.y; });\n }\n int id=sz(tree);\n tree.eb(mid);\n tree[id].l = makeKDTree(l, mid, depth+1);\n tree[id].r = makeKDTree(mid+1, r, depth+1);\n return id;\n }\n vi find(int sx, int tx, int sy, int ty) {\n vi result;\n find_sub(0, sx, tx, sy, ty, 0, result);\n return result;\n }\n void find_sub(int v, int sx, int tx, int sy, int ty, int depth, vi& result) {\n if (v == -1) return;\n const Point& p = ps[tree[v].ind];\n if (sx <= p.x && p.x <= tx && sy <= p.y && p.y <= ty) result.push_back(p.id);\n int axis = depth % 2;\n if (axis == 0) { // X軸\n if (tree[v].l != -1 && sx <= p.x) find_sub(tree[v].l, sx, tx, sy, ty, depth + 1, result);\n if (tree[v].r != -1 && p.x <= tx) find_sub(tree[v].r, sx, tx, sy, ty, depth + 1, result);\n } else { // Y軸\n if (tree[v].l != -1 && sy <= p.y) find_sub(tree[v].l, sx, tx, sy, ty, depth + 1, result);\n if (tree[v].r != -1 && p.y <= ty) find_sub(tree[v].r, sx, tx, sy, ty, depth + 1, result);\n }\n }\n};\n\nint main() {\n int n; cin >> n;\n vc<Point> ps(n);\n rep(i,n){\n cin >> ps[i].x >> ps[i].y;\n ps[i].id = i;\n }\n KDTree kdtree(ps);\n int q; cin >> q;\n rep(i,q){\n int sx, tx, sy, ty;\n cin >> sx >> tx >> sy >> ty;\n vi res = kdtree.find(sx, tx, sy, ty);\n sort(all(res));\n for (int id : res) cout << id << '\\n';\n cout << '\\n';\n }\n return 0;\n}", "accuracy": 1, "time_ms": 270, "memory_kb": 19968, "score_of_the_acc": -0.4705, "final_rank": 3 }, { "submission_id": "aoj_DSL_2_C_10993946", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n// 点を表す構造体\nstruct Point {\n int id; // 元のインデックス\n int x, y;\n};\n\n// k-d treeをカプセル化する構造体\nstruct KDTree {\n \n // k-d treeのノードを表す内部構造体\n struct Node {\n int location; // pointsベクタ内のインデックス\n int left_child;\n int right_child;\n\n // コンストラクタ\n Node(int loc) : location(loc), left_child(-1), right_child(-1) {}\n };\n\n // --- メンバー変数 ---\n std::vector<Point> points; // 点の元データを保持\n std::vector<Node> tree; // k-d treeのノード配列\n int root; // 根ノードのインデックス\n\n // --- コンストラクタ ---\n // 点のベクタを受け取り、k-d treeを構築する\n KDTree(const std::vector<Point>& initial_points) {\n // 元のデータをコピー\n points = initial_points;\n \n // treeベクタのメモリを事前に確保 (N個のノードが作られるため)\n tree.reserve(points.size()); \n \n // 構築処理を呼び出し、根ノードのインデックスを保存\n root = makeKDTree(0, points.size(), 0);\n }\n\nprivate:\n // --- プライベートメンバー関数 (内部処理) ---\n\n // k-d treeを構築する再帰関数\n // [l, r) の範囲の点で、深さdepthの木を構築し、その根のID (treeベクタのインデックス) を返す\n int makeKDTree(int l, int r, int depth) {\n // 範囲に点がない場合\n if (l >= r) {\n return -1; // -1をNULLノードとする\n }\n\n int axis = depth % 2;\n int mid = (l + r) / 2;\n\n // nth_elementの比較関数をラムダ式で定義\n if (axis == 0) { // X軸で分割\n std::nth_element(points.begin() + l, points.begin() + mid, points.begin() + r, \n [](const Point& a, const Point& b) { return a.x < b.x; });\n } else { // Y軸で分割\n std::nth_element(points.begin() + l, points.begin() + mid, points.begin() + r, \n [](const Point& a, const Point& b) { return a.y < b.y; });\n }\n\n // 新しいノードを作成し、treeベクタに追加\n tree.emplace_back(mid); // Node(mid) を構築して追加\n int current_node_id = tree.size() - 1; // 追加されたノードのインデックス\n\n // 再帰的に左右の子を構築\n tree[current_node_id].left_child = makeKDTree(l, mid, depth + 1);\n tree[current_node_id].right_child = makeKDTree(mid + 1, r, depth + 1);\n\n return current_node_id;\n }\n\n // k-d treeを探索する再帰関数\n // 結果を result ベクタ (参照渡し) に格納する\n void find(int v, int sx, int tx, int sy, int ty, int depth, std::vector<int>& result) {\n // v == -1 はNULLノード\n if (v == -1) {\n return;\n }\n\n // 現在のノードが持つ点を取得 (const参照で効率化)\n const Point& p = points[tree[v].location];\n\n // 点pがクエリ領域に含まれるかチェック\n if (sx <= p.x && p.x <= tx && sy <= p.y && p.y <= ty) {\n result.push_back(p.id);\n }\n\n int axis = depth % 2;\n\n if (axis == 0) { // X軸\n // 左の子の領域 (x <= p.x) がクエリ領域 (sx <= x) と交差するなら探索\n if (tree[v].left_child != -1 && sx <= p.x) {\n find(tree[v].left_child, sx, tx, sy, ty, depth + 1, result);\n }\n // 右の子の領域 (x >= p.x) がクエリ領域 (x <= tx) と交差するなら探索\n if (tree[v].right_child != -1 && p.x <= tx) {\n find(tree[v].right_child, sx, tx, sy, ty, depth + 1, result);\n }\n } else { // Y軸\n // 左の子の領域 (y <= p.y) がクエリ領域 (sy <= y) と交差するなら探索\n if (tree[v].left_child != -1 && sy <= p.y) {\n find(tree[v].left_child, sx, tx, sy, ty, depth + 1, result);\n }\n // 右の子の領域 (y >= p.y) がクエリ領域 (y <= ty) と交差するなら探索\n if (tree[v].right_child != -1 && p.y <= ty) {\n find(tree[v].right_child, sx, tx, sy, ty, depth + 1, result);\n }\n }\n }\n\npublic:\n // --- パブリックメンバー関数 (外部へのインターフェース) ---\n\n // 領域探索を実行し、結果のベクタを返す\n std::vector<int> search(int sx, int tx, int sy, int ty) {\n std::vector<int> result;\n \n // プライベートの探索関数を呼び出す\n find(root, sx, tx, sy, ty, 0, result);\n \n // 結果をIDでソート\n std::sort(result.begin(), result.end());\n \n return result;\n }\n};\n\nint main() {\n int n;\n scanf(\"%d\", &n);\n\n // 点データをstd::vectorで読み込む\n std::vector<Point> initial_points(n);\n for (int i = 0; i < n; i++) {\n scanf(\"%d %d\", &initial_points[i].x, &initial_points[i].y);\n initial_points[i].id = i;\n }\n\n // KDTreeのインスタンスを作成\n // コンストラクタが呼ばれ、木が自動的に構築される\n KDTree kdtree(initial_points);\n\n int q;\n scanf(\"%d\", &q);\n\n for (int i = 0; i < q; i++) {\n int sx, tx, sy, ty;\n scanf(\"%d %d %d %d\", &sx, &tx, &sy, &ty);\n \n // searchメソッドを呼び出して結果を取得\n std::vector<int> result = kdtree.search(sx, tx, sy, ty);\n \n // 出力\n for (int id : result) {\n printf(\"%d\\n\", id);\n }\n printf(\"\\n\");\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 20056, "score_of_the_acc": -0.357, "final_rank": 2 }, { "submission_id": "aoj_DSL_2_C_10993930", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n// 点の最大数\n#define MAX_N 500000\n\n// 点を表す構造体\nstruct Point {\n int id; // 元のインデックス\n int x, y;\n};\n\n// k-d treeのノードを表す構造体\nstruct Node {\n int location; // points配列内のインデックス\n int left_child;\n int right_child;\n};\n\n// グローバル変数\nPoint points[MAX_N]; // 点の配列\nNode tree[MAX_N]; // ツリーのノード配列\nint node_counter = 0; // ノードを割り当てるためのカウンタ\nstd::vector<int> result_vector; // クエリ結果を格納するベクタ\n\n// x座標で比較するための関数\nbool compareX(const Point& a, const Point& b) {\n return a.x < b.x;\n}\n\n// y座標で比較するための関数\nbool compareY(const Point& a, const Point& b) {\n return a.y < b.y;\n}\n\n// k-d treeを構築する再帰関数\n// [l, r) の範囲の点で、深さdepthの木を構築し、その根のIDを返す\nint makeKDTree(int l, int r, int depth) {\n // 範囲に点がない場合\n if (l >= r) {\n return -1; // -1をNULLノードとする\n }\n\n // 分割軸 (0: x, 1: y)\n int axis = depth % 2;\n \n // 中央値のインデックス\n int mid = (l + r) / 2;\n\n // nth_elementを使い、[l, r)の範囲でmid番目に来る要素をO(N)で見つける\n // これにより、points[mid]が中央値となり、\n // [l, mid)にはそれ以下、[mid+1, r)にはそれ以上の要素が配置される\n if (axis == 0) { // X軸で分割\n std::nth_element(points + l, points + mid, points + r, compareX);\n } else { // Y軸で分割\n std::nth_element(points + l, points + mid, points + r, compareY);\n }\n\n // 新しいノードを作成\n int current_node_id = node_counter++;\n tree[current_node_id].location = mid;\n \n // 再帰的に左右の子を構築\n tree[current_node_id].left_child = makeKDTree(l, mid, depth + 1);\n tree[current_node_id].right_child = makeKDTree(mid + 1, r, depth + 1);\n\n return current_node_id;\n}\n\n// k-d treeを探索する関数\nvoid find(int v, int sx, int tx, int sy, int ty, int depth) {\n // NULLノードに到達したら終了\n if (v == -1) {\n return;\n }\n\n // 現在のノードの点を取得\n Point p = points[tree[v].location];\n\n // 点pがクエリ領域に含まれるかチェック\n if (sx <= p.x && p.x <= tx && sy <= p.y && p.y <= ty) {\n result_vector.push_back(p.id);\n }\n\n // 分割軸\n int axis = depth % 2;\n\n if (axis == 0) { // X軸\n // 左の子の領域 (x <= p.x) がクエリ領域 (sx <= x) と交差するなら探索\n if (tree[v].left_child != -1 && sx <= p.x) {\n find(tree[v].left_child, sx, tx, sy, ty, depth + 1);\n }\n // 右の子の領域 (x >= p.x) がクエリ領域 (x <= tx) と交差するなら探索\n if (tree[v].right_child != -1 && p.x <= tx) {\n find(tree[v].right_child, sx, tx, sy, ty, depth + 1);\n }\n } else { // Y軸\n // 左の子の領域 (y <= p.y) がクエリ領域 (sy <= y) と交差するなら探索\n if (tree[v].left_child != -1 && sy <= p.y) {\n find(tree[v].left_child, sx, tx, sy, ty, depth + 1);\n }\n // 右の子の領域 (y >= p.y) がクエリ領域 (y <= ty) と交差するなら探索\n if (tree[v].right_child != -1 && p.y <= ty) {\n find(tree[v].right_child, sx, tx, sy, ty, depth + 1);\n }\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n\tcin.tie(0);\n int n;\n scanf(\"%d\", &n);\n\n for (int i = 0; i < n; i++) {\n scanf(\"%d %d\", &points[i].x, &points[i].y);\n points[i].id = i;\n }\n\n // k-d treeを構築 (根のIDが返る)\n int root = makeKDTree(0, n, 0);\n\n int q;\n scanf(\"%d\", &q);\n\n for (int i = 0; i < q; i++) {\n int sx, tx, sy, ty;\n scanf(\"%d %d %d %d\", &sx, &tx, &sy, &ty);\n \n // クエリ結果をクリア\n result_vector.clear();\n \n // k-d treeを探索\n find(root, sx, tx, sy, ty, 0);\n \n // 結果をIDでソート\n std::sort(result_vector.begin(), result_vector.end());\n \n // 出力\n for (int id : result_vector) {\n printf(\"%d\\n\", id);\n }\n printf(\"\\n\"); // 各クエリの後に空行\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 14792, "score_of_the_acc": -0.2975, "final_rank": 1 }, { "submission_id": "aoj_DSL_2_C_10993927", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n// 点の最大数\n#define MAX_N 100000\n\n// 点を表す構造体\nstruct Point {\n int id; // 元のインデックス\n int x, y;\n};\n\n// k-d treeのノードを表す構造体\nstruct Node {\n int location; // points配列内のインデックス\n int left_child;\n int right_child;\n};\n\n// グローバル変数\nPoint points[MAX_N]; // 点の配列\nNode tree[MAX_N]; // ツリーのノード配列\nint node_counter = 0; // ノードを割り当てるためのカウンタ\nstd::vector<int> result_vector; // クエリ結果を格納するベクタ\n\n// x座標で比較するための関数\nbool compareX(const Point& a, const Point& b) {\n return a.x < b.x;\n}\n\n// y座標で比較するための関数\nbool compareY(const Point& a, const Point& b) {\n return a.y < b.y;\n}\n\n// k-d treeを構築する再帰関数\n// [l, r) の範囲の点で、深さdepthの木を構築し、その根のIDを返す\nint makeKDTree(int l, int r, int depth) {\n // 範囲に点がない場合\n if (l >= r) {\n return -1; // -1をNULLノードとする\n }\n\n // 分割軸 (0: x, 1: y)\n int axis = depth % 2;\n \n // 中央値のインデックス\n int mid = (l + r) / 2;\n\n // nth_elementを使い、[l, r)の範囲でmid番目に来る要素をO(N)で見つける\n // これにより、points[mid]が中央値となり、\n // [l, mid)にはそれ以下、[mid+1, r)にはそれ以上の要素が配置される\n if (axis == 0) { // X軸で分割\n std::nth_element(points + l, points + mid, points + r, compareX);\n } else { // Y軸で分割\n std::nth_element(points + l, points + mid, points + r, compareY);\n }\n\n // 新しいノードを作成\n int current_node_id = node_counter++;\n tree[current_node_id].location = mid;\n \n // 再帰的に左右の子を構築\n tree[current_node_id].left_child = makeKDTree(l, mid, depth + 1);\n tree[current_node_id].right_child = makeKDTree(mid + 1, r, depth + 1);\n\n return current_node_id;\n}\n\n// k-d treeを探索する関数\nvoid find(int v, int sx, int tx, int sy, int ty, int depth) {\n // NULLノードに到達したら終了\n if (v == -1) {\n return;\n }\n\n // 現在のノードの点を取得\n Point p = points[tree[v].location];\n\n // 点pがクエリ領域に含まれるかチェック\n if (sx <= p.x && p.x <= tx && sy <= p.y && p.y <= ty) {\n result_vector.push_back(p.id);\n }\n\n // 分割軸\n int axis = depth % 2;\n\n if (axis == 0) { // X軸\n // 左の子の領域 (x <= p.x) がクエリ領域 (sx <= x) と交差するなら探索\n if (tree[v].left_child != -1 && sx <= p.x) {\n find(tree[v].left_child, sx, tx, sy, ty, depth + 1);\n }\n // 右の子の領域 (x >= p.x) がクエリ領域 (x <= tx) と交差するなら探索\n if (tree[v].right_child != -1 && p.x <= tx) {\n find(tree[v].right_child, sx, tx, sy, ty, depth + 1);\n }\n } else { // Y軸\n // 左の子の領域 (y <= p.y) がクエリ領域 (sy <= y) と交差するなら探索\n if (tree[v].left_child != -1 && sy <= p.y) {\n find(tree[v].left_child, sx, tx, sy, ty, depth + 1);\n }\n // 右の子の領域 (y >= p.y) がクエリ領域 (y <= ty) と交差するなら探索\n if (tree[v].right_child != -1 && p.y <= ty) {\n find(tree[v].right_child, sx, tx, sy, ty, depth + 1);\n }\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n\tcin.tie(0);\n int n;\n scanf(\"%d\", &n);\n\n for (int i = 0; i < n; i++) {\n scanf(\"%d %d\", &points[i].x, &points[i].y);\n points[i].id = i;\n }\n\n // k-d treeを構築 (根のIDが返る)\n int root = makeKDTree(0, n, 0);\n\n int q;\n scanf(\"%d\", &q);\n\n for (int i = 0; i < q; i++) {\n int sx, tx, sy, ty;\n scanf(\"%d %d %d %d\", &sx, &tx, &sy, &ty);\n \n // クエリ結果をクリア\n result_vector.clear();\n \n // k-d treeを探索\n find(root, sx, tx, sy, ty, 0);\n \n // 結果をIDでソート\n std::sort(result_vector.begin(), result_vector.end());\n \n // 出力\n for (int id : result_vector) {\n printf(\"%d\\n\", id);\n }\n printf(\"\\n\"); // 各クエリの後に空行\n }\n\n return 0;\n}", "accuracy": 0.5, "time_ms": 20, "memory_kb": 5912, "score_of_the_acc": -0.0231, "final_rank": 17 }, { "submission_id": "aoj_DSL_2_C_10955026", "code_snippet": "#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nclass Node{\n public:\n int location;\n int p,l,r;\n Node(){}\n};//class后面要加分号\nclass Point{\n public:\n int id,x,y;\n Point(){}\n Point(int id,int x,int y):id(id),x(x),y(y){}//:符号后说明把括号里面的值交给前面那个成员变量\n bool operator <(const Point &p)const{//操作符重载,使小于号在对于point的比较时换成id的大小来排列,&和指针一样给地址但更方便,访问时没有指针那么多规则,更像它自己。最后一个const是保证不改变本身的point\n return id<p.id;//class和struct很像都用.来访问\n }\n void print(){//类里面访问自己的成员变量不用加前缀\n printf(\"%d\\n\",id);\n }\n};\nconst int MAX=10000000;\nconst int NIL=-1;\nint N;\nint np;\nNode T[MAX];\nPoint P[MAX];\nbool lessX(const Point &p1,const Point &p2){//自定义比较器,可以自定义比较规则,非默认,当用sort要把这个加上,当p1的x小于p2的x,bool返回true,这样比较大小进行排列\n return p1.x<p2.x;\n}\nbool lessY(const Point &p1,const Point &p2){\n return p1.y<p2.y;\n}\nint makeKDTree(int l,int r,int depth){\n if(!(l<r))return NIL;\n int mid=(l+r)/2;\n if(depth%2==0){//分奇偶来分别用x,y指标,这样空间利用和搜索效率都提高了,下面的find也要分奇偶用不同指标来寻找\n sort(P+l,P+r,lessX);\n }else sort(P+l,P+r,lessY);\n int t=np++;\n T[t].location=mid;//mid是排好顺序的序列的中间项的小标不是搜索树的下标,但是下面的l和r确是\n T[t].l=makeKDTree(l,mid,depth+1);\n T[t].r=makeKDTree(mid+1,r,depth+1);\n return t;\n}\nvoid find(int v,int sx,int tx,int sy,int ty,int depth,vector<Point> &ans){\n int x=P[T[v].location].x;\n int y=P[T[v].location].y;\n if(x>=sx&&x<=tx&&y>=sy&&y<=ty){\n ans.push_back(P[T[v].location]);\n }\n if(depth%2==0){\n if(T[v].l!=NIL&&x>=sx){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);//上面引用&好处的体现\n }\n if(T[v].r!=NIL&&x<=tx){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }else {\n if(T[v].l!=NIL&&y>=sy){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);\n }\n if(T[v].r!=NIL&&y<=ty){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }\n}\nint main(){\n scanf(\"%d\",&N);\n np=0;\n for(int i=0;i<N;i++){\n int x,y;\n scanf(\"%d %d\",&x,&y);\n P[i]=Point(i,x,y);\n T[i].r=T[i].l=T[i].p=NIL;\n }\n int q;\n scanf(\"%d\",&q);\n vector<Point> ans;\n int root=makeKDTree(0,N,0);//t不是全局变量返回的不是递归很多次的t;\n for(int i=0;i<q;i++){\n int sx,tx,sy,ty;\n scanf(\"%d %d %d %d\",&sx,&tx,&sy,&ty);\n ans.clear();\n find(root,sx,tx,sy,ty,0,ans);\n sort(ans.begin(),ans.end());\n for(int j=0;j<(int)ans.size();j++){\n ans[j].print();\n }\n printf(\"\\n\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 17164, "score_of_the_acc": -0.5061, "final_rank": 4 }, { "submission_id": "aoj_DSL_2_C_10955024", "code_snippet": "#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nclass Node{\n public:\n int location;\n int p,l,r;\n Node(){}\n};//class后面要加分号\nclass Point{\n public:\n int id,x,y;\n Point(){}\n Point(int id,int x,int y):id(id),x(x),y(y){}//:符号后说明把括号里面的值交给前面那个成员变量\n bool operator <(const Point &p)const{//操作符重载,使小于号在对于point的比较时换成id的大小来排列,&和指针一样给地址但更方便,访问时没有指针那么多规则,更像它自己。最后一个const是保证不改变本身的point\n return id<p.id;//class和struct很像都用.来访问\n }\n void print(){//类里面访问自己的成员变量不用加前缀\n printf(\"%d\\n\",id);\n }\n};\nconst int MAX=100000;\nconst int NIL=-1;\nint N;\nint np;\nNode T[MAX];\nPoint P[MAX];\nbool lessX(const Point &p1,const Point &p2){//自定义比较器,可以自定义比较规则,非默认,当用sort要把这个加上,当p1的x小于p2的x,bool返回true,这样比较大小进行排列\n return p1.x<p2.x;\n}\nbool lessY(const Point &p1,const Point &p2){\n return p1.y<p2.y;\n}\nint makeKDTree(int l,int r,int depth){\n if(!(l<r))return NIL;\n int mid=(l+r)/2;\n if(depth%2==0){//分奇偶来分别用x,y指标,这样空间利用和搜索效率都提高了,下面的find也要分奇偶用不同指标来寻找\n sort(P+l,P+r,lessX);\n }else sort(P+l,P+r,lessY);\n int t=np++;\n T[t].location=mid;//mid是排好顺序的序列的中间项的小标不是搜索树的下标,但是下面的l和r确是\n T[t].l=makeKDTree(l,mid,depth+1);\n T[t].r=makeKDTree(mid+1,r,depth+1);\n return t;\n}\nvoid find(int v,int sx,int tx,int sy,int ty,int depth,vector<Point> &ans){\n int x=P[T[v].location].x;\n int y=P[T[v].location].y;\n if(x>=sx&&x<=tx&&y>=sy&&y<=ty){\n ans.push_back(P[T[v].location]);\n }\n if(depth%2==0){\n if(T[v].l!=NIL&&x>=sx){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);//上面引用&好处的体现\n }\n if(T[v].r!=NIL&&x<=tx){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }else {\n if(T[v].l!=NIL&&y>=sy){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);\n }\n if(T[v].r!=NIL&&y<=ty){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }\n}\nint main(){\n scanf(\"%d\",&N);\n np=0;\n for(int i=0;i<N;i++){\n int x,y;\n scanf(\"%d %d\",&x,&y);\n P[i]=Point(i,x,y);\n T[i].r=T[i].l=T[i].p=NIL;\n }\n int q;\n scanf(\"%d\",&q);\n vector<Point> ans;\n int root=makeKDTree(0,N,0);//t不是全局变量返回的不是递归很多次的t;\n for(int i=0;i<q;i++){\n int sx,tx,sy,ty;\n scanf(\"%d %d %d %d\",&sx,&tx,&sy,&ty);\n ans.clear();\n find(root,sx,tx,sy,ty,0,ans);\n sort(ans.begin(),ans.end());\n for(int j=0;j<(int)ans.size();j++){\n ans[j].print();\n }\n printf(\"\\n\");\n }\n return 0;\n}", "accuracy": 0.5, "time_ms": 60, "memory_kb": 5636, "score_of_the_acc": -0.0611, "final_rank": 18 }, { "submission_id": "aoj_DSL_2_C_10955019", "code_snippet": "#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nclass Node{\n public:\n int location;\n int p,l,r;\n Node(){}\n};//class后面要加分号\nclass Point{\n public:\n int id,x,y;\n Point(){}\n Point(int id,int x,int y):id(id),x(x),y(y){}//:符号后说明把括号里面的值交给前面那个成员变量\n bool operator <(const Point &p)const{//操作符重载,使小于号在对于point的比较时换成id的大小来排列,&和指针一样给地址但更方便,访问时没有指针那么多规则,更像它自己。最后一个const是保证不改变本身的point\n return id<p.id;//class和struct很像都用.来访问\n }\n void print(){//类里面访问自己的成员变量不用加前缀\n printf(\"%d\\n\",id);\n }\n};\nconst int MAX=50001;\nconst int NIL=-1;\nint N;\nint np;\nNode T[MAX];\nPoint P[MAX];\nbool lessX(const Point &p1,const Point &p2){//自定义比较器,可以自定义比较规则,非默认,当用sort要把这个加上,当p1的x小于p2的x,bool返回true,这样比较大小进行排列\n return p1.x<p2.x;\n}\nbool lessY(const Point &p1,const Point &p2){\n return p1.y<p2.y;\n}\nint makeKDTree(int l,int r,int depth){\n if(!(l<r))return NIL;\n int mid=(l+r)/2;\n if(depth%2==0){//分奇偶来分别用x,y指标,这样空间利用和搜索效率都提高了,下面的find也要分奇偶用不同指标来寻找\n sort(P+l,P+r,lessX);\n }else sort(P+l,P+r,lessY);\n int t=np++;\n T[t].location=mid;//mid是排好顺序的序列的中间项的小标不是搜索树的下标,但是下面的l和r确是\n T[t].l=makeKDTree(l,mid,depth+1);\n T[t].r=makeKDTree(mid+1,r,depth+1);\n return t;\n}\nvoid find(int v,int sx,int tx,int sy,int ty,int depth,vector<Point> &ans){\n int x=P[T[v].location].x;\n int y=P[T[v].location].y;\n if(x>=sx&&x<=tx&&y>=sy&&y<=ty){\n ans.push_back(P[T[v].location]);\n }\n if(depth%2==0){\n if(T[v].l!=NIL&&x>=sx){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);//上面引用&好处的体现\n }\n if(T[v].r!=NIL&&x<=tx){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }else {\n if(T[v].l!=NIL&&y>=sy){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);\n }\n if(T[v].r!=NIL&&y<=ty){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }\n}\nint main(){\n scanf(\"%d\",&N);\n np=0;\n for(int i=0;i<N;i++){\n int x,y;\n scanf(\"%d %d\",&x,&y);\n P[i]=Point(i,x,y);\n T[i].r=T[i].l=T[i].p=NIL;\n }\n int q;\n scanf(\"%d\",&q);\n vector<Point> ans;\n int root=makeKDTree(0,N,0);//t不是全局变量返回的不是递归很多次的t;\n for(int i=0;i<q;i++){\n int sx,tx,sy,ty;\n scanf(\"%d %d %d %d\",&sx,&tx,&sy,&ty);\n ans.clear();\n find(root,sx,tx,sy,ty,0,ans);\n sort(ans.begin(),ans.end());\n for(int j=0;j<(int)ans.size();j++){\n ans[j].print();\n }\n printf(\"\\n\");\n }\n return 0;\n}", "accuracy": 0.4166666666666667, "time_ms": 20, "memory_kb": 4172, "score_of_the_acc": 0, "final_rank": 19 }, { "submission_id": "aoj_DSL_2_C_10955013", "code_snippet": "#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nclass Node{\n public:\n int location;\n int p,l,r;\n Node(){}\n};//class后面要加分号\nclass Point{\n public:\n int id,x,y;\n Point(){}\n Point(int id,int x,int y):id(id),x(x),y(y){}//:符号后说明把括号里面的值交给前面那个成员变量\n bool operator <(const Point &p)const{//操作符重载,使小于号在对于point的比较时换成id的大小来排列,&和指针一样给地址但更方便,访问时没有指针那么多规则,更像它自己。最后一个const是保证不改变本身的point\n return id<p.id;//class和struct很像都用.来访问\n }\n void print(){//类里面访问自己的成员变量不用加前缀\n printf(\"%d\\n\",id);\n }\n};\nconst int MAX=50000;\nconst int NIL=-1;\nint N;\nint np;\nNode T[MAX];\nPoint P[MAX];\nbool lessX(const Point &p1,const Point &p2){//自定义比较器,可以自定义比较规则,非默认,当用sort要把这个加上,当p1的x小于p2的x,bool返回true,这样比较大小进行排列\n return p1.x<p2.x;\n}\nbool lessY(const Point &p1,const Point &p2){\n return p1.y<p2.y;\n}\nint makeKDTree(int l,int r,int depth){\n if(!(l<r))return NIL;\n int mid=(l+r)/2;\n if(depth%2==0){//分奇偶来分别用x,y指标,这样空间利用和搜索效率都提高了,下面的find也要分奇偶用不同指标来寻找\n sort(P+l,P+r,lessX);\n }else sort(P+l,P+r,lessY);\n int t=np++;\n T[t].location=mid;//mid是排好顺序的序列的中间项的小标不是搜索树的下标,但是下面的l和r确是\n T[t].l=makeKDTree(l,mid,depth+1);\n T[t].r=makeKDTree(mid+1,r,depth+1);\n return t;\n}\nvoid find(int v,int sx,int tx,int sy,int ty,int depth,vector<Point> &ans){\n int x=P[T[v].location].x;\n int y=P[T[v].location].y;\n if(x>=sx&&x<=tx&&y>=sy&&y<=ty){\n ans.push_back(P[T[v].location]);\n }\n if(depth%2==0){\n if(T[v].l!=NIL&&x>=sx){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);//上面引用&好处的体现\n }\n if(T[v].r!=NIL&&x<=tx){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }else {\n if(T[v].l!=NIL&&y>=sy){\n find(T[v].l,sx,tx,sy,ty,depth+1,ans);\n }\n if(T[v].r!=NIL&&y<=ty){\n find(T[v].r,sx,tx,sy,ty,depth+1,ans);\n }\n }\n}\nint main(){\n scanf(\"%d\",&N);\n np=0;\n for(int i=0;i<N;i++){\n int x,y;\n scanf(\"%d %d\",&x,&y);\n P[i]=Point(i,x,y);\n T[i].r=T[i].l=T[i].p=NIL;\n }\n int q;\n scanf(\"%d\",&q);\n vector<Point> ans;\n int root=makeKDTree(0,N,0);//t不是全局变量返回的不是递归很多次的t;\n for(int i=0;i<q;i++){\n int sx,tx,sy,ty;\n scanf(\"%d %d %d %d\",&sx,&tx,&sy,&ty);\n ans.clear();\n find(root,sx,tx,sy,ty,0,ans);\n sort(ans.begin(),ans.end());\n for(int j=0;j<(int)ans.size();j++){\n ans[j].print();\n }\n printf(\"\\n\");\n }\n return 0;\n}", "accuracy": 0.4166666666666667, "time_ms": 20, "memory_kb": 4340, "score_of_the_acc": -0.0022, "final_rank": 20 }, { "submission_id": "aoj_DSL_2_C_10954976", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\n#include<tuple>\n#include<climits>\n#include<iterator>\nusing namespace std;\n\nclass kDtree{\n\tusing T = tuple<int, int, int>;\n\tusing Iter = vector<T>::iterator;\n\tkDtree *l = nullptr, *r = nullptr;\n\tIter begin, end;\n\tint xmax = INT_MIN, xmin = INT_MAX, ymax = INT_MIN, ymin = INT_MAX, size = 0;\npublic:\n\tkDtree(Iter b, Iter e, bool divx = true): begin(b), end(e){\n\t\tfor(auto p = begin; p != end; p++){\n\t\t\tauto [x, y, z] = *p;\n\t\t\txmax = max(xmax, x);\n\t\t\txmin = min(xmin, x);\n\t\t\tymax = max(ymax, y);\n\t\t\tymin = min(ymin, y);\n\t\t}\n\t\tsize = int(end - begin);\n\t\tif(size <= 1) return;\n\t\tauto cn = begin + size / 2;\n\t\tif(divx) nth_element(begin, cn, end, [](T a, T b){return get<0>(a) < get<0>(b);});\n\t\telse nth_element(begin, cn, end, [](T a, T b){return get<1>(a) < get<1>(b);});\n\t\tl = new kDtree(begin, cn, !divx);\n\t\tr = new kDtree(cn, end, !divx);\n\t}\n\t\n\t~kDtree(){ delete l; delete r;}\n\t\n\tvoid Get(int x1, int x2, int y1, int y2, vector<int>& out){\n\t\tif(x1 > xmax || x2 < xmin || y1 > ymax || y2 < ymin) return;\n\t\tif(x1 <= xmin && x2 >= xmax && y1 <= ymin && y2 >= ymax) {\n\t\t\tfor(auto p = begin; p != end; p++) out.push_back(get<2>(*p));\n\t\t\treturn;\n\t\t}\n\t\tl->Get(x1, x2, y1, y2, out);\n\t\tr->Get(x1, x2, y1, y2, out);\n\t}\n};\n\nint main(){\n\tint n, q;\n\tcin >> n;\n\tvector<tuple<int, int, int>> xy(n);\n\tfor(int i = 0; i < n; i++){\n\t\tget<2>(xy[i]) = i;\n\t\tcin >> get<0>(xy[i]) >> get<1>(xy[i]);\n\t}\n\tkDtree kd(xy.begin(), xy.end());\n\tcin >> q;\n\tint sx, tx, sy, ty;\n\twhile(q--){\n\t\tcin >> sx >> tx >> sy >> ty;\n\t\tvector<int> num;\n\t\tkd.Get(sx, tx, sy, ty, num);\n\t\tif(!num.empty()) {\n\t\t\tsort(num.begin(), num.end());\n\t\t\tfor(auto i : num) cout << i << endl;\n\t\t}\n\t\tcout << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 550, "memory_kb": 70048, "score_of_the_acc": -1.428, "final_rank": 13 }, { "submission_id": "aoj_DSL_2_C_10954942", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\n#include<tuple>\n#include<climits>\nusing namespace std;\n\nclass kDtree{\n\tusing T = tuple<int, int, int>;\n\tusing Iter = vector<T>::iterator;\n\tkDtree *l = nullptr, *r = nullptr;\n\tIter begin, end;\n\tint xmax = INT_MIN, xmin = INT_MAX, ymax = INT_MIN, ymin = INT_MAX, size = 0;\npublic:\n\tkDtree(Iter b, Iter e, bool divx = true): begin(b), end(e){\n\t\tfor(auto p = begin; p != end; p++){\n\t\t\tauto [x, y, z] = *p;\n\t\t\txmax = max(xmax, x);\n\t\t\txmin = min(xmin, x);\n\t\t\tymax = max(ymax, y);\n\t\t\tymin = min(ymin, y);\n\t\t}\n\t\tsize = int(end - begin);\n\t\tif(size <= 1) return;\n\t\tauto cn = begin + size / 2;\n\t\tif(divx) nth_element(begin, cn, end, [](T a, T b){return get<0>(a) < get<0>(b);});\n\t\telse nth_element(begin, cn, end, [](T a, T b){return get<1>(a) < get<1>(b);});\n\t\tl = new kDtree(begin, cn, !divx);\n\t\tr = new kDtree(cn, end, !divx);\n\t}\n\t\n\t~kDtree(){ delete l; delete r;}\n\t\n\tvector<int> Get(int x1, int x2, int y1, int y2){\n\t\tvector<int> t, u;\n\t\tif(x1 > xmax || x2 < xmin || y1 > ymax || y2 < ymin) return t;\n\t\tif(x1 <= xmin && x2 >= xmax && y1 <= ymin && y2 >= ymax) {\n\t\t\tfor(auto p = begin; p != end; p++) t.push_back(get<2>(*p));\n\t\t\treturn t;\n\t\t}\n\t\tt = l->Get(x1, x2, y1, y2);\n\t\tu = r->Get(x1, x2, y1, y2);\n\t\tt.insert(t.end(), u.begin(), u.end());\n\t\treturn t;\n\t}\n};\n\nint main(){\n\tint n, q;\n\tcin >> n;\n\tvector<tuple<int, int, int>> xy(n);\n\tfor(int i = 0; i < n; i++){\n\t\tget<2>(xy[i]) = i;\n\t\tcin >> get<0>(xy[i]) >> get<1>(xy[i]);\n\t}\n\tkDtree kd(xy.begin(), xy.end());\n\tcin >> q;\n\tint sx, tx, sy, ty;\n\twhile(q--){\n\t\tcin >> sx >> tx >> sy >> ty;\n\t\tauto num = kd.Get(sx, tx, sy, ty);\n\t\tif(!num.empty()) {\n\t\t\tsort(num.begin(), num.end());\n\t\t\tfor(auto i : num) cout << i << endl;\n\t\t}\n\t\tcout << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 580, "memory_kb": 70048, "score_of_the_acc": -1.4593, "final_rank": 14 }, { "submission_id": "aoj_DSL_2_C_10886945", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define rep2(i, s, n) for (ll i = (s); i < (n); i++)\n\nclass node {\n public:\n int location;\n int p, l, r;\n node() {}\n};\n\nclass point {\n public:\n int id, x, y;\n point() {}\n point(int id, int x, int y): id(id), x(x), y(y) {}\n bool operator < (const point &p) const {\n return id < p.id;\n }\n\n void print() {\n printf(\"%d\\n\", id);\n }\n};\n\nstatic const int MAX = 1000000;\nstatic const int NIL = -1;\nint n;\npoint p[MAX];\nnode T[MAX];\nint np;\n\nbool lessx(const point &p1, const point &p2) {\n return p1.x < p2.x;\n}\nbool lessy(const point &p1, const point &p2) {\n return p1.y < p2.y;\n}\n\nint makekdtree(int l, int r, int depth) {\n if (!(l < r)) {\n return NIL;\n }\n int mid = (l + r) / 2;\n int t = np++;\n if (depth % 2 == 0) {\n sort(p+l, p+r, lessx);\n }\n else {\n sort(p+l, p+r, lessy);\n }\n T[t].location = mid;\n T[t].l = makekdtree(l, mid, depth+1);\n T[t].r = makekdtree(mid + 1, r, depth+1);\n return t;\n}\n\nvoid find (int v, int sx, int tx, int sy, int ty, int depth, vector<point> &ans) {\n int x = p[T[v].location].x;\n int y = p[T[v].location].y;\n if (sx <= x && x <= tx && sy <= y && y <= ty) {\n ans.push_back(p[T[v].location]);\n }\n if (depth % 2 == 0) {\n if (T[v].l != NIL) {\n if (sx <= x) {\n find(T[v].l, sx, tx, sy, ty, depth+1, ans);\n }\n }\n if (T[v].r != NIL) {\n if (x <= tx) {\n find(T[v].r, sx, tx, sy, ty, depth+1, ans);\n }\n }\n }\n else {\n if (T[v].l != NIL) {\n if (sy <= y) {\n find(T[v].l, sx, tx, sy, ty, depth+1, ans);\n }\n }\n if (T[v].r != NIL) {\n if (y <= ty) {\n find(T[v].r, sx, tx, sy, ty, depth+1, ans);\n }\n }\n }\n}\n\n\n\nvoid solve() {\n int x, y;\n scanf(\"%d\", &n);\n for (int i = 0; i < n; ++i) {\n scanf(\"%d %d\", &x, &y);\n p[i] = point(i, x, y);\n T[i].l = T[i].r = T[i].p = NIL;\n }\n\n np = 0;\n int root = makekdtree(0, n, 0);\n\n int q;\n scanf(\"%d\", &q);\n int sx, tx, sy, ty;\n vector<point> ans;\n for (int i = 0; i < q; i++) {\n scanf(\"%d %d %d %d\", &sx, &tx, &sy, &ty);\n ans.clear();\n find(root, sx, tx, sy, ty, 0, ans);\n sort(ans.begin(), ans.end());\n for (int j = 0; j < ans.size(); j++) {\n ans[j].print();\n }\n printf(\"\\n\");\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 20152, "score_of_the_acc": -0.525, "final_rank": 5 }, { "submission_id": "aoj_DSL_2_C_10873646", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\n\nclass Node {\n public:\n int location;\n int p, l, r;\n Node() = default;\n};\n\nclass Point {\n public:\n int id, x, y;\n Point() = default;\n Point(int id, int x, int y) : id(id), x(x), y(y) {}\n bool operator < (const Point &p) const {\n return id < p.id;\n }\n\n void print() {\n printf(\"%d\\n\", id);\n }\n};\n\nstatic const int MAX = 1000000;\nstatic const int NIL = -1;\n\nint N;\nPoint P[MAX];\nNode T[MAX];\nint np;\n\nbool lessX(const Point &p1, const Point &p2) { return p1.x < p2.x; }\nbool lessY(const Point &p1, const Point &p2) { return p1.y < p2.y; }\n\nint makeKDTree(int l, int r, int depth) {\n if ( !(l < r) ) return NIL;\n int mid = (l+r)/2;\n int t = np++;\n if (depth % 2 == 0) {\n sort(P + l, P + r, lessX);\n } else {\n sort(P + l, P + r, lessY);\n }\n T[t].location = mid;\n T[t].l = makeKDTree(l, mid, depth+1);\n T[t].r = makeKDTree(mid+1, r, depth+1);\n\n return t;\n}\n\nvoid find(int v, int sx, int tx, int sy, int ty, int depth, vector<Point> &ans) {\n int x = P[T[v].location].x;\n int y = P[T[v].location].y;\n\n if (sx <= x && x <= tx && sy <= y && y <= ty) {\n ans.push_back(P[T[v].location]);\n }\n\n if (depth % 2 == 0) {\n if (T[v].l != NIL) {\n if (sx <= x) find(T[v].l, sx, tx, sy, ty, depth+1, ans);\n }\n if (T[v].r != NIL) {\n if (x <= tx) find(T[v].r, sx, tx, sy, ty, depth+1, ans);\n }\n } else {\n if (T[v].l != NIL) {\n if (sy <= y) find(T[v].l, sx, tx, sy, ty, depth+1, ans);\n }\n if (T[v].r != NIL) {\n if (y <= ty) find(T[v].r, sx, tx, sy, ty, depth+1, ans);\n }\n }\n}\n\nint main()\n{\n int x, y;\n scanf(\"%d\", &N);\n rep(i,N) {\n scanf(\"%d %d\", &x, &y);\n P[i] = Point(i,x,y);\n T[i].l = T[i].r = T[i].p = NIL;\n }\n\n np = 0;\n\n int root = makeKDTree(0,N,0);\n\n int q;\n scanf(\"%d\", &q);\n int sx, tx, sy, ty;\n vector<Point> ans;\n for (int i=0; i<q; i++) {\n scanf(\"%d %d %d %d\", &sx, &tx, &sy, &ty);\n ans.clear();\n find(root, sx, tx, sy, ty, 0, ans);\n sort(ans.begin(), ans.end());\n for (int j=0; j<ans.size(); j++) {\n ans[j].print();\n }\n printf(\"\\n\");\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 19816, "score_of_the_acc": -0.5518, "final_rank": 7 }, { "submission_id": "aoj_DSL_2_C_10851606", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <cmath>\n#include <cstdlib>\nusing namespace std;\n\nstruct Point {\n int id, x, y;\n Point() {}\n Point(int _id, int _x, int _y) : id(_id), x(_x), y(_y){}\n\n bool operator < (const Point &p) const {\n return id < p.id;\n }\n};\n\nstruct Node {\n int location;\n int p, l, r;\n Node() {}\n};\n\nconst int MAX = 1000000;\nconst int NIL = -1;\n\nint N;\nPoint p[MAX];\nNode T[MAX];\nint np;\n\nbool lessX(const Point &p1, const Point &p2) { return p1.x < p2.x; }\nbool lessY(const Point &p1, const Point &p2) { return p1.y < p2.y; }\n\nint makeKDTree(int l, int r, int depth) {\n if (!(l < r)) return NIL;\n int mid = (l + r) / 2;\n int t = np++;\n if (depth % 2 == 0) {\n sort(p+l, p+r, lessX);\n } else {\n sort(p+l, p+r, lessY);\n }\n T[t].location = mid;\n T[t].l = makeKDTree(l, mid, depth+1);\n T[t].r = makeKDTree(mid+1, r, depth+1);\n return t;\n}\n\nvector<Point> ans;\nvoid find(int v, int sx, int tx, int sy, int ty, int depth, vector<Point> &ans) {\n int x = p[T[v].location].x;\n int y = p[T[v].location].y;\n \n if (sx <= x && x <= tx && sy <= y && y <= ty) {\n ans.push_back(p[T[v].location]);\n }\n\n if (depth % 2 == 0) {\n if (T[v].l != NIL) {\n if (sx <= x) find(T[v].l, sx, tx, sy, ty, depth+1, ans);\n }\n if (T[v].r != NIL) {\n if (x <= tx) find(T[v].r, sx, tx, sy, ty, depth+1, ans);\n }\n } else {\n if (T[v].l != NIL) {\n if (sy <= y) find(T[v].l, sx, tx, sy, ty, depth+1, ans);\n }\n if (T[v].r != NIL) {\n if (y <= ty) find(T[v].r, sx, tx, sy, ty, depth+1, ans);\n }\n }\n}\n\nint main() {\n //freopen(\"in.txt\", \"r\", stdin);\n //freopen(\"out.txt\", \"w\", stdout);\n int x, y;\n scanf(\"%d\", &N);\n for (int i = 0; i < N; i++) {\n scanf(\"%d %d\", &x, &y);\n p[i] = Point(i, x, y);\n T[i].l = T[i].r = T[i].p = NIL;\n }\n\n np = 0;\n\n int root = makeKDTree(0, N, 0);\n int q;\n scanf(\"%d\", &q);\n int sx, tx, sy, ty;\n for (int i = 0; i < q; i++) {\n scanf(\"%d %d %d %d\", &sx, &tx, &sy, &ty);\n ans.clear();\n find(root, sx, tx, sy, ty, 0, ans);\n sort(ans.begin(), ans.end());\n for (int j = 0; j < ans.size(); j++) {\n printf(\"%d\\n\", ans[j].id);\n }\n printf(\"\\n\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 350, "memory_kb": 19868, "score_of_the_acc": -0.5525, "final_rank": 8 }, { "submission_id": "aoj_DSL_2_C_10809764", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n#define elif else if\n#define gcd __gcd\n#define lcm(a,b) (a*b)/gcd(a,b)\n#define pb push_back\n#define vi vector<int>\n#define vpi vector<pair<int,int>>\n#define vvi vector<vector<int>>\n#define pii pair<int,int>\n#define fi first\n#define se second\n#define all(x) x.begin(),x.end()\n#define unique(x) x.erase(unique(all(x)),x.end())\n#define mp map<int,int>\n#define si set<int>\n#define msi multiset<int>\n#define input(x) for(auto &i:x) cin>>i;\n#define print(x) for(auto i:x) cout<<i<<\" \"; cout<<endl;\n#define debugv(v) for(auto i:v) cerr<<i<<\" \"; cerr<<endl;\n#define debug(x) cerr<<#x<<\" = \"<<x<<endl;\nconst int N=2e5+5;\nconst int MOD=1e9+7;\nconst int MOD2=998244353;\nconst int INF=1e18;\n// #include <ext/pb_ds/assoc_container.hpp>\n// #include <ext/pb_ds/tree_policy.hpp>\n// using namespace __gnu_pbds;\n// typedef tree<\n// int,\n// null_type,\n// less<int>,\n// rb_tree_tag,\n// tree_order_statistics_node_update\n// > ordered_set;\n// typedef tree<\n// pair<int,int>,\n// null_type,\n// less<pair<int,int>>,\n// rb_tree_tag,\n// tree_order_statistics_node_update\n// > ordered_multiset;\n\nint ceil_div(int a, int b) {\n return (a + b - 1) / b;\n}\n\nbool sieve[N];\nint hp[N];\nvoid sieve_eratosthenes(){\n sieve[0]=sieve[1]=true;\n for(int i=2;i<N;i++){\n if(sieve[i]==false){\n hp[i]=i;\n for(int j=2*i;j<N;j+=i){\n hp[j]=i;\n sieve[j]=true;\n }\n }\n }\n}\n\nint binmul(int a,int b,int MOD=MOD){\n int ans=0;\n while(b>0){\n if(b&1){\n ans=(ans+a)%MOD;\n }\n a=(a+a)%MOD;\n b>>=1;\n }\n return ans;\n}\n\nint binexp(int a,int b,int MOD=MOD){\n int ans=1;\n while(b>0){\n if(b&1){\n // ans=binmul(ans,a)%MOD;\n ans=(ans*a)%MOD;\n }\n // a=binmul(a,a)%MOD;\n a=(a*a)%MOD;\n b>>=1;\n }\n return ans;\n}\n\nbool comp(pii a, pii b) {\n if(a.fi == b.fi) {\n return a.se<b.se;\n }\n return a.fi < b.fi;\n // if(a.se==b.se) return a.fi<b.fi;\n // return a.se<b.se;\n}\n\nconst int gN=4e3+5;\nvi graph[N];\n\n#define cerr if(false)cerr\n\nvoid solve(){\n int n;\n cin>>n;\n map<int,vpi>m;\n for(int i=0;i<n;i++){\n int x,y;\n cin>>x>>y;\n m[x].pb({y,i});\n }\n for(auto &elem: m){\n sort(all(elem.second));\n // debug(elem.first);\n // for(auto i: elem.second){\n // debug(i.fi);\n // }\n }\n int q;\n cin>>q;\n while(q--){\n int sx,tx,sy,ty;\n cin>>sx>>tx>>sy>>ty;\n auto it=m.lower_bound(sx);\n if(it==m.end() || it->first>tx) {\n cout<<endl;\n continue;\n }\n auto it_end=m.upper_bound(tx);\n // it_end--;\n // debug(it_end->first);\n vi ans;\n for(auto i=it;i!=it_end;i++){\n auto ity=lower_bound(all(i->second),make_pair(sy,-INF));\n cerr<<i->first<<\" \"<<ity->fi<<\" \"<<ity->se<<endl;\n if(ity==i->second.end() || ity->fi>ty) {\n continue;\n }\n auto ity_end=upper_bound(all(i->second),make_pair(ty,INF));\n // ity_end--;\n for(auto j=ity;j!=ity_end;j++){\n ans.pb(j->se);\n }\n }\n sort(all(ans));\n for(auto i: ans){\n cout<<i<<endl;\n }\n cout<<endl;\n }\n}\n\nint32_t main(){\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n int t=1;\n // cin>>t;\n while(t--){\n // debug(t);\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 380, "memory_kb": 53144, "score_of_the_acc": -1.0262, "final_rank": 11 }, { "submission_id": "aoj_DSL_2_C_10781233", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int NIL = -1;\n\nstruct Node\n{\n int l = NIL, r = NIL;\n int location = NIL;\n};\n\nclass Point\n{\npublic:\n int id, x, y;\n Point() {}\n Point(int id, int x, int y) : id(id), x(x), y(y) {}\n};\n\nint np = 0;\n\nvector<Point> P;\nvector<Node> T;\nvector<int> ans;\n\nint make2DTree(int l, int r, int depth)\n{\n if ( !(l < r) ) return NIL;\n\n int mid = (l+r) / 2;\n int t = np++;\n\n if (depth % 2 == 0)\n {\n sort(P.begin()+l, P.begin()+r, [](const Point &p1, const Point &p2){ return p1.x < p2.x; });\n }\n else\n {\n sort(P.begin()+l, P.begin()+r, [](const Point &p1, const Point &p2){ return p1.y < p2.y; });\n }\n\n T[t].location = mid;\n T[t].l = make2DTree(l, mid, depth+1);\n T[t].r = make2DTree(mid+1, r, depth+1);\n\n return t;\n}\n\nvoid find(int v, int sx, int tx, int sy, int ty, int depth)\n{\n int x = P[T[v].location].x;\n int y = P[T[v].location].y;\n\n if (sx <= x && x <= tx && sy <= y && y <= ty)\n {\n ans.push_back(P[T[v].location].id);\n }\n\n if (depth % 2 == 0)\n {\n if (T[v].l != NIL && x >= sx)\n find(T[v].l, sx, tx, sy, ty, depth+1);\n if (T[v].r != NIL && x <= tx)\n find(T[v].r, sx, tx, sy, ty, depth+1);\n }\n else\n {\n if (T[v].l != NIL && y >= sy)\n find(T[v].l, sx, tx, sy, ty, depth+1);\n if (T[v].r != NIL && y <= ty)\n find(T[v].r, sx, tx, sy, ty, depth+1);\n }\n\n return;\n}\n\nint main()\n{\n int n;\n cin >> n;\n P = vector<Point>(n);\n T = vector<Node>(n);\n\n for (int i = 0; i < n; i++)\n {\n int xi, yi;\n cin >> xi >> yi;\n P[i] = Point(i, xi, yi);\n }\n\n int root = make2DTree(0, n, 0);\n\n int q;\n cin >> q;\n\n for (int i = 0; i < q; i++)\n {\n ans.clear();\n int sxi, txi, syi, tyi;\n cin >> sxi >> txi >> syi >> tyi;\n find(root, sxi, txi, syi, tyi, 0);\n sort(ans.begin(), ans.end());\n for (auto j : ans) printf(\"%d\\n\", j);\n printf(\"\\n\");\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 430, "memory_kb": 14264, "score_of_the_acc": -0.5613, "final_rank": 9 }, { "submission_id": "aoj_DSL_2_C_10776618", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point{\n int x, y;\n int ind;\n};\n\nstruct Node{\n Point point;\n Node *left, *right;\n};\n\nNode* build(vector<Point>&points, int depth = 0){\n if(points.empty()) return nullptr;\n\n int axis = depth % 2;\n auto cmp = [axis](Point a, Point b){\n return axis == 0 ? a.x < b.x : a.y < b.y;\n };\n\n sort(points.begin(), points.end(), cmp);\n\n int mid = points.size()/2;\n\n Node* root = new Node{points[mid], nullptr, nullptr};\n\n vector<Point> left_points(points.begin(), points.begin() + mid);\n vector<Point> right_points(points. begin() + mid + 1, points.end());\n\n root->left = build(left_points, depth+1);\n root->right = build(right_points, depth+1);\n\n return root;\n}\n\nvoid range_search(vector<int>&ans, Node* root, int xmin, int xmax, int ymin, int ymax, int depth = 0){\n if(!root) return;\n\n int x = root->point.x;\n int y = root->point.y;\n\n if(x >= xmin && x <= xmax && y >= ymin && y <= ymax){\n ans.push_back(root->point.ind);\n }\n int axis = depth % 2;\n\n if((axis == 0 && x >= xmin) || (axis == 1 && y >= ymin)){\n range_search(ans,root->left, xmin, xmax, ymin, ymax,depth+1);\n }\n if((axis == 0 && x <= xmax) || (axis == 1 && y <= ymax)){\n range_search(ans,root->right, xmin, xmax, ymin, ymax,depth+1);\n }\n}\n\n\nint main(){\n int n;\n cin >> n;\n\n vector<Point> arr(n);\n\n for(int i = 0; i < n; i++){\n cin >> arr[i].x >> arr[i].y;\n arr[i].ind = i;\n }\n\n Node* root = build(arr);\n\n int q;\n cin >> q;\n\n while(q--){\n int xmax, xmin, ymin, ymax;\n cin >> xmin >> xmax >> ymin >> ymax;\n vector<int> ans;\n range_search(ans,root, xmin,xmax,ymin,ymax);\n sort(ans.begin(), ans.end());\n for(int i = 0; i < ans.size(); i++) cout << ans[i] << endl;\n cout << endl;\n }\n\n}", "accuracy": 1, "time_ms": 980, "memory_kb": 43036, "score_of_the_acc": -1.5168, "final_rank": 15 }, { "submission_id": "aoj_DSL_2_C_10754731", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nusing ull=unsigned long long;\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n#define loop(n) for (int tjh = 0; tjh < (int)(n); ++tjh)\nconstexpr int mi=-2'000'000'000;constexpr int ma=2'000'000'000;\nsigned main() {\n cin.tie(0)->sync_with_stdio(0);\n cout<<fixed<<setprecision(16);\n int n;cin>>n;\n vector<int>x(n),y(n);\n rep(i,n)cin>>x[i]>>y[i];\n vector<int>p(n);iota(p.begin(), p.end(),0);\n vector<int>lx{},rx{},ly{},ry{},cl{},cr{};\n lx.reserve(1<<20);rx.reserve(1<<20);\n ly.reserve(1<<20);ry.reserve(1<<20);\n cl.reserve(1<<20);cr.reserve(1<<20);\n {\n auto f=[&](\n auto self,\n const vector<int>::iterator l,\n const vector<int>::iterator r,\n const bool fl,const int c\n )->void {\n for (auto i=l;i!=r;++i) {\n if (x[*i]<lx[c])lx[c]=x[*i];\n if (x[*i]>rx[c])rx[c]=x[*i];\n if (y[*i]<ly[c])ly[c]=y[*i];\n if (y[*i]>ry[c])ry[c]=y[*i];\n }\n const int d=(int)distance(l,r);\n if (d==1){cl[c]=*l;return;}\n const auto m=l+(d>>1);\n nth_element(l,m,r,[&](int s,int t) {\n return fl?y[s]<y[t]:x[s]<x[t];\n });\n {\n const int c0=(int)lx.size();\n cl[c]=c0;\n lx.push_back(ma);rx.push_back(mi);\n ly.push_back(ma);ry.push_back(mi);\n cl.push_back(-1);cr.push_back(-1);\n self(self,l,m,!fl,c0);\n }\n {\n const int c0=(int)lx.size();\n cr[c]=c0;\n lx.push_back(ma);rx.push_back(mi);\n ly.push_back(ma);ry.push_back(mi);\n cl.push_back(-1);cr.push_back(-1);\n self(self,m,r,!fl,c0);\n }\n };\n lx.push_back(ma);rx.push_back(mi);\n ly.push_back(ma);ry.push_back(mi);\n cl.push_back(-1);cr.push_back(-1);\n f(f,p.begin(),p.end(),false,0);\n }\n {\n int q;cin>>q;int sx,sy,tx,ty;\n vector<int>res{};res.reserve(100);\n auto f=[&](auto self,int c)->void {\n if (max(sx,lx[c])>min(tx,rx[c])||max(sy,ly[c])>min(ty,ry[c]))return;\n if (cr[c]==-1){res.push_back(cl[c]);return;}\n self(self,cl[c]);self(self,cr[c]);\n };\n for (;q--;) {\n cin>>sx>>tx>>sy>>ty;res.resize(0);\n f(f,0);ranges::sort(res);\n for (const auto i:res)cout<<i<<'\\n';\n cout<<'\\n';\n }\n }\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 31932, "score_of_the_acc": -0.5462, "final_rank": 6 }, { "submission_id": "aoj_DSL_2_C_10747374", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nstruct node{\n vector<int> point = vector<int>(2);\n node *left, *right;\n int id;\n};\nnode* make(vector<int> point1){\n node* temp=new node;\n temp->point[0]=point1[0];\n temp->point[1]=point1[1];\n temp->left=nullptr;\n temp->right=nullptr;\n return temp;\n}\nnode* build(vector<pair<vector<int>, int>> &points, int l, int r, int axis) {\n if (l > r) return nullptr;\n int m = (l + r) / 2;\n // Sort the subset by axis\n nth_element(points.begin() + l, points.begin() + m, points.begin() + r + 1,\n [axis](const pair<vector<int>, int> &a, const pair<vector<int>, int> &b) {\n return a.first[axis] < b.first[axis];\n });\n node* root = new node;\n root->point = points[m].first;\n root->id = points[m].second;\n root->left = build(points, l, m - 1, 1 - axis);\n root->right = build(points, m + 1, r, 1 - axis);\n return root;\n}\n\nvoid search(node* root,vector<int> query,int axis,vector<int> &final){\n if(root==nullptr){\n return;\n }\n if(root->point[0]>=query[0]&&root->point[0]<=query[1]&&root->point[1]>=query[2]&&root->point[1]<=query[3]){\n final.push_back(root->id);\n search(root->left,query,1-axis,final);\n search(root->right,query,1-axis,final);\n return;\n }\n if(root->point[axis]<(query)[2*axis]){\n search(root->right,query,1-axis,final);\n return;\n }\n if(root->point[axis]>(query)[2*axis+1]){\n search(root->left,query,1-axis,final);\n return;\n }\n search(root->left,query,1-axis,final);\n search(root->right,query,1-axis,final);\n return;\n \n}\nint main() {\n\t// your code goes here\n\tint n;\n\tcin>>n;\n\tvector<pair<vector<int>, int>> pts;\n for(int i=0; i<n; i++) {\n vector<int> point1(2);\n cin >> point1[0] >> point1[1];\n pts.push_back({point1, i});\n }\n node* root = build(pts, 0, n-1, 0);\n\n\tint q;\n\tcin>>q;\n\tvector<int> query(4);\n\tfor(int i=0;i<q;i++){\n\t vector<int> final;\n\t cin>>query[0]>>query[1]>>query[2]>>query[3];\n\t search(root,query,0,final);\n\t sort(final.begin(),final.end());\n\t for(int j=0;j<final.size();j++){\n\t cout<<final[j]<<endl;\n\t }\n\t cout<<endl;\n\t}\n\t\n\n}", "accuracy": 1, "time_ms": 980, "memory_kb": 79376, "score_of_the_acc": -2, "final_rank": 16 }, { "submission_id": "aoj_DSL_2_C_10721191", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nstruct node{\n int ls,rs,x,y,t,id;\n};\nstruct node1{\n int x,y,id;\n}; \nconst int N=5e5+5;\nnode tree[N];\nint idx=0;\nbool cmp1(node1 a,node1 b){\n return a.x<b.x;\n}\nbool cmp2(node1 a,node1 b){\n return a.y<b.y;\n}\nnode1 P[N];\nint build(int l,int r,int t=0){\n if(l==r){\n tree[idx++]={-1,-1,P[l].x,P[l].y,t,P[l].id};\n return idx-1;\n } \n if(t==0) sort(P+l,P+r+1,cmp1);\n else sort(P+l,P+r+1,cmp2);\n int mid=(l+r)>>1;\n int now=idx++;\n tree[now]={-1,-1,P[mid].x,P[mid].y,t,P[mid].id};\n if(l<=mid-1){\n int ind=build(l,mid-1,1-t);\n tree[now].ls=ind;\n }\n if(mid+1<=r){\n int ind=build(mid+1,r,1-t);\n tree[now].rs=ind;\n }\n return now;\n}\nint sx,tx,sy,ty;\nvector<int>ids;\nvoid query(int u=0,int t=0){\n if(u==-1) return;\n int ls=tree[u].ls,rs=tree[u].rs,id=tree[u].id;\n int x=tree[u].x,y=tree[u].y;\n if(x>=sx&&x<=tx&&y>=sy&&y<=ty) ids.push_back(id);\n if(t==0){\n if(x<=tx) query(rs,1-t);\n if(x>=sx) query(ls,1-t);\n }else{\n if(y<=ty) query(rs,1-t);\n if(y>=sy) query(ls,1-t);\n }\n}\nvoid solve(){\n int n;cin>>n;\n for(int i=0;i<n;i++){\n cin>>P[i].x>>P[i].y;\n P[i].id=i;\n }\n build(0,n-1);\n int q;cin>>q;\n while(q--){\n cin>>sx>>tx>>sy>>ty;\n if(n==0){\n cout<<endl;\n continue;\n }\n query();\n sort(ids.begin(),ids.end());\n for(auto x:ids) cout<<x<<endl;\n cout<<endl;\n ids.clear();\n }\n}\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(0),cout.tie(0);\n int T=1;\n // cin>>T;\n for(int t=1;t<=T;t++){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 490, "memory_kb": 38104, "score_of_the_acc": -0.9408, "final_rank": 10 } ]
aoj_ALDS1_15_B_cpp
Fractional Knapsack Problem You have $N$ items that you want to put them into a knapsack of capacity $W$. Item $i$ ($1 \le i \le N$) has weight $w_i$ and value $v_i$ for the weight. When you put some items into the knapsack, the following conditions must be satisfied: The total value of the items is as large as possible. The total weight of the selected items is at most $W$. You can break some items if you want. If you put $w'$($0 \le w' \le w_i$) of item $i$, its value becomes $\displaystyle v_i \times \frac{w'}{w_i}.$ Find the maximum total value of items in the knapsack. Input $N$ $W$ $v_1$ $w_1$ $v_2$ $w_2$ : $v_N$ $w_N$ The first line consists of the integers $N$ and $W$. In the following $N$ lines, the value and weight of the $i$-th item are given. Output Print the maximum total value of the items in a line. The output must not contain an error greater than $10^{-6}$. Constraints $1 \le N \le 10^5$ $1 \le W \le 10^9$ $1 \le v_i \le 10^9 (1 \le i \le N)$ $1 \le w_i \le 10^9 (1 \le i \le N)$ Sample Input 1 3 50 60 10 100 20 120 30 Sample Output 1 240 When you put 10 of item $1$, 20 of item $2$ and 20 of item $3$, the total value is maximized. Sample Input 2 3 50 60 13 100 23 120 33 Sample Output 2 210.90909091 When you put 13 of item $1$, 23 of item $2$ and 14 of item $3$, the total value is maximized. Note some outputs can be a real number. Sample Input 3 1 100 100000 100000 Sample Output 3 100
[ { "submission_id": "aoj_ALDS1_15_B_11063373", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef struct items{\n int v;\n int w;\n float r;\n int s=0;\n\n}it;\n\nint main (){\n int n, c, tw=0;\n double sum=0;\n it x[100000];\n\n cin >> n >> c;\n\n for(int i=0; i<n; i++){\n cin >> x[i].v >> x[i].w;\n x[i].r = (float)x[i].v/x[i].w;\n }\n\n sort(x, x + n, [](const it &a,const it &b){\n return a.r > b.r;\n });\n \n\n for(int i=0; i<n; i++){\n\n \n if(x[i].w < c-tw){\n sum+= x[i].v;\n tw += x[i].w;\n }\n else if (x[i].w >= c-tw){\n sum+= x[i].v*((double)(c-tw)/x[i].w);\n break;\n }\n }\n\n if(sum == int(sum)) cout << (int) sum << endl;\n else cout << fixed << setprecision(8) << sum << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5108, "score_of_the_acc": -0.5977, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_15_B_11027238", "code_snippet": "#include <bits/stdc++.h>\n#define Kareem \\\n ios::sync_with_stdio(0); \\\n cin.tie(0); \\\n cout.tie(0);\nusing namespace std;\n#define int long long\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define msb(x) (63 - __builtin_clzll(x))\n#define lsb(x) (__builtin_ctzll(x))\n#define bit_count(x) (__builtin_popcountll(x))\nint di[] = {0, 0, 1, -1, 1, 1, -1, -1};\nint dj[] = {1, -1, 0, 0, 1, -1, 1, -1};\n// R L D U DR DL UR UL\nconst int M=1e9+7;\nconst int N=1e5+5;\nvoid file()\n{\n#ifndef ONLINE_JUDGE\n freopen(\"input.txt\", \"r\", stdin);\n freopen(\"output.txt\", \"w\", stdout);\n#endif\n}\n\nvoid solve()\n{\n int n,w;cin>>n>>w;\n int v[n],weight[n];\n vector<pair<double,int>>percent(n);\n for (int i = 0; i < n; i++)\n {\n cin>>v[i]>>weight[i];\n percent[i].second=i;\n percent[i].first=double(v[i])/weight[i];\n }\n sort(rall(percent));\n double ans=0;\n for (int i = 0; i < n; i++)\n {\n int item=percent[i].second;\n if(weight[item]<=w){\n ans+=v[item];\n w-=weight[item];\n }else{\n ans+=double(v[item]*w)/weight[item];\n break;\n }\n }\n cout<<fixed<<setprecision(8)<<ans<<'\\n';\n}\nsigned main()\n{\n Kareem;\n //file();\n //int tc;cin>>tc;while(tc--)\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6132, "score_of_the_acc": -0.1784, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_15_B_11010232", "code_snippet": "/**\n * author: MOAZ_KING\n * created: 01.11.2025 16:02:25\n**/\n#include <bits/stdc++.h>\n#define double long double\nusing namespace std;\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int64_t n, w;\n cin >> n >> w;\n vector<pair<double, double>> v(n);\n for (auto& [a, b] : v) {\n cin >> a >> b;\n }\n sort(v.begin(), v.end(),\n [] (auto a, auto b) {\n auto x = a.first / a.second;\n auto y = b.first / b.second;\n return x > y;\n });\n double ans = 0;\n for (auto& [a, b] : v) {\n if (w >= b) {\n ans += a;\n w -= b;\n } else {\n ans += (w / b) * a;\n break;\n }\n }\n cout << fixed << setprecision(9) << ans;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 6168, "score_of_the_acc": -0.6813, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_15_B_11003553", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nstruct item{\n long double v,w,r;\n};\n\nbool comp (item i1, item i2)\n{\n return (i1.r>i2.r);\n}\n\nint main()\n{\n int n,cap;\n cin >> n>>cap;\n item arr[n+5];\n for (int i=0;i<n;i++)\n {\n cin >> arr[i].v >>arr[i].w ;\n arr[i].r = (arr[i].v/arr[i].w);\n }\n\n sort (arr,arr+n,comp);\n\n long double profit=0;\n\n for (int i=0;i<n;i++)\n {\n if (arr[i].w<=cap)\n {\n profit += arr[i].v;\n cap-= arr[i].w ;\n }\n else {\n profit+= cap*arr[i].r;\n break;\n }\n }\n cout <<fixed<<setprecision(10)<< profit <<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 8120, "score_of_the_acc": -1.3351, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_15_B_10999038", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nstruct item\n{\n\n double price, weight, unitprice;\n};\n\nbool comp(item item1, item item2)\n{\n return item1.unitprice > item2.unitprice;\n}\n\nint main()\n{\n int N;\n double cap;\n cin>>N>>cap;\n item arr[N+5];\n for(int i=0; i<N; i++)\n {\n cin>>arr[i].price>>arr[i].weight;\n arr[i].unitprice = arr[i].price / arr[i].weight;\n }\n sort(arr, arr+N, comp);\n double profit=0;\n for(int i=0; i<N; i++)\n {\n if(arr[i].weight<=cap)\n {\n cap = cap-arr[i].weight;\n profit = profit+ arr[i].price;\n }\n else\n {\n profit += (cap*arr[i].unitprice);\n break;\n }\n\n }\n printf(\"%.10lf\", profit);\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5808, "score_of_the_acc": -1.1529, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_15_B_10901134", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\nusing mint = modint998244353;\n// using mint = modint1000000007;\n// using mint = double;\n#endif\n#define overload4(_1,_2,_3,_4,name,...) name\n#define overload3(_1,_2,_3,name,...) name\n#define rep1(n) for(ll i=0;i<n;++i)\n#define rep2(i,n) for(ll i=0;i<n;++i)\n#define rep3(i,a,b) for(ll i=a;i<b;++i)\n#define rep4(i,a,b,c) for(ll i=a;i<b;i+=c)\n#define rep(...) overload4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)\n#define rrep1(n) for(ll i=n;i--;)\n#define rrep2(i,n) for(ll i=n;i--;)\n#define rrep3(i,a,b) for(ll i=b;i-->(a);)\n#define rrep4(i,a,b,c) for(ll i=(a)+((b)-(a)-1)/(c)*(c);i>=(a);i-=c)\n#define repsq(i, n) for (ll i = 1; ((i) * (i) < n); ++i)\n#define rrep(...) overload4(__VA_ARGS__,rrep4,rrep3,rrep2,rrep1)(__VA_ARGS__)\n#define len(x) (int)(x).size()\n#define sum(...) accumulate(all(__VA_ARGS__),0LL)\n#define uniq(vec) sort(all(vec)); vec.erase(unique(all(vec)),end(vec))\n#define rev(vec) reverse(vec.begin(), vec.end())\n#define each(x, a) for(auto& x : a)\n#define elif else if\n#define pb push_back\n#define eb emplace_back\n#define lexi lexicographical_compare\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define Test int t; cin >> t; while(t--)\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\n#define dbg(...) cout << #__VA_ARGS__ << \" = \", _print(__VA_ARGS__)\n#define sint(...) int __VA_ARGS__; in(__VA_ARGS__)\n#define sll(...) ll __VA_ARGS__; in(__VA_ARGS__)\n#define sstr(...) string __VA_ARGS__; in(__VA_ARGS__)\n#define sch(...) char __VA_ARGS__; in(__VA_ARGS__)\n#define sdbl(...) double __VA_ARGS__; in(__VA_ARGS__)\n#define sld(...) ld __VA_ARGS__; in(__VA_ARGS__)\n#define svll(n, v) vll v(n); scan(v)\n#define svii(n, v) vii v(n); scan(v)\n#define svec(type, n, v) vector<type> v(n); scan(v)\n#define s1vll(n,v) vll v(n + 1); rep(i, 1, n + 1) cin >> v[i];\n#define s1vii(n,v) vii v(n + 1); rep(i, 1, n + 1) cin >> v[i];\n// ----------------------------------------------------------------------------------------\n#define FLUSH cin.ignore(numeric_limits<streamsize>::max(), '\\n') //Forget whatever is there in the current line and go to the next line. Use cin.ignore() for ignorning the very next character.\n#define avoidBlanks while (cin.peek() == '\\n') cin.ignore()\n// ----------------------------------------------------------------------------------------\n//binarySearch macros\n// ----------------------------------------------------------------------------------------\n#define lb(v,target) lower_bound(all(v), target)\n#define rlb(v,target) lower_bound(rall(v), target)\n#define lbset(s,target) s.lower_bound(target)\n#define ub(v,target) upper_bound(all(v), target)\n#define lbidx(v,target) lb(v,target)-v.begin()\n#define ubidx(v,target) ub(v,target)-v.begin()\n#define rub(v,target) upper_bound(rall(v), target) //Equivalent to finding the largest element smaller than or equal to target\n#define ubset(s,target) s.upper_bound(target)\n//vector macros\n#define ins(v,idx, value) (v).insert((v).begin() + (idx), value)\n//for inserting an elem at an index in the vector\n#define voc(str) (std::vector<std::decay_t<decltype(str[0])>>((str).begin(), (str).end()))\n#define vjoin(v1, v2) (v1.insert(v1.end(), v2.begin(), v2.end()))\n#define rotatel(v, k) rotate((v).begin(), (v).begin() + ((k) % (v).size()), (v).end())\n#define rotater(v, k) rotate((v).rbegin(), (v).rbegin() + ((k) % (v).size()), (v).rend())\n// ----------------------------------------------------------------------------------------\n//math macros\n#define manhdist(x1,y1,x2,y2) abs(x1-x2)+abs(y1-y2)\n#define digitcount(n) ((n) == 0 ? 1 : (int)log10(abs(n)) + 1)\n#define cdiv(a, b) (((a) + (b) - 1) / (b))\n// ----------------------------------------------------------------------------------------\n//string macros\n#define str(x) to_string(x)\n#define tolower(s) transform(s.begin(), s.end(), s.begin(), ::tolower)\n\n// ----------------------------------------------------------------------------------------\n//array macros\n#define cleantable(m,v) memset(m,v,sizeof(m));\n// ----------------------------------------------------------------------------------------\n//character macros\n#define ctoi(c) ((c) - '0')\n// ----------------------------------------------------------------------------------------\n//bit macros\n#define bit(x, i) (((x) >> (i)) & 1)\n#define popcount(x) __builtin_popcountll(x)\n#define lsb(x) ((x) & -(x))\n//\n#define print_range(v, i, j) copy((v).begin() + (i), (v).begin() + (j), ostream_iterator<decltype((v)[0])>(cout, \" \"))\n\n//\nconst int dx4[4] = {1, 0, -1, 0}, dy4[4] = {0, 1, 0, -1};\nconst int dx8[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst int dy8[8] = {0, 1, 1, 1, 0, -1, -1, -1};\n\n// ----------------------------------------------------------------------------------------\nusing ll = long long;\nusing ld = long double;\nusing ull = unsigned long long;\nusing vch = vector<char>;\nusing vvcc = vector<vch>;\nusing vll = vector<ll>;\nusing pll = pair<ll, ll>;\nusing pdd = pair<long double, long double>;\nusing pii = pair<int, int>;\nusing vvll = vector<vll>;\nusing vii = vector<int>;\nusing vvii = vector<vii>;\nusing vecs = vector<string>;\nusing vpii = vector<pair<int, int>>;\nusing vvpii = vector<vpii>;\nusing vch = vector<char>;\nusing vvch = vector<vector<char>>;\nusing vpll = vector<pair<ll, ll>>;\nusing vpci = vector<pair<char,int>>;\nusing vpcl = vector<pair<char,ll>>;\nusing vvpll = vector<vpll>;\nusing vbl = vector<bool>;\nusing vvbl = vector<vector<bool>>;\nusing usetii = unordered_set<int>;\nusing usetll = unordered_set<ll>;\nusing setii = set<int>;\nusing setll = set<ll>;\nusing setpll = set<pll>;\nusing setpii = set<pii>;\nusing setstr = set<string>;\nusing usetpll = unordered_set<pll>;\nusing usetpii = unordered_set<pii>;\nusing stkint = stack<int>;\nusing stkll = stack<ll>;\nusing stkpii = stack<pii>;\nusing stkpll = stack<pll>;\nstatic constexpr ll inf = 1000000000000000000LL;\nstatic constexpr ll ninf = -1000000000000000000LL;\n// ----------------------------------------------------------------------------------------\ntemplate<class T> auto vmin(const T& a){ return *min_element(all(a)); }\ntemplate<class T> auto vmax(const T& a){ return *max_element(all(a)); }\ntemplate<class T> void chmin(T& a, T b) { if (a > b) a = b; }\ntemplate<class T> void chmax(T& a, T b) { if (a < b) a = b; }\ntemplate<class T, class U> bool chmin(T& a, const U& b){ if(a > T(b)){ a = b; return 1; } return 0; }\ntemplate<class T, class U> bool chmax(T& a, const U& b){ if(a < T(b)){ a = b; return 1; } return 0; }\ntemplate<typename T>\nusing maxpq = priority_queue<T>;\ntemplate<typename T>\nusing minpq = priority_queue<T, vector<T>, greater<T>>;\n\n \n//scan\ninline void scan() {}\ninline void scan(int &a) { std::cin >> a; }\ninline void scan(unsigned &a) { std::cin >> a; }\ninline void scan(long &a) { std::cin >> a; }\ninline void scan(long long &a) { std::cin >> a; }\ninline void scan(unsigned long long &a) { std::cin >> a; }\ninline void scan(char &a) { std::cin >> a; }\ninline void scan(float &a) { std::cin >> a; }\ninline void scan(double &a) { std::cin >> a; }\ninline void scan(long double &a) { std::cin >> a; }\ninline void scan(std::vector<bool> &vec) {\n for (int32_t i = 0; i < vec.size(); i++) {\n int a;\n scan(a);\n vec[i] = a;\n }\n}\ninline void scan(std::string &a) { std::cin >> a; }\ntemplate <class T>\ninline void scan(std::vector<T> &vec);\ntemplate <class T, size_t size>\ninline void scan(std::array<T, size> &vec);\ntemplate <class T, class L>\ninline void scan(std::pair<T, L> &p);\ntemplate <class T, size_t size>\ninline void scan(T (&vec)[size]);\ntemplate <class T>\ninline void scan(std::vector<T> &vec) {\n for (auto &i : vec) scan(i);\n}\ntemplate <class T>\ninline void scan(std::deque<T> &vec) {\n for (auto &i : vec) scan(i);\n}\ntemplate <class T, size_t size>\ninline void scan(std::array<T, size> &vec) {\n for (auto &i : vec) scan(i);\n}\ntemplate <class T, class L>\ninline void scan(std::pair<T, L> &p) {\n scan(p.first);\n scan(p.second);\n}\ntemplate <class T, size_t size>\ninline void scan(T (&vec)[size]) {\n for (auto &i : vec) scan(i);\n}\ntemplate <class T>\ninline void scan(T &a) {\n std::cin >> a;\n}\ninline void in() {}\ntemplate <class Head, class... Tail>\ninline void in(Head &head, Tail &...tail) {\n scan(head);\n in(tail...);\n}\n \n//print\ninline void print() { std::cout << ' '; }\ninline void print(const bool &a) { std::cout << a; }\ninline void print(const int &a) { std::cout << a; }\ninline void print(const unsigned &a) { std::cout << a; }\ninline void print(const long &a) { std::cout << a; }\ninline void print(const long long &a) { std::cout << a; }\ninline void print(const unsigned long long &a) { std::cout << a; }\ninline void print(const char &a) { std::cout << a; }\ninline void print(const char a[]) { std::cout << a; }\ninline void print(const float &a) { std::cout << a; }\ninline void print(const double &a) { std::cout << a; }\ninline void print(const long double &a) { std::cout << a; }\ninline void print(const std::string &a) {\n for (auto &&i : a) print(i);\n}\ntemplate <class T>\ninline void print(const std::vector<T> &vec);\ntemplate <class T, size_t size>\ninline void print(const std::array<T, size> &vec);\ntemplate <class T, class L>\ninline void print(const std::pair<T, L> &p);\ntemplate <class T, size_t size>\ninline void print(const T (&vec)[size]);\ntemplate <class T>\ninline void print(const std::vector<T> &vec) {\n if (vec.empty()) return;\n print(vec[0]);\n for (auto i = vec.begin(); ++i != vec.end();) {\n std::cout << ' ';\n print(*i);\n }\n}\ntemplate <typename T>\ninline void print(const std::set<T>& s) {\n if (s.empty()) return;\n auto it = s.begin();\n print(*it);\n for (++it; it != s.end(); ++it) {\n cout << ' ';\n print(*it);\n }\n}\n\ntemplate <class T>\ninline void print(const std::deque<T> &vec) {\n if (vec.empty()) return;\n print(vec[0]);\n for (auto i = vec.begin(); ++i != vec.end();) {\n std::cout << ' ';\n print(*i);\n }\n}\ntemplate <class T, size_t size>\ninline void print(const std::array<T, size> &vec) {\n print(vec[0]);\n for (auto i = vec.begin(); ++i != vec.end();) {\n std::cout << ' ';\n print(*i);\n }\n}\ntemplate <class T, class L>\ninline void print(const std::pair<T, L> &p) {\n print(p.first);\n std::cout << ' ';\n print(p.second);\n}\ntemplate <class T, size_t size>\ninline void print(const T (&vec)[size]) {\n print(vec[0]);\n for (auto i = vec; ++i != end(vec);) {\n std::cout << ' ';\n print(*i);\n }\n}\ntemplate <class T>\ninline void print(const T &a) {\n std::cout << a;\n}\ninline void out() { std::cout << '\\n'; }\ntemplate <class T>\ninline void out(const T &t) {\n print(t);\n std::cout << '\\n';\n}\ntemplate <class Head, class... Tail>\ninline void out(const Head &head, const Tail &...tail) {\n print(head);\n std::cout << ' ';\n out(tail...);\n}\n\ntemplate<typename T>\nvoid __print(const T &x) { cout << x; }\n\ntemplate<typename T, typename V>\nvoid __print(const pair<T, V> &x) {\n cout << \"{\"; __print(x.first); cout << \", \"; __print(x.second); cout << \"}\";\n}\n\ntemplate<typename T>\nvoid __print(const vector<T> &v) {\n cout << \"[\";\n for (size_t i = 0; i < v.size(); ++i) {\n __print(v[i]);\n if (i + 1 != v.size()) cout << \", \";\n }\n cout << \"]\";\n}\n\ntemplate<typename T>\nvoid __print(const set<T> &v) {\n cout << \"{\";\n bool first = true;\n for (auto &i : v) {\n if (!first) cout << \", \";\n __print(i);\n first = false;\n }\n cout << \"}\";\n}\n\ntemplate<typename T>\nvoid __print(const multiset<T> &v) { __print(set<T>(v.begin(), v.end())); }\n\ntemplate<typename K, typename V>\nvoid __print(const map<K, V> &v) {\n cout << \"{\";\n bool first = true;\n for (auto &i : v) {\n if (!first) cout << \", \";\n __print(i);\n first = false;\n }\n cout << \"}\";\n}\n\ntemplate<typename T>\nvoid __print(const unordered_set<T> &v) { __print(set<T>(v.begin(), v.end())); }\n\ntemplate<typename K, typename V>\nvoid __print(const unordered_map<K, V> &v) { __print(map<K, V>(v.begin(), v.end())); }\n\nvoid _print() { cout << endl; }\n\ntemplate<typename T, typename... V>\nvoid _print(T t, V... v) {\n __print(t);\n if (sizeof...(v)) cout << \", \";\n _print(v...);\n}\n//redefined find template to give -1 if key not found.\ntemplate<typename Container, typename Key>\ninline int find_idx(const Container &c, const Key &key) {\n auto it = std::find(std::begin(c), std::end(c), key);\n if (it == std::end(c)) return -1;\n return int(std::distance(std::begin(c), it));\n}\n\ntemplate<typename T, typename Func>\nT bitwise_bs(T start, int maxpow, Func works, bool maximise = true) {\n T cur = start;\n for (T step = (1LL << maxpow); step > 0; step >>= 1) {\n if (maximise) {\n if (works(cur + step)) cur += step;\n } else {\n if (works(cur - step)) cur -= step;\n }\n }\n return cur;\n}\n\n\n\nstruct IoSetup {\n IoSetup() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n cerr << fixed << setprecision(15);\n }\n} iosetup;\n\nconst int residues[] = {1, 7, 11, 13, 17, 19, 23, 29};\n\nvll primes_upto(ll n) \n{\n if (n < 2) return {};\n\n bitset<50000001> is_prime;\n is_prime.set();\n is_prime[0] = 0; // 1 is not prime\n\n vll primes = {2, 3, 5};\n\n int sqrt_n = sqrt(n);\n\n for (int p = 7; p <= sqrt_n; p += 2) {\n // Check only numbers coprime to 2, 3, 5\n ll mod30 = p % 30;\n bool good = false;\n each(r,residues)\n if (r == mod30) good = true;\n\n if (!good) continue;\n if (!is_prime[p/2]) continue;\n\n for (int j = p*p; j <= n; j += 2*p) {\n is_prime[j/2] = 0;\n }\n }\n\n for (int p = 7; p <= n; p += 2) {\n int mod30 = p % 30;\n each(r,residues) {\n if (mod30 == r) {\n if (is_prime[p/2]) primes.push_back(p);\n break;\n }\n }\n }\n\n return primes;\n}\nll power(ll a, ll b) \n{\n ll result = 1;\n while (b > 0) {\n if (b % 2 == 1) result *= a;\n a *= a;\n b /= 2;\n }\n return result;\n}\n\nstring to_base(ll a,ll b)\n{\n if (b<2 || b>36) throw invalid_argument(\"base out of range\");\n if (a == 0) return \"0\";\n static const char* digits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n string s;\n while (a > 0) {\n int rem = a % b;\n s.pb(digits[rem]);\n a /= b;\n }\n reverse(all(s));\n return s;\n}\n\ntemplate <typename T>\nstd::vector<T> vslice(const std::vector<T>& v, int l, int r) {\n if (l < 0) l += v.size(); // Handle negative indexing like Python\n if (r < 0) r += v.size();\n l = std::max(0, l);\n r = std::min((int)v.size(), r);\n if (l > r) l = r; // Avoid invalid range\n return std::vector<T>(v.begin() + l, v.begin() + r);\n}\n\n\nvll all_divisors(ll n) {\n vll divs;\n for (ll i = 1; i * i <= n; ++i) {\n if (n % i == 0) {\n divs.push_back(i);\n if (i != n / i) divs.push_back(n / i);\n }\n }\n sort(all(divs));\n return divs;\n}\n\nvll pqtop(priority_queue<ll>pq,ll k)\n{\n vll res;\n while (k-- && !pq.empty()) {\n res.pb(pq.top());\n pq.pop();\n }\n return res;\n}\n\n//Classic template\n\ntemplate <typename F>\nll bsta(F check, ll ok, ll ng, bool check_ok = true) {\n if (check_ok) assert(check(ok));\n while (abs(ok - ng) > 1) {\n ll x = (ok + ng) / 2;\n (check(x) ? ok : ng) = x;\n }\n return ok;\n}\n\n\n\nstruct pair_hash {\n size_t operator()(const pll& p) const {\n return hash<ll>()(p.first) ^ (hash<ll>()(p.second) << 1);\n }\n};\ninline string toLowerCopy(const string &s) {\n string t = s;\n transform(t.begin(), t.end(), t.begin(), ::tolower);\n return t;\n}\n\nint main() \n{\n sll(n,w);\n vector<long double> val(n),wei(n);\n vector<long double>per(n);\n vector<vector<long double>> item;\n rep(n)\n {\n in(val[i],wei[i]);\n per[i] = (long double)val[i]/(long double)wei[i];\n item.pb({per[i],val[i],wei[i]});\n }\n sort(all(item),greater<>());\n long double ans = 0;\n rep(i,0,n)\n {\n long double used = min(item[i][2],(long double)w);\n ans += item[i][0] * used;\n w-=used;\n }\n \n out(ans);\n \n \n}", "accuracy": 1, "time_ms": 50, "memory_kb": 16556, "score_of_the_acc": -1.6667, "final_rank": 13 }, { "submission_id": "aoj_ALDS1_15_B_10803559", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <tuple>\n\n\nusing namespace std;\nusing ll = long long;\n\nint main() {\n int n;\n ll w;\n cin >> n >> w;\n\n\tvector<tuple<double, ll, ll>> items(n);\n for (int i = 0; i < n; i++) {\n\t\tcin >> get<1>(items[i]) >> get<2>(items[i]);\n get<0>(items[i]) = (double)(get<1>(items[i])) / get<2>(items[i]);\n }\n sort(items.begin(), items.end(), [](auto& a, auto& b) {\n return get<0>(a) > get<0>(b);\n });\n\n \n double wKnapsack = 0;\n double totalValue = 0;\n\tint i = 0;\n while ((wKnapsack < w) && (i != n)) {\n\t\tdouble ratio = get<0>(items[i]);\n ll value = get<1>(items[i]);\n\t\tll Wt = get<2>(items[i]);\n\n if (Wt + wKnapsack <= w) {\n\t\t\twKnapsack += Wt;\n totalValue += value;\n }\n else {\n\t\t\ttotalValue += (w - wKnapsack) * ratio;\n wKnapsack = w;\n }\n i++;\n }\n\n cout.precision(10);\n cout << fixed << totalValue << '\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5420, "score_of_the_acc": -0.6223, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_15_B_10797747", "code_snippet": "#include \"bits/stdc++.h\"\n\nusing namespace std;\nusing ll = long long;\n\nint main() {\n int n;\n ll capacity;\n cin >> n >> capacity;\n\n vector<ll> w(n), v(n);\n vector<pair<double, int>> r;\n\n for (int i = 0; i < n; ++i) {\n cin >> v[i] >> w[i];\n double ratio = static_cast<double>(v[i]) / w[i];\n r.push_back({ratio, i});\n }\n\n sort(r.begin(), r.end());\n\n double value = 0.0;\n\n for (int i = n - 1; i >= 0 && capacity > 0; --i) {\n int idx = r[i].second;\n if (w[idx] <= capacity) {\n value += v[idx];\n capacity -= w[idx];\n } else {\n value += r[i].first * capacity;\n capacity = 0;\n }\n }\n\n cout << fixed << setprecision(10) << value << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 6708, "score_of_the_acc": -0.8905, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_15_B_10737836", "code_snippet": "#include <stdio.h>\n#include <stdlib.h>\n\n// 品物の情報を保持する構造体\ntypedef struct {\n long long value;\n long long weight;\n double density; // 重さ1あたりの価値\n} Item;\n\n// qsortで密度を降順にソートするための比較関数\nint compareItems(const void *a, const void *b) {\n Item *itemA = (Item *)a;\n Item *itemB = (Item *)b;\n if (itemA->density < itemB->density) {\n return 1;\n } else if (itemA->density > itemB->density) {\n return -1;\n }\n return 0;\n}\n\nint main() {\n int N;\n long long W;\n scanf(\"%d %lld\", &N, &W);\n\n Item *items = (Item *)malloc(sizeof(Item) * N);\n\n for (int i = 0; i < N; i++) {\n scanf(\"%lld %lld\", &items[i].value, &items[i].weight);\n items[i].density = (double)items[i].value / items[i].weight;\n }\n\n // 価値密度で品物を降順にソート\n qsort(items, N, sizeof(Item), compareItems);\n\n double total_value = 0.0;\n\n // 価値密度が高い順にナップサックに詰めていく\n for (int i = 0; i < N; i++) {\n if (W == 0) {\n break; // ナップサックが満杯\n }\n \n // 品物iを詰める量を決める\n // ナップサックの残り容量と品物の重さのうち、小さい方\n long long take_weight = (items[i].weight < W) ? items[i].weight : W;\n \n // 詰めた分だけ価値を合計に加算\n total_value += (double)take_weight * items[i].density;\n \n // ナップサックの残り容量を減らす\n W -= take_weight;\n }\n\n printf(\"%.12f\\n\", total_value);\n\n free(items);\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7112, "score_of_the_acc": -0.4223, "final_rank": 3 }, { "submission_id": "aoj_ALDS1_15_B_10737831", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <iomanip> // std::setprecision\nusing namespace std;\n\nstruct Item {\n double value; // 価値\n double weight; // 重さ\n double value_per_weight; // 価値/重さの比\n};\n\n// 比較用関数\nbool compare(const Item &a, const Item &b) {\n return a.value_per_weight > b.value_per_weight; // 高いものから順に\n}\n\nint main() {\n int N; // 品物の数\n long long W; // ナップサックの容量\n cin >> N >> W;\n\n vector<Item> items(N);\n\n // 入力を受け取る\n for (int i = 0; i < N; i++) {\n cin >> items[i].value >> items[i].weight;\n items[i].value_per_weight = items[i].value / items[i].weight;\n }\n\n // 価値/重さの比で降順に並べ替える\n sort(items.begin(), items.end(), compare);\n\n double total_value = 0; // 最大の価値の合計\n\n for (int i = 0; i < N; i++) {\n if (W == 0) break; // ナップサックがいっぱいになった場合\n\n if (W >= items[i].weight) {\n // その品物をすべて詰めることができる\n W -= items[i].weight;\n total_value += items[i].value;\n } else {\n // ナップサックに入る分だけ詰める\n total_value += items[i].value_per_weight * W;\n W = 0; // ナップサックがいっぱいになったので終了\n }\n }\n\n // 結果の出力(小数点以下6桁まで表示)\n cout << fixed << setprecision(6) << total_value << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 5456, "score_of_the_acc": -0.9585, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_15_B_10732145", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\n\nint main() {\n ios::sync_with_stdio(false); cin.tie(NULL);\n int n, w; cin >> n >> w;\n vector<pair<int, int>> itm(n);\n for(auto &x:itm) cin >> x.first >> x.second;\n\n auto cmp = [](const auto &a, const auto &b) {\n return (double)a.first/a.second >(double)b.first/b.second;\n };\n sort(itm.begin(), itm.end(), cmp);\n int i=0; double res = 0.0;\n int curcap = w;\n for(int i=0;i<n;i++) {\n if(itm[i].second<=curcap) {\n res+= itm[i].first; curcap-= itm[i].second;\n } else {\n res += (1.0 *itm[i].first/itm[i].second*curcap);\n break;\n }\n }\n if((res-(int) res) < 1e-7) cout << (int) res << '\\n';\n else printf(\"%.8lf\\n\", res);\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3868, "score_of_the_acc": -0.1667, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_15_B_10728068", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Item{\n double weight;\n double profit;\n double ratio;\n int index;\n};\n\nint main(){\n int n;\n cin>>n;\n vector<Item> items(n);\n double capacity;\n cin>>capacity;\n for(int i=0; i<n; i++){\n //cin>>items[i].weight>>items[i].profit;\n cin>>items[i].profit>>items[i].weight;\n items[i].ratio = items[i].profit/items[i].weight;\n items[i].index = i;\n }\n\n //double capacity = 50;\n //cin>>capacity;\n sort(items.begin(), items.end(), [](const Item &a, const Item &b){\n return a.ratio > b.ratio;});\n\n vector<double>x(n,0.0);\n double total = 0.0;\n double remaining = capacity;\n\n for(int i=0; i<n; ++i){\n if(items[i].weight <=remaining){\n x[i] = 1.0;\n total += items[i].profit;\n remaining -= items[i].weight;\n }\n else{\n x[i] = remaining/items[i].weight;\n total += x[i]*items[i].profit;\n remaining = 0;\n break;\n }\n }\n\n cout<<setprecision(15)<<total;\n}", "accuracy": 0.34, "time_ms": 40, "memory_kb": 5376, "score_of_the_acc": -0.6189, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_15_B_10728031", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Item{\n double weight;\n double profit;\n double ratio;\n int index;\n};\n\nint main(){\n int n;\n cin>>n;\n vector<Item> items(n);\n double capacity;\n cin>>capacity;\n for(int i=0; i<n; i++){\n //cin>>items[i].weight>>items[i].profit;\n cin>>items[i].profit>>items[i].weight;\n items[i].ratio = items[i].profit/items[i].weight;\n items[i].index = i;\n }\n\n //double capacity = 50;\n //cin>>capacity;\n sort(items.begin(), items.end(), [](const Item &a, const Item &b){\n return a.ratio > b.ratio;});\n\n vector<double>x(n,0.0);\n double total = 0.0;\n double remaining = capacity;\n\n for(int i=0; i<n; ++i){\n if(items[i].weight <=remaining){\n x[i] = 1.0;\n total += items[i].profit;\n remaining -= items[i].weight;\n }\n else{\n x[i] = remaining/items[i].weight;\n total += x[i]*items[i].profit;\n remaining = 0;\n break;\n }\n }\n\n cout<<setprecision(9)<<total;\n}", "accuracy": 0.34, "time_ms": 40, "memory_kb": 5372, "score_of_the_acc": -0.6185, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_15_B_10727964", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n bool comp(pair<int,int>a,pair<int,int>b){\n return a.first*b.second>b.first*a.second;\n}\n \nint main()\n{ \n \n int c,n;\n cin>>n>>c;\n vector<int>val(n);\n vector<int>wt(n);\n for(int i=0;i<n;i++){\n cin>>val[i]>>wt[i];\n }\n \n vector<pair<int,int>>items;\n\n for(int i=0;i<val.size();i++){\n items.emplace_back(val[i],wt[i]);\n }\n\n sort(items.begin(),items.end(),comp);\n\n double profit=0;\n for(int i=0;i<val.size();i++){\n if(items[i].second>c){\n double vw=((double)items[i].first/(double)items[i].second)*(c*1.00);\n profit+=vw;\n break;\n } \n if(items[i].second<=c) {profit+=items[i].first;\n c-=items[i].second;}\n if(c==0) break;\n }\n cout<<setprecision(1000000)<<profit<<endl;\n\n \n}", "accuracy": 0.34, "time_ms": 30, "memory_kb": 7256, "score_of_the_acc": -0.6004, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_15_B_10727963", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n\nvoid solve()\n{\n ll n, w;\n cin >> n >> w;\n vector<pair<pair<double, double>, double>> vec(n + 1);\n for (int i = 1; i <= n; i++) {\n cin >> vec[i].first.first >> vec[i].first.second;\n vec[i].second = vec[i].first.first / vec[i].first.second;\n }\n auto comp = [] (pair<pair<double, double>, double> a, pair<pair<double, double>, double> b) {\n return a.second >= b.second;\n };\n sort(vec.begin(), vec.end(), comp);\n double ans = 0;\n for (auto it: vec) {\n double val = it.second;\n double amt = it.first.second;\n if (amt <= w) {\n ans += (amt * val);\n w -= amt;\n }\n else {\n ans += (((double)w) * val);\n w = 0;\n }\n }\n cout << setprecision(10) << fixed << ans << \"\\n\";\n}\n\nint main()\n{\n cin.tie(NULL);\n ios_base::sync_with_stdio(false);\n\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 5428, "score_of_the_acc": -0.4563, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_15_B_10710602", "code_snippet": "// nur_008\n// بِسْمِ اللَّهِ الرَّحْمَـٰنِ الرَّحِيمِ\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long int;\nusing ld = double;\nbool cmp(pair<int, pair<int, ld>> a, pair<int, pair<int, ld>> b)\n{\n return a.second.second > b.second.second;\n}\nvoid champ()\n{\n ll n, m;\n cin >> n >> m;\n ld taka = 0;\n vector<pair<ll, pair<ll, ld>>> vp;\n for (int i = 0; i < n; i++)\n {\n ll x, y;\n cin >> x >> y;\n ld w = (ld)x / (ld)y;\n vp.push_back({x, {y, w}});\n }\n sort(vp.begin(), vp.end(), cmp);\n int i = 0;\n // for (auto [a, b] : vp)\n // {\n // cout << a << \" \" << b.first << \" \" << b.second << \" \\n\";\n // }\n while (m>0 && i < n)\n {\n ll mini = min(m, vp[i].second.first);\n taka += (ld)mini * vp[i].second.second;\n m -= mini;\n vp[i].second.first -= mini;\n if (vp[i].second.first == 0)\n i++;\n }\n ll money = taka;\n if (money == taka)\n {\n cout << money << \"\\n\";\n }\n else\n cout << fixed << setprecision(8) << taka << \"\\n\";\n}\nint main()\n{\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n int t = 1;\n // cin >> t;\n while (t--)\n {\n champ();\n }\n return 0;\n // اللّٰهُ أَكْبَر\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7368, "score_of_the_acc": -0.4425, "final_rank": 4 } ]
aoj_ALDS1_15_C_cpp
Activity Selection Problem There are $n$ acitivities with start times $\{s_i\}$ and finish times $\{t_i\}$. Assuming that a person can only work on a single activity at a time, find the maximum number of activities that can be performed by a single person. Input $n$ $s_1$ $t_1$ $s_2$ $t_2$ : $s_n$ $t_n$ The first line consists of the integer $n$. In the following $n$ lines, the start time $s_i$ and the finish time $t_i$ of the activity $i$ are given. 出力 Print the maximum number of activities in a line. Constraints $1 \le n \le 10^5$ $1 \le s_i \lt t_i \le 10^9 (1 \le i \le n)$ Sample Input 1 5 1 2 3 9 3 5 5 9 6 8 Sample Output 1 3 Sample Input 2 3 1 5 3 4 2 5 Sample Output 2 1 Sample Input 3 3 1 2 2 3 3 4 Sample Output 3 2
[ { "submission_id": "aoj_ALDS1_15_C_11063446", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef struct time{\n int s;\n int f;\n}tym;\n\nint main(){\n int n, c=1;\n tym t[100000];\n cin >> n;\n\n for(int i=0; i<n; i++){\n cin >> t[i].s >> t[i].f;\n }\n\n sort(t, t + n, [](const tym &a,const tym &b){\n return a.f < b.f;\n });\n\n int lf= t[0].f;\n for(int i=1; i<n; i++){\n if(t[i].s>lf){\n c++;\n lf=t[i].f;\n }\n }\n\n cout << c << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 4200, "score_of_the_acc": -0.5392, "final_rank": 9 }, { "submission_id": "aoj_ALDS1_15_C_10999053", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Activity {\n int start;\n int finish;\n};\n\n\nbool compare(Activity a, Activity b) {\n return a.finish < b.finish;\n}\n\nint main() {\n int n;\n cin >> n;\n\n Activity activities[100000];\n for (int i = 0; i < n; i++) {\n cin >> activities[i].start >> activities[i].finish;\n }\n\n\n sort(activities, activities + n, compare);\n\n int count = 1;\n int j = 0;\n\n for (int i = 0; i < n; i++) {\n\n if (activities[i].start > activities[j].finish) {\n count++;\n j=i;\n }\n }\n\n cout << count << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4136, "score_of_the_acc": -0.6632, "final_rank": 14 }, { "submission_id": "aoj_ALDS1_15_C_10998971", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct activity {\n string name;\n float s, t;\n};\n\nbool comp(activity act1, activity act2) {\n return (act1.t < act2.t);\n}\n\nint main() {\n int n;\n\n cin >> n;\n\n activity ar[n + 5];\n\n for (int i = 0; i < n; i++) {\n cin >> ar[i].s >> ar[i].t;\n }\n\n sort(ar, ar + n, comp);\n\n int j = 0, cnt = 1;\n\n\n for (int i = 1; i < n; i++) {\n if (ar[i].s > ar[j].t) {\n cnt++;\n j = i;\n\n }\n }\n\n\n cout << cnt << endl;\n\n return 0;\n}", "accuracy": 0.68, "time_ms": 80, "memory_kb": 7224, "score_of_the_acc": -2, "final_rank": 18 }, { "submission_id": "aoj_ALDS1_15_C_10998953", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nstruct act\n {\n int s;\n int e;\n };\nbool esot (act a,act b)\n{\n if(a.e<b.e)\n return true;\n else\n return false;\n}\nint main()\n{\n \n int t;\n cin>>t;\n act a[t+1];\n for (int i = 0; i < t; i++)\n {\n cin>>a[i].s>>a[i].e;\n }\n sort(a,a+t,esot);\n int select=1;\n int tim = a[0].e;\n int j=0;\n for (int i = 1; i < t; i++)\n {\n if(a[j].e<a[i].s)\n {\n select++;\n j = i;\n }\n }\n cout<< select<< endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4156, "score_of_the_acc": -0.6691, "final_rank": 15 }, { "submission_id": "aoj_ALDS1_15_C_10998944", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Activity {\n double start;\n double end;\n};\n\nbool custom(Activity a, Activity b) {\n return a.end < b.end;\n}\n\nint main() {\n int n;\n cin >> n;\n\n Activity act[n];\n for (int i = 0; i < n; i++) {\n cin >> act[i].start >> act[i].end;\n }\n\n sort(act, act + n, custom);\n\n int count = 1;\n double last_end = act[0].end;\n\n for (int i = 1; i < n; i++){\n if (act[i].start > last_end){\n count++;\n last_end = act[i].end;\n }\n }\n\n cout << count << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5060, "score_of_the_acc": -1.2207, "final_rank": 17 }, { "submission_id": "aoj_ALDS1_15_C_10742908", "code_snippet": "#include <stdio.h>\n#include <stdlib.h>\n\n// 活動の開始時刻と終了時刻を保持する構造体\ntypedef struct {\n int s; // 開始時刻\n int t; // 終了時刻\n} Activity;\n\n// qsortライブラリ関数で使うための比較関数\n// 活動を終了時刻 `t` の昇順でソートする\nint compare_activities(const void* a, const void* b) {\n Activity* act1 = (Activity*)a;\n Activity* act2 = (Activity*)b;\n \n if (act1->t < act2->t) {\n return -1;\n } else if (act1->t > act2->t) {\n return 1;\n }\n // 終了時刻が同じ場合は順序を問わない\n return 0;\n}\n\nint main(void) {\n int n;\n scanf(\"%d\", &n);\n\n // 活動が0個の場合は0を出力して終了\n if (n == 0) {\n printf(\"0\\n\");\n return 0;\n }\n\n // n個の活動を格納するためのメモリを動的に確保\n Activity* activities = (Activity*)malloc(n * sizeof(Activity));\n if (activities == NULL) {\n // メモリ確保に失敗した場合\n return 1;\n }\n\n // n個の活動の開始時刻と終了時刻を読み込む\n for (int i = 0; i < n; i++) {\n scanf(\"%d %d\", &activities[i].s, &activities[i].t);\n }\n\n // 活動を終了時刻の早い順にソートする\n qsort(activities, n, sizeof(Activity), compare_activities);\n\n int selected_count = 1; // 最初の活動は必ず選択する\n int last_finish_time = activities[0].t; // 最後に選択した活動の終了時刻\n\n // 2番目以降の活動を順にチェックする\n for (int i = 1; i < n; i++) {\n // 現在チェックしている活動の開始時刻が、\n // 最後に選んだ活動の終了時刻より後であれば、重ならないので選択できる\n if (activities[i].s > last_finish_time) {\n selected_count++;\n last_finish_time = activities[i].t; // 最後に選んだ活動の情報を更新\n }\n }\n\n // 選択できた活動の最大数を出力\n printf(\"%d\\n\", selected_count);\n\n // 確保したメモリを解放\n free(activities);\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4212, "score_of_the_acc": -0.257, "final_rank": 4 }, { "submission_id": "aoj_ALDS1_15_C_10696717", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nbool cmp(pair<int,int>a,pair<int,int>b)\n{\n return a.second<b.second;\n}\nint main()\n{\n int n;\n cin>>n;\n vector<pair<int,int>>v;\n for(int i=0;i<n;i++)\n {\n int start,end;\n cin>>start>>end;\n v.push_back(make_pair(start,end));\n }\n sort(v.begin(),v.end(),cmp);\n int count=1,finish=v[0].second;\n for(int i=1;i<n;i++)\n {\n if(finish<v[i].first)\n {\n count++;\n finish=v[i].second;\n }\n }\n cout<<count<<endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4132, "score_of_the_acc": -0.662, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_15_C_10696676", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n\n vector<pair<int, int>> activities(n);\n\n for (int i = 0; i < n; i++) {\n cin >> activities[i].second >> activities[i].first;\n }\n\n sort(activities.begin(), activities.end());\n\n int count = 0;\n int lastEnd = 0;\n\n for (auto act : activities) {\n int end = act.first;\n int start = act.second;\n\n if (start > lastEnd) { \n count++;\n lastEnd = end;\n }\n }\n\n cout << count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3908, "score_of_the_acc": -0.4533, "final_rank": 8 }, { "submission_id": "aoj_ALDS1_15_C_10696574", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n\n vector<pair<int, int>> activities(n);\n\n for (int i = 0; i < n; i++) {\n cin >> activities[i].second >> activities[i].first;\n }\n\n sort(activities.begin(), activities.end());\n\n int count = 0;\n int lastEnd = 0;\n\n for (auto act : activities) {\n int end = act.first;\n int start = act.second;\n\n if (start > lastEnd) { // changed >= to >\n count++;\n lastEnd = end;\n }\n }\n\n cout << count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3876, "score_of_the_acc": -0.4439, "final_rank": 6 }, { "submission_id": "aoj_ALDS1_15_C_10696493", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nbool cmp(pair<int,int>a,pair<int,int>b)\n{\n return a.second<b.second;\n}\nint main()\n{\n int n;\n cin>>n;\n vector<pair<int,int>>v;\n for(int i=0;i<n;i++)\n {\n int start,end;\n cin>>start>>end;\n v.push_back(make_pair(start,end));\n }\n sort(v.begin(),v.end(),cmp);\n int count=1,finish=v[0].second;\n for(int i=1;i<n;i++)\n {\n if(finish<v[i].first)\n {\n count++;\n finish=v[i].second;\n }\n }\n cout<<count<<endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4132, "score_of_the_acc": -0.662, "final_rank": 12 }, { "submission_id": "aoj_ALDS1_15_C_10636643", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nstruct Act {\n double a, b;\n};\nbool comp(Act a1, Act a2){\n return(a1.b<a2.b);\n}\n int main(){\n\n int n;\n cin>> n;\n Act arr[n] ;\n for(int i=0; i<n; i++){\n cin>>arr[i].a>> arr[i].b;\n\n }\n\n sort(arr, arr+n, comp);\n int j=0, cnt=1;\n for(int i=1; i<n; i++){\n if(arr[j].b<arr[i].a){\n cnt++;\n j=i;\n }\n }\n cout<<cnt <<endl;\n }", "accuracy": 1, "time_ms": 70, "memory_kb": 4984, "score_of_the_acc": -1.1983, "final_rank": 16 }, { "submission_id": "aoj_ALDS1_15_C_10568026", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n\n int n, count = 0, last_end = -1;\n cin >> n;\n\n vector<pair<int, int>> activities(n);\n for (int i = 0; i < n; ++i)\n cin >> activities[i].second >> activities[i].first;\n\n sort(activities.begin(), activities.end());\n\n for (auto& [end, start] : activities) if (start > last_end) {\n count++;\n last_end = end;\n }\n\n cout << count << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3868, "score_of_the_acc": -0.0129, "final_rank": 1 }, { "submission_id": "aoj_ALDS1_15_C_10565863", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ii = pair<int,int>;\nusing vii = vector<ii> ;\nusing vi = vector<int> ;\n#define ln '\\n'\n#define ll long long\n#define pb push_back\n#define fi first\n#define se second\n#define sz(v) ((int)(v).size())\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define f(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define fer(i, b, a) for(ll i = (ll)a - 1; i >= (ll)b; i--)\n\nvoid so(int test){\n int n;\n cin >> n;\n vii v(n+1);\n f(i,1,n+1){\n cin >> v[i].fi >> v[i].se;\n }\n\n sort(all(v));\n\n vi dp(n+2,0);\n\n auto nex = [&](int x){\n auto [a,b] = v[x];\n int lo = x+1, lf = n,mid;\n while(lo < lf){\n mid = (lo+lf)/2;\n if(v[mid].fi > b){\n lf = mid ;\n }else{\n lo = mid+1;\n }\n }\n if(v[lo].fi > b)return lo;\n return -1;\n };\n\n for(int i = 1; i <= n ; i++){\n if(nex(i) != -1)dp[nex(i)] = max(dp[i] + 1,dp[nex(i)]);\n else dp[n+1] = max(dp[n+1],dp[i] + 1);\n dp[i+1] = max(dp[i+1], dp[i]);\n }\n cout << dp[n+1] << ln;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint tt = 1;\n\tint test = 1;\n\twhile (tt--){\n\t\tso(test++);\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 4392, "score_of_the_acc": -0.4528, "final_rank": 7 }, { "submission_id": "aoj_ALDS1_15_C_10560727", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\tvector<pair<int, int>> v(n);\n\tfor (auto& [l, r] : v) cin >> l >> r;\n\tsort(v.begin(), v.end(), [&] (auto a, auto b) {\n\t\treturn a.second < b.second;\t\n\t});\n\tint last = -1, cnt = 0;\n\tfor (auto [l, r] : v) {\n\t\tif (last >= l) continue;\n\t\tlast = r;\n\t\tcnt += 1;\n\t}\n\tcout << cnt << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3824, "score_of_the_acc": -0.4286, "final_rank": 5 }, { "submission_id": "aoj_ALDS1_15_C_10514400", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nstruct Act {\n int start;\n int end;\n};\n\nbool comp(const Act& a, const Act& b) {\n if (a.end == b.end)\n return a.start < b.start;\n else\n return a.end < b.end;\n}\n\nint main()\n{\n int n;\n std::cin >> n;\n std::vector<Act> act(n);\n for (int i = 0; i < n; i++)\n std::cin >> act[i].start >> act[i].end;\n\n std::sort(act.begin(), act.end(), comp);\n\n int count = 1;\n int et = act[0].end;\n for (int i = 1; i < n; i++) {\n if (et < act[i].start) {\n count++;\n et = act[i].end;\n }\n }\n\n std::cout << count << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3868, "score_of_the_acc": -0.5844, "final_rank": 10 }, { "submission_id": "aoj_ALDS1_15_C_10465775", "code_snippet": "#include <bits/stdc++.h>\n#define _ ios_base::sync_with_stdio(0); cin.tie(0);\nusing namespace std;\n\nint main() { _\n int N;\n cin >> N;\n\n vector<pair<int, int>> activities;\n\n for (int i = 0; i < N; ++i) {\n int s, t;\n cin >> s >> t;\n activities.push_back({t, s});\n }\n\n sort(activities.begin(), activities.end());\n\n int maxActivities = 0, lastFinish = 0;\n\n for (int i = 0; i < N; ++i) {\n int start = activities[i].second;\n int finish = activities[i].first;\n\n if (start > lastFinish) {\n ++maxActivities;\n lastFinish = finish;\n }\n }\n\n cout << maxActivities << '\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4124, "score_of_the_acc": -0.0882, "final_rank": 2 }, { "submission_id": "aoj_ALDS1_15_C_10465521", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n int N;\n cin >> N;\n int numAtivs = 0, fim_geral = 0;\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> minHeap;\n for(int i = 0; i <N; i++){\n int s, t;\n cin >> s >> t;\n minHeap.push({t,s});\n }\n\n while(!minHeap.empty()){\n pair<int,int> aux = minHeap.top();\n minHeap.pop();\n int inicio = aux.second;\n int fim = aux.first;\n if(inicio > fim_geral){\n numAtivs++;\n fim_geral = fim;\n }\n }\n cout << numAtivs << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4128, "score_of_the_acc": -0.6608, "final_rank": 11 }, { "submission_id": "aoj_ALDS1_15_C_10465374", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n cin >> n;\n vector<pair<int,int>> activities;\n for (int i = 0; i < n; i++) {\n int s, t;\n cin >> s >> t;\n activities.emplace_back(t, s);\n }\n sort(activities.begin(), activities.end());\n int count = 0;\n int last_end = -1;\n for (auto &act : activities) {\n int finish = act.first;\n int start = act.second;\n if (start > last_end) {\n count++;\n last_end = finish;\n }\n }\n cout << count << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4156, "score_of_the_acc": -0.0976, "final_rank": 3 } ]
aoj_DSL_3_C_cpp
The Number of Windows For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and $Q$ integers $x_i$ as queries, for each query, print the number of combinations of two integers $(l, r)$ which satisfies the condition: $1 \leq l \leq r \leq N$ and $a_l + a_{l+1} + ... + a_{r-1} + a_r \leq x_i$. Constraints $1 \leq N \leq 10^5$ $1 \leq Q \leq 500$ $1 \leq a_i \leq 10^9$ $1 \leq x_i \leq 10^{14}$ Input The input is given in the following format. $N$ $Q$ $a_1$ $a_2$ ... $a_N$ $x_1$ $x_2$ ... $x_Q$ Output For each query, print the number of combinations in a line. Sample Input 1 6 5 1 2 3 4 5 6 6 9 12 21 15 Sample Output 1 9 12 15 21 18
[ { "submission_id": "aoj_DSL_3_C_11066206", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define FASTIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n#define FOR(i,a,b) for(int i=a;i<b;i++)\n#define ROF(i,a,b) for(int i=b-1;i>=a;i--) \n#define vecin(vec,n) for(int i=0;i<n;i++) cin>>vec[i];\n#define vecprint(vec) for(auto &it: vec) cout<<it<<\" \"; cout<<\"\\n\";\n#define ll long long\n#define vll vector<ll>\n#define pll pair<ll,ll>\n#define vpll vector<pll>\n#define fi first \n#define se second \n#define yes cout<<\"YES\\n\";\n#define no cout<<\"NO\\n\";\n#define line cout<<\"\\n\";\n#define pb push_back\n#define popb pop_back\n#define maxofvec(v) *max_element(v.begin(),v.end())\n#define minofvec(v) *min_element(v.begin(),v.end())\n#define sortall(n) sort(n.begin(),n.end())\n#define reversevs(n) reverse(n.begin(),n.end())\n#define sumvec(v) accumulate(v.begin(),v.end(),0LL)\n\nconst int M = 1e9+7;\nbool ispow2(ll n){\n return (n && !((n-1)&n));\n}\nll gcd(ll a,ll b){\n if(b==0) return a;\n return gcd(b,a%b);\n}\nll stringcnt1 (string &s){\n int n=s.size();\n int cnt=0;\n FOR(i,0,n){\n if(s[i]=='1') cnt++;\n }\n return cnt;\n}\n\n\n\n\n/*===================[ Start ]====================*/\n\n\nvoid yoo(){\n ll n,q;cin>>n>>q;\n vll vec(n);vecin(vec,n);\n while(q--){\n ll x;cin>>x;\n ll ans=0;\n ll l=0,r=0;\n ll sum = vec[l];\n if(sum<=x) ans++;\n while(r+1<n){\n r++;\n sum+=vec[r];\n if(sum<=x) ans+=(r-l+1);\n else{\n while(sum>x){\n sum-=vec[l];\n l++;\n }\n ans+=(r-l+1);\n }\n \n }\n cout<<ans;line\n }\n}\n\nint main(){\n FASTIO;\n int t;t=1;\n // cin>>t;\n while(t--)\n yoo();\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 3856, "score_of_the_acc": -0.2291, "final_rank": 1 }, { "submission_id": "aoj_DSL_3_C_11048243", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); ++i)\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n int N, Q;\n cin >> N >> Q;\n\n vector<ll> A(N);\n rep(i, N) cin >> A[i];\n vector<ll> X(N);\n rep(i, Q) cin >> X[i];\n\n vector<ll> res_list;\n rep(i, Q) {\n ll x = X[i];\n int r = 0;\n ll sum = 0;\n ll res = 0;\n rep(l, N) {\n while (r < N && sum <= x) {\n if (sum + A[r] > x) break;\n sum += A[r];\n r++;\n }\n\n res += (r - l);\n if (l == r)\n r++;\n else\n sum -= A[l];\n }\n res_list.push_back(res);\n }\n\n for (ll res : res_list) cout << res << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 4612, "score_of_the_acc": -1.3814, "final_rank": 20 }, { "submission_id": "aoj_DSL_3_C_11014818", "code_snippet": "#define _GLIBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < (int)n; i++)\nusing ll = long long;\n\nint main() {\n int n, q;\n cin >> n >> q;\n vector<int> v(n);\n rep(i,n) cin >> v[i];\n\n rep(i,q) {\n ll x;\n cin >> x;\n\n int r = 0;\n ll sum = 0, ans = 0;\n for(int l = 0; l < n; l++) {\n while(r < n && sum+v[r] <= x) {\n sum += v[r];\n r++;\n }\n ans += r-l;\n if(r == l) r++;\n else sum -= v[l];\n }\n cout << ans << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 3572, "score_of_the_acc": -0.6806, "final_rank": 9 }, { "submission_id": "aoj_DSL_3_C_11014783", "code_snippet": "#define _GLIBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < (int)n; i++)\nusing ll = long long;\n\nint main() {\n int n, q;\n cin >> n >> q;\n vector<int> v(n+1);\n vector<ll> x(n);\n rep(i,n) cin >> v[i+1];\n rep(i,q) cin >> x[i];\n\n rep(i,q) {\n int r = 1;\n ll sum = 0, ans = 0;\n for(int l = 1; l <= n; l++) {\n sum -= v[l-1];\n while(r <= n && sum+v[r] <= x[i]) {\n sum += v[r];\n r++;\n }\n ans += r-l;\n if(r == l-1) r++;\n }\n cout << ans << \"\\n\";\n }\n\n /*rep(i,q) {\n ll x;\n cin >> x;\n int r = 1;\n ll sum = 0, ans = 0;\n for(int l = 1; l <= n; l++) {\n sum -= v[l-1];\n while(r <= n && sum+v[r] <= x) {\n sum += v[r];\n r++;\n }\n ans += r-l;\n if(r == l-1) r++;\n }\n cout << ans << \"\\n\";\n }*/\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 4324, "score_of_the_acc": -1.3302, "final_rank": 18 }, { "submission_id": "aoj_DSL_3_C_11014775", "code_snippet": "#define _GLIBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < (int)n; i++)\nusing ll = long long;\n\nint main() {\n int n, q;\n cin >> n >> q;\n vector<int> v(n+1);\n rep(i,n) cin >> v[i+1];\n\n rep(i,q) {\n ll x;\n cin >> x;\n int r = 1;\n ll sum = 0, ans = 0;\n for(int l = 1; l <= n; l++) {\n sum -= v[l-1];\n while(r <= n && sum+v[r] <= x) {\n sum += v[r];\n r++;\n }\n ans += r-l;\n if(r == l-1) r++;\n }\n cout << ans << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 3556, "score_of_the_acc": -0.5984, "final_rank": 8 }, { "submission_id": "aoj_DSL_3_C_11014774", "code_snippet": "#define _GLIBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < (int)n; i++)\nusing ll = long long;\n\nint main() {\n int n, q;\n cin >> n >> q;\n vector<int> v(n+1);\n rep(i,n) cin >> v[i+1];\n\n rep(i,q) {\n ll x;\n cin >> x;\n int r = 2;\n ll sum = v[1], ans = 0;\n for(int l = 1; l <= n; l++) {\n sum -= v[l-1];\n while(r <= n && sum+v[r] <= x) {\n sum += v[r];\n r++;\n }\n if(sum <= x) ans += r-l;\n if(r == l-1) r++;\n }\n cout << ans << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 3516, "score_of_the_acc": -0.7857, "final_rank": 14 }, { "submission_id": "aoj_DSL_3_C_10994267", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\nint main() {\n int n,q; cin >> n >> q;\n vll a(n);\n rep(i,n)cin>>a[i];\n vll s(n+1);\n rep(i,n)s[i+1]=s[i]+a[i];\n rep(re,q){\n ll x; cin >> x;\n ll ans=0;\n int r=0;\n rep(l,n+1){\n while(r<n+1&&s[r]-s[l]<=x)r++;\n ans+=r-l-1;\n if(l==r)r++;\n }\n cout << ans << \"\\n\";\n }\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 4652, "score_of_the_acc": -1.1226, "final_rank": 16 }, { "submission_id": "aoj_DSL_3_C_10993097", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main() {\n\tll n, q;\n\tcin >> n >> q;\n\tvector<ll>a(n);\n\tfor (ll i = 0; i < n; i++)cin >> a[i];\n\t//solve\n\tvector<ll> ans;\n\n\twhile (q--) {\n\t\tll x;\n\t\tcin >> x;\n\t\tll right = 0;\n\t\tll sum = 0;\n\t\tll cnt = 0;\n\t\tll before = 0;\n\t\tfor (ll i = 0; i < n; i++) {\n\t\t\tsum -= before;\n\t\t\tfor (int j = right; j < n; j++) {\n\t\t\t\tsum += a[j];\n\t\t\t\tif (sum > x) {\n\t\t\t\t\tsum -= a[j];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tright++;\n\t\t\t}\n\t\t\t cnt += right - i;\n\t\t\t before = a[i];\n\t\t}\n\t\tans.push_back(cnt);\n\t}\n\tfor (ll x : ans)cout << x << '\\n';\n\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 3904, "score_of_the_acc": -0.69, "final_rank": 10 }, { "submission_id": "aoj_DSL_3_C_10967991", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef pair<int, int> pii;\ntypedef pair<double, double> pdd;\ntypedef pair<ll, ll> pll;\ntypedef vector<pii> vpi;\ntypedef vector<pll> vpl;\ntypedef double dl;\n\n#define PB push_back\n#define F first\n#define S second\n#define MP make_pair\n#define endl '\\n'\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define sz(x) (ll) x.size()\n#define mid(l, r) ((r + l) / 2)\n#define left(node) (node * 2)\n#define right(node) (node * 2 + 1)\n#define mx_int_prime 999999937\n\nconst double PI = acos(-1);\nconst double eps = 1e-9;\nconst int infi = 2000000000;\nconst ll infLL = 9000000000000000000;\n#define MOD 1000000007\n\n#define mem(a, b) memset(a, b, sizeof(a))\n#define gcd(a, b) __gcd(a, b)\n#define sqr(a) ((a) * (a))\n\nvoid solve()\n{\n ll N, Q;\n cin >> N >> Q;\n\n vl v(N);\n for (ll i = 0; i < N; i++)\n {\n cin >> v[i];\n }\n\n vl que(Q);\n for (ll i = 0; i < Q; i++)\n {\n cin >> que[i];\n }\n\n for (auto q : que)\n {\n\n ll l = 0, r = 0;\n ll sum = v[0];\n ll ans = 0;\n\n while (r < N)\n {\n\n while (sum > q)\n {\n sum -= v[l];\n if (v[l] > q)\n {\n r++;\n if (r < N)\n {\n sum += v[r];\n }\n }\n l++;\n }\n \n if (r < N)\n {\n ans += (r - l) + 1;\n }\n\n r++;\n if (r < N)\n {\n sum += v[r];\n }\n }\n cout << ans << endl;\n }\n}\n\nint main()\n{\n // ll t;\n // cin>>t;\n // while(t--){\n solve();\n // }\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 3872, "score_of_the_acc": -0.5256, "final_rank": 6 }, { "submission_id": "aoj_DSL_3_C_10946498", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing int64 = long long;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int N, Q;\n cin >> N >> Q;\n vector<int64> a(N);\n for (int i = 0; i < N; ++i) cin >> a[i];\n\n while (Q--) {\n int64 x;\n cin >> x;\n int64 ans = 0, sum = 0;\n int l = 0;\n for (int r = 0; r < N; ++r) {\n sum += a[r];\n while (l <= r && sum > x) sum -= a[l++];\n ans += (r - l + 1);\n }\n cout << ans << '\\n';\n }\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 3820, "score_of_the_acc": -0.2763, "final_rank": 2 }, { "submission_id": "aoj_DSL_3_C_10934282", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\n#define endl '\\n'\n#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n#define fraction(a) cout.unsetf(ios::floatfield); cout.precision(a); cout.setf(ios::fixed,ios::floatfield);\n#define file() freopen(\"input.txt\",\"r\",stdin);freopen(\"output.txt\",\"w\",stdout);\nconst double PI = acos(-1);\nconst int MOD = 1e9+7;\nconst double eps = 1e-9;\ntemplate < typename F, typename S >\nostream& operator << ( ostream& os, const pair< F, S > & p ) {\n return os << \"(\" << p.first << \", \" << p.second << \")\";\n}\ntemplate < typename T >\nostream &operator << ( ostream & os, const vector< T > &v ) {\n os << \"{\";\n for(auto it = v.begin(); it != v.end(); ++it) {\n if( it != v.begin() ) os << \", \";\n os << *it;\n }\n return os << \"}\";\n}\ntemplate < typename T >\nostream &operator << ( ostream & os, const set< T > &v ) {\n os << \"[\";\n for(auto it = v.begin(); it != v.end(); ++it) {\n if( it != v.begin() ) os << \", \";\n os << *it;\n }\n return os << \"]\";\n}\ntemplate < typename T >\nostream &operator << ( ostream & os, const multiset< T > &v ) {\n os << \"[\";\n for(auto it = v.begin(); it != v.end(); ++it) {\n if( it != v.begin() ) os << \", \";\n os << *it;\n }\n return os << \"]\";\n}\ntemplate < typename F, typename S >\nostream &operator << ( ostream & os, const map< F, S > &v ) {\n os << \"[\";\n for(auto it = v.begin(); it != v.end(); ++it) {\n if( it != v.begin() ) os << \", \";\n os << it->first << \" = \" << it->second;\n }\n return os << \"]\";\n}\n#define dbg(args...) do {cerr << #args << \" : \"; faltu(args); } while(0)\nvoid faltu () {\n cerr << endl;\n}\ntemplate <typename T>\nvoid faltu( T a[], int n ) {\n for(int i = 0; i < n; ++i) cerr << a[i] << ' ';\n cerr << endl;\n}\ntemplate <typename T, typename ... hello>\nvoid faltu( T arg, const hello &... rest) {\n cerr << arg << ' ';\n faltu(rest...);\n}\nbool cmp(const pair<int,int>&p1, const pair<int,int>&p2) {\n if(p1.first<p2.first) return 1;\n if(p1.first==p2.first) return p1.second>p2.second;\n return 0;\n}\nvector<bool> prime (int n) {\n vector<bool> isPrime(n+1,true);\n isPrime[0]=isPrime[1]=false;\n for(int i=2; i*i<=n; i++) {\n if(isPrime[i]) {\n for(int j=i*i; j<=n; j+=i) isPrime[j]=false;\n }\n }\n return isPrime;\n}\nvoid solve()\n{ \n int n, k;\n cin >> n >> k;\n vector <int> v(n);\n for(auto &a:v) cin >> a;\n while(k--)\n {\n int x;\n cin >> x;\n int r = 0, l=0, sum=0, ans=0;\n while(r<n)\n {\n sum+=v[r];\n while(sum>x)\n {\n sum-=v[l];\n ++l;\n }\n ans+=r-l+1;\n ++r;\n }\n cout << ans << endl;\n }\n}\nint32_t main()\n{\n optimize();\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 3876, "score_of_the_acc": -0.3854, "final_rank": 5 }, { "submission_id": "aoj_DSL_3_C_10933298", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint main(void) {\n int N, Q;\n scanf(\"%d %d\", &N, &Q);\n vector<int> a(N);\n rep(i,N) scanf(\"%d\", &a[i]);\n \n while(Q--) {\n ll x;\n scanf(\"%lld\", &x);\n \n int now = 0;\n ll nsum = 0, ans = 0;\n rep(i,N) {\n if(i != 0) nsum -= a[i - 1];\n \n while(now < N and nsum + a[now] <= x) {\n nsum += a[now];\n ++now;\n }\n \n ans += (now - i);\n }\n \n printf(\"%lld\\n\", ans);\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 3660, "score_of_the_acc": -0.3113, "final_rank": 3 }, { "submission_id": "aoj_DSL_3_C_10933268", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint a[100000];\n\nint main(void) {\n int N, Q;\n scanf(\"%d %d\", &N, &Q);\n rep(i,N) scanf(\"%d\", &a[i]);\n \n vector<ll> S(N + 1);\n rep(i,N) S[i + 1] = S[i] + a[i];\n \n while(Q--) {\n ll x;\n scanf(\"%lld\", &x);\n \n int now = upper_bound(S.begin(), S.end(), x) - S.begin() - 1;\n ll ans = now;\n \n for(int i = 1; i < N; ++i) {\n while(now < N and S[now + 1] - S[i] <= x) ++now;\n ans += (now - i);\n }\n \n printf(\"%lld\\n\", ans);\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 4356, "score_of_the_acc": -0.7803, "final_rank": 13 }, { "submission_id": "aoj_DSL_3_C_10933266", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint main(void) {\n int N, Q;\n scanf(\"%d %d\", &N, &Q);\n vector<int> a(N);\n rep(i,N) scanf(\"%d\", &a[i]);\n \n vector<ll> S(N + 1);\n rep(i,N) S[i + 1] = S[i] + a[i];\n \n while(Q--) {\n ll x;\n scanf(\"%lld\", &x);\n \n int now = upper_bound(S.begin(), S.end(), x) - S.begin() - 1;\n ll ans = now;\n \n for(int i = 1; i < N; ++i) {\n while(now < N and S[now + 1] - S[i] <= x) ++now;\n ans += (now - i);\n }\n \n printf(\"%lld\\n\", ans);\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 4452, "score_of_the_acc": -0.7022, "final_rank": 11 }, { "submission_id": "aoj_DSL_3_C_10933264", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int N, Q;\n scanf(\"%d %d\", &N, &Q);\n vector<int> a(N);\n rep(i,N) scanf(\"%d\", &a[i]);\n \n vector<ll> S(N + 1);\n rep(i,N) S[i + 1] = S[i] + a[i];\n \n while(Q--) {\n ll x;\n scanf(\"%lld\", &x);\n \n int now = upper_bound(S.begin(), S.end(), x) - S.begin() - 1;\n ll ans = now;\n \n for(int i = 1; i < N; ++i) {\n while(now < N and S[now + 1] - S[i] <= x) ++now;\n ans += (now - i);\n }\n \n printf(\"%lld\\n\", ans);\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 4424, "score_of_the_acc": -0.7547, "final_rank": 12 }, { "submission_id": "aoj_DSL_3_C_10933235", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\ntypedef long long ll;\n\nint N, Q;\nint a[100000];\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n cin >> N >> Q;\n rep(i,N) cin >> a[i];\n \n vector<ll> S(N + 1, 0);\n rep(i,N) S[i + 1] = S[i] + a[i];\n \n while(Q--) {\n ll x;\n cin >> x;\n \n int now = upper_bound(S.begin(), S.end(), x) - S.begin() - 1;\n ll ans = now;\n \n for(int i = 1; i < N; ++i) {\n while(now < N and S[now + 1] - S[i] <= x) ++now;\n ans += (now - i);\n }\n \n cout << ans << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 4288, "score_of_the_acc": -0.5916, "final_rank": 7 }, { "submission_id": "aoj_DSL_3_C_10933212", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int N, Q;\n cin >> N >> Q;\n vector<int> a(N);\n rep(i,N) cin >> a[i];\n \n vector<ll> S(N + 1, 0);\n rep(i,N) S[i + 1] = S[i] + a[i];\n \n while(Q--) {\n ll x;\n cin >> x;\n \n int now = upper_bound(S.begin(), S.end(), x) - S.begin() - 1;\n ll ans = now;\n \n for(int i = 1; i < N; ++i) {\n while(now < N and S[now + 1] - S[i] <= x) ++now;\n ans += (now - i);\n }\n \n cout << ans << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 4404, "score_of_the_acc": -0.8127, "final_rank": 15 }, { "submission_id": "aoj_DSL_3_C_10926367", "code_snippet": "#include<bits/stdc++.h>\n//#include<atcoder/all>\nusing namespace std;\n//using namespace atcoder;\n#define pb push_back\n#define rep(i,n) for(ll i=0;i<n;++i)\n#define rrep(i,n) for(ll i=n-1;i>=0;--i)\n#define yesno(flg) if(flg){cout<<\"YES\"<<endl;}else{cout<<\"NO\"<<endl;}\n#define print(a) cout<<a<<endl\ntypedef long long ll;\ntypedef pair<ll, ll> P1;\ntypedef pair<pair<ll,ll>,ll > Pl;\nconst ll INF=1LL<<30;\n\n#define ALL(a) (a).begin(),(a).end()\n#define vi vector<int>\n#define vl vector<ll>\n#define so(a) sort(a.begin(),a.end())\nstruct edge\n{\n\tint to, cost;\n};\nstruct pos{\n\t// 1 変数を入れる;\n\tll r;\n\n};\nvoid chmin(int &a, int b) {\n\tif (a > b) {\n\t\ta = b;\n\t}\n}\ntemplate<class T> inline bool chmax(T& a, T b) {\n\tif (a < b) {\n\t\ta = b; return true;\n\t} return false;\n\n}\n\ntemplate <typename Tu>\nstatic inline constexpr bool is_multiplication_safe(Tu a, Tu b)\n{\n\treturn !a || b <= std::numeric_limits<Tu>::max() / a;\n}\nusing pint=pair<int,int>;\n//gcd=最大公約数\nll dp[100001][8];\nint mod=1e9;\nint solve(int n,string s){\n\tvector<int> mx(2),cnt(2);\n\tfor(int i=0; i<n;){\n\t\tint r=i+1;\n\t\twhile(r<n && s[i]==s[r]){\n\t\t\tr++;\n\t\t}\n\t\tint len=r-i;\n\t\tint c=s[i]-'0';\n\t\tmx[c]=max(mx[c],len);\n\t\tcnt[c]+=len;\n\t\ti=r;\n\t}\n\tint ans=2*n;\n\tfor(int i=0; i<2; i++){\n\t\tans=min(ans,(cnt[i]-mx[i])*2+(n-cnt[i]));\n\t}\n\treturn ans;\n}\n//図書館メモ 哲学 経営学\nint main(){\n\tll n,q;\n\tcin>>n>>q;\n\tll a[n+1],b[n+1];\n\n\tll x[q];\n\tfor(int i=1; i<=n; i++){\n\t\tcin>>a[i];\n\t}\n\tb[0]=0;\n\tfor(int i=1; i<=n; i++){\n\t\tb[i]=b[i-1]+a[i];\n\t}\n\tint min=0;\n\tfor(int i=0; i<q; i++){\n\t\tcin>>x[i];\n\t\tll ans=0;\n\t\tint max=1;\n\t\tmin=0;\n\n\t\t\twhile(max<=n){\n\t\t\t\tif(b[max]-b[min]<=x[i]){\n\t\t\t\t\tans+=max-min;\n\n\t\t\t\t\tmax++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tmin++;\n\t\t\t}\n\t\tprint(ans);\n\t}\n\n\n\n\n\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 5000, "score_of_the_acc": -1.2143, "final_rank": 17 }, { "submission_id": "aoj_DSL_3_C_10903412", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n, q;\n cin >> n >> q;\n\n vector<int> v(n);\n for (auto &x : v) cin >> x;\n\n while (q--) {\n long long x, currSum = 0, ans = 0;\n cin >> x;\n\n queue<int> q;\n\n for (int i = 0; i < n; i++) {\n currSum += v[i];\n q.push(v[i]);\n\n while (currSum > x) {\n currSum -= q.front();\n q.pop();\n }\n ans += (long long)q.size();\n }\n\n cout << ans << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 4040, "score_of_the_acc": -1.3531, "final_rank": 19 }, { "submission_id": "aoj_DSL_3_C_10857827", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nusing ll=long long;\nusing ld=long double;\nusing pl=pair<ll,ll>;\nusing vpl=vector<pl>;\nusing vl=vector<ll>;\nusing vvl=vector<vl>;\n\n#define rep(i,n) for(long long i=0LL;i<n;i++)\n#define rrep(i,a,b) for(long long i=a;i>=b;i--)\n#define FOR(i,k,n) for(long long i=k;i<n;i++)\n#define ALL(v) v.begin(),v.end()\ntemplate<typename T>ostream&operator<<(ostream& os,vector<T>&v){for(int i = 0;i < int(size(v));i++)os << v[i] << (i+1==int(size(v))?\"\":\" \");return os;}\ntemplate<typename T>istream&operator>>(istream& is,vector<T>&v){for(auto &in : v)is >> in;return is;}\nll INF = (1ll << 60) - 6846976;\n/* INF = (1ll << 60) - 6846976*/\n\n\n// #include<atcoder/all> \n// using namespace atcoder;\n// using mint = modint998244353;ll mod = 998244353;\n// //using mint = modint1000000007;ll mod = 1000000007;\n// //using mint = modint;\n// using vm = vector<mint>;\n// using vvm = vector<vm>;\n// ostream&operator<<(ostream& os,vector<mint>&v){for(int i = 0;i < int(size(v));i++)os << v[i].val() << (i+1==int(size(v))?\"\":\" \");return os;}\n\n\nvl dx = {1,0,-1,0}, dy = {0,1,0,-1};\n//----------------------------------------------\n\n\n\n\n\n\n\nint main(){\n ios::sync_with_stdio(false);cin.tie(nullptr);cout<<fixed<<setprecision(15);\n//==============================================\n ll N,Q;\n cin>>N>>Q;\n vl A(N);\n cin>>A;\n rep(qi,Q){\n ll X; cin>>X;\n ll ans = 0;\n ll right = 0;\n ll now = 0;\n rep(left,N){\n while(right+1<=N && now+A[right] <= X){\n now += A[right];\n right++;\n }\n ans += right-left;\n if(right==left) right++;\n else now -= A[left];\n }\n cout << ans << endl;\n\n\n\n }\n\n\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 3868, "score_of_the_acc": -0.3801, "final_rank": 4 } ]
aoj_DSL_4_A_cpp
Union of Rectangles Given a set of $N$ axis-aligned rectangles in the plane, find the area of regions which are covered by at least one rectangle. Input The input is given in the following format. $N$ $x1_1$ $y1_1$ $x2_1$ $y2_1$ $x1_2$ $y1_2$ $x2_2$ $y2_2$ : $x1_N$ $y1_N$ $x2_N$ $y2_N$ ($x1_i, y1_i$) and ($x2_i, y2_i$) are the coordinates of the top-left corner and the bottom-right corner of the $i$-th rectangle respectively. Constraints $ 1 \leq N \leq 2000 $ $ −10^9 \leq x1_i < x2_i\leq 10^9 $ $ −10^9 \leq y1_i < y2_i\leq 10^9 $ Output Print the area of the regions. Sample Input 1 2 0 0 3 4 1 2 4 3 Sample Output 1 13 Sample Input 2 3 1 1 2 5 2 1 5 2 1 2 2 5 Sample Output 2 7 Sample Input 3 4 0 0 3 1 0 0 1 3 0 2 3 3 2 0 3 3 Sample Output 3 8
[ { "submission_id": "aoj_DSL_4_A_11064592", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < n; ++i)\n\nint main() {\n int N;\n cin >> N;\n vector<int> X1, X2, Y1, Y2, X, Y;\n rep(i, N) {\n int x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n X1.push_back(x1);\n X2.push_back(x2);\n Y1.push_back(y1);\n Y2.push_back(y2);\n X.push_back(x1);\n X.push_back(x2);\n Y.push_back(y1);\n Y.push_back(y2);\n }\n\n // 座標圧縮\n auto X_uni = X, Y_uni = Y;\n sort(X_uni.begin(), X_uni.end());\n sort(Y_uni.begin(), Y_uni.end());\n X_uni.erase(unique(X_uni.begin(), X_uni.end()), X_uni.end());\n Y_uni.erase(unique(Y_uni.begin(), Y_uni.end()), Y_uni.end());\n\n vector<int> X1_id(N), X2_id(N), Y1_id(N), Y2_id(N);\n rep(i, N) {\n auto id_x1 = lower_bound(X_uni.begin(), X_uni.end(), X1[i]);\n auto id_x2 = lower_bound(X_uni.begin(), X_uni.end(), X2[i]);\n auto id_y1 = lower_bound(Y_uni.begin(), Y_uni.end(), Y1[i]);\n auto id_y2 = lower_bound(Y_uni.begin(), Y_uni.end(), Y2[i]);\n X1_id[i] = id_x1 - X_uni.begin();\n X2_id[i] = id_x2 - X_uni.begin();\n Y1_id[i] = id_y1 - Y_uni.begin();\n Y2_id[i] = id_y2 - Y_uni.begin();\n }\n\n int R = X_uni.size(), C = Y_uni.size();\n // imos法で埋めていく\n vector<vector<int>> S(R, vector<int>(C, 0));\n rep(i, N) {\n int x1 = X1_id[i], x2 = X2_id[i], y1 = Y1_id[i], y2 = Y2_id[i];\n S[x1][y1]++;\n S[x1][y2]--;\n S[x2][y1]--;\n S[x2][y2]++;\n }\n\n rep(i, R) rep(j, C - 1) S[i][j + 1] += S[i][j];\n rep(i, R - 1) rep(j, C) S[i + 1][j] += S[i][j];\n\n ll res = 0;\n rep(i, R - 1) {\n rep(j, C - 1) {\n ll cur_area =\n (ll)(X_uni[i + 1] - X_uni[i]) * (Y_uni[j + 1] - Y_uni[j]);\n if (S[i][j]) res += cur_area;\n }\n }\n\n cout << res << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 65844, "score_of_the_acc": -0.3051, "final_rank": 3 }, { "submission_id": "aoj_DSL_4_A_11050529", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> \ninline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> \ninline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> \npair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> \nvector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> \nvector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> \nstruct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> \nstd::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> \nstd::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> \nT pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> \nT fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> \nT perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> \nT comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> \nvoid fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> \nvoid fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> \nvector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> \nvector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> \nvector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\ntemplate<typename T> \nvector<T> compress(vector<T> &A) {\n vector<T> vals = A;\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n\n for(int i = 0; i < (int)A.size(); i++) {\n A[i] = lower_bound(vals.begin(), vals.end(), A[i]) - vals.begin();\n }\n return vals;\n}\ntemplate<typename T>\nvector<T> compress2(vector<T> &A1, vector<T> &A2) {\n vector<T> vals;\n int N = A1.size();\n for(int i = 0; i < N; i++) {\n for(T d = 0; d <= 1; d++) {\n T a1 = A1[i] + d;\n T a2 = A2[i] + d;\n vals.push_back(a1);\n vals.push_back(a2);\n }\n }\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n \n for(int i = 0; i < N; i++) {\n A1[i] = lower_bound(vals.begin(), vals.end(), A1[i]) - vals.begin();\n A2[i] = lower_bound(vals.begin(), vals.end(), A2[i]) - vals.begin();\n }\n return vals;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//最小全域木\nll Kruskal(const WeightedGraph &G) {\n int N = G.size();\n return 0;\n}\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n, sz;\n vector<long long> node;\n function<ll(ll, ll)> op = [](ll a, ll b) {return max(a,b);}; //セグ木上の積\n ll e = 0; //セグ木上の積の単位元\n\n SegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, e);\n }\n SegTree(vector<long long> a) {\n sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, e);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = op(node[2*i+1], node[2*i+2]);\n }\n\n //a_iを取得\n long long get(int i) {\n return node[n-1+i];\n }\n //[a,b)における積\n long long prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return e;\n if(a <= l and r <= b) return node[k];\n long long vl = prod(a, b, 2*k+1, l, (l+r)/2);\n long long vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return op(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = op(node[2*i+1], node[2*i+2]);\n }\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n const ll ex = 0, //セグ木上の積の単位元\n em = 0; //遅延評価木上の積の単位元\n function<ll(ll, ll)> fx = [](ll x, ll y) {return x+y;}, //セグ木上の積\n fa = [](ll x, ll a) {return x+a;}, //遅延評価木からセグ木への作用\n fm = [](ll a, ll b) {return a+b;}, //遅延評価木上の積\n fp = [](ll a, ll n) {return a*n;}; //区間長の作用への影響\n\n LazySegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n }\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = fx(node[2*i+1], node[2*i+2]);\n }\n\n void eval(int k, int len) {\n if(lazy[k] == em) return;\n\n node[k] = fa(node[k], fp(lazy[k], len));\n if(k < n-1) {\n lazy[2*k+1] = fm(lazy[2*k+1], lazy[k]);\n lazy[2*k+2] = fm(lazy[2*k+2], lazy[k]);\n }\n lazy[k] = em;\n }\n //区間[a,b)を値xに更新\n void update(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] = fm(lazy[k], x);\n eval(k, r - l);\n }else {\n update(a, b, x, 2*k+1, l, (l+r)/2);\n update(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = fx(node[2*k+1], node[2*k+2]);\n }\n }\n //区間[a,b)の積を取得\n ll prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return ex;\n if(a <= l and r <= b) return node[k];\n \n ll vl = prod(a, b, 2*k+1, l, (l+r)/2);\n ll vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return fx(vl, vr);\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//平方分割\nstruct Backet {\n vector<ll> array;\n vector<ll> backet;\n int N, M;\n\n Backet(vector<ll> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n void add(int i, ll x) {\n array[i] += x;\n backet[i/M] += x;\n }\n //区間[i,j)の和\n ll getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n ll s = 0;\n if(l > r) {\n rep(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n rep(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n//最小共通祖先\nstruct LCA {\n Graph G;\n int N, LOG_N;\n vector<int> depth;\n vector<vector<int>> par;\n\n function<void(int)> dfs = [&](int v) {\n for(auto next_v : G[v]) {\n if(depth[next_v] != inf) continue;\n depth[next_v] = depth[v] + 1;\n par[0][next_v] = v;\n dfs(next_v);\n }\n return;\n };\n\n LCA(Graph &g) {\n G = g;\n N = G.size();\n depth.resize(N, inf);\n depth[0] = 0;\n LOG_N = 0;\n while((1<<LOG_N) < N) LOG_N++;\n par.resize(LOG_N+1, vector<int>(N));\n dfs(0);\n rep(i,1,LOG_N) {\n rep(j,0,N) {\n if(par[i-1][j] == -1) par[i][j] = -1;\n else par[i][j] = par[i-1][par[i-1][j]];\n }\n }\n }\n\n int ancestor(int u, int k) {\n int g = 0;\n while(k > 0) {\n if(k % 2 == 1) u = par[g][u];\n k /= 2;\n g++;\n }\n return u;\n }\n\n int lca(int u, int v) {\n int d1 = depth[u], d2 = depth[v];\n if(d1 < d2) v = ancestor(v, d2-d1);\n if(d1 > d2) u = ancestor(u, d1-d2);\n\n if(u == v) return u;\n for(int k = LOG_N; k >= 0; k--) {\n if(par[k][u] != par[k][v]) {\n u = par[k][u];\n v = par[k][v];\n }\n }\n return par[0][u];\n }\n\n int dist(int u, int v) {\n return depth[u] + depth[v] - 2*depth[lca(u, v)];\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N; cin >> N;\n vll X1(N), Y1(N), X2(N), Y2(N);\n rep(i,0,N) {\n cin >> X1[i] >> Y1[i] >> X2[i] >> Y2[i];\n }\n auto x = compress2(X1, X2);\n auto y = compress2(Y1, Y2);\n int H = x.size(), W = y.size();\n \n vvi S(H, vi(W, 0));\n rep(i,0,N) {\n S[X1[i]][Y1[i]]++;\n S[X2[i]][Y2[i]]++;\n S[X1[i]][Y2[i]]--;\n S[X2[i]][Y1[i]]--;\n }\n \n rep(i,1,H) rep(j,0,W) S[i][j] += S[i-1][j];\n rep(i,0,H) rep(j,1,W) S[i][j] += S[i][j-1];\n ll ans = 0;\n rep(i,0,H) rep(j,0,W) {\n if(S[i][j] > 0) {\n ans += (x[i+1] - x[i])*(y[j+1] - y[j]);\n }\n }\n cout << ans << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 253560, "score_of_the_acc": -1.4135, "final_rank": 13 }, { "submission_id": "aoj_DSL_4_A_10994377", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* compress\n X を座圧して書き換える\n 返り値: val(val[i]=座圧後のiの元の値)\n 計算量: O(n log n)\n*/\ntemplate <typename T>\nvc<T> compress(vector<T> &X) {\n vc<T> vals = X;\n sort(all(vals));\n vals.erase(unique(all(vals)), vals.en);\n for(auto &xi: X) xi = lower_bound(all(vals), xi) - vals.bg;\n return vals;\n}\n\nint main() {\n int n; cin >> n;\n vi x1s(n),y1s(n),x2s(n),y2s(n),xs,ys;\n rep(i,n){\n cin >> x1s[i] >> y1s[i] >> x2s[i] >> y2s[i];\n xs.pb(x1s[i]);\n xs.pb(x2s[i]);\n ys.pb(y1s[i]);\n ys.pb(y2s[i]);\n }\n vi orix=compress(xs), oriy=compress(ys);\n for(auto &xi: x1s) xi = lower_bound(all(orix), xi) - orix.bg;\n for(auto &xi: x2s) xi = lower_bound(all(orix), xi) - orix.bg;\n for(auto &yi: y1s) yi = lower_bound(all(oriy), yi) - oriy.bg;\n for(auto &yi: y2s) yi = lower_bound(all(oriy), yi) - oriy.bg;\n int H=sz(orix),W=sz(oriy);\n vvll grid(H,vll(W));\n rep(i,n){\n int x1=x1s[i],y1=y1s[i],x2=x2s[i],y2=y2s[i];\n grid[x1][y1]++;\n grid[x2][y1]--;\n grid[x1][y2]--;\n grid[x2][y2]++;\n }\n rep(i,H)rep(j,W-1) grid[i][j+1]+=grid[i][j];\n rep(i,H-1)rep(j,W) grid[i+1][j]+=grid[i][j];\n ll ans=0;\n rep(i,H-1)rep(j,W-1)if(grid[i][j])ans+=(ll)(orix[i+1]-orix[i])*(oriy[j+1]-oriy[j]);\n cout << ans << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 128352, "score_of_the_acc": -0.6114, "final_rank": 6 }, { "submission_id": "aoj_DSL_4_A_10934298", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint N;\nint A[2000], B[2000], C[2000], D[2000];\nint S[4000][4000];\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n cin >> N;\n rep(i,N) cin >> A[i] >> C[i] >> B[i] >> D[i];\n \n vector<ll> X(2 * N), Y(2 * N);\n rep(i,N) X[i] = A[i], X[i + N] = B[i], Y[i] = C[i], Y[i + N] = D[i];\n sort(X.begin(), X.end());\n X.erase(unique(X.begin(), X.end()), X.end());\n sort(Y.begin(), Y.end());\n Y.erase(unique(Y.begin(), Y.end()), Y.end());\n \n int Xs = X.size(), Ys = Y.size();\n rep(i,N) {\n int Ax = lower_bound(X.begin(), X.end(), A[i]) - X.begin(), Bx = lower_bound(X.begin(), X.end(), B[i]) - X.begin();\n int Cy = lower_bound(Y.begin(), Y.end(), C[i]) - Y.begin(), Dy = lower_bound(Y.begin(), Y.end(), D[i]) - Y.begin();\n ++S[Ax][Cy], --S[Bx][Cy], --S[Ax][Dy], ++S[Bx][Dy];\n }\n \n rep(i,Xs) rep(j,Ys - 1) S[i][j + 1] += S[i][j];\n rep(i,Xs - 1) rep(j,Ys) S[i + 1][j] += S[i][j];\n \n ll ans = 0;\n rep(i,Xs - 1) rep(j,Ys - 1) if(S[i][j] >= 1) ans += (X[i + 1] - X[i]) * (Y[j + 1] - Y[j]);\n \n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 65952, "score_of_the_acc": -0.2678, "final_rank": 2 }, { "submission_id": "aoj_DSL_4_A_10934284", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint main(void) {\n int N;\n cin >> N;\n \n vector<int> A(N), B(N), C(N), D(N);\n rep(i,N) cin >> A[i] >> C[i] >> B[i] >> D[i];\n \n vector<ll> X(2 * N), Y(2 * N);\n rep(i,N) X[i] = A[i], X[i + N] = B[i], Y[i] = C[i], Y[i + N] = D[i];\n sort(X.begin(), X.end());\n X.erase(unique(X.begin(), X.end()), X.end());\n sort(Y.begin(), Y.end());\n Y.erase(unique(Y.begin(), Y.end()), Y.end());\n \n int Xs = X.size(), Ys = Y.size();\n vector<vector<int>> S(Xs, vector<int>(Ys, 0));\n rep(i,N) {\n int Ax = lower_bound(X.begin(), X.end(), A[i]) - X.begin(), Bx = lower_bound(X.begin(), X.end(), B[i]) - X.begin();\n int Cy = lower_bound(Y.begin(), Y.end(), C[i]) - Y.begin(), Dy = lower_bound(Y.begin(), Y.end(), D[i]) - Y.begin();\n ++S[Ax][Cy], --S[Bx][Cy], --S[Ax][Dy], ++S[Bx][Dy];\n }\n \n rep(i,Xs) rep(j,Ys - 1) S[i][j + 1] += S[i][j];\n rep(i,Xs - 1) rep(j,Ys) S[i + 1][j] += S[i][j];\n \n ll ans = 0;\n rep(i,Xs - 1) rep(j,Ys - 1) if(S[i][j] >= 1) ans += (X[i + 1] - X[i]) * (Y[j + 1] - Y[j]);\n \n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 65880, "score_of_the_acc": -0.3052, "final_rank": 4 }, { "submission_id": "aoj_DSL_4_A_10913572", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\nint main(){\n\tint N;\n\tcin >> N;\n\tvector<vector<long long>> lef(N, vector<long long>(2)), rig(lef);\n\tvector<long long> tmp;\n\tfor(int i = 0; i < N; i++){\n\t\tcin >> lef[i][0] >> lef[i][1];\n\t\tcin >> rig[i][0] >> rig[i][1];\n\t\tfor(int j = 0; j < 2; j++){\n\t\t\ttmp.push_back(lef[i][j]);\n\t\t\ttmp.push_back(rig[i][j]);\n\t\t}\n\t}\n\tsort(tmp.begin(), tmp.end());\n\ttmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());\n\t\n\tvector<vector<int>> grid(tmp.size(), vector<int>(tmp.size(), 0));\n\tfor(int i = 0, a, b, c, d; i < N; i++){\n\t\ta = lower_bound(tmp.begin(), tmp.end(), lef[i][0]) - tmp.begin();\n\t\tb = lower_bound(tmp.begin(), tmp.end(), lef[i][1]) - tmp.begin();\n\t\tc = lower_bound(tmp.begin(), tmp.end(), rig[i][0]) - tmp.begin();\n\t\td = lower_bound(tmp.begin(), tmp.end(), rig[i][1]) - tmp.begin();\n\t\tgrid[a][b]++;\n\t\tgrid[a][d]--;\n\t\tgrid[c][b]--;\n\t\tgrid[c][d]++;\n\t}\n\tfor(int i = 0, s = tmp.size(); i < s; i++)\n\t\tfor(int j = 1; j < s; j++) grid[i][j] += grid[i][j - 1];\n\tfor(int i = 0, s = tmp.size(); i < s; i++)\n\t\tfor(int j = 1; j < s; j++) grid[j][i] += grid[j - 1][i];\n\t\n\tlong long ans = 0;\n\tfor(int i = 0, s = tmp.size(); i < s - 1; i++){\n\t\tfor(int j = 0; j < s - 1;){\n\t\t\tif(grid[i][j] > 0){\n\t\t\t\tint n = j;\n\t\t\t\twhile(grid[i][++j] > 0);\n\t\t\t\tans += (tmp[j] - tmp[n]) * (tmp[i + 1] - tmp[i]);\n\t\t\t}else j++;\n\t\t}\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 410, "memory_kb": 253952, "score_of_the_acc": -1.7547, "final_rank": 17 }, { "submission_id": "aoj_DSL_4_A_10878987", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing LL = long long;\n\nint main() {\n int N; cin >> N;\n vector<int> X(2 * N), Y(2 * N);\n set<int> setX, setY;\n for (int i = 0; i < 2 * N; i+= 2) {\n cin >> X[i] >> Y[i] >> X[i + 1] >> Y[i + 1];\n setX.insert(X[i]); setX.insert(X[i + 1]); setY.insert(Y[i]); setY.insert(Y[i + 1]);\n }\n\n vector<int> uX(setX.begin(), setX.end());\n vector<int> uY(setY.begin(), setY.end());\n sort(uX.begin(), uX.end());\n sort(uY.begin(), uY.end());\n\n int W = uX.size();\n int H = uY.size();\n vector<vector<int>> imos(H, vector<int>(W,0)); //imos[i][j] = uY[i]からuY[i + 1], uX[i]からuX[i + 1]の長方形ブロックについて\n for (int i = 0; i < N; ++i) {\n int c1 = lower_bound(uX.begin(), uX.end(), X[2 * i]) - uX.begin();\n int c2 = lower_bound(uX.begin(), uX.end(), X[2 * i + 1]) - uX.begin();\n int r1 = lower_bound(uY.begin(), uY.end(), Y[2 * i]) - uY.begin();\n int r2 = lower_bound(uY.begin(), uY.end(), Y[2 * i + 1]) - uY.begin();\n imos[r1][c1]++;\n imos[r1][c2]--;\n imos[r2][c1]--;\n imos[r2][c2]++;\n }\n\n for (int i = 0; i < H; ++i) {\n for (int j = 1; j < W; ++j) {\n imos[i][j] += imos[i][j-1];\n }\n }\n for (int j = 0; j < W; ++j) {\n for (int i = 1; i < H; ++i) {\n imos[i][j] += imos[i - 1][j];\n }\n }\n LL total_area = 0;\n for (int i = 0; i < H-1; ++i) {\n for (int j = 0; j < W-1; ++j) {\n if (imos[i][j] > 0) {\n LL width = uX[j + 1] - uX[j];\n LL height = uY[i + 1] - uY[i];\n total_area += width * height;\n }\n }\n }\n\n cout << total_area << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 66072, "score_of_the_acc": -0.4758, "final_rank": 5 }, { "submission_id": "aoj_DSL_4_A_10874706", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nint main(){\n ll N; cin>>N;\n vector<ll> X1(N),Y1(N),X2(N),Y2(N);\n for(int i=0;i<N;i++) cin>>X1[i]>>Y1[i]>>X2[i]>>Y2[i];\n\n vector<ll> Xatsu,Yatsu;\n for(int i=0;i<N;i++){\n Xatsu.push_back(X1[i]);\n Yatsu.push_back(Y1[i]);\n Xatsu.push_back(X2[i]);\n Yatsu.push_back(Y2[i]);\n }\n sort(Xatsu.begin(),Xatsu.end());\n sort(Yatsu.begin(),Yatsu.end());\n Xatsu.erase(unique(Xatsu.begin(),Xatsu.end()),Xatsu.end());\n Yatsu.erase(unique(Yatsu.begin(),Yatsu.end()),Yatsu.end());\n\n vector<vector<ll>> imos(Xatsu.size(),vector<ll>(Yatsu.size(),0));\n for(int i=0;i<N;i++){\n ll x1=lower_bound(Xatsu.begin(),Xatsu.end(),X1[i])-Xatsu.begin();\n ll y1=lower_bound(Yatsu.begin(),Yatsu.end(),Y1[i])-Yatsu.begin();\n ll x2=lower_bound(Xatsu.begin(),Xatsu.end(),X2[i])-Xatsu.begin();\n ll y2=lower_bound(Yatsu.begin(),Yatsu.end(),Y2[i])-Yatsu.begin();\n\n imos[x1][y1]++;\n imos[x1][y2]--;\n imos[x2][y1]--;\n imos[x2][y2]++;\n }\n for(int i=0;i<Xatsu.size();i++){\n for(int j=1;j<Yatsu.size();j++){\n imos[i][j]+=imos[i][j-1];\n }\n }\n for(int i=0;i<Yatsu.size();i++){\n for(int j=1;j<Xatsu.size();j++){\n imos[j][i]+=imos[j-1][i];\n }\n }\n\n ll ans=0;\n for(int i=0;i<Xatsu.size()-1;i++){\n for(int j=0;j<Yatsu.size()-1;j++){\n if(imos[i][j]>0) ans+=(Xatsu[i+1]-Xatsu[i])*(Yatsu[j+1]-Yatsu[j]);\n }\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 128424, "score_of_the_acc": -0.7815, "final_rank": 9 }, { "submission_id": "aoj_DSL_4_A_10851239", "code_snippet": "#include <iostream>\n#include <algorithm>\n\n#define N (2000* 2 + 1)\n\nusing namespace std;\n\nstruct Node{\n\tint x, y1, y2;\n\tint val;\n\tNode(int x = 0, int y1 = 0, int y2 = 0, int val = 0) : x(x), y1(y1), y2(y2), val(val){}\n} node[N];\n\nint cmp(const Node& l, const Node& r){\n\tif(l.x != r.x) return l.x < r.x;\n\telse return l.val > r.val;\n}\n\nlong long y[N];\nint n, q;\nlong long tree[N << 2];\nlong long lazy[N << 2];\n\n// root == 1\nvoid build(int idx, int start, int end){\n\n\tif(start == end){\n\t\ttree[idx] = 0;\n\t\tlazy[idx] = 0;\n\t} \n\telse{\n\t\tint mid = (start + end) / 2;\n\t\tbuild(idx * 2, start, mid);\n\t\tbuild(idx * 2 + 1, mid + 1, end);\n\t\ttree[idx] = 0;\n\t\tlazy[idx] = 0;\n\t}\n}\n\n\nvoid update(int idx, int start, int end, int l, int r, int val){\n\t\n\tif(lazy[idx] != 0){\n\t\ttree[idx] += lazy[idx];\n\t\tif(start != end){\n\t\t\tlazy[idx * 2] += lazy[idx];\n\t\t\tlazy[idx * 2 + 1] += lazy[idx];\n\t\t}\n\t\tlazy[idx] = 0;\n\t}\n\t\n\tif(start > end || start > r || end < l) return;\n//\tcout << start << \" \" << end << \" \" << l << \" \" << r << endl;\n\t\n\tif(start >= l && end <= r){\n\t\ttree[idx] += val;\n\t\tif(start != end){\n\t\t\tlazy[idx * 2] += val;\n\t\t\tlazy[idx * 2 + 1] += val;\n\t\t}\n\t\treturn;\n\t}\n\t\n\tint mid = (start + end) / 2;\n\tupdate(idx * 2, start, mid, l , r, val);\n\tupdate(idx * 2 + 1, mid + 1, end, l , r, val);\n\ttree[idx] = min(tree[idx * 2], tree[idx * 2 + 1]);\n}\n\nlong long query(int idx, int start, int end, int l, int r){\n\tif(start > end || start > r || end < l) return 0;\n\t\n\tif(lazy[idx] != 0){\n\t\ttree[idx] += lazy[idx];\n\t\tif(start != end){\n\t\t\tlazy[idx * 2] += lazy[idx];\n\t\t\tlazy[idx * 2 + 1] += lazy[idx];\n\t\t}\n\t\tlazy[idx] = 0;\n\t}\n\tif(start >= l && end <= r){\n\t\tif(tree[idx]){\n//\t\t\tcout << y[end + 1 - 1] << \" \" << y[start - 1] << endl;\n\t\t\treturn (y[end + 1 - 1] - y[start - 1]);\n\t\t} \n//\t\telse return 0;\n\t}\n\tif(start == end){\n\t\tif(tree[idx]) return (y[end + 1 - 1] - y[start - 1]);\n\t\telse return 0;\n\t}\n\tint mid = (start + end) / 2;\n\tlong long p1 = query(idx * 2, start, mid, l, r);\n\tlong long p2 = query(idx * 2 + 1, mid + 1, end, l, r);\n\treturn (p1 + p2);\n}\n\nint main(){\n\t\n\tint x1, y1, x2, y2;\n\tint node_idx = 0, y_idx = 0;\n\tlong long ans = 0;\n\t\n\tcin >> n;\n\t\n\tbuild(1, 1, N);\n\t\n\tfor(int i = 0; i < n; i++){\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n\t\tnode[node_idx++] = Node(x1, y1, y2, 1); \n\t\tnode[node_idx++] = Node(x2, y1, y2, -1);\n\t\ty[y_idx++] = y1;\n\t\ty[y_idx++] = y2;\n\t}\n\tsort(node, node + n * 2, cmp);\n\tsort(y, y + n * 2);\n\t\n\tfor(int i = 0; i < n * 2 - 1 ; i++){\n\t\tint L = lower_bound(y, y + n * 2, node[i].y1) - y + 1;\n\t\tint R = lower_bound(y, y + n * 2, node[i].y2) - y;\n\t\t\n//\t\tcout << L << \" \" << R << \" \";\n\t\t\n\t\tupdate(1, 1, n * 2 - 1, L, R, node[i].val);\n/*\t\t\n\t\tfor(int j = 0; j < 7; j++){\n\t\t\tcout << tree[j + 1] << \" \";\n\t\t}\n\t\tcout << endl;\n*/\t\n//\t\tcout << (node[i + 1].x - node[i].x) << \" \" << query(1, 1, 2 * n - 1, 1, 2 * n - 1) << endl;\n\t\tans += (node[i + 1].x - node[i].x) * query(1, 1, 2 * n - 1, 1, 2 * n - 1);\t\n\t\t\n\t}\n\t\n\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3656, "score_of_the_acc": -0.0566, "final_rank": 1 }, { "submission_id": "aoj_DSL_4_A_10730773", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nconst ll INF = LLONG_MAX / 4;\nconst ll mod1 = 1000000007;\nconst ll mod9 = 998244353;\nconst ll Hash = 10000000000000061;\n#define all(a) (a).begin(),(a).end()\n#define rep(i, n) for (ll i = 0; (i) < (n); ++(i))\n#define reps(i, l, r) for(ll i = (l); (i) < (r); ++(i))\nll dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nll dy[8] = {0, -1, -1, -1, 0, 1, 1, 1};\ntemplate <typename T>\nbool chmax(T &a, const T& b) {\n if (a < b) { a = b; return true; }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T& b) {\n if (a > b) { a = b; return true; }\n return false;\n}\n\n#define EPS (1e-10)\n#define equals(a, b) (fabs((a) - (b)) < EPS)\nclass Point {\npublic:\n ld x;\n ld y;\n Point(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}\n Point operator+(Point p) { return Point(x + p.x, y + p.y); }\n Point operator-(Point p) { return Point(x - p.x, y - p.y); }\n Point operator*(ld a) { return Point(a * x, a * y); }\n Point operator/(ld a) { return Point(x / a, y / a); }\n\n ld abs() { return sqrt(norm()); }\nld norm() { return x * x + y * y; }\n\n bool operator<(const Point& p) const {\n return !equals(x, p.x) ? x < p.x : y < p.y;\n }\n bool operator==(const Point& p) const {\n return fabs(x - p.x) < (1e-10) && fabs(y - p.y) < (1e-10);\n }\n};\ntypedef Point Vector;\nstruct Segment {\n Point A;\n Point B;\n};\ntypedef Segment Line;\nclass Circle {\npublic:\n Point C;\n ld r;\n Circle(Point C = Point(), ld r = 0.0) : C(C), r(r) {}\n};\ntypedef vector<Point> Polygon;\n\nvoid solve(){\n ll N; cin >> N;\n vector<pll> z(N*2);\n vector<ll> x(N*2), y(N*2);\n rep(i, N*2){\n ll a, b; cin >> a >> b;\n z[i] = {a, b};\n x[i] = a, y[i] = b;\n }\n sort(all(x));\n x.erase(unique(all(x)), x.end());\n sort(all(y));\n y.erase(unique(all(y)), y.end());\n ll X = x.size(), Y = y.size();\n rep(i, N*2){\n ll a = lower_bound(all(x), z[i].first) - x.begin();\n ll b = lower_bound(all(y), z[i].second) - y.begin();\n z[i] = {a, b};\n }\n vector<vector<ll>> imos(X, vector<ll>(Y, 0));\n rep(i, N){\n ll a = z[i*2].first, b = z[i*2].second, c = z[i*2+1].first, d = z[i*2+1].second;\n imos[a][b]++; imos[c][d]++; imos[a][d]--; imos[c][b]--;\n }\n\n rep(i, X){\n rep(k, Y-1){\n imos[i][k+1] += imos[i][k];\n }\n }\n rep(k, Y){\n rep(i, X-1){\n imos[i+1][k] += imos[i][k];\n }\n }\n ll ans = 0;\n rep(i, X-1){\n rep(k, Y-1){\n if(imos[i][k]>0){\n ans += (x[i+1] - x[i]) * (y[k+1] - y[k]);\n }\n }\n }\n cout << ans << endl;\n}\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n cout << fixed << setprecision(20);\n \n solve();\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 128340, "score_of_the_acc": -0.8378, "final_rank": 10 }, { "submission_id": "aoj_DSL_4_A_10696579", "code_snippet": "// #ifndef ONLINE_JUDGE\n// #define _GLIBCXX_DEBUG//[]で配列外参照をするとエラーにしてくれる。上下のやつがないとTLEになるので注意 ABC311Eのサンプル4みたいなデバック中のTLEは防げないので注意\n// #endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n// #include <atcoder/all>\n// using namespace atcoder;\n\n\ntemplate<typename T> using vc = vector<T>;//prioriy_queueに必要なのでここにこれ書いてます\ntemplate<typename T> using vv = vc<vc<T>>;\n\n//-------------1.型系---------------\nusing ll = long long;\nll INF = 2e18;\n\n// #include <boost/multiprecision/cpp_int.hpp>//インストール的なのをしてないとできないので注意\n// namespace multip = boost::multiprecision;\n// //using lll = multip::cpp_int;//無制限を使いたいときはこっちを使う\n// using lll = multip::int128_t;\n\nusing ld = long double;\nusing bl = bool;\n// using mint = modint998244353;\n//using mint = modint1000000007;\n//using mint = modint;//使うときはコメントアウトを外す\n//mint::set_mod(m);//使うときはコメントアウトを外す\n\ntemplate<class T> using pq = priority_queue<T, vc<T>>;//大きい順\ntemplate<class T> using pq_g = priority_queue<T, vc<T>, greater<T>>;//小さい順\n//-----------------------------------\n\n\n\n//-------------2.配列系--------------\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\nusing vb = vc<bl>; using vvb = vv<bl>; using vvvb = vv<vb>;\nusing vld = vc<ld>; using vvld = vv<ld>; using vvvld = vv<vld>;\nusing pii = pair<int, int>;\nusing pll = pair<ll, ll>;\n// using vmint = vc<mint>; using vvmint = vv<mint>; using vvvmint = vv<vmint>;\n\n//配列外参照対策のやつは一番上の行にあります\n\n#define rep(i,n) for(ll i = 0; i < (n); ++i)//↓でrepを使うので書いてます\ntemplate<class T>istream& operator>>(istream& i, vc<T>& v) { rep(j, size(v))i >> v[j]; return i; }\n\nusing ar2 = array<ll, 2>;\n\n//----------------------------------\n\n\n\n//--------3.コード短縮化とか---------\n#define rep(i,n) for(ll i = 0; i < (n); ++i)\n#define rrep(i,n) for(ll i = 1; i <= (n); ++i)\n#define drep(i,n) for(ll i = (n)-1; i >= 0; --i)\n#define nfor(i,s,n) for(ll i=s;i<n;i++)//i=s,s+1...n-1 ノーマルfor\n#define dfor(i,s,n) for(ll i = (s)-1; i>=n;i--)//s-1スタートでnまで落ちる\n\n#define nall(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n\n#define chmax(x,y) x = max(x,y)\n#define chmin(x,y) x = min(x,y)\n\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n\n\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\n#define YN {cout<<\"Yes\"<<endl;}else{cout<<\"No\"<<endl;}// if(a==b)YN;\n#define dame cout<<-1<<endl\n\n\n#define vc_unique(v) v.erase( unique(v.begin(), v.end()), v.end() );\n#define vc_rotate(v) rotate(v.begin(),v.begin()+1,v.end());\n\n#define pop_cnt(s) ll(popcount(uint64_t(s)))\n\n#define next_p(v) next_permutation(v.begin(),v.end())\n\n//if (regex_match(s, regex(\"\")))YN;//文字列sの判定を行う。コメントアウトを外して「\"\"」の中に判定する内容を入れる\n\n//-------------------------------\n\n\n\n\n//---------4.グリッド系----------\nvl di = { 0,1,0,-1 };//vl di={0,1,1,1,0,-1,-1,-1};\nvl dj = { 1,0,-1,0 };//vl dj={1,1,0,-1,-1,-1,0,1};\n\nbool out_grid(ll i, ll j, ll h, ll w) {//trueならcontinue\n return (!(0 <= i && i < h && 0 <= j && j < w));\n}\n\n#define vvl_kaiten_r(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//時計回りに90°回転\n#define vvl_kaiten_l(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//反時計周りに90°回転\n\n#define vs_kaiten_r(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//文字列版 時計回りに90°回転\n#define vs_kaiten_l(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//文字列版 反時計周りに90°回転\n\n\n#define vvl_tenti(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][i]=v[i][j];swap(nx,v);}\n#define vs_tenti(v) {ll n = size(v); vs nx(n, string(n,'.')); rep(i, n)rep(j, n)nx[j][i] = v[i][j]; swap(nx, v);}\n\n//--------------------------------\n\n\n\n\n//-----------5.数学系--------------\n#define yu_qurid(x,y) ((x)*(x)+(y)*(y))//ユークリッド距離 sqrtはしてないなので注意\n#define mannhattan(x1,x2,y1,y2) (abs(x1-x2)+abs(y1-y2)) // マンハッタン距離 = |x1-x2|+|y1-y2|\n\ntemplate<class T>T tousa_sum1(T l, T d, T r) {//初項,公差,末項 で総和を求める\n T wide = (r - l) / d + 1;\n return (l + r) * wide / 2;\n}\ntemplate<class T>T tousa_sum2(T a, T d, T n) {//初項,交差,項数 で総和を求める\n return (a * 2 + d * (n - 1)) * n / 2;\n}\nll kousa_kousuu(ll l, ll r, ll d) {//初項,末項,交差 で等差数列の項数を求める\n return (r - l) / d + 1;\n}\n// mint touhi_sum(mint a, mint r, ll n) {//初項,公比,項数で等比数列の総和を求める\n// if (r == 1) {\n// return a * n;\n// }\n// mint bunsi = a * (r.pow(n) - mint(1));\n// mint bunbo = r - 1;\n// return bunsi / bunbo;\n// }\n\nll nc2(ll x) { return x * (x - 1) / 2; }\nll nc3(ll x) { return x * (x - 1) * (x - 2) / 6; }\n\n//----------------------------------------------\n\n\n\n\n//-----------6.デバックや出力系------------------\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\nvoid mukou_debug(vvl to, bool yukou) {//GRAPH × GRAPH用の無向グラフを出力する\n ll n = size(to); ll cnt = 0;//辺の本数\n vc<pair<ll, ll>>v; rep(i, n)for (ll t : to[i]) if (i < t || yukou)cnt++, v.eb(i + 1, t + 1);//有向グラフなら全部OK、違うなら無向なのでf<tのみ見る、using Pのやつを別のにしたいときのためにPを使わずにpair<ll,ll>にしてる\n cout << n << ' ' << cnt << endl; for (auto [f, t] : v)cout << f << ' ' << t << endl;\n}\n\n#define vc_cout(v){ll n = size(v);rep(i,n)cout<<v[i]<<endl;}//一次元配列を出力する\n#define vv_cout(v){ll n = size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<' ';}cout<<endl;}}//二次元配列を出力する\n\nint main(){\n ll n;\n cin >> n;\n vc<pair<pll, pll>> rect(n);\n rep(i, n){\n ll x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n rect[i] = make_pair(make_pair(x1, y1), make_pair(x2, y2));\n }\n\n vl xs, ys;\n rep(i, n){\n xs.push_back(rect[i].first.first);\n xs.push_back(rect[i].second.first);\n\n ys.push_back(rect[i].first.second);\n ys.push_back(rect[i].second.second);\n }\n\n sort(nall(xs));\n sort(nall(ys));\n\n vc_unique(xs);\n vc_unique(ys);\n\n vc<pair<pll, pll>> rectComp(n);\n rep(i, n){\n rectComp[i].first.first = lower_bound(nall(xs), rect[i].first.first) - xs.begin();\n rectComp[i].second.first = lower_bound(nall(xs), rect[i].second.first) - xs.begin();\n\n rectComp[i].first.second = lower_bound(nall(ys), rect[i].first.second) - ys.begin();\n rectComp[i].second.second = lower_bound(nall(ys), rect[i].second.second) - ys.begin();\n }\n\n vvl grid(xs.size() + 1, vl(ys.size() + 1, 0));\n rep(i, n){\n auto [p1, p2] = rectComp[i];\n auto [x1, y1] = p1;\n auto [x2, y2] = p2;\n\n grid[x1][y1]++;\n grid[x2][y1]--;\n grid[x1][y2]--;\n grid[x2][y2]++;\n }\n\n rep(i, xs.size()) rep(j, ys.size()){\n grid[i+1][j] += grid[i][j];\n }\n\n rep(i, xs.size()) rep(j, ys.size()){\n grid[i][j+1] += grid[i][j];\n }\n\n ll ans = 0;\n rep(i, xs.size()-1) rep(j, ys.size()){\n if(grid[i][j] > 0){\n ans += (xs[i+1] - xs[i])*(ys[j+1] - ys[j]);\n }\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 128376, "score_of_the_acc": -0.6115, "final_rank": 7 }, { "submission_id": "aoj_DSL_4_A_10631924", "code_snippet": "#pragma region Macros\n#include <bits/stdc++.h>\n\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\nusing lint = long long;\nusing mint = modint998244353;\nusing ull = unsigned long long;\nusing ld = long double;\nusing int128 = __int128_t;\n#define all(x) (x).begin(), (x).end()\n#define EPS 1e-8\n#define uniqv(v) v.erase(unique(all(v)), v.end())\n#define OVERLOAD_REP(_1, _2, _3, name, ...) name\n#define REP1(i, n) for (auto i = std::decay_t<decltype(n)>{}; (i) != (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\n#define log(x) cout << x << endl\n#define logfixed(x) cout << fixed << setprecision(10) << x << endl;\n#define logy(bool) \\\n if (bool) { \\\n cout << \"Yes\" << endl; \\\n } else { \\\n cout << \"No\" << endl; \\\n }\n\nostream &operator<<(ostream &dest, __int128_t value) {\n ostream::sentry s(dest);\n if (s) {\n __uint128_t tmp = value < 0 ? -value : value;\n char buffer[128];\n char *d = end(buffer);\n do {\n --d;\n *d = \"0123456789\"[tmp % 10];\n tmp /= 10;\n } while (tmp != 0);\n if (value < 0) {\n --d;\n *d = '-';\n }\n int len = end(buffer) - d;\n if (dest.rdbuf()->sputn(d, len) != len) {\n dest.setstate(ios_base::badbit);\n }\n }\n return dest;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v) {\n for (int i = 0; i < (int)v.size(); i++) {\n os << v[i] << (i + 1 != (int)v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const set<T> &set_var) {\n for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {\n os << *itr;\n ++itr;\n if (itr != set_var.end()) os << \" \";\n itr--;\n }\n return os;\n}\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const map<T, U> &map_var) {\n for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {\n os << itr->first << \" -> \" << itr->second << \"\\n\";\n }\n return os;\n}\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const pair<T, U> &pair_var) {\n os << \"(\" << pair_var.first << \", \" << pair_var.second << \")\";\n return os;\n}\n\nvoid out() { cout << '\\n'; }\ntemplate <class T, class... Ts>\nvoid out(const T &a, const Ts &...b) {\n cout << a;\n (cout << ... << (cout << ' ', b));\n cout << '\\n';\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v) {\n for (T &in : v) is >> in;\n return is;\n}\n\ninline void in(void) { return; }\ntemplate <typename First, typename... Rest>\nvoid in(First &first, Rest &...rest) {\n cin >> first;\n in(rest...);\n return;\n}\n\ntemplate <typename T>\nbool chmax(T &a, const T &b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T &b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n\nvector<lint> dx8 = {1, 1, 0, -1, -1, -1, 0, 1};\nvector<lint> dy8 = {0, 1, 1, 1, 0, -1, -1, -1};\nvector<lint> dx4 = {1, 0, -1, 0};\nvector<lint> dy4 = {0, 1, 0, -1};\n\n#pragma endregion\n\nint main() {\n cin.tie(0)->sync_with_stdio(0);\n int n;\n in(n);\n vector<lint> xl(n), yl(n), xr(n), yr(n);\n vector<lint> tx, ty;\n\n rep(i, n) {\n in(xl[i], yl[i], xr[i], yr[i]);\n tx.emplace_back(xl[i]);\n tx.emplace_back(xr[i]);\n tx.emplace_back(xl[i] + 1);\n tx.emplace_back(xr[i] + 1);\n ty.emplace_back(yl[i]);\n ty.emplace_back(yr[i]);\n ty.emplace_back(yl[i]) + 1;\n ty.emplace_back(yr[i]) + 1;\n }\n\n sort(all(tx));\n sort(all(ty));\n uniqv(tx);\n uniqv(ty);\n\n rep(i, n) {\n xl[i] = distance(tx.begin(), lower_bound(all(tx), xl[i]));\n xr[i] = distance(tx.begin(), lower_bound(all(tx), xr[i]));\n yl[i] = distance(ty.begin(), lower_bound(all(ty), yl[i]));\n yr[i] = distance(ty.begin(), lower_bound(all(ty), yr[i]));\n }\n int h = ty.size();\n int w = tx.size();\n vector g(h, vector(w, int(0)));\n rep(i, n) {\n g[yl[i]][xl[i]]++;\n g[yl[i]][xr[i]]--;\n g[yr[i]][xl[i]]--;\n g[yr[i]][xr[i]]++;\n }\n\n rep(i, h) {\n rep(j, w - 1) {\n g[i][j + 1] += g[i][j];\n }\n }\n\n rep(j, w) {\n rep(i, h - 1) {\n g[i + 1][j] += g[i][j];\n }\n }\n\n lint res = 0;\n rep(i, h) {\n rep(j, w) {\n if (g[i][j] > 0) {\n res += (ty[i + 1] - ty[i]) * (tx[j + 1] - tx[j]);\n }\n }\n }\n\n out(res);\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 128768, "score_of_the_acc": -0.8583, "final_rank": 11 }, { "submission_id": "aoj_DSL_4_A_10619380", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i< (n); ++i)\nusing ll = long long;\ntemplate<typename T=int>\nstruct CC {\n\tbool initialized;\n\tvector<T> xs;\n\tCC(): initialized(false) {}\n\tvoid add(T x) { xs.push_back(x);}\n\tvoid init() {\n\t\tsort(xs.begin(), xs.end());\n\t\txs.erase(unique(xs.begin(),xs.end()),xs.end());\n\t\tinitialized = true;\n\t}\n\tint operator()(T x) {\n\t\tif (!initialized) init();\n\t\treturn upper_bound(xs.begin(), xs.end(), x) - xs.begin() - 1;\n\t}\n\tT operator[](int i) {\n\t\tif (!initialized) init();\n\t\treturn xs[i];\n\t}\n\tint size() {\n\t\tif (!initialized) init();\n\t\treturn xs.size();\n\t}\n};\nint main() {\n int n; cin >> n;\n\tvector<ll> x1(n), y1(n), x2(n), y2(n);\n\tCC<ll> X, Y;\n rep(i, n){\n\t\tcin >> x1[i] >> y1[i] >> x2[i] >> y2[i];\n\t\tX.add(x1[i]);X.add(x2[i]);\n\t\tY.add(y1[i]);Y.add(y2[i]);\n\t}\n\tvector<vector<int>> S(2001, vector<int>(2001, 0));\n\trep(i, n){\n\t\tS[X(x1[i])][Y(y1[i])]++;\n\t\tS[X(x1[i])][Y(y2[i])]--;\n\t\tS[X(x2[i])][Y(y1[i])]--;\n\t\tS[X(x2[i])][Y(y2[i])]++;\n\t}\n\trep(i, 2000)rep(j, 2001){\n\t\tS[i+1][j]+=S[i][j];\n\t}\n\trep(i, 2001)rep(j, 2000){\n\t\tS[i][j+1]+=S[i][j];\n\t}\n\tll ans = 0;\n rep(i, 2001)rep(j, 2001){\n\t\tif(S[i][j] >= 1){\n\t\t\tans += (X[i+1]-X[i])*(Y[j+1]-Y[j]);\n\t\t}\n\t}\n\tcout << ans << endl;\n\n\n\t\t\n}", "accuracy": 0.82, "time_ms": 10, "memory_kb": 18956, "score_of_the_acc": -0.0611, "final_rank": 19 }, { "submission_id": "aoj_DSL_4_A_10619303", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i< (n); ++i)\nusing ll = long long;\ntemplate<typename T=int>\nstruct CC {\n\tbool initialized;\n\tvector<T> xs;\n\tCC(): initialized(false) {}\n\tvoid add(T x) { xs.push_back(x);}\n\tvoid init() {\n\t\tsort(xs.begin(), xs.end());\n\t\txs.erase(unique(xs.begin(),xs.end()),xs.end());\n\t\tinitialized = true;\n\t}\n\tint operator()(T x) {\n\t\tif (!initialized) init();\n\t\treturn upper_bound(xs.begin(), xs.end(), x) - xs.begin() - 1;\n\t}\n\tT operator[](int i) {\n\t\tif (!initialized) init();\n\t\treturn xs[i];\n\t}\n\tint size() {\n\t\tif (!initialized) init();\n\t\treturn xs.size();\n\t}\n};\nint main() {\n int n; cin >> n;\n\tvector<ll> x1(n), y1(n), x2(n), y2(n);\n\tCC X, Y;\n rep(i, n){\n\t\tcin >> x1[i] >> y1[i] >> x2[i] >> y2[i];\n\t\tX.add(x1[i]);X.add(x2[i]);\n\t\tY.add(y1[i]);Y.add(y2[i]);\n\t}\n\tvector<vector<int>> S(2001, vector<int>(2001, 0));\n\trep(i, n){\n\t\tS[X(x1[i])][Y(y1[i])]++;\n\t\tS[X(x1[i])][Y(y2[i])]--;\n\t\tS[X(x2[i])][Y(y1[i])]--;\n\t\tS[X(x2[i])][Y(y2[i])]++;\n\t}\n\trep(i, 2000)rep(j, 2001){\n\t\tS[i+1][j]+=S[i][j];\n\t}\n\trep(i, 2001)rep(j, 2000){\n\t\tS[i][j+1]+=S[i][j];\n\t}\n\tll ans = 0;\n rep(i, 2001)rep(j, 2001){\n\t\tif(S[i][j] >= 1){\n\t\t\tans += (X[i+1]-X[i])*(Y[j+1]-Y[j]);\n\t\t}\n\t}\n\tcout << ans << endl;\n\n\n\t\t\n}", "accuracy": 0.48, "time_ms": 10, "memory_kb": 18956, "score_of_the_acc": -0.0611, "final_rank": 20 }, { "submission_id": "aoj_DSL_4_A_10544084", "code_snippet": "#pragma GCC optimize(\"Ofast,unroll-loops\")\n#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nusing u8=uint8_t;\nusing u16=uint16_t;\nusing u32=uint32_t;\nusing u64=uint64_t;\nusing i128=__int128;\nusing u128=unsigned __int128;\nusing ld=long double;\nusing str=string;\ntemplate<class F>using fn=function<F>;\nusing pii=pair<int,int>;\nusing pll=pair<ll,ll>;\n#define eval3(a,b,c,d,...)d\n#define eval4(a,b,c,d,e,...)e\n#define eval5(a,b,c,d,e,f,...)f\n#define eval6(a,b,c,d,e,f,g,...)g\ntemplate<class T>using vc=vector<T>;\ntemplate<class T>using vvc=vc<vc<T>>;\ntemplate<class T>using vvvc=vc<vvc<T>>;\ntemplate<class T>using vvvvc=vc<vvvc<T>>;\n#define vv(T,x,h,...)vvc<T>x(h,vc<T>(__VA_ARGS__));\n#define vvv(T,x,h,w,...)vvvc<T>x(h,vector(w,vc<T>(__VA_ARGS__)));\n#define vvvv(T,x,a,b,c,...)vvvvc<T>x(a,vector(b,vector(c,vc<T>(__VA_ARGS__))));\nusing vi=vc<int>;\nusing vl=vc<ll>;\ntemplate<class T>using pq=priority_queue<T>;\ntemplate<class T>using pqg=priority_queue<T,vc<T>,greater<T>>;\ntemplate<class T>using max_queue=pq<T>;\ntemplate<class T>using min_queue=pqg<T>;\n#define loop while(1)\n#define rep0(n)for(ll __=0;__<ll(n);++__)\n#define rep1(i,n)for(ll i=0;i<ll(n);++i)\n#define rep2(i,a,b)for(ll i=a;i<ll(b);++i)\n#define rep3(i,a,b,c)for(ll i=a;i<ll(b);i+=c)\n#define rep(...)eval4(__VA_ARGS__,rep3,rep2,rep1,rep0)(__VA_ARGS__)\n#define repr1(i,n)for(ll i=n;i-->0;)\n#define repr2(i,a,b)for(ll i=b;i-->ll(a);)\n#define repr(...)eval3(__VA_ARGS__,repr2,repr1,rep0)(__VA_ARGS__)\n#define per(...)repr(__VA_ARGS__)\n#define rrep1(i,n)for(ll i=n;i>0;i--)\n#define rrep2(i,a,b)for(ll i=a;i>ll(b);i--)\n#define rrep3(i,a,b,c)for(ll i=a;i>ll(b);i+=c)\n#define rrep(...)eval4(__VA_ARGS__,rrep3,rrep2,rrep1,rep0)(__VA_ARGS__)\n#define iter1(a,A)for(auto a:A)\n#define iter2(a,b,A)for(auto[a,b]:A)\n#define iter3(a,b,c,A)for(auto[a,b,c]:A)\n#define iter4(a,b,c,d,A)for(auto[a,b,c,d]:A)\n#define iter5(a,b,c,d,e,A)for(auto[a,b,c,d,e]:A)\n#define iter(...)eval6(__VA_ARGS__,iter5,iter4,iter3,iter2,iter1)(__VA_ARGS__)\n#define iter_mut1(a,A)for(auto&a:A)\n#define iter_mut2(a,b,A)for(auto&[a,b]:A)\n#define iter_mut3(a,b,c,A)for(auto&[a,b,c]:A)\n#define iter_mut4(a,b,c,d,A)for(auto&[a,b,c,d]:A)\n#define iter_mut5(a,b,c,d,e,A)for(auto&[a,b,c,d,e]:A)\n#define iter_mut(...)eval6(__VA_ARGS__,\\\niter_mut5,iter_mut4,iter_mut3,iter_mut2,iter_mut1)(__VA_ARGS__)\n#define iter_ref1(a,A)for(const auto&a:A)\n#define iter_ref2(a,b,A)for(const auto&[a,b]:A)\n#define iter_ref3(a,b,c,A)for(const auto&[a,b,c]:A)\n#define iter_ref4(a,b,c,d,A)for(const auto&[a,b,c,d]:A)\n#define iter_ref5(a,b,c,d,e,A)for(const auto&[a,b,c,d,e]:A)\n#define iter_ref(...)eval6(__VA_ARGS__,\\\niter_ref5,iter_ref4,iter_ref3,iter_ref2,iter_ref1)(__VA_ARGS__)\n#define endl '\\n'\n#define elif else if\n#define fi first\n#define se second\n#define be begin()\n#define en end()\n#define rbe rbegin()\n#define ren rend()\n#define MP make_pair\n#define MT make_tuple\n#define pb push_back\n#define eb emplace_back\n#define emp emplace\n#define fr front()\n#define bk back()\n#define stoi stoll\n#define ALL(a)(a).be,(a).en\n#define RALL(a)(a).rbe,(a).ren\n#define LB(a,x)std::lower_bound(ALL(a),(x))\n#define UB(a,x)std::upper_bound(ALL(a),(x))\n#define LBI(a,x)LB(a,x)-(a).be\n#define UBI(a,x)UB(a,x)-(a).be\n#define lb(a,x)std::lower_bound(ALL(a),(x))\n#define ub(a,x)std::upper_bound(ALL(a),(x))\n#define lbi(a,x)LB(a,x)-(a).be\n#define ubi(a,x)UB(a,x)-(a).be\n#define len(a)ll(a.size())\n#define PI 3.14159265358979323846\ntemplate<class T>\nint ctz(T x){return __builtin_ctzll(x);}\nint ctz(u128 x){\n\tu64 y=x&u64(-1);\n\treturn y?ctz(y):64+ctz(u64(x>>64));\n}\nint ctz(i128 x){return ctz((u128)x);}\ntemplate<class T>\nint clz(T x){return __builtin_clzll(x);}\nint clz(u128 x){\n\tu64 y=x>>64;\n\treturn y?clz(y):64+clz((u64)x);\n}\nint clz(i128 x){return clz((u128)x);}\ntemplate<class T>int lsb(T x){return x?ctz(x):-1;}\ntemplate<class T>int msb(T x){return x?63-clz(x):-1;}\nint msb(u128 x){return x?127-clz(x):-1;}\nint msb(i128 x){return msb((u128)x);}\ntemplate<class T>int bitlen(T x){return msb(x)+1;}\ntemplate<class T>\nll popcnt(T x){return __builtin_popcountll(x);}\nll popcnt(u128 x){return popcnt(u64(x&u64(-1)))+popcnt(u64(x>>64));}\nll popcnt(i128 x){return popcnt((u128)x);}\n#define popcount(x)popcnt(x)\ntemplate<class T>\nint parity(T x){return __builtin_parityll(x);}\ntemplate<class T,class U>\nbool chmax(T&a,U b){return b>a?a=b,1:0;}\ntemplate<class T,class U>\nbool chmin(T&a,U b){return b<a?a=b,1:0;}\ntemplate<class...T>\nconstexpr auto MIN(T... a){\n\treturn min(initializer_list<common_type_t<T...>>{a...});\n}\ntemplate<class...T>\nconstexpr auto MAX(T... a){\n\treturn max(initializer_list<common_type_t<T...>>{a...});\n}\ntemplate<class T>\nT max(const vc<T>&a){return *max_element(ALL(a));}\ntemplate<class T>\nT min(const vc<T>&a){return *min_element(ALL(a));}\ntemplate<class T>\nT max(const vvc<T>&a){\n\tT y=max(a[0]);\n\trep(i,1,len(a))chmax(y,max(a[i]));\n\treturn y;\n}\ntemplate<class T>\nT min(const vvc<T>&a){\n\tT y=min(a[0]);\n\trep(i,1,len(a))chmin(y,min(a[i]));\n\treturn y;\n}\nconstexpr int GCD(){return 0;}\ntemplate<class T>constexpr T GCD(T x){return x;}\ntemplate<class T,class...Ts>\nconstexpr auto GCD(T a,Ts...b){\n\tif constexpr(!sizeof...(Ts))return a;\n\telse {\n\t\tusing X=common_type_t<T,common_type_t<Ts...>>;\n\t\treturn gcd<X>(a,GCD(b...));\n\t}\n}\ntemplate<class T>\nint signum(T x){return x<0?-1:x>0;}\ntemplate<class A>\nvoid sort(A&a){sort(ALL(a));}\ntemplate<class A>\nvoid rsort(A&a){sort(RALL(a));}\ntemplate<class A>\nvoid reverse(A&a){reverse(ALL(a));}\n#define UNIQUE(a)sort(a),a.erase(unique(ALL(a)),a.en)\ntemplate<class A>\nA unique(A a){\n\tUNIQUE(a);\n\treturn a;\n}\ntemplate<class A,class F>\nvoid filter(A&a,F f){\n\ta.erase(remove_if(ALL(a),[&](auto&x){return !f(x);}),a.en);\n}\ntemplate<class T,class U>\ncommon_type_t<T,U>ceil_div(T a,U b){\n\treturn a/b+((a^b)>0&&a%b);\n};\ntemplate<class T,class U>\ncommon_type_t<T,U>floor_div(T a,U b){\n\treturn a/b-((a^b)<0&&a%b);\n};\ntemplate<class T,class U>\nT sum(const vc<U>&a){return accumulate(ALL(a),T{});}\ntemplate<class T>\nT sum(const vc<T>&a){return sum<T,T>(a);}\ntemplate<class T>T sum(){return T{};}\ntemplate<class...T>\ncommon_type_t<T...>sum(T...a){return(common_type_t<T...>{}+...+a);}\ntemplate<class T=ll>\nconstexpr T ten(int k){return k?ten<T>(k-1)*10:1;}\ntemplate<class A>\nbool all(A a){\n\titer_ref(x,a)if(!x)return 0;\n\treturn 1;\n}\ntemplate<class A,class F>\nbool all(A a,F f){\n\titer_ref(x,a)if(!f(x))return 0;\n\treturn 1;\n}\ntemplate<class A>\nbool any(A a){\n\titer_ref(x,a)if(x)return 1;\n\treturn 0;\n}\ntemplate<class A,class F>\nbool any(A a,F f){\n\titer_ref(x,a)if(f(x))return 1;\n\treturn 0;\n}\ntemplate<class T>\nvc<T>get(const vc<T>&a,const vc<int>&p){\n\tint n=len(p);\n\tvc<T>b(n);\n\trep(i,n)b[i]=a[p[i]];\n\treturn b;\n}\nvc<char>get(const string&a,const vc<int>&p){\n\tint n=len(p);\n\tvc<char>b(n);\n\trep(i,n)b[i]=a[p[i]];\n\treturn b;\n}\nvc<int>argperm(const vc<int>&a){\n\tint n=len(a);\n\tvc<int>p(n);\n\trep(i,n)p[a[i]]=i;\n\treturn p;\n}\ntemplate<class A>\nvc<int>argsort(const A&a,bool desc=0,bool rev=0){\n\tint n=len(a);\n\tvc<int>p(n);\n\trep(i,n)p[i]=i;\n\tsort(ALL(p),[&](int i,int j){\n\t\tif(a[i]!=a[j])return desc?a[i]>a[j]:a[i]<a[j];\n\t\treturn rev?i>j:i<j;\n\t});\n\treturn p;\n}\ntemplate<class T=int>\nvc<T>iota(int n,T x={}){\n\tvc<T>a(n);\n\trep(i,n)a[i]=i+x;\n\treturn a;\n}\ntemplate<class T>\nT POP(vc<T>&a){T x=a.bk;a.pop_back();return x;}\ni128 abs(i128 x){return x<0?-x:x;}\nstring to_string(u128 x){\n\tif(x==0)return \"0\";\n\tstring s;\n\twhile(x){\n\t\ts+=x%10+'0';\n\t\tx/=10;\n\t}\n\treverse(s);\n\treturn s;\n}\nstring to_string(i128 x){\n\tif(x==0)return \"0\";\n\tbool neg=0;\n\tif(x<0){neg=1,x=-x;}\n\tstring s;\n\twhile(x){\n\t\ts+=x%10+'0';\n\t\tx/=10;\n\t}\n\tif(neg)s+='-';\n\treverse(s);\n\treturn s;\n}\ntemplate<class T,class U,class F>\nauto binarysearch(F f,T ok0,U ng0,bool check=1){\n\tusing X=common_type_t<T,U>;\n\tX ok=ok0,ng=ng0;\n\tif(check)assert(f(ok));\n\twhile(abs(ok-ng)>1){\n\t\tX x=(ok+ng)/2;\n\t\t(f(x)?ok:ng)=x;\n\t}\n\treturn ok;\n}\ntemplate<class T,class U,class F>\nauto binarysearch(T ok0,U ng0,F f,bool check=1){\n\tusing X=common_type_t<T,U>;\n\tX ok=ok0,ng=ng0;\n\tif(check)assert(f(ok));\n\twhile(abs(ok-ng)>1){\n\t\tX x=(ok+ng)/2;\n\t\t(f(x)?ok:ng)=x;\n\t}\n\treturn ok;\n}\ntemplate<class F>\nstruct REC{\n\tF f;\n\tREC(F f):f(f){}\n\ttemplate<class...X>\n\tauto operator()(X...x){return f(f,x...);}\n};\nnamespace io{\ntemplate<class T>\nconstexpr bool is_128=is_same_v<T,i128>||is_same_v<T,u128>;\nconstexpr int N=1<<16;\nstruct I{\nchar b[N],*r=b+N,*p=r;\nconstexpr inline void load(int need){\n\tif(int d=r-p;d<need){\n\t\td=fread(copy_n(p,d,b),1,p-b,stdin);\n\t\tp=b;\n\t}\n}\nvoid skip(){while(*p<=' ')++p;}\nvoid sc(char&c){\n\tload(5);\n\tskip();\n\tc=*p++;\n}\nvoid sc(string&s){\n\ts.clear();\n\tload(5);\n\tskip();\n\tdo{\n\t\ts+=*p++;\n\t\tload(1);\n\t}while(*p>' ');\n\t++p;\n}\nvoid sc(double&x){\n\tstring s;\n\tsc(s);\n\tx=stod(s);\n}\ntemplate<class T>\nenable_if_t<is_integral_v<T>>sc(T&x){\n\tload(25);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\tbool ok=0;\n\twhile(1){\n\t\tint d=0;\n\t\tfor(int i=0;i<9;i++){\n\t\t\tif(*p<=' '){\n\t\t\t\tok=1;\n\t\t\t\tif(i)x=x*ten<int>(i)+d;\n\t\t\t\t++p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\td=d*10+(*p++-'0');\n\t\t}\n\t\tif(ok)break;\n\t\tx=x*ten<int>(9)+d;\n\t}\n\tif(neg)x=-x;\n}\ntemplate<class T>\nenable_if_t<is_128<T>>sc(T&x){\n\tload(45);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\twhile(1){\n\t\tuint64_t d;\n\t\tmemcpy(&d,p,8);\n\t\td-=0x3030303030303030;\n\t\tif(d&0x8080808080808080)break;\n\t\td=(d*10+(d>>8))&0xff00ff00ff00ff;\n\t\td=(d*100+(d>>16))&0xffff0000ffff;\n\t\td=(d*10000+(d>>32))&0xffffffff;\n\t\tx=x*100000000+d;\n\t\tp+=8;\n\t}\n\tint d=0,c=0;\n\twhile(*p>' '){\n\t\td=d*10+(*p++-'0');\n\t\t++c;\n\t}\n\t++p;\n\tif(c)x=x*ten<int>(c)+d;\n\tif(neg)x=-x;\n}\ntemplate<class T,class U>\nvoid sc(pair<T,U>&x){sc(x.fi),sc(x.se);}\ntemplate<int k=0,class T>\nvoid sc_tup(T&x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tsc(get<k>(x));\n\t\tsc_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid sc(tuple<T...>&x){sc_tup(x);}\ntemplate<class T>\nvoid sc(vc<T>&a){iter_mut(x,a)sc(x);}\ntemplate<class T>I&operator>>(T&x){sc(x);return *this;}\n}i;\ntemplate<class...T>\nvoid in(T&...x){(i.sc(x),...);}\nstruct O{\nchar b[N],*r=b+N,*p=b;\nconstexpr inline void flush(int need=N){\n\tif(r-p<need){\n\t\tfwrite(b,1,p-b,stdout);\n\t\tp=b;\n\t}\n}\n~O(){flush();}\nvoid pr(char c){\n\tflush(1);\n\t*p++=c;\n}\nvoid pr(bool x){pr(x?'1':'0');}\nvoid pr(const char*s){\n\tint n=strlen(s);\n\tfor(int i=0;i<n;i++)pr(s[i]);\n}\nvoid pr(string s){for(char c:s)pr(c);}\nvoid pr(double x){\n\tostringstream os;\n\tos<<setprecision(18)<<x;\n\tpr(os.str());\n}\nvoid pr(long double x){pr((double)x);}\nstatic constexpr auto num=[](){\n\tarray<array<char,4>,10000>num={};\n\tfor(int i=10000;i--;){\n\t\tint x=i;\n\t\tfor(int j=4;j--;)num[i][j]=x%10|'0',x/=10;\n\t}\n\treturn num;\n}();\nchar tmp[20];\ntemplate<class T>\nenable_if_t<is_integral_v<T>>pr(T x){\n\tflush(20);\n\tif(x<0)*p++='-',x=-x;\n\tint i;\n\tfor(i=20;x>=10000;){\n\t\ti-=4;\n\t\tmemcpy(tmp+i,&num[x%10000][0],4);\n\t\tx/=10000;\n\t}\n\tif(x>=1000)p=copy_n(&num[x][0],4,p);\n\telse if(x>=100)p=copy_n(&num[x][1],3,p);\n\telse if(x>=10)p=copy_n(&num[x][2],2,p);\n\telse *p++=x|'0';\n\tp=copy_n(tmp+i,20-i,p);\n}\ntemplate<int k=16>\nvoid w4(ll x){\n\tif constexpr(k==4){\n\t\tp=copy_n(&num[x][0],4,p);\n\t\treturn;\n\t}else{\n\t\tp=copy_n(&num[x/ten<ll>(k-4)][0],4,p);\n\t\tw4<k-4>(x%ten<ll>(k-4));\n\t}\n}\ntemplate<class T>\nenable_if_t<is_128<T>>pr(T x){\n\tflush(40);\n\tif(x<0)*p++='-',x=-x;\n\tif(x<ten<T>(16))pr(static_cast<ll>(x));\n\telse if(x<ten<T>(32)){\n\t\tpr(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}else{\n\t\tpr(static_cast<int>(x/ten<T>(32)));\n\t\tx%=ten<T>(32);\n\t\tw4(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}\n}\ntemplate<class T,class U>\nvoid pr(pair<T,U>x){pr(x.fi),pr(' '),pr(x.se);}\ntemplate<int k=0,class T>\nvoid pr_tup(T x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tif constexpr(k)pr(' ');\n\t\tpr(get<k>(x));\n\t\tpr_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid pr(tuple<T...>x){pr_tup(x);}\ntemplate<class T>\nvoid pr(vc<T>a){\n\tint n=len(a);\n\trep(i,n){\n\t\tif(i)pr(' ');\n\t\tpr(a[i]);\n\t}\n}\ntemplate<class T>\nvoid pr(const vvc<T>&a){\n\tint n=len(a);\n\trep(i,n){\n\t\tif(i)pr('\\n');\n\t\tpr(a[i]);\n\t}\n}\ntemplate<class T,class U>\nvoid pr(const vc<pair<T,U>>&a){\n\tint n=len(a);\n\trep(i,n){\n\t\tif(i)pr('\\n');\n\t\tpr(a[i]);\n\t}\n}\ntemplate<class...T>\nvoid pr(const vc<tuple<T...>>&a){\n\tint n=len(a);\n\trep(i,n){\n\t\tif(i)pr('\\n');\n\t\tpr(a[i]);\n\t}\n}\ntemplate<class T>O&operator<<(T x){pr(x);return *this;}\n}o;\nvoid flush(){o.flush();}\nvoid out(){o.pr('\\n');}\ntemplate<char end='\\n',char sep=' ',class T,class...Ts>\nvoid out(T&&x,Ts&&...a){\n\to.pr(x);\n\t((o.pr(sep),o.pr(a)),...);\n\to.pr(end);\n}\n}\nusing io::in,io::out,io::flush;\n#define cin io::i\n#define cout io::o\n#define INT(...)int __VA_ARGS__;in(__VA_ARGS__);\n#define LL(...)ll __VA_ARGS__;in(__VA_ARGS__);\n#define U32(...)u32 __VA_ARGS__;in(__VA_ARGS__);\n#define U64(...)u64 __VA_ARGS__;in(__VA_ARGS__);\n#define STR(...)string __VA_ARGS__;in(__VA_ARGS__);\n#define CHR(...)char __VA_ARGS__;in(__VA_ARGS__);\n#define DBL(...)double __VA_ARGS__;in(__VA_ARGS__);\n#define I128(...)i128 __VA_ARGS__;in(__VA_ARGS__);\nvoid decr(){}\ntemplate<class T,class...Ts>\nvoid decr(T&x,Ts&...a){\n\t--x;\n\tdecr(a...);\n}\n#define INT1(...)INT(__VA_ARGS__);decr(__VA_ARGS__);\n#define LL1(...)LL(__VA_ARGS__);decr(__VA_ARGS__);\n#define VEC(T,x,n)vc<T>x(n);in(x);\n#define VV(T,x,h,w)vv(T,x,h,w);in(x);\n#ifdef LOCAL\n#define dbg(...)out(__VA_ARGS__)\n#define SHOW(...)out('[',#__VA_ARGS__,\"]:\",__VA_ARGS__)\n#else\n#define dbg(...)\n#define SHOW(...)\n#endif\n#define multicase INT(tt);while(tt--)\n#define yesno(y,n)void y(bool f=1){out(f?#y:#n);}void n(bool f=1){y(!f);}\nyesno(Yes,No)\ntemplate<class T>\nstruct coord_comp{\n\tvc<T>v;\n\tbool built=0;\n\tcoord_comp(){}\n\tcoord_comp(const vc<T>&a){init(a);}\n\ttemplate<class A>void init(const A&a){\n\t\tint n=len(a);\n\t\tv.resize(n);\n\t\trep(i,n)v[i]=a[i];\n\t\tbuilt=0;\n\t}\n\tvoid add(T x){v.pb(x),built=0;}\n\tvoid build(){\n\t\tif(built)return;\n\t\tbuilt=1;\n\t\tUNIQUE(v);\n\t}\n\tll size(){build();return len(v);}\n\ttemplate<bool strict=0>int operator()(T x){\n\t\tbuild();\n\t\tint i=LBI(v,x);\n\t\tif constexpr(strict)assert(0<=i&&i<len(v)&&v[i]==x);\n\t\treturn i;\n\t}\n\tint lower_bound(T x){build();return LBI(v,x);}\n\tT operator[](int i){\n\t\tassert(0<=i&&i<size());\n\t\treturn v[i];\n\t}\n};\ntemplate<class T>\nstruct cumsum2d_dual{\n\tint n=0,m=0;\n\tvvc<T>d,s;\n\tbool built=0;\n\tcumsum2d_dual(){}\n\tcumsum2d_dual(int n,int m){init(n,m);}\n\tcumsum2d_dual(int n,int m,T x){init(n,m,x);}\n\tcumsum2d_dual(const vvc<T>&a){init(a);}\n\ttemplate<class U>cumsum2d_dual(const vvc<U>&a){init(a);}\n\ttemplate<class F>cumsum2d_dual(int n,int m,F f){init(n,m,f);}\n\tvoid init(int n,int m){\n\t\tthis->n=n;\n\t\tthis->m=m;\n\t\td.assign(n,vc<T>(m));\n\t\tbuilt=0;\n\t}\n\tvoid init(int n,int m,T x){\n\t\tinit(n,m);\n\t\tif(n>0&&m>0)d[0][0]=x;\n\t}\n\ttemplate<class U>void init(const vvc<U>&a){\n\t\tinit(len(a),len(a[0]),[&](int i,int j){return a[i][j];});\n\t}\n\ttemplate<class F>void init(int n,F f){\n\t\tinit(n,m);\n\t\trep(i,n)rep(j,m)d[i][j]=f(i,j);\n\t\trep(i,n)rep(j,m-1)d[i][j+1]-=d[i][j];\n\t\trep(i,n-1)rep(j,m)d[i+1][j]-=d[i][j];\n\t}\n\tvoid build(){\n\t\tif(built)return;\n\t\tbuilt=1;\n\t\ts=d;\n\t\trep(i,n)rep(j,m-1)s[i][j+1]+=s[i][j];\n\t\trep(i,n-1)rep(j,m)s[i+1][j]+=s[i][j];\n\t}\n\tconst vc<T>&operator[](int i){\n\t\tassert(0<=i&&i<n);\n\t\tbuild();\n\t\treturn s[i];\n\t}\n\tT get(int i,int j){return (*this)[i][j];}\n\tconst vvc<T>&get_all(){build();return s;}\n\ttemplate<bool strict=1>\n\tvoid add(int i,int j,T v){\n\t\tif constexpr(strict)assert(0<=i&&i<=n&&0<=j&&j<=m);\n\t\telse chmax(i,0),chmax(j,0);\n\t\tif(i<n&&j<m)d[i][j]+=v,built=0;\n\t}\n\ttemplate<bool strict=1>\n\tvoid add(int xl,int xr,int yl,int yr,T v){\n\t\tif constexpr(strict){\n\t\t\tassert(0<=xl&&xl<=xr&&xr<=n);\n\t\t\tassert(0<=yl&&yl<=yr&&yr<=m);\n\t\t}\n\t\tif(xr<=xl||xr<=0||n<=xl)return;\n\t\tif(yr<=yl||yr<=0||m<=yl)return;\n\t\tadd(xl,yl,v);\n\t\tadd(xl,yr,-v);\n\t\tadd(xr,yl,-v);\n\t\tadd(xr,yr,v);\n\t}\n};\nint main(){\n\tINT(n);\n\tvc<tuple<int,int,int,int>>p(n);\n\tcin>>p;\n\tcoord_comp<int>comp_x,comp_y;\n\titer(a,b,c,d,p){\n\t\tcomp_x.add(a);\n\t\tcomp_x.add(c);\n\t\tcomp_y.add(b);\n\t\tcomp_y.add(d);\n\t}\n\tint h=len(comp_x)-1,w=len(comp_y)-1;\n\tcumsum2d_dual<int>s(h,w);\n\titer(a,b,c,d,p){\n\t\ta=comp_x(a);\n\t\tb=comp_y(b);\n\t\tc=comp_x(c);\n\t\td=comp_y(d);\n\t\ts.add(a,c,b,d,1);\n\t}\n\tll ans=0;\n\trep(i,h)rep(j,w)if(s[i][j]){\n\t\tans+=(comp_x[i+1]-comp_x[i])*ll(comp_y[j+1]-comp_y[j]);\n\t}\n\tout(ans);\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 128364, "score_of_the_acc": -0.6681, "final_rank": 8 }, { "submission_id": "aoj_DSL_4_A_10462030", "code_snippet": "// #include <atcoder/all>\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconstexpr ll inf = (1LL << 61);\nll dx[4] = {0, 1, 0, -1};\nll dy[4] = {-1, 0, 1, 0};\n#define rep(i, n) for (ll i = 0; i < (ll)(n); ++i)\n#define REP(i, init, n) for (ll i = (ll)init; i < (ll)(n); ++i)\n// ll op(ll a, ll b) { return min(a, b); }\n// ll e() { return inf; }\n\nauto comp(vector<int>& v1, vector<int>& v2) {\n vector<int> ret;\n ll n = v1.size();\n rep(i, n) {\n rep(j, 2) {\n ret.push_back(v1[i] + j);\n ret.push_back(v2[i] + j);\n }\n }\n sort(ret.begin(), ret.end());\n ret.erase(unique(ret.begin(), ret.end()), ret.end());\n rep(i, n) {\n v1[i] = lower_bound(ret.begin(), ret.end(), v1[i]) - ret.begin();\n v2[i] = lower_bound(ret.begin(), ret.end(), v2[i]) - ret.begin();\n }\n return ret;\n}\n\nint main() {\n ll n;\n cin >> n;\n vector<int> x1(n), x2(n), y1(n), y2(n);\n rep(i, n) cin >> x1[i] >> y1[i] >> x2[i] >> y2[i];\n auto vx = comp(x1, x2);\n auto vy = comp(y1, y2);\n ll X = vx.size(), Y = vy.size();\n vector<vector<int>> g(X + 1, vector<int>(Y + 1, 0));\n rep(i, n) {\n g[x1[i]][y1[i]]++;\n g[x1[i]][y2[i]]--;\n g[x2[i]][y1[i]]--;\n g[x2[i]][y2[i]]++;\n }\n rep(i, X) rep(j, Y + 1) g[i + 1][j] += g[i][j];\n rep(i, Y) rep(j, X + 1) g[j][i + 1] += g[j][i];\n ll ans = 0;\n rep(i, X - 1) {\n rep(j, Y - 1) {\n if (g[i][j] != 0) {\n ans += (ll)(vx[i + 1] - vx[i]) * (vy[j + 1] - vy[j]);\n }\n }\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 540, "memory_kb": 253508, "score_of_the_acc": -1.9982, "final_rank": 18 }, { "submission_id": "aoj_DSL_4_A_10216274", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<long long> compress(vector<long long> &c1, vector<long long> &c2){\n vector<long long> res;\n int n = c1.size();\n for(int i = 0; i < n; i++){\n for(int j = 0; j < 2; j++){\n long long t1 = c1[i] + j;\n long long t2 = c2[i] + j;\n res.push_back(t1);\n res.push_back(t2);\n }\n }\n sort(res.begin(), res.end());\n res.erase(unique(res.begin(), res.end()), res.end());\n for(int i = 0; i < n; i++){\n c1[i] = lower_bound(res.begin(), res.end(), c1[i]) - res.begin();\n c2[i] = lower_bound(res.begin(), res.end(), c2[i]) - res.begin();\n }\n return res;\n}\n\nint main(){\n int n; cin>>n;\n vector<long long> x1(n), x2(n), y1(n), y2(n);\n for(int i = 0; i < n; i++){\n cin>>x1[i]>>y1[i]>>x2[i]>>y2[i];\n }\n \n vector<long long> x = compress(x1, x2);\n vector<long long> y = compress(y1, y2);\n \n int w = x.size();\n int h = y.size();\n \n vector<vector<int>> imos(w + 1, vector<int>(h + 1, 0));\n for(int i = 0; i < n; i++){\n imos[x1[i]][y1[i]]++;\n imos[x2[i]][y2[i]]++;\n imos[x1[i]][y2[i]]--;\n imos[x2[i]][y1[i]]--;\n }\n \n for(int i = 1; i < w; i++) for(int j = 0; j < h; j++) imos[i][j] += imos[i - 1][j];\n for(int i = 0; i < w; i++) for(int j = 1; j < h; j++) imos[i][j] += imos[i][j - 1];\n \n long long ans = 0;\n for(int i = 0; i < w - 1; i++) for(int j = 0; j < h - 1; j++){\n if(imos[i][j]) ans += (x[i + 1] - x[i]) * (y[j + 1] - y[j]);\n }\n cout << ans << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 253616, "score_of_the_acc": -1.4138, "final_rank": 14 }, { "submission_id": "aoj_DSL_4_A_10216245", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<long long> compress(vector<long long> &c1, vector<long long> &c2){\n vector<long long> res;\n int n = c1.size();\n for(int i = 0; i < n; i++){\n for(long long j = 0; j < 2; j++){\n long long t1 = c1[i] + j;\n long long t2 = c2[i] + j;\n res.push_back(t1);\n res.push_back(t2);\n }\n }\n sort(res.begin(), res.end());\n res.erase(unique(res.begin(), res.end()), res.end());\n for(int i = 0; i < n; i++){\n c1[i] = lower_bound(res.begin(), res.end(), c1[i]) - res.begin();\n c2[i] = lower_bound(res.begin(), res.end(), c2[i]) - res.begin();\n }\n return res;\n}\n\nint main(){\n int n; cin>>n;\n vector<long long> x1(n), y1(n), x2(n), y2(n);\n for(int i = 0; i < n; i++){\n cin>>x1[i]>>y1[i]>>x2[i]>>y2[i];\n }\n vector<long long> x = compress(x1, x2);\n vector<long long> y = compress(y1, y2);\n \n int w = x.size();\n int h = y.size();\n \n vector<vector<int>> imos(w, vector<int>(h, 0));\n for(int i = 0; i < n; i++){\n imos[x1[i]][y1[i]]++;\n imos[x1[i]][y2[i]]--;\n imos[x2[i]][y1[i]]--;\n imos[x2[i]][y2[i]]++;\n }\n \n for(int i = 1; i < w; i++) for(int j = 0; j < h; j++){\n imos[i][j] += imos[i - 1][j];\n }\n for(int i = 0; i < w; i++) for(int j = 1; j < h; j++){\n imos[i][j] += imos[i][j - 1];\n }\n \n long long ans = 0;\n \n for(int i = 0; i < w - 1; i++) for(int j = 0; j < h - 1; j++){\n if(imos[i][j]) ans += (x[i + 1] - x[i]) * (y[j + 1] - y[j]);\n }\n \n cout << ans << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 253624, "score_of_the_acc": -1.4515, "final_rank": 16 }, { "submission_id": "aoj_DSL_4_A_10216238", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntemplate <typename T>\nvector<T> compress(vector<T> &C1, vector<T> &C2) {\n vector<T> vals;\n int N = (int)C1.size();\n for (int i = 0; i < N; i++) {\n for (T d = 0; d <= 1; d++) {\n T tc1 = C1[i] + d;\n T tc2 = C2[i] + d;\n vals.push_back(tc1);\n vals.push_back(tc2);\n }\n }\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n for (int i = 0; i < N; i++) {\n C1[i] = lower_bound(vals.begin(), vals.end(), C1[i]) - vals.begin();\n C2[i] = lower_bound(vals.begin(), vals.end(), C2[i]) - vals.begin();\n }\n return vals;\n}\n\nint main(){\n int n; cin>>n;\n vector<long long> x1(n), y1(n), x2(n), y2(n);\n for(int i = 0; i < n; i++){\n cin>>x1[i]>>y1[i]>>x2[i]>>y2[i];\n }\n vector<long long> x = compress(x1, x2);\n vector<long long> y = compress(y1, y2);\n \n int w = x.size();\n int h = y.size();\n \n vector<vector<int>> imos(w, vector<int>(h, 0));\n for(int i = 0; i < n; i++){\n imos[x1[i]][y1[i]]++;\n imos[x1[i]][y2[i]]--;\n imos[x2[i]][y1[i]]--;\n imos[x2[i]][y2[i]]++;\n }\n \n for(int i = 1; i < w; i++) for(int j = 0; j < h; j++){\n imos[i][j] += imos[i - 1][j];\n }\n for(int i = 0; i < w; i++) for(int j = 1; j < h; j++){\n imos[i][j] += imos[i][j - 1];\n }\n \n long long ans = 0;\n \n for(int i = 0; i < w - 1; i++) for(int j = 0; j < h - 1; j++){\n if(imos[i][j]) ans += (x[i + 1] - x[i]) * (y[j + 1] - y[j]);\n }\n \n cout << ans << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 253616, "score_of_the_acc": -1.4138, "final_rank": 14 }, { "submission_id": "aoj_DSL_4_A_10216176", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntemplate <typename T>\nvector<T> compress(vector<T> &C1, vector<T> &C2) {\n vector<T> vals;\n int N = (int)C1.size();\n for (int i = 0; i < N; i++) {\n for (T d = 0; d <= 1; d++) {\n T tc1 = C1[i] + d;\n T tc2 = C2[i] + d;\n vals.push_back(tc1);\n vals.push_back(tc2);\n }\n }\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n for (int i = 0; i < N; i++) {\n C1[i] = lower_bound(vals.begin(), vals.end(), C1[i]) - vals.begin();\n C2[i] = lower_bound(vals.begin(), vals.end(), C2[i]) - vals.begin();\n }\n return vals;\n}\n\nint main(){\n int n; cin>>n;\n vector<long long> x1(n), x2(n), y1(n), y2(n);\n for(int i = 0; i < n; i++){\n cin>>x1[i]>>y1[i]>>x2[i]>>y2[i];\n }\n vector<long long> x = compress(x1, x2);\n vector<long long> y = compress(y1, y2);\n \n int w = (int)x.size();\n int h = (int)y.size();\n \n vector<vector<int>> imos(w, vector<int>(h, 0));\n\n for(int i = 0; i < n; i++){\n imos[x1[i]][y1[i]]++;\n imos[x1[i]][y2[i]]--;\n imos[x2[i]][y1[i]]--;\n imos[x2[i]][y2[i]]++;\n }\n\n for(int i = 1; i < w; i++) for(int j = 0; j < h; j++){\n imos[i][j] += imos[i - 1][j];\n }\n for(int i = 0; i < w; i++) for(int j = 1; j < h; j++){\n imos[i][j] += imos[i][j - 1];\n }\n \n long long ans = 0;\n for(int i = 0; i < w - 1; i++) for(int j = 0; j < h - 1; j++){\n if(imos[i][j]) ans += (x[i + 1] - x[i]) * (y[j + 1] - y[j]);\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 253512, "score_of_the_acc": -1.4133, "final_rank": 12 } ]
aoj_DSL_5_B_cpp
The Maximum Number of Overlaps Given a set of $N$ axis-aligned rectangular seals, find the number of overlapped seals on the region which has the maximum number of overlapped seals. Input The input is given in the following format. $N$ $x1_1$ $y1_1$ $x2_1$ $y2_1$ $x1_2$ $y1_2$ $x2_2$ $y2_2$ : $x1_N$ $y1_N$ $x2_N$ $y2_N$ ($x1_i, y1_i$) and ($x2_i, y2_i$) are the coordinates of the top-left and the bottom-right corner of the $i$-th seal respectively. Constraints $ 1 \leq N \leq 100000 $ $ 0 \leq x1_i < x2_i \leq 1000 $ $ 0 \leq y1_i < y2_i \leq 1000 $ $ x1_i, y1_i, x2_i, y2_i$ are given in integers Output Print the maximum number of overlapped seals in a line. Sample Input 1 2 0 0 3 2 2 1 4 3 Sample Output 1 2 Sample Input 2 2 0 0 2 2 2 0 4 2 Sample Output 2 1 Sample Input 3 3 0 0 2 2 0 0 2 2 0 0 2 2 Sample Output 3 3
[ { "submission_id": "aoj_DSL_5_B_11044734", "code_snippet": "// --- Start of include: ./../../akakoi_lib/template/template.cpp ---\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i,n) for(ll i=0;i<(ll)(n);++i)\nbool chmax(int& a, int b) {return a<b?a=b,1:0;}\n// int main() {\n// ios::sync_with_stdio(false);\n// cin.tie(0);\n// }\n// --- End of include: ./../../akakoi_lib/template/template.cpp ---\n// --- Start of include: ./../../akakoi_lib/gomi/seg2D_light.cpp ---\ntemplate <class T, T (*op)(T, T), T (*e)()>\nstruct Seg2DLight {\nprivate:\n int h, w, hs, ws;\n vector<vector<T>> data;\n inline int bit_length(int x) {\n return x ? 32 - __builtin_clz(x) : 0;\n }\npublic:\n Seg2DLight(int h, int w) : h(h), w(w) {\n hs = 1<<bit_length(h);\n ws = 1<<bit_length(w);\n data.resize(hs*2, vector<T>(ws*2, e()));\n }\n void build(vector<vector<T>> a) {\n rep(i, h) rep(j, w) { data[i+hs][j+ws] = a[i][j]; }\n for (int i = hs; i < hs+h; ++i) {\n for (int j = ws-1; j > 0; --j) {\n data[i][j] = op(data[i][j<<1], data[i][j<<1|1]);\n }\n }\n for (int i = hs-1; i > 0; --i) {\n for (int j = 1; j < ws*2; ++j) {\n data[i][j] = op(data[i<<1][j], data[i<<1|1][j]);\n }\n }\n }\n T get(int y, int x) { return data[y+hs][x+ws]; }\n void set(int y, int x, T v) {\n assert(0 <= y && y < h); assert(0 <= x && x < w);\n y += hs; x += ws;\n data[y][x] = v;\n for (int nx = x; nx > 1; nx >>= 1) {\n data[y][nx>>1] = op(data[y][nx], data[y][nx^1]);\n }\n for (int ny = y; ny > 1; ny >>= 1) {\n int nx = x;\n data[ny>>1][nx] = op(data[ny][nx], data[ny^1][nx]);\n for (nx >>= 1; nx >= 1; nx >>= 1) {\n data[ny>>1][nx] = op(data[ny>>1][nx<<1], data[ny>>1][nx<<1|1]);\n }\n }\n }\n T prod(int u, int d, int l, int r) {\n assert(0 <= u && u <= d && d <= h);\n assert(0 <= l && l <= r && r <= w);\n u += hs; d += hs;\n l += ws; r += ws;\n T ans = e();\n auto pw = [&] (vector<T> &dat) -> void {\n int nl = l, nr = r;\n while (nl < nr) {\n if (nl & 1) ans = op(ans, dat[nl++]);\n if (nr & 1) ans = op(ans, dat[--nr]);\n nl >>= 1; nr >>= 1;\n }\n };\n while (u < d) {\n if (u & 1) pw(data[u++]);\n if (d & 1) pw(data[--d]);\n u >>= 1; d >>= 1;\n }\n return ans;\n }\n};\n// --- End of include: ./../../akakoi_lib/gomi/seg2D_light.cpp ---\n\nint op(int s, int t) { return s + t; }\nint e() { return 0; }\n\nvoid solve() {\n int n; cin >> n;\n int M = 1001;\n Seg2DLight<int, op, e> seg(M, M);\n vector<vector<int>> A(M, vector<int>(M, 1));\n seg.build(A);\n rep(i, M) rep(j, M) {\n seg.set(i, j, 0);\n }\n\n rep(i, n) {\n int a, b, c, d; cin >> a >> b >> c >> d;\n seg.set(a, b, seg.get(a, b) + 1);\n seg.set(a, d, seg.get(a, d) - 1);\n seg.set(c, b, seg.get(c, b) - 1);\n seg.set(c, d, seg.get(c, d) + 1);\n }\n int ans = 0;\n rep(i, M) rep(j, M) {\n chmax(ans, seg.prod(0, i+1, 0, j+1));\n }\n cout << ans << endl;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n solve();\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 27364, "score_of_the_acc": -1.7317, "final_rank": 19 }, { "submission_id": "aoj_DSL_5_B_11044733", "code_snippet": "// --- Start of include: ./../../akakoi_lib/template/template.cpp ---\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i,n) for(ll i=0;i<(ll)(n);++i)\nbool chmin(int& a, int b) {return a>b?a=b,1:0;}\nbool chmax(int& a, int b) {return a<b?a=b,1:0;}\n// int main() {\n// ios::sync_with_stdio(false);\n// cin.tie(0);\n// }\n// --- End of include: ./../../akakoi_lib/template/template.cpp ---\n// --- Start of include: ./../../akakoi_lib/gomi/seg2D_light.cpp ---\ntemplate <class T, T (*op)(T, T), T (*e)()>\nstruct Seg2DLight {\nprivate:\n int h, w, hs, ws;\n vector<vector<T>> data;\n inline int bit_length(int x) {\n return x ? 32 - __builtin_clz(x) : 0;\n }\npublic:\n Seg2DLight(int h, int w) : h(h), w(w) {\n hs = 1<<bit_length(h);\n ws = 1<<bit_length(w);\n data.resize(hs*2, vector<T>(ws*2, e()));\n }\n void build(vector<vector<T>> a) {\n rep(i, h) rep(j, w) { data[i+hs][j+ws] = a[i][j]; }\n for (int i = hs; i < hs+h; ++i) {\n for (int j = ws-1; j > 0; --j) {\n data[i][j] = op(data[i][j<<1], data[i][j<<1|1]);\n }\n }\n for (int i = hs-1; i > 0; --i) {\n for (int j = 1; j < ws*2; ++j) {\n data[i][j] = op(data[i<<1][j], data[i<<1|1][j]);\n }\n }\n }\n T get(int y, int x) { return data[y+hs][x+ws]; }\n void set(int y, int x, T v) {\n assert(0 <= y && y < h); assert(0 <= x && x < w);\n y += hs; x += ws;\n data[y][x] = v;\n for (int nx = x; nx > 1; nx >>= 1) {\n data[y][nx>>1] = op(data[y][nx], data[y][nx^1]);\n }\n for (int ny = y; ny > 1; ny >>= 1) {\n int nx = x;\n data[ny>>1][nx] = op(data[ny][nx], data[ny^1][nx]);\n for (nx >>= 1; nx >= 1; nx >>= 1) {\n data[ny>>1][nx] = op(data[ny>>1][nx<<1], data[ny>>1][nx<<1|1]);\n }\n }\n }\n T prod(int u, int d, int l, int r) {\n assert(0 <= u && u <= d && d <= h);\n assert(0 <= l && l <= r && r <= w);\n u += hs; d += hs;\n l += ws; r += ws;\n T ans = e();\n auto pw = [&] (vector<T> &dat) -> void {\n int nl = l, nr = r;\n while (nl < nr) {\n if (nl & 1) ans = op(ans, dat[nl++]);\n if (nr & 1) ans = op(ans, dat[--nr]);\n nl >>= 1; nr >>= 1;\n }\n };\n while (u < d) {\n if (u & 1) pw(data[u++]);\n if (d & 1) pw(data[--d]);\n u >>= 1; d >>= 1;\n }\n return ans;\n }\n};\n// --- End of include: ./../../akakoi_lib/gomi/seg2D_light.cpp ---\n\nint op(int s, int t) { return s + t; }\nint e() { return 0; }\n\nvoid solve() {\n int n; cin >> n;\n int M = 1000;\n Seg2DLight<int, op, e> seg(M, M);\n vector<vector<int>> A(M, vector<int>(M, 1));\n seg.build(A);\n rep(i, M) rep(j, M) {\n seg.set(i, j, 0);\n }\n\n rep(i, n) {\n int a, b, c, d; cin >> a >> b >> c >> d;\n seg.set(a, b, seg.get(a, b) + 1);\n seg.set(a, d, seg.get(a, d) - 1);\n seg.set(c, b, seg.get(c, b) - 1);\n seg.set(c, d, seg.get(c, d) + 1);\n }\n int ans = 0;\n rep(i, M) rep(j, M) {\n chmax(ans, seg.prod(0, i+1, 0, j+1));\n }\n cout << ans << endl;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n solve();\n}", "accuracy": 0.23333333333333334, "time_ms": 220, "memory_kb": 27360, "score_of_the_acc": -1.5093, "final_rank": 20 }, { "submission_id": "aoj_DSL_5_B_10996293", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vec<vv<T>>;\ntemplate <class T> using minpq = priority_queue<T, vec<T>, greater<T>>;\n#define rep(i, r) for (ll i = 0; i < (r); i++)\n#define reps(i, l, r) for (ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for (ll i = (r) - 1; i >= l; i--)\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\ntemplate <typename T>\nbool chmax(T& a, const T& b) {\n return a < b ? a = b, true : false;\n}\ntemplate <typename T>\nbool chmin(T& a, const T& b) {\n return a > b ? a = b, true : false;\n}\ntemplate <typename T>\nstruct BIT2d {\n ll h, w;\n vv<T> bit;\n BIT2d(ll H, ll W) : h(H + 1), w(W + 1) {\n bit.resize(h + 3, vec<T>(w + 3, T(0)));\n }\n void add(ll x, ll y, T c) {\n if (x < 0 || x >= h || y < 0 || y >= w) return;\n for (ll a = (++y, ++x); a <= h; a += a & -a) {\n for (ll b = y; b <= w; b += b & -b) {\n bit[a][b] += c;\n }\n }\n }\n void imos(ll x1, ll y1, ll x2, ll y2, T c) {\n add(x1, y1, c);\n add(x1, y2, -c);\n add(x2, y1, -c);\n add(x2, y2, c);\n }\n T sum(ll x, ll y) {\n if (x <= 0 || y <= 0) return T(0);\n if (x > h) x = h;\n if (y > w) y = w;\n T ret = 0;\n for (ll a = (y, x); a > 0; a -= a & -a) {\n for (ll b = y; b > 0; b -= b & -b) {\n ret += bit[a][b];\n }\n }\n\t\treturn ret;\n }\n T sum(ll x1, ll y1, ll x2, ll y2) {\n if (x1 > x2 || y1 > y2) return T(0);\n return sum(x2, y2) - sum(x2, y1) - sum(x1, y2) + sum(x1, y1);\n }\n};\nvoid solve() {\n ll n; cin >> n;\n\tBIT2d<ll> bit(1010, 1010);\n\trep(i, n) {\n\t\tll x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;\n\t\t// cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;\n\t\tbit.imos(x1, y1, x2, y2, 1);\n\t}\n\tll ans = 0;\n\trep(i, 1011) rep(j, 1011) {\n\t\t// cout << bit.sum(i, j) << \" \\n\"[j == 99];\n\t\tchmax(ans, bit.sum(i, j));\n\t}\n\tcout << ans << endl;\n}\nint main() {\n ll T = 1;\n // cin >> T;\n while (T--) solve();\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 11392, "score_of_the_acc": -0.3047, "final_rank": 10 }, { "submission_id": "aoj_DSL_5_B_10996292", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vec<vv<T>>;\ntemplate <class T> using minpq = priority_queue<T, vec<T>, greater<T>>;\n#define rep(i, r) for (ll i = 0; i < (r); i++)\n#define reps(i, l, r) for (ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for (ll i = (r) - 1; i >= l; i--)\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\ntemplate <typename T>\nbool chmax(T& a, const T& b) {\n return a < b ? a = b, true : false;\n}\ntemplate <typename T>\nbool chmin(T& a, const T& b) {\n return a > b ? a = b, true : false;\n}\ntemplate <typename T>\nstruct BIT2d {\n ll h, w;\n vv<T> bit;\n BIT2d(ll H, ll W) : h(H + 1), w(W + 1) {\n bit.resize(h + 3, vec<T>(w + 3, T(0)));\n }\n void add(ll x, ll y, T c) {\n if (x < 0 || x >= h || y < 0 || y >= w) return;\n for (ll a = (++y, ++x); a <= h; a += a & -a) {\n for (ll b = y; b <= w; b += b & -b) {\n bit[a][b] += c;\n }\n }\n }\n void imos(ll x1, ll y1, ll x2, ll y2, T c) {\n add(x1, y1, c);\n add(x1, y2, -c);\n add(x2, y1, -c);\n add(x2, y2, c);\n }\n T sum(ll x, ll y) {\n if (x < 0 || y < 0) return T(0);\n if (x > h) x = h;\n if (y > w) y = w;\n T ret = 0;\n for (ll a = (y, x); a > 0; a -= a & -a) {\n for (ll b = y; b > 0; b -= b & -b) {\n ret += bit[a][b];\n }\n }\n\t\treturn ret;\n }\n T sum(ll x1, ll y1, ll x2, ll y2) {\n if (x1 > x2 || y1 > y2) return T(0);\n return sum(x2, y2) - sum(x2, y1 - 1) - sum(x1 - 1, y2) + sum(x1 - 1, y1 - 1);\n }\n};\nvoid solve() {\n ll n; cin >> n;\n\tBIT2d<ll> bit(1010, 1010);\n\trep(i, n) {\n\t\tll x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;\n\t\t// cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;\n\t\tbit.imos(x1, y1, x2, y2, 1);\n\t}\n\tll ans = 0;\n\trep(i, 1010) rep(j, 1010) {\n\t\t// cout << bit.sum(i, j) << \" \\n\"[j == 99];\n\t\tchmax(ans, bit.sum(i, j));\n\t}\n\tcout << ans << endl;\n}\nint main() {\n ll T = 1;\n // cin >> T;\n while (T--) solve();\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 11392, "score_of_the_acc": -0.3047, "final_rank": 10 }, { "submission_id": "aoj_DSL_5_B_10996290", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vec<vv<T>>;\ntemplate <class T> using minpq = priority_queue<T, vec<T>, greater<T>>;\n#define rep(i, r) for (ll i = 0; i < (r); i++)\n#define reps(i, l, r) for (ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for (ll i = (r) - 1; i >= l; i--)\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\ntemplate <typename T>\nbool chmax(T& a, const T& b) {\n return a < b ? a = b, true : false;\n}\ntemplate <typename T>\nbool chmin(T& a, const T& b) {\n return a > b ? a = b, true : false;\n}\ntemplate <typename T>\nstruct BIT2d {\n ll h, w;\n vv<T> bit;\n BIT2d(ll H, ll W) : h(H + 1), w(W + 1) {\n bit.resize(h + 3, vec<T>(w + 3, T(0)));\n }\n void add(ll x, ll y, T c) {\n if (x < 0 || x >= h || y < 0 || y >= w) return;\n for (ll a = (++y, ++x); a <= h; a += a & -a) {\n for (ll b = y; b <= w; b += b & -b) {\n bit[a][b] += c;\n }\n }\n }\n void imos(ll x1, ll y1, ll x2, ll y2, T c) {\n add(x1, y1, c);\n add(x1, y2, -c);\n add(x2, y1, -c);\n add(x2, y2, c);\n }\n T sum(ll x, ll y) {\n if (x < 0 || y < 0) return T(0);\n if (x >= h) x = h - 1;\n if (y >= w) y = w - 1;\n T ret = 0;\n for (ll a = (++y, ++x); a > 0; a -= a & -a) {\n for (ll b = y; b > 0; b -= b & -b) {\n ret += bit[a][b];\n }\n }\n\t\treturn ret;\n }\n T sum(ll x1, ll y1, ll x2, ll y2) {\n if (x1 > x2 || y1 > y2) return T(0);\n return sum(x2, y2) - sum(x2, y1 - 1) - sum(x1 - 1, y2) + sum(x1 - 1, y1 - 1);\n }\n};\nvoid solve() {\n ll n; cin >> n;\n\tBIT2d<ll> bit(1010, 1010);\n\trep(i, n) {\n\t\tll x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;\n\t\t// cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;\n\t\tbit.imos(x1, y1, x2, y2, 1);\n\t}\n\tll ans = 0;\n\trep(i, 1010) rep(j, 1010) {\n\t\t// cout << bit.sum(i, j) << \" \\n\"[j == 99];\n\t\tchmax(ans, bit.sum(i, j));\n\t}\n\tcout << ans << endl;\n}\nint main() {\n ll T = 1;\n // cin >> T;\n while (T--) solve();\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 11392, "score_of_the_acc": -0.3047, "final_rank": 10 }, { "submission_id": "aoj_DSL_5_B_10994492", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* compress\n X を座圧して書き換える\n 返り値: val(val[i]=座圧後のiの元の値)\n 計算量: O(n log n)\n*/\ntemplate <typename T>\nvc<T> compress(vector<T> &X) {\n vc<T> vals = X;\n sort(all(vals));\n vals.erase(unique(all(vals)), vals.en);\n for(auto &xi: X) xi = lower_bound(all(vals), xi) - vals.bg;\n return vals;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n \tcin.tie(0);\n int n; cin >> n;\n vi x1s(n),y1s(n),x2s(n),y2s(n),xs,ys;\n rep(i,n){\n cin >> x1s[i] >> y1s[i] >> x2s[i] >> y2s[i];\n xs.pb(x1s[i]);\n xs.pb(x2s[i]);\n ys.pb(y1s[i]);\n ys.pb(y2s[i]);\n }\n vi orix=compress(xs), oriy=compress(ys);\n for(auto &xi: x1s) xi = lower_bound(all(orix), xi) - orix.bg;\n for(auto &xi: x2s) xi = lower_bound(all(orix), xi) - orix.bg;\n for(auto &yi: y1s) yi = lower_bound(all(oriy), yi) - oriy.bg;\n for(auto &yi: y2s) yi = lower_bound(all(oriy), yi) - oriy.bg;\n int H=sz(orix),W=sz(oriy);\n vvll grid(H,vll(W));\n rep(i,n){\n int x1=x1s[i],y1=y1s[i],x2=x2s[i],y2=y2s[i];\n grid[x1][y1]++;\n grid[x2][y1]--;\n grid[x1][y2]--;\n grid[x2][y2]++;\n }\n rep(i,H)rep(j,W-1) grid[i][j+1]+=grid[i][j];\n rep(i,H-1)rep(j,W) grid[i+1][j]+=grid[i][j];\n ll ans=0;\n rep(i,H-1)rep(j,W-1)chmax(ans,grid[i][j]);\n cout << ans << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 15392, "score_of_the_acc": -0.4487, "final_rank": 14 }, { "submission_id": "aoj_DSL_5_B_10940508", "code_snippet": "// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3\")\n// #pragma GCC optimize(\"unroll-loops\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// #include <atcoder/all>\n// using namespace atcoder;\n\nusing ll = long long;\n#define rep(i, n) for (ll i = 0; i < (ll)(n); ++i)\n\nconst ll dy[] = {-1, 0, 0, 1};\nconst ll dx[] = {0, -1, 1, 0};\n\ntemplate <class T, class T1, class T2> bool isrange(T target, T1 low, T2 high) { return low <= target && target < high; }\ntemplate <class T, class U> T min(const T &t, const U &u) { return t < u ? t : u; }\ntemplate <class T, class U> T max(const T &t, const U &u) { return t < u ? u : t; }\ntemplate <class T, class U> bool chmin(T &t, const U &u) { if (t > u) { t = u; return true; } return false; }\ntemplate <class T, class U> bool chmax(T &t, const U &u) { if (t < u) { t = u; return true; } return false; }\n\n// #include \"titan_cpplib/others/io.cpp\"\n// #include \"titan_cpplib/others/print.cpp\"\n\n\nnamespace titan23 {\n\ntemplate <class T, T (*op)(T, T), T (*e)()>\nclass SegmentTree2D {\nprivate:\n int h, w;\n int hs, ws;\n vector<vector<T>> data;\n\n inline int bit_length(int x) const {\n return x ? 32 - __builtin_clz(x) : 0;\n }\n\npublic:\n SegmentTree2D() {}\n SegmentTree2D(int h, int w) : h(h), w(w) {\n hs = 1<<bit_length(h);\n ws = 1<<bit_length(w);\n data.resize(hs*2, vector<T>(ws*2, e()));\n }\n\n T get(int y, int x) const {\n return data[y+hs][x+ws];\n }\n\n void set(int y, int x, T v) {\n y += hs; x += ws;\n data[y][x] = v;\n for (int nx = x; nx > 1; nx >>= 1) {\n data[y][nx>>1] = op(data[y][nx], data[y][nx^1]);\n }\n for (int ny = y; ny > 1; ny >>= 1) {\n int nx = x;\n data[ny>>1][nx] = op(data[ny][nx], data[ny^1][nx]);\n for (nx >>= 1; nx >= 1; nx >>= 1) {\n data[ny>>1][nx] = op(data[ny>>1][nx << 1], data[ny>>1][nx<<1|1]);\n }\n }\n }\n\n T prod(int u, int d, int l, int r) const {\n assert(0 <= u && u <= d && d <= h);\n assert(0 <= l && l <= r && r <= w);\n u += hs; d += hs;\n l += ws; r += ws;\n T ans = e();\n\n auto prodW = [&] (const vector<T> &dat) -> void {\n int nl = l, nr = r;\n while (nl < nr) {\n if (nl & 1) ans = op(ans, dat[nl++]);\n if (nr & 1) ans = op(ans, dat[--nr]);\n nl >>= 1; nr >>= 1;\n }\n };\n\n while (u < d) {\n if (u & 1) prodW(data[u++]);\n if (d & 1) prodW(data[--d]);\n u >>= 1; d >>= 1;\n }\n return ans;\n }\n};\n} // namespace titan23\n\nint op(int s, int t) { return s + t;}\nint e() { return 0; }\nconst int MAX = 1001;\n\nvoid solve() {\n int n; cin >> n;\n titan23::SegmentTree2D<int, op, e> seg(MAX+1, MAX+1);\n rep(i, n) {\n int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;\n seg.set(y1, x1, seg.get(y1, x1) + 1);\n seg.set(y1, x2, seg.get(y1, x2) - 1);\n seg.set(y2, x1, seg.get(y2, x1) - 1);\n seg.set(y2, x2, seg.get(y2, x2) + 1);\n }\n\n int ans = 0;\n rep(i, MAX) rep(j, MAX) {\n ans = max(ans, seg.prod(0, i+1, 0, j+1));\n }\n cout << ans << endl;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout << fixed << setprecision(15);\n cerr << fixed << setprecision(15);\n\n int t = 1;\n // cin >> t;\n for (int i = 0; i < t; ++i) {\n solve();\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 19544, "score_of_the_acc": -1.0797, "final_rank": 18 }, { "submission_id": "aoj_DSL_5_B_10934318", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint N;\nint S[1001][1001];\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n cin >> N;\n rep(i,N) {\n short x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n ++S[x1][y1], --S[x2][y1], --S[x1][y2], ++S[x2][y2];\n }\n \n rep(i,1001) rep(j,1000) S[i][j + 1] += S[i][j];\n rep(i,1000) rep(j,1001) S[i + 1][j] += S[i][j];\n \n int ans = 0;\n rep(i,1001) rep(j,1001) if(ans < S[i][j]) ans = S[i][j];\n cout << ans << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7368, "score_of_the_acc": -0.0117, "final_rank": 3 }, { "submission_id": "aoj_DSL_5_B_10853871", "code_snippet": "#include \"bits/stdc++.h\"\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\nconst int INT = 1e9;\nconst ll LINF = 1e18;\n\nvoid solve(){\n int N; cin >> N;\n vector<vector<int>> imos(1010,vector<int>(1010,0));\n for(int i = 0; i < N;i++){\n int x1,y1,x2,y2; cin >> x1 >> y1 >> x2 >> y2;\n x1++;y1++;x2++;y2++;\n imos[x1][y1]++;\n imos[x1][y2]--;\n imos[x2][y1]--;\n imos[x2][y2]++;\n }\n int ans = 0;\n for(int i = 1; i< 1010;i++){\n for(int j = 1; j< 1010;j++){\n imos[i][j] += (imos[i-1][j]+imos[i][j-1]-imos[i-1][j-1]);\n ans = max(ans,imos[i][j]);\n }\n }\n cout << ans << endl;\n}\nint main(void){\n cin.tie(0); ios_base::sync_with_stdio(false);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7044, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DSL_5_B_10814030", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n#define elif else if\n#define gcd __gcd\n#define lcm(a,b) (a*b)/gcd(a,b)\n#define pb push_back\n#define vi vector<int>\n#define vpi vector<pair<int,int>>\n#define vvi vector<vector<int>>\n#define pii pair<int,int>\n#define fi first\n#define se second\n#define all(x) x.begin(),x.end()\n#define unique(x) x.erase(unique(all(x)),x.end())\n#define mp map<int,int>\n#define si set<int>\n#define msi multiset<int>\n#define input(x) for(auto &i:x) cin>>i;\n#define print(x) for(auto i:x) cout<<i<<\" \"; cout<<endl;\n#define debugv(v) for(auto i:v) cerr<<i<<\" \"; cerr<<endl;\n#define debug(x) cerr<<#x<<\" = \"<<x<<endl;\nconst int N=2e5+5;\nconst int MOD=1e9+7;\nconst int MOD2=998244353;\nconst int INF=1e18;\n// #include <ext/pb_ds/assoc_container.hpp>\n// #include <ext/pb_ds/tree_policy.hpp>\n// using namespace __gnu_pbds;\n// typedef tree<\n// int,\n// null_type,\n// less<int>,\n// rb_tree_tag,\n// tree_order_statistics_node_update\n// > ordered_set;\n// typedef tree<\n// pair<int,int>,\n// null_type,\n// less<pair<int,int>>,\n// rb_tree_tag,\n// tree_order_statistics_node_update\n// > ordered_multiset;\n\nint ceil_div(int a, int b) {\n return (a + b - 1) / b;\n}\n\nbool sieve[N];\nint hp[N];\nvoid sieve_eratosthenes(){\n sieve[0]=sieve[1]=true;\n for(int i=2;i<N;i++){\n if(sieve[i]==false){\n hp[i]=i;\n for(int j=2*i;j<N;j+=i){\n hp[j]=i;\n sieve[j]=true;\n }\n }\n }\n}\n\nint binmul(int a,int b,int MOD=MOD){\n int ans=0;\n while(b>0){\n if(b&1){\n ans=(ans+a)%MOD;\n }\n a=(a+a)%MOD;\n b>>=1;\n }\n return ans;\n}\n\nint binexp(int a,int b,int MOD=MOD){\n int ans=1;\n while(b>0){\n if(b&1){\n // ans=binmul(ans,a)%MOD;\n ans=(ans*a)%MOD;\n }\n // a=binmul(a,a)%MOD;\n a=(a*a)%MOD;\n b>>=1;\n }\n return ans;\n}\n\nbool comp(pii a, pii b) {\n if(a.fi == b.fi) {\n return a.se<b.se;\n }\n return a.fi < b.fi;\n // if(a.se==b.se) return a.fi<b.fi;\n // return a.se<b.se;\n}\n\nconst int gN=4e3+5;\nvi graph[N];\n\n// #define cerr if(false)cerr\n\nvector<int> riffle( vector<int>& f){\n int N = (int)f.size();\n vector<int> g;\n g.reserve(N);\n for(int i = 0; i < N; i += 2) g.push_back(f[i]); // odd positions in 1-based indexing\n for(int i = 1; i < N; i += 2) g.push_back(f[i]); // even positions in 1-based indexing\n return g;\n}\n\nvoid solve(){\n int nn;\n cin>>nn;\n int n=1000;\n vvi grid(n+1,vi(n+1,0));\n for(int i=1;i<=nn;i++){\n int x1,y1,x2,y2;\n cin>>x1>>y1>>x2>>y2;\n grid[x1][y1]++;\n grid[x2][y2]++;\n grid[x1][y2]--;\n grid[x2][y1]--;\n }\n for(int i=1;i<=n;i++){\n grid[i][0]+=grid[i-1][0];\n grid[0][i]+=grid[0][i-1];\n }\n for(int i=1;i<=n;i++){\n for(int j=1;j<=n;j++){\n grid[i][j] += (grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1]);\n }\n }\n int mx=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n mx=max(mx,grid[i][j]);\n }\n }\n cout<<mx<<endl;\n}\n\nint32_t main(){\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n int t=1;\n // cin>>t;\n while(t--){\n // debug(t);\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 17204, "score_of_the_acc": -0.4029, "final_rank": 13 }, { "submission_id": "aoj_DSL_5_B_10806509", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N=1001;\nint main() {\n\t// your code goes here\n\tint n;\n\tcin>>n;\n\tvector<vector<int>> v(N,vector<int>(N,0));\n\tint x1,y1,x2,y2;\n\tfor(int i=0;i<n;i++){\n\t cin>>x1>>y1>>x2>>y2;\n\t v[x1][y1]++;\n\t v[x2][y1]--;\n\t v[x1][y2]--;\n\t v[x2][y2]++;\n\t}\n\tint ans=0;\n\tfor(int i=0;i<N;i++){\n\t for(int j=0;j<N;j++){\n\t if(i>0){\n\t v[i][j]+=v[i-1][j];\n\t }\n\t if(j>0){\n\t v[i][j]+=v[i][j-1];\n\t }\n\t if(i>0&&j>0){\n\t v[i][j]-=v[i-1][j-1];\n\t }\n\t ans=max(ans,v[i][j]);\n\t }\n\t}\n\tcout<<ans<<endl;\n\t\n\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 7400, "score_of_the_acc": -0.1239, "final_rank": 5 }, { "submission_id": "aoj_DSL_5_B_10448143", "code_snippet": "#define _USE_MATH_DEFINES\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <map>\n\nusing namespace std;\n\ntypedef pair<long long int, long long int> P;\nlong long int INF = 1e18;\n\nint a[1100][1100] = {};\n\nint main(){\n\t\n\tint N;\n\tcin >> N;\n\t\n\tfor(int i = 0; i < N; i++){\n\t\tint x1, y1, x2, y2;\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n\t\ta[x1][y1]++;\n\t\ta[x1][y2]--;\n\t\ta[x2][y1]--;\n\t\ta[x2][y2]++;\n\t}\n\t\n\tfor(int i = 0; i <= 1000; i++){\n\t\tfor(int j = 1; j <= 1000; j++){\n\t\t\ta[i][j] += a[i][j - 1];\n\t\t}\n\t}\n\t\n\tfor(int i = 0; i <= 1000; i++){\n\t\tfor(int j = 1; j <= 1000; j++){\n\t\t\ta[j][i] += a[j - 1][i];\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tfor(int i = 0; i <= 1000; i++){\n\t\tfor(int j = 0; j <= 1000; j++){\n\t\t\tans = max(ans, a[i][j]);\n\t\t}\n\t}\n\tcout << ans << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 7740, "score_of_the_acc": -0.1362, "final_rank": 6 }, { "submission_id": "aoj_DSL_5_B_10358428", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n\nint N;\nint W = 0,H = 0;\n\nint main(){\n //入力\n cin >> N;\n vector<int> x1(N),y1(N),x2(N),y2(N);\n for(int i=0;i< N;i++){\n cin >> x1[i] >> y1[i] >> x2[i] >> y2[i];\n W = max(W,x2[i]);\n H = max(H,y2[i]);\n }\n\n vector<vector<int>> Z(W+2, vector<int>(H+2, 0));\n //各頂点\n for(int i=0;i<N;i++){\n Z[x1[i]][y1[i]] += 1;\n Z[x1[i]][y2[i]] -=1;\n Z[x2[i]][y1[i]] -=1;\n Z[x2[i]][y2[i]] +=1;\n }\n\n //累積和横\n for(int i=0;i<=W;i++){\n for(int j=1;j<=H;j++){\n Z[i][j] += Z[i][j-1];\n }\n }\n //縦\n for(int i=0;i<=H;i++){\n for(int j=1;j<=W;j++){\n Z[j][i] += Z[j-1][i];\n }\n }\n //最大値を求める\n int ans = 0;\n for (int i = 0; i <= W; i++){\n for (int j = 0; j <= H; j++){\n ans = max(ans, Z[i][j]);\n }\n }\n\n cout << ans <<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8600, "score_of_the_acc": -0.1671, "final_rank": 8 }, { "submission_id": "aoj_DSL_5_B_10358394", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n\nint N;\nint W = 0,H = 0;\n\nint main(){\n //入力\n cin >> N;\n vector<int> x1(N),y1(N),x2(N),y2(N);\n for(int i=0;i< N;i++){\n cin >> x1[i] >> y1[i] >> x2[i] >> y2[i];\n W = max(W,x2[i]);\n H = max(H,y2[i]);\n }\n\n vector<vector<int>> Z(H+2, vector<int>(W+2, 0));\n //各頂点\n for(int i=0;i<N;i++){\n Z[y1[i]][x1[i]] += 1;\n Z[y1[i]][x2[i]] -=1;\n Z[y2[i]][x1[i]] -=1;\n Z[y2[i]][x2[i]] +=1;\n }\n\n //累積和横\n for(int i=0;i<=H;i++){\n for(int j=1;j<=W;j++){\n Z[i][j] += Z[i][j-1];\n }\n }\n //縦\n for(int i=0;i<=W;i++){\n for(int j=1;j<=H;j++){\n Z[j][i] += Z[j-1][i];\n }\n }\n //最大値を求める\n int ans = 0;\n for (int i = 0; i <= H; i++){\n for (int j = 0; j <= W; j++){\n ans = max(ans, Z[i][j]);\n }\n }\n\n cout << ans <<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8620, "score_of_the_acc": -0.1679, "final_rank": 9 }, { "submission_id": "aoj_DSL_5_B_10322928", "code_snippet": "#include <atcoder/all>\n#include <bits/stdc++.h>\n#define rep(i, a, b) for (ll i = (ll)(a); i < (ll)(b); i++)\nusing namespace atcoder;\nusing namespace std;\n\ntypedef long long ll;\n\ntemplate <typename T> struct TDS {\n // 区間はすべて半開区間\n int h, w;\n bool rect = false, init = false;\n vector<vector<T>> v, vv, s;\n TDS() {}\n TDS(int h, int w) : h(h), w(w) {\n v = vector<vector<T>>(h, vector<T>(w));\n vv = vector<vector<T>>(h + 1, vector<T>(w + 1));\n }\n void add_point(int i, int j, T c) { v[i][j] += c; }\n void add_point(int li, int ri, int lj, int rj, T c) {\n rect |= true;\n vv[li][lj] += c;\n vv[li][rj] -= c;\n vv[ri][lj] -= c;\n vv[ri][rj] += c;\n }\n void make() {\n init = true;\n s = vector<vector<T>>(h + 1, vector<T>(w + 1));\n if (rect) {\n rect = false;\n vector ss = vector<vector<T>>(h, vector<T>(w));\n rep(i, 0, h) {\n rep(j, 0, w) {\n ss[i][j] = vv[i][j];\n if (j > 0)\n ss[i][j] += ss[i][j - 1];\n }\n }\n rep(j, 0, w) {\n rep(i, 1, h) { ss[i][j] += ss[i - 1][j]; }\n }\n rep(i, 0, h) rep(j, 0, w) add_point(i, j, ss[i][j]);\n }\n rep(i, 0, h) {\n rep(j, 0, w) { s[i + 1][j + 1] = s[i + 1][j] + v[i][j]; }\n }\n rep(j, 0, w) {\n rep(i, 0, h) { s[i + 1][j + 1] += s[i][j + 1]; }\n }\n }\n T sum(int li, int ri, int lj, int rj) {\n if (!init)\n make();\n if (lj >= rj || li >= ri)\n return 0LL;\n T ret = s[ri][rj] - s[ri][lj] - s[li][rj] + s[li][lj];\n return ret;\n }\n};\n\nint main() {\n cin.tie(0);\n cout.tie(0);\n ios::sync_with_stdio(0);\n int n;\n cin >> n;\n TDS<ll> tds(1001, 1001);\n rep(i, 0, n) {\n int lx, ly, rx, ry;\n cin >> lx >> ly >> rx >> ry;\n tds.add_point(lx, rx, ly, ry, 1);\n }\n int ans = 0;\n rep(i, 0, 1001) rep(j, 0, 1001) {\n ans = max(ans, (int)tds.sum(i, i + 1, j, j + 1));\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 34816, "score_of_the_acc": -1.037, "final_rank": 17 }, { "submission_id": "aoj_DSL_5_B_10320592", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\n#define rep(i,n,m) for(int i=(int)(n);i < (int)(m); i++)\n#define repm(i,n,m) for(int i=(int)(n);i >= (int)(m); i--)\n// #define _GLIBCXX_DEBUG\nusing namespace std;\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n int n;\n cin >> n;\n int m = 1001;\n vector<vector<int>> A(m,vector<int>(m,0));\n int x1,y1,x2,y2;\n rep(i,0,n){\n cin >> x1 >> y1 >> x2 >> y2;\n A[x1][y1]++;\n A[x1][y2]--;\n A[x2][y1]--;\n A[x2][y2]++;\n }\n rep(i,1,m)rep(j,0,m){\n A[j][i] += A[j][i-1];\n }\n rep(i,1,m)rep(j,0,m){\n A[i][j] += A[i-1][j];\n }\n int ans = 0;\n rep(i,0,m)rep(j,0,m){\n ans = max(ans,A[i][j]);\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7048, "score_of_the_acc": -0.0372, "final_rank": 4 }, { "submission_id": "aoj_DSL_5_B_10201250", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Aliases\nusing ll = long long int;\nusing lld = long double;\nusing ull = unsigned long long;\n\n// Constants \nconst lld pi = 3.141592653589793238;\nconst ll INF = LLONG_MAX;\nconst ll mod = 1e9 + 7;\nconst int inf = INT_MAX;\n\n// TypeDEf\ntypedef pair<ll, ll> pll;\ntypedef vector<ll> vll;\ntypedef vector<vll> vvll;\ntypedef vector<int> vint;\ntypedef vector<pll> vpll;\ntypedef vector<string> vs;\ntypedef unordered_map<ll, ll> umll;\ntypedef map<ll, ll> mll;\n\n// Macros\n#define ff first\n#define ss second\n#define p_b push_back\n#define p_p pop_back\n#define mp make_pair\n#define For(i, n) for (ll i = 0; i < n; i++)\n#define input(arr) for(ll i=0;i<arr.size();i++)cin>>arr[i];\n#define outputSpace(arr) for(ll i=0;i<arr.size();i++){cout<<arr[i]<<\" \";} cout<<endl;\n#define outputEndl(arr) for(ll i=0;i<arr.size();i++)cout<<arr[i]<<endl;\n#define printYes cout << \"YES\\n\";\n#define printminus1 cout << \"-1\\n\";\n#define print1 cout << \"1\\n\";\n#define print0 cout << \"0\\n\";\n#define printNo cout << \"NO\\n\";\n#define vr(v) v.begin(), v.end()\n#define rv(v) v.end(), v.begin()\n#define sortv(v) sort(v.begin(), v.end())\n#define sumv(v) accumulate(v.begin(), v.end(), 0)\n#define sortvg(v) sort(v.begin(), v.end(), greater<ll>())\n#define reversev(v) reverse(v.begin(), v.end())\n#define reversevIdx(v, i, j) reverse(v.begin() + i, v.begin() + j)\n#define endll '\\n'\n#define sp \" \"\n#define Endl endl;\n\ntemplate <typename T>\nll sumvec(vector<T> v)\n{\nll n = v.size();\nll s = 0;\nFor(i, n) s += v[i];\nreturn s;\n}\n//=============================================================================================================================\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n/////////////////////////////////////// DO NOT TOUCH BEFORE THIS LINE ///////////////////////////////////////////\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// Mathematical functions\nll gcd(ll a, ll b)\n{\nif (b == 0)\nreturn a;\nreturn gcd(b, a % b);\n} //__gcd\nll lcm(ll a, ll b) { return (a / gcd(a, b) * b); }\nll moduloMultiplication(ll a, ll b, ll mod)\n{\nll res = 0;\na %= mod;\nwhile (b)\n{\nif (b & 1)\nres = (res + a) % mod;\nb >>= 1;\n}\nreturn res;\n}\nll powermod(ll x, ll y, ll p)\n{\nll res = 1;\nx = x % p;\nif (x == 0)\nreturn 0;\nwhile (y > 0)\n{\nif (y & 1)\nres = (res * x) % p;\ny = y >> 1;\nx = (x * x) % p;\n}\nreturn res;\n}\n\n// Graph-dfs\n// bool gone[MN];\n// vector<int> adj[MN];\n// void dfs(int loc){\n// gone[loc]=true;\n// for(auto x:adj[loc])if(!gone[x])dfs(x);\n// }\n\n// Sorting\nbool sorta(const pair<ll, ll> &a, const pair<ll, ll> &b) { return (a.second < b.second); }\nbool sortd(const pair<ll, ll> &a, const pair<ll, ll> &b) { return (a.second > b.second); }\n\n// Bits\nstring decToBinary(int n)\n{\nstring s = \"\";\nint i = 0;\nwhile (n > 0)\n{\ns = to_string(n % 2) + s;\nn = n / 2;\ni++;\n}\nreturn s;\n}\nll binaryToDecimal(string n)\n{\nstring num = n;\nll dec_value = 0;\nll base = 1;\nll len = num.length();\nfor (ll i = len - 1; i >= 0; i--)\n{\nif (num[i] == '1')\ndec_value += base;\nbase = base * 2;\n}\nreturn dec_value;\n}\n\n// Check\nbool isPrime(ll n)\n{\nif (n <= 1)\nreturn false;\nif (n <= 3)\nreturn true;\nif (n % 2 == 0 || n % 3 == 0)\nreturn false;\nfor (int i = 5; i * i <= n; i = i + 6)\nif (n % i == 0 || n % (i + 2) == 0)\nreturn false;\nreturn true;\n}\nbool isPowerOfTwo(int n)\n{\nif (n == 0)\nreturn false;\nreturn (n & (n - 1)) == 0;\n}\nbool isPerfectSquare(ll x)\n{\nif (x >= 0)\n{\nll sr = sqrt(x);\nreturn (sr * sr == x);\n}\nreturn false;\n}\n\n// No fucks here Please !!!\n// Code\nbool isSubstring(const std::string &s1, const std::string &s2)\n{\n// Use the find function to search for s1 in s2\nreturn s2.find(s1) != std::string::npos;\n}\nint countdigit(int n)\n{\nint count = 0;\nwhile (n > 0)\n{\ncount++;\nn /= 10;\n}\nreturn count;\n}\nll sumofdigit(ll n)\n{\nll sum = 0;\nwhile (n > 0)\n{\nsum += n % 10;\nn /= 10;\n}\nreturn sum;\n}\n\nll reverse(ll n)\n{\nll r = 0;\nwhile (n > 0)\n{\nr *= 10;\nr += n % 10;\nn /= 10;\n}\nreturn r;\n}\n\n//=================================================SOLVE-ANS===================================================================\n\n// TRY TO USE LL INSTEAD OF INT PLEASE\n\n\nvoid primeFact(int x, map<ll,ll>&m){\nwhile(x%2==0){\nm[2]++;\nx/=2;\n}\nfor(ll i=3;i*i<=x;i++){\nwhile((x%i)==0){\nm[i]++;\nx/=i;\n}\n}\nif(x>1)m[x]++; // for prime no check\n}\n\n\nvector<bool> primeNumber(ll l)\n{\nvector<bool> isprime(l + 1, true);\nvector<ll> prime;\n\nisprime[0] = isprime[1] = false;\nfor (ll i = 2; i*i <= l; ++i)\n{\nif (isprime[i])\n{\nprime.push_back(i);\nfor (ll j = i * i; j <= l; j += i)\nisprime[j] = false;\n}\n}\n\nreturn isprime;\n}\n\nll binexp(ll no, ll power, ll val) {\nif (power == 0) {\nreturn 1;\n}\nll mid = power / 2;\nll u = binexp(no, mid, val);\n\nif (u == -1 || u > val / u) return -1; \nu *= u;\nif (power & 1) {\nif (u > val / no) return -1; \nu *= no;\n}\nreturn u;\n}\n\nll ModuloInv(ll a, ll b, ll m){ // a,m-2,m\nll no=1;\nwhile(b){\nif(b&1){\n// odd\nno= (no * a )%m;\n}\na=(a*a)%m;\nb=b>>1; // half right shift\n}\nreturn no;\n}\n\nvoid incBit(ll val,vector<ll>&ind){\nint i=0;\nwhile(val){\nif(val&1){\nind[i]++;\n}\ni++;\nval=val>>1;\n}\nreturn;\n}\n\n// bool check(ll mid){\n// ll no=mid;\n// for(int i=0;i<n;i++){\n// if(no>=arr[i].first){\n// no+=arr[i].second;\n// }\n// else{\n// return false;\n// }\n// }\n// return true;\n// } \n\n\n// Aggressive COWs\n// int check(ll &mid ,vector<ll>&stalls , ll &k){\n// int n =stalls.size();\n\n// int start=stalls[0];\n// int obt=1;\n// for(;obt<k;obt++){\n// int ind=lower_bound(stalls.begin(),stalls.end(),start+mid)-stalls.begin();\n\n// if(ind==n){\n// return false;\n// }\n// else if(ind<n){\n// start=stalls[ind];\n// }\n// }\n// return obt==k;\n\n// }\n\n\nvoid solve(){\n \n \n ll n=1005;\n ll q;\n cin>>q;\n\n\n vector<vector<int>>adj(n+1,vector<int>(n+1,0));\n vector<vector<int>>arr(n+1,vector<int>(n+1,0));\n\n\n \n while(q--){\n ll x1,y1,x2,y2;\n cin>>x1>>y1>>x2>>y2;\n x1++;\n y1++;\n x2++;\n y2++;\n arr[x1][y1]++;\n arr[x2][y2]++;\n arr[x1][y2]--;\n arr[x2][y1]--;\n }\n\n\n for(int i=1;i<=n;i++){\n for(int j=1;j<=n;j++){\n arr[i][j]+=arr[i-1][j]+arr[i][j-1]-arr[i-1][j-1];\n\n }\n }\n\n\n ll ans=0;\n \n for(int i=0;i<arr.size();i++){\n for(int j=0;j<arr.size();j++){\n ans=max((int)ans,arr[i][j]);\n }\n\n }\n cout<<ans<<endl;\n}\n\n\n\nint main()\n{ \nios::sync_with_stdio(false);\ncin.tie(0);\n// int t;\n// cin>>t;\n// while(t--)\nsolve();\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11012, "score_of_the_acc": -0.1429, "final_rank": 7 }, { "submission_id": "aoj_DSL_5_B_10142189", "code_snippet": "#if __has_include(<atcoder/all>)\n#include<atcoder/all>\nusing namespace atcoder;\nusing mint=modint998244353;\nusing mint1=modint1000000007;\n#endif\n#if __has_include(<ext/pb_ds/assoc_container.hpp>) && __has_include(<ext/pb_ds/tree_policy.hpp>)\n#include<ext/pb_ds/assoc_container.hpp>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\ntemplate<class s,class t>using __gnu_map=tree<s,t,std::less<s>,rb_tree_tag,tree_order_statistics_node_update>;\ntemplate<class s,class t>struct gnu_map:public __gnu_map<s,t>{\n\tusing iterator=typename __gnu_map<s,t>::iterator;\n\titerator get(int64_t idx){return this->find_by_order(idx<0?this->size()-idx:idx);}\n\tsize_t ord(const s&key){return this->order_of_key(key);}\n};\ntemplate<class s>struct gnu_set:public gnu_map<s,null_type>{gnu_map<s,null_type>::iterator operator[](int64_t i){return this->get(i);}};\n#endif\n#include <bits/stdc++.h>\nusing namespace std;\nusing std::cin;\nusing std::cout;\nusing sstream=stringstream;\n#define RET return\n#define int long long\n#define itn long long\n#define fi first\n#define se second\n#define endl '\\n'\n#define sn(i,c) \" \\n\"[i==c];\n#define rsv(n) reserve(n)\n#define pf(a) push_front(a)\n#define pb(a) push_back(a)\n#define eb(...) emplace_back(__VA_ARGS__)\n#define ppf() pop_front()\n#define ppb() pop_back()\n#define pp() pop()\n#define ins(a) insert(a)\n#define emp(...) emplace(__VA_ARGS__)\n#define ers(a) erase(a)\n#define cont(a) contains(a)\n#define mp(f,s) make_pair(f,s)\n#define A(a) begin(a),end(a)\n#define I(a,i) begin(a),begin(a)+(i)\n#define elif(c) else if(c)\n#define _SEL4(_1,_2,_3,_4,name,...) name\n#define _SEL3(_1,_2,_3,name,...) name\n#define _REP4(i,s,n,st) for(int i=(s);i<(n);i+=(st))\n#define _REP3(i,s,n) _REP4(i,s,n,1)\n#define _REP2(i,n) _REP3(i,0,n)\n#define _REP1(n) _REP2(_,n)\n#define _RREP4(i,n,t,s) for(int i=(n);i>=(t);i-=(s))\n#define _RREP3(i,n,t) _RREP4(i,n,t,1)\n#define _RREP2(i,n) _RREP3(i,n,0)\n#define _ITER2(x,a) for(auto&x:a)\n#define _ITER3(x,y,a) for(auto&[x,y]:a)\n#define _CTER2(x,a) for(const auto&x:a)\n#define _CTER3(x,y,a) for(const auto&[x,y]:a)\n#define rep(...) _SEL4(__VA_ARGS__,_REP4,_REP3,_REP2,_REP1)(__VA_ARGS__)\n#define rrep(...) _SEL4(__VA_ARGS__,_RREP4,_RREP3,_RREP2,_REP1)(__VA_ARGS__)\n#define forif(c,...) rep(__VA_ARGS__)if(c)\n#define iter(...) _SEL3(__VA_ARGS__,_ITER3,_ITER2)(__VA_ARGS__)\n#define cter(...) _SEL3(__VA_ARGS__,_CTER3,_CTER2)(__VA_ARGS__)\n#define _LB_BEX(b,e,x) lower_bound(b,e,x)\n#define _LB_BEXG(b,e,x,g) lower_bound(b,e,x,g)\n#define _UB_BEX(b,e,x) upper_bound(b,e,x)\n#define _UB_BEXG(b,e,x,g) upper_bound(b,e,x,g)\n#define lb(...) _SEL4(__VA_ARGS__,_LB_BEXG,_LB_BEX)(__VA_ARGS__)\n#define ub(...) _SEL4(__VA_ARGS__,_UB_BEXG,_UB_BEX)(__VA_ARGS__)\n#define rev(a) reverse(A(a))\n#define minel(a) min_element(A(a))\n#define maxel(a) max_element(A(a))\n#define acm(a) accumulate(A(a),0ll)\n#define nxpm(a) next_permutation(A(a))\n#define Sort(a) sort(A(a))\n#define uni(a) Sort(a);a.erase(unique(A(a)),a.end())\n#define swapcase(a) a=(isalpha(a)?a^32:a)\n#define NL cout<<'\\n'\ntemplate<class f>using gr=greater<f>;\ntemplate<class f>using vc=vector<f>;\ntemplate<class f>using vv=vc<vc<f>>;\ntemplate<class f>using v3=vv<vc<f>>;\ntemplate<class f>using v4=vv<vv<f>>;\ntemplate<class f>using pq=priority_queue<f>;\ntemplate<class f>using pqg=priority_queue<f, vc<f>, gr<f>>;\n#define uset unordered_set\n#define umap unordered_map\nusing i8=int8_t; using i16=int16_t; using i32=int32_t; using i64=int64_t; using i128=__int128_t;\nusing u8=uint8_t;using u16=uint16_t;using u32=uint32_t;using u64=uint64_t;using u128=__uint128_t;\nusing intw=__int128_t;using uintw=__uint128_t; using it=i32;\nusing f32=float;using f64=double;using f128=long double;\nusing vi=vc<int>;using vb=vc<bool>;\nusing pi=pair<int,int>;\nusing str=string;using vs=vc<str>;\nusing pqgp=pqg<pi>;\n#define double f128\nconstexpr int inf=1ll<<60,minf=-inf;\nconstexpr char sep='\\n';\nconstexpr array<pi,8>dc={{{1,0},{0,1},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}};\ntemplate<class T,class U>inline void chmax(T&a,const U&b){if(a<b)a=b;}\ntemplate<class T,class U>inline void chmin(T&a,const U&b){if(a>b)a=b;}\n#define yes cout<<\"Yes\\n\"\n#define no cout<<\"No\\n\"\n#define yn(c) (c)?yes:no\n#if __cplusplus <= 202002L\n#else\n#define C const\nnamespace vies=std::views;\n#define DR(i) views::drop(i)\n#define TK(i) views::take(i)\n#define RV views::reverse\n#define IOTA vies::iota\n#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)\n#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)\n#define STR(...) str __VA_ARGS__;in(__VA_ARGS__)\n#define VI(a,n) vi a(n);in(a)\n#define VS(a,n) vs a(n);in(a)\n#define UV(u,v) INT(u,v);u--,v--\n#define UVW(u,v,w) INT(u,v,w);u--,v--\ntemplate<integral T,integral U>inline auto ceil(C T a,C U b){return(a+b-1)/b;}\ntemplate<integral T,integral U>inline auto floor(C T a,C U b){return a/b-(a%b&&(a^b)<0);}\ntemplate<class T,class U>concept LUBI= same_as<T,vc<U>>||same_as<T,deque<U>>||is_array_v<T>;\n#define TP template<class T,class U,typename cp=less<U>>\n#define RL requires LUBI<T,U>\nTP u64 lbi(C T&v,C U&x,cp cmp=cp())RL{RET lb(A(v),x,cmp)-begin(v);}\nTP u64 ubi(C T&v,C U&x,cp cmp=cp())RL{RET ub(A(v),x,cmp)-begin(v);}\nTP u64 lbi(u64 i,C T&v,C U&x,cp cmp=cp())RL{RET lb(i+A(v),x,cmp)-begin(v);}\nTP u64 ubi(u64 i,C T&v,C U&x,cp cmp=cp())RL{RET ub(i+A(v),x,cmp)-begin(v);}\nTP u64 lbi(C T&v,u64 i,C U&x,cp cmp=cp())RL{RET lb(I(v,i),x,cmp)-begin(v);}\nTP u64 ubi(C T&v,u64 i,C U&x,cp cmp=cp())RL{RET ub(I(v,i),x,cmp)-begin(v);}\nTP u64 lbi(u64 i,C T&v,u64 e,C U&x,cp cmp=cp())RL{RET lb(i+I(v,e),x,cmp)-begin(v);}\nTP u64 ubi(u64 i,C T&v,u64 e,C U&x,cp cmp=cp())RL{RET ub(i+I(v,e),x,cmp)-begin(v);}\n#undef TP\n#undef RL\n#define TP template\nTP<class T>concept Lint=is_integral_v<T>&&sizeof(T)>8;\nTP<Lint T>ostream&operator<<(ostream&dst,T val){\n\tostream::sentry s(dst);\n\tif(!s)return dst;\n\tchar _O128[64];\n\tchar*d=end(_O128);\n\tbool vsign=val<0;\n\tuintw v=val;\n\tif(vsign&&val!=numeric_limits<T>::min())v=1+~(uintw)val;\n\tdo{\n\t\t*(--d)=\"0123456789\"[v%10];\n\t\tv/=10;\n\t}while(v!=0);\n\tif(vsign)*(--d)='-';\n\tsize_t len=end(_O128)-d;\n\tif(dst.rdbuf()->sputn(d,len)!=len)dst.setstate(ios_base::badbit);\n\treturn dst;\n}\nTP<Lint T>istream&operator>>(istream&src,T&val) {\n\tstr s;src>>s;\n\tbool is_neg=numeric_limits<T>::is_signed&&s.size()>0&&s[0]=='-';\n\tfor(val=0;C auto&x:s|views::drop(is_neg))val=10*val+x-'0';\n\tif(is_neg)val*=-1;\n\treturn src;\n}\n#define MUT make_unsigned_t\nTP<integral T>i32 pcnt(T p){return popcount(MUT<T>(p));}\nTP<integral T>i32 lsb(T p){return countl_zero(MUT<T>(p));}\nTP<integral T>i32 msb(T p){return countr_zero(MUT<T>(p));}\nTP<i32 N,integral T>void putbit(T s){\n\tchar buf[N+1]={0};\n\tfor(char*itr=buf+N-1;itr>=buf;itr--,s>>=1)\n\t\t*itr='0'+(s&1);\n\tcout<<buf<<sep;\n}\nTP<class T>concept Itrabl=requires(C T&x){x.begin();x.end();}&&!std::is_same_v<T,string>;\nTP<class T>concept IItrabl=Itrabl<T>&&Itrabl<typename T::value_type>;\nTP<class T>concept ModInt=requires(C T&x){x.val();};\nTP<class T>concept NLobj=Itrabl<T>||std::is_same_v<T,string>;\nTP<ModInt T>istream&operator>>(istream&is,T&v){int x;is>>x;v=x;return is;}\nTP<Itrabl T>istream&operator>>(istream&is,T&v){iter(x,v)is>>x;return is;}\nTP<class T,class U>istream&operator>>(istream&is,pair<T,U>&v){return is>>v.first>>v.second;}\nTP<class T>void in(T&a){cin>>a;}\nTP<class T,class... Ts>void in(T&a,Ts&... b){in(a);in(b...);}\nTP<class T,class U>vc<pair<T,U>>zip(size_t n,size_t m){\n\tvc<pair<T,U>>r(min(n,m));\n\titer(x,y,r)in(x);\n\titer(x,y,r)in(y);\n\treturn move(r);\n}\nTP<class T,class U>vc<pair<T,U>>zip(size_t n){return move(zip<T,U>(n,n));}\nTP<ModInt T>ostream&operator<<(ostream&os,const T&v){return os<<v.val(); }\nTP<Itrabl T>ostream&operator<<(ostream&os,const T&v){rep(i,v.size())os<<v[i]<<(i+1<v.size()?\" \":\"\");return os;}\nTP<IItrabl T>ostream&operator<<(ostream&os,const T&v){rep(i,v.size())os<<v[i]<<(i+1<v.size()?\"\\n\":\"\");return os;}\nTP<class T,class U>ostream&operator<<(ostream&os,const pair<T,U>&v){return os<<'('<<v.first<<','<<v.second<<')';}\nostream*dos=&cout;\nint32_t OFLG; // 0:first, 1:notNLobj, 2:NLobj\nTP<class T>void _out(const T&a){if(OFLG)(*dos)<<\"0 \\n\"[OFLG]<<a;else(*dos)<<a;OFLG=1;}\nTP<NLobj T>void _out(const T&a){(*dos)<<(OFLG?\"\\n\":\"\")<<a;OFLG=2;}\nTP<class T,class...Ts>void _out(const T&a,const Ts&... b){_out(a);_out(b...);}\nTP<class... Ts>void out(const Ts&... v){OFLG=0;_out(v...);(*dos)<<sep;}\n#undef TP\n#undef C\n#endif\n#ifdef LOCAL\n#define dput(...) dos=&cerr;putv(__VA_ARGS__);dos=&cout\n#else\n#define dput(...)\n#endif\n\n\nvoid slv(){\n\tINT(n);\n\tvv<it>imos(1002,vc<it>(1002,0));\n\trep(n){\n\t\tINT(a,b,x,y);\n\t\t++imos[a][b];\n\t\t++imos[x][y];\n\t\t--imos[a][y];\n\t\t--imos[x][b];\n\t}\n\trep(i,1002)\n\trep(j,1,1002)\n\t\timos[i][j]+=imos[i][j-1];\n\trep(i,1,1002)\n\trep(j,1002)\n\t\timos[i][j]+=imos[i-1][j];\n\titn ans=0;\n\trep(i,1002)rep(j,1002)chmax(ans,imos[i][j]);\n\tout(ans);\n}\n\nsigned main(){\n\tcin.tie(0)->sync_with_stdio(0);\n\tcout<<fixed<<setprecision(15);\n\tslv();\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7296, "score_of_the_acc": -0.0091, "final_rank": 2 }, { "submission_id": "aoj_DSL_5_B_10073058", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<int,int>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nll max_overlap( int H, int W, const vector<pair<P,P>> &sticker ){\n\n ll res = 0, s = 0;\n vector<vector<ll>> sum;\n\n for( int i = 0 ; i <= H ; i++ ){\n vector<ll> tmp;\n for( int j = 0 ; j <= W ; j++ )\n tmp.push_back( 0 );\n sum.push_back( tmp );\n }\n for( int i = 0 ; i < sticker.size() ; i++ ){\n P lu = sticker[i].first, rb = sticker[i].second;\n int x1 = lu.first, x2 = rb.first, y1 = lu.second, y2 = rb.second;\n for( int i = y1 ; i < y2 ; i++ ){\n sum[i][x1]++;\n sum[i][x2]--;\n }\n }\n for( int i = 0 ; i <= H ; i++ ){\n for( int j = 0 ; j <= W ; j++ ){\n s += sum[i][j];\n res = max( res, s );\n }\n }\n return res;\n\n}\n\nint main(){\n\n int N, H = 0, W = 0, x1, x2, y1, y2;\n vector<pair<P,P>> sticker;\n\n cin >> N;\n for( int i = 0 ; i < N ; i++ ){\n cin >> x1 >> y1 >> x2 >> y2;\n sticker.push_back( make_pair( make_pair( x1, y1 ), make_pair( x2, y2 ) ) );\n W = max( W, x1 ); W = max( W, x2 );\n H = max( H, y1 ); H = max( H, y2 );\n }\n cout << max_overlap( H, W, sticker ) << endl;\n\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 12504, "score_of_the_acc": -0.604, "final_rank": 16 }, { "submission_id": "aoj_DSL_5_B_10073057", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<int,int>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\ntemplate <typename U>\nvoid print( vector< vector<U> > v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() ; i++ ){\n if( v[i].size() == 0 )\n return;\n }\n for( int i = 0 ; i < v.size() ; i++ ){\n for( int j = 0 ; j < v[i].size() - 1 ; j++ )\n cout << v[i][j] << ' ';\n cout << v[i][v[i].size()-1] << endl;\n }\n}\n\nll max_overlap( int H, int W, const vector<pair<P,P>> &sticker ){\n\n ll res = 0, s = 0;\n vector<vector<ll>> sum;\n\n for( int i = 0 ; i <= H ; i++ ){\n vector<ll> tmp;\n for( int j = 0 ; j <= W ; j++ )\n tmp.push_back( 0 );\n sum.push_back( tmp );\n }\n for( int i = 0 ; i < sticker.size() ; i++ ){\n P lu = sticker[i].first, rb = sticker[i].second;\n int x1 = lu.first, x2 = rb.first, y1 = lu.second, y2 = rb.second;\n for( int i = y1 ; i < y2 ; i++ ){\n sum[i][x1]++;\n sum[i][x2]--;\n }\n }\n for( int i = 0 ; i <= H ; i++ ){\n for( int j = 0 ; j <= W ; j++ ){\n s += sum[i][j];\n res = max( res, s );\n }\n }\n return res;\n\n}\n\nint main(){\n\n int N, H = 0, W = 0, x1, x2, y1, y2;\n vector<pair<P,P>> sticker;\n\n cin >> N;\n for( int i = 0 ; i < N ; i++ ){\n cin >> x1 >> y1 >> x2 >> y2;\n sticker.push_back( make_pair( make_pair( x1, y1 ), make_pair( x2, y2 ) ) );\n W = max( W, x1 ); W = max( W, x2 );\n H = max( H, y1 ); H = max( H, y2 );\n }\n cout << max_overlap( H, W, sticker ) << endl;\n\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 12444, "score_of_the_acc": -0.6018, "final_rank": 15 } ]
aoj_DSL_5_A_cpp
The Maximum Number of Customers $N$ persons visited a restaurant. The restaurant is open from 0 to $T$. The $i$-th person entered the restaurant at $l_i$ and left at $r_i$. Find the maximum number of persons during the business hours. Constraints $ 1 \leq N \leq 10^5 $ $ 1 \leq T \leq 10^5 $ $ 0 \leq l_i < r_i \leq T $ Input The input is given in the following format. $N$ $T$ $l_1$ $r_1$ $l_2$ $r_2$ : $l_N$ $r_N$ Output Print the maximum number of persons in a line. Sample Input 1 6 10 0 2 1 3 2 6 3 8 4 10 5 10 Sample Output 1 4 Sample Input 2 2 2 0 1 1 2 Sample Output 2 1
[ { "submission_id": "aoj_DSL_5_A_10994563", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\nint main() {\n ios::sync_with_stdio(false);\n \tcin.tie(0);\n int n,t; cin >> n >> t;\n vi sum(t+1);\n rep(i,n){\n int l,r; cin >> l >> r;\n sum[l]++; sum[r]--;\n }\n rep(i,t)sum[i+1]+=sum[i];\n cout << *max_element(all(sum)) << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3560, "score_of_the_acc": -0.005, "final_rank": 1 }, { "submission_id": "aoj_DSL_5_A_10934310", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint N, T;\nint c[100001];\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int N, T;\n cin >> N >> T;\n \n rep(i,N) {\n int l, r;\n cin >> l >> r;\n ++c[l], --c[r];\n }\n \n int ans = 0, now = 0;\n rep(i,T) {\n now += c[i];\n if(ans < now) ans = now;\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3840, "score_of_the_acc": -0.012, "final_rank": 5 }, { "submission_id": "aoj_DSL_5_A_10934305", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,n) for(int i = 0; i < n; ++i)\nusing ll = long long;\n\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int N, T;\n cin >> N >> T;\n \n vector<int> c(T + 1, 0);\n rep(i,N) {\n int l, r;\n cin >> l >> r;\n \n ++c[l], --c[r];\n }\n \n rep(i,T) c[i + 1] += c[i];\n \n int ans = 0;\n rep(i,T + 1) ans = max(ans, c[i]);\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3608, "score_of_the_acc": -0.0062, "final_rank": 3 }, { "submission_id": "aoj_DSL_5_A_10853228", "code_snippet": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace __gnu_pbds;\n\n#define endl '\\n'\n#define MAX\n\ntypedef long long ll;\ntypedef pair<int,int> pii;\n//typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set;\n\n\n\nint main(){\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\t\n\tint n,t;\n\tcin >> n >> t;\n\tvector<pii> events;\n\tfor(int i = 0; i < n; i++){\n\t int l,r;\n\t cin >> l >> r;\n\t events.push_back({l,1});\n\t events.push_back({r,-1});\n\t}\n\tsort(events.begin(),events.end());\n\tint people = 0;\n\tint solve = 0;\n\tfor(int i = 0; i < events.size();i++){\n\t people += events[i].second;\n\t solve = max(solve,people);\n\t}\n\n cout << solve << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5200, "score_of_the_acc": -0.0763, "final_rank": 11 }, { "submission_id": "aoj_DSL_5_A_10823911", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std ;\n#define pb push_back\n#define ll long long \n#define N 100100\n\nll mid(ll l ,ll r){\n return (l+r)/2;\n}\n\nll t[4*N];\n\nvoid build(ll ind ,ll l, ll r){\n if(l==r){\n t[ind] = 0;\n return;\n }\n ll m = mid(l,r);\n build(2*ind,l,m);\n build(2*ind+1,m+1,r);\n t[ind] = 0;\n}\n\nvoid update(ll ind , ll l ,ll r, ll pos , ll x){\n if(pos<l or pos>r)return;\n if(l==r){\n t[ind]+=x;\n return;\n }\n ll m = mid(l,r);\n if(m>=pos)update(2*ind,l,m,pos,x);\n else update(2*ind+1,m+1,r,pos,x);\n t[ind] = t[2*ind] + t[2*ind+1];\n}\n\nll sum(ll ind , ll l , ll r , ll ql , ll qr){\n if(r<ql or l>qr)return 0;\n if(l>=ql and r<=qr)return t[ind];\n ll m = mid(l,r);\n return sum(2*ind,l,m,ql,qr) + sum(2*ind+1,m+1,r,ql,qr);\n}\n\nvoid solve(){\n\n ll n,t;\n cin>>n>>t;\n\n // build(1,1,N);\n\n for(ll i=0;i<n;i++){\n ll l,r;\n cin>>l>>r;\n l++ , r++;\n update(1,1,N,l,1);\n update(1,1,N,r,-1);\n }\n ll ans = 0;\n for(ll i=1;i<N;i++){\n ans = max(ans,sum(1,1,N,1,i));\n }\n\n cout<<ans<<endl;\n \n}\n \nint main(){\n int t =1;\n // cin>>t;\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5448, "score_of_the_acc": -0.1734, "final_rank": 14 }, { "submission_id": "aoj_DSL_5_A_10707114", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\n#define endl '\\n'\n#define MAXN 1000010\n#define vi vector<int>\n#define pii pair<int, int>\n#define vii vector<pii>\n#define ALL(x) x.begin(), x.end()\nusing namespace std;\nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n int n, n1, t; cin >> n >> t;\n vi start, ended;\n vii intervals;\n n1 = n;\n while (n1--){\n int l, r; cin >> l >> r;\n intervals.emplace_back(l, r);\n start.push_back(l);\n ended.push_back(r);\n }\n sort(ALL(start));\n sort(ALL(ended));\n int max = -MAXN;\n for (int i = 1; i < t; ++i) {\n auto it = lower_bound(ALL(ended), i);\n auto it1 = lower_bound(ALL(start),i);\n int cant = it - ended.begin();\n int cant1 = start.end() - it1;\n int sum = n - cant - cant1;\n if(sum > max) {\n max = sum;\n }\n }\n cout << max << endl;\n return 0;\n}", "accuracy": 0.8461538461538461, "time_ms": 20, "memory_kb": 5048, "score_of_the_acc": -0.0725, "final_rank": 19 }, { "submission_id": "aoj_DSL_5_A_10448094", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main() {\n ll n, t;\n cin >> n >> t;\n vector<ll> vec(t+2,0);\n for (ll i = 0; i < n; i++) {\n ll l, r;\n cin >> l >> r;\n vec[l]++;\n vec[r]--;\n }\n\n ll ans = vec[0];\n for (ll i = 1; i < t+2; i++) {\n vec[i] = vec[i] + vec[i-1];\n ans = max(ans, vec[i]);\n }\n\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3900, "score_of_the_acc": -0.0741, "final_rank": 10 }, { "submission_id": "aoj_DSL_5_A_10448092", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main() {\n ll n, t;\n cin >> n >> t;\n vector<ll> vec(t+2,0);\n for (ll i = 0; i < n; i++) {\n ll l, r;\n cin >> l >> r;\n vec[l]++;\n vec[r]--;\n }\n\n ll ans = 0;\n for (ll i = 1; i < t+2; i++) {\n vec[i] = vec[i] + vec[i-1];\n ans = max(ans, vec[i]);\n }\n\n cout << ans << endl;\n return 0;\n}", "accuracy": 0.8461538461538461, "time_ms": 30, "memory_kb": 3864, "score_of_the_acc": -0.0732, "final_rank": 20 }, { "submission_id": "aoj_DSL_5_A_10448088", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n, t;\n cin >> n >> t;\n vector<int> vec(t+2,0);\n for (int i = 0; i < n; i++) {\n int l, r;\n cin >> l >> r;\n vec[l]++;\n vec[r]--;\n }\n\n int ans = 0;\n for (int i = 1; i < t+2; i++) {\n vec[i] = vec[i] + vec[i-1];\n ans = max(ans, vec[i]);\n }\n\n cout << ans << endl;\n return 0;\n}", "accuracy": 0.8461538461538461, "time_ms": 30, "memory_kb": 3636, "score_of_the_acc": -0.0675, "final_rank": 18 }, { "submission_id": "aoj_DSL_5_A_10380256", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint N,T;cin>>N>>T;\n\tvector<int>cnt(T+2,0);\n\tfor(int i=0;i<N;i++){\n\t\tint l,r;cin>>l>>r;\n\t\tcnt[l]++,cnt[r]--;\n\t}\n\tint ans=0;\n\tfor(int i=0;i<=T;i++){\n\t\tcnt[i+1]+=cnt[i];\n\t\tans=max(ans,cnt[i]);\n\t}\n\tcout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3712, "score_of_the_acc": -0.0391, "final_rank": 7 }, { "submission_id": "aoj_DSL_5_A_10380253", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint N,T;cin>>N>>T;\n\tvector<int>cnt(T+2,0);\n\tfor(int i=0;i<N;i++){\n\t\tint l,r;cin>>l>>r;\n\t\tcnt[l]++,cnt[r]--;\n\t}\n\tint ans=0;\n\tfor(int i=0;i<T;i++){\n\t\tcnt[i+1]+=cnt[i];\n\t\tans=max(ans,cnt[i+1]);\n\t}\n\tcout<<ans<<endl;\n}", "accuracy": 0.8461538461538461, "time_ms": 20, "memory_kb": 3712, "score_of_the_acc": -0.0391, "final_rank": 17 }, { "submission_id": "aoj_DSL_5_A_10372522", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e6 + 5, MOD = 1e9 + 7;\n\nint ps[N];\n\nint main(){\n ios::sync_with_stdio(NULL);\n cin.tie(NULL); cout.tie(NULL);\n\n // freopen(taskname\".inp\", \"r\", stdin);\n // freopen(taskname\".out\", \"w\", stdout);\n\n int n, t;\n cin >> n >> t;\n\n for (int i = 1; i <= n; i++){\n int x, y;\n cin >> x >> y;\n\n ps[x]++;\n ps[y]--;\n }\n\n int maxi = 0;\n for (int i = 0; i <= t; i++){\n ps[i] += ps[i - 1];\n maxi = max(maxi, ps[i]);\n }\n\n cout << maxi << '\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3764, "score_of_the_acc": -0.0101, "final_rank": 4 }, { "submission_id": "aoj_DSL_5_A_10342315", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n\tint n,t;\n\tcin>>n>>t;\n\tvector<int>s(t+2);\n\tfor(int i=0;i<n;i++){\n\t\tint l,r;\n\t\tcin>>l>>r;\n\t\ts[l]++;\n\t\ts[r]--;\n\t}\n\tfor(int i=0;i<=t;i++)s[i+1]+=s[i];\n\tcout<<*max_element(s.begin(),s.end())<<'\\n';\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3628, "score_of_the_acc": -0.0673, "final_rank": 9 }, { "submission_id": "aoj_DSL_5_A_10322923", "code_snippet": "#include <atcoder/all>\n#include <bits/stdc++.h>\n#define rep(i, a, b) for (ll i = (ll)(a); i < (ll)(b); i++)\nusing namespace atcoder;\nusing namespace std;\n\ntypedef long long ll;\n\nstruct LongImos {\n ll n;\n map<ll, ll> ma;\n vector<ll> li, ri, sum;\n\n LongImos() { ma[inf()] = 0; }\n ll inf() { return 2e18; }\n void add(ll l, ll r, ll c) {\n // [l, r] <- +c\n ma[l] += c;\n ma[r + 1] -= c;\n }\n void make() {\n li = vector<ll>(0);\n ri = vector<ll>(0);\n sum = vector<ll>(0);\n ll nowt = -inf(), nowc = 0;\n for (auto p : ma) {\n auto key = p.first;\n auto val = p.second;\n li.push_back(nowt);\n ri.push_back(key - 1);\n sum.push_back(nowc);\n nowt = key;\n nowc += val;\n }\n }\n};\n\nint main() {\n cin.tie(0);\n cout.tie(0);\n ios::sync_with_stdio(0);\n int n, t;\n cin >> n >> t;\n LongImos imos;\n rep(i, 0, n) {\n ll l, r;\n cin >> l >> r;\n imos.add(l, r - 1, 1);\n }\n int ans = 0;\n imos.make();\n rep(i, 0, imos.li.size()) { ans = max(ans, (int)imos.sum[i]); }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 6400, "score_of_the_acc": -0.1366, "final_rank": 12 }, { "submission_id": "aoj_DSL_5_A_10319078", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\n#define rep(i,n,m) for(int i=(int)(n);i < (int)(m); i++)\n#define repm(i,n,m) for(int i=(int)(n);i >= (int)(m); i--)\n// #define _GLIBCXX_DEBUG\nusing namespace std;\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n int n,t;\n cin >> n >> t;\n vector<int> A(t,0);\n int left, right;\n rep(i,0,n){\n cin >> left >> right;\n A[left]++;\n if(right < t) A[right]--;\n }\n int ans = A[0];\n rep(i,1,t){\n A[i] += A[i-1];\n ans = max(ans, A[i]);\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3600, "score_of_the_acc": -0.006, "final_rank": 2 }, { "submission_id": "aoj_DSL_5_A_10316842", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int N,T;\n cin>>N>>T;\n vector<int>l(N);\n vector<int>r(N);\n vector<int>d(T);\n vector<int>A(10000000);\n for(int i=0;i<N;i++){\n cin>>l[i]>>r[i];\n \n d[l[i]]++;\n d[r[i]]--;\n \n }\n A[-1]=0;\n for(int i=0;i<T;i++){\n A[i]=A[i-1]+d[i];\n }\n int m=0;\n for(int i=0;i<T;i++){\n // cout<<A[i]<<endl;\n m=max(m,A[i]);\n }\n cout<<m<<endl;\n}\n\n\n // g++ a.cpp -o a", "accuracy": 1, "time_ms": 30, "memory_kb": 43340, "score_of_the_acc": -1.0606, "final_rank": 16 }, { "submission_id": "aoj_DSL_5_A_10311457", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\n#define rep(i,n,m) for(int i=(int)(n);i < (int)(m); i++)\n#define repm(i,n,m) for(int i=(int)(n);i >= (int)(m); i--)\n// #define _GLIBCXX_DEBUG\nusing namespace std;\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n int n,t;\n cin >> n >> t;\n vector<int> L(n),R(n),table(t,0);\n rep(i,0,n) cin >> L[i] >> R[i];\n rep(i,0,n){\n table[L[i]]++;\n table[R[i]]--;\n }\n rep(i,1,t){\n table[i] += table[i-1];\n }\n int ans = 0;\n rep(i,0,t){\n ans = max(ans, table[i]);\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4396, "score_of_the_acc": -0.0259, "final_rank": 6 }, { "submission_id": "aoj_DSL_5_A_10311021", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\n#define rep(i,n,m) for(int i=(int)(n);i < (int)(m); i++)\n#define repm(i,n,m) for(int i=(int)(n);i >= (int)(m); i--)\n// #define _GLIBCXX_DEBUG\nusing namespace std;\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n int n,t;\n cin >> n >> t;\n vector<pair<int,int>> LR(2*n);\n rep(i,0,n){\n cin >> LR[i].first >> LR[n+i].first;\n LR[i].second = 1;\n LR[n+i].second = -1;\n }\n sort(LR.begin(),LR.end());\n int cnt = 0, ans = 0;\n rep(i,0,2*n){\n cnt += LR[i].second;\n ans = max(ans,cnt);\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4668, "score_of_the_acc": -0.063, "final_rank": 8 }, { "submission_id": "aoj_DSL_5_A_10073015", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nll max_customer( ll T, const vector<P> &time ){\n\n ll res = 0, s = 0;\n vector<ll> sum;\n\n for( int i = 0 ; i < T ; i++ )\n sum.push_back( 0 );\n for( int i = 0 ; i < time.size() ; i++ ){\n sum[time[i].first]++;\n sum[time[i].second]--;\n }\n for( int i = 0 ; i < T ; i++ ){\n s += sum[i];\n res = max( res, s );\n }\n return res;\n\n}\n\nint main(){\n\n int N;\n ll T, l, r;\n vector<P> time;\n\n cin >> N >> T;\n for( int i = 0 ; i < N ; i++ ){\n cin >> l >> r;\n time.push_back( make_pair( l, r ) );\n }\n cout << max_customer( T, time ) << endl;\n\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 6512, "score_of_the_acc": -0.1394, "final_rank": 13 }, { "submission_id": "aoj_DSL_5_A_10049722", "code_snippet": "#include <stdio.h>\n#define TMAX 100001\n#define THALF 50000\n\nvoid fill(int *p, int T, int d)\n{\n\tint i;\n\tfor(i=0; i<T; i++){\n\t\t*(p+i) = d;\n\t}\n}\nvoid stak(int *p, int head, int end, int d)\n{\n\tint i;\n\tfor(i=head; i<end; i++){\n\t\t*(p+i) += d;\n\t}\n}\n\nint main(void)\n{\n int N, T, t[TMAX], in, out, d, sw, max=0, i, j;\n scanf(\"%d%d\", &N, &T);\n\tscanf(\"%d%d\", &in, &out);\n\tsw = (THALF > out - in ? 1 : 2);\n\tswitch(sw){\n\t\tcase 1:\n\t\t\tfill(t, T, 0);\n\t\t\tstak(t, in, out, 1);\n\t\t\tfor(i=1; i<N; i++){\n\t\t\t\tscanf(\"%d%d\", &in, &out);\n\t\t\t\tstak(t, in, out, 1);\n \t\t}\n\t\t for(j=0; j<T; j++){\n\t\t max = (max < *(t+j) ? *(t+j) : max);\n\t\t }\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tfill(t, T, N);\n\t\t\tstak(t, 0, in, -1);\n\t\t\tstak(t, out, T, -1);\n\t\t\tfor(i=1; i<N; i++){\n\t\t\t\tscanf(\"%d%d\", &in, &out);\n\t\t\t\tstak(t, 0, in, -1);\n\t\t\t\tstak(t, out, T, -1);\n\t\t\t}\n\t\t\tfor(j=0; j<T; j++){\n\t\t\t\tmax = (max < *(t+j) ? *(t+j) : max);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n printf(\"%d\\n\", max);\n return 0;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 3360, "score_of_the_acc": -1, "final_rank": 15 } ]
aoj_GRL_1_B_cpp
Single Source Shortest Path (Negative Edges) Input An edge-weighted graph G ( V , E ) and the source r . | V | | E | r s 0 t 0 d 0 s 1 t 1 d 1 : s |E|-1 t |E|-1 d |E|-1 |V| is the number of vertices and |E| is the number of edges in G . The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph. s i and t i represent source and target vertices of i -th edge (directed) and d i represents the cost of the i -th edge. Output If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value) which is reachable from the source r , print NEGATIVE CYCLE in a line. Otherwise, print c 0 c 1 : c |V|-1 The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print " INF ". Constraints 1 ≤ |V| ≤ 1000 0 ≤ |E| ≤ 2000 -10000 ≤ d i ≤ 10000 There are no parallel edges There are no self-loops Sample Input 1 4 5 0 0 1 2 0 2 3 1 2 -5 1 3 1 2 3 2 Sample Output 1 0 2 -3 -1 Sample Input 2 4 6 0 0 1 2 0 2 3 1 2 -5 1 3 1 2 3 2 3 1 0 Sample Output 2 NEGATIVE CYCLE Sample Input 3 4 5 1 0 1 2 0 2 3 1 2 -5 1 3 1 2 3 2 Sample Output 3 INF 0 -5 -3
[ { "submission_id": "aoj_GRL_1_B_10447635", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\ntypedef pair<ll, ll> P;\n\nint main() {\n ll n, m, s;\n cin >> n >> m >> s;\n\n const ll INF = 8e18;\n vector<vector<ll>> dist(n,vector<ll>(n,INF));\n for (ll i = 0; i < n; i++) dist[i][i] = 0;\n\n vector<vector<P>> graph(n);\n for (ll i = 0; i < m; i++) {\n ll a, b, d;\n cin >> a >> b >> d;\n graph[a].emplace_back(b, d);\n dist[a][b] = min(dist[a][b], d);\n }\n\n for (ll k = 0; k < n; k++) {\n for (ll i = 0; i < n; i++) {\n for (ll j = 0; j < n; j++) {\n if (dist[i][k] == INF || dist[k][j] == INF) continue;\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n }\n }\n }\n\n vector<bool> visited(n,false);\n auto dfs = [&](auto dfs, ll x) -> void {\n visited[x] = true;\n for (auto edge : graph[x]) {\n ll nex = edge.first;\n ll cost = edge.second;\n\n if (visited[nex]) continue;\n dfs(dfs, nex);\n }\n };\n\n dfs(dfs, s);\n for (int i = 0; i < n; i++) {\n if (!visited[i]) continue;\n if (dist[i][i] < 0) {\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n }\n\n\n for (ll j = 0; j < n; j++) {\n if (dist[s][j] == INF) {\n cout << \"INF\" << endl;\n } else {\n cout << dist[s][j] << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 450, "memory_kb": 11264, "score_of_the_acc": -0.6801, "final_rank": 8 }, { "submission_id": "aoj_GRL_1_B_9965512", "code_snippet": "#include <bits/stdc++.h>\n\n\nusing namespace std;\n//make -f ../makefile SRC=\n/*\n*/\n\n\n//------------------------------------------------------------------------------\nbool DEBUG = false;\nconst int INF = 2147483647;\n\nconst int MAX_N = 1000;\nstatic int G[MAX_N][MAX_N];\nstatic int D[MAX_N];\n\n//------------------------------------------------------------------------------\nbool bellman_ford(int N, int src)\n{\n //--------------------------------------------------------------------------\n // init params:\n for (int n=0; n<N; ++n) D[n] = INF;\n D[src] = 0;\n\n //--------------------------------------------------------------------------\n // do this N times:\n for (int unused=0; unused<N-1; ++unused)\n {\n // for each edge:\n for (int v=0; v<N; ++v)\n {\n if (D[v] == INF) continue;\n for (int w=0; w<N; ++w)\n {\n if (w == v || G[v][w] == INF) continue;\n // relax the edge:\n if (D[w] == INF || D[w] > D[v]+G[v][w]) D[w] = D[v] + G[v][w];\n }\n }\n }\n\n if (DEBUG) {for (int v=0; v<N; ++v) if (D[v] != INF) printf(\"v=%d, D=%d\\n\", v, D[v]);}\n\n for (int v=0; v<N; ++v)\n {\n for (int w=0; w<N; ++w)\n {\n if (w == v || G[v][w] == INF) continue;\n if (D[v] == INF) continue;\n if (D[w] > D[v] + G[v][w])\n {\n return true;\n }\n }\n }\n return false;\n}\n//------------------------------------------------------------------------------\nvoid floyd_warshall(int N)\n{\n for (int k=0; k<N; k++)\n {\n for (int i=0; i<N; i++)\n {\n if (G[i][k] == INF) continue;\n for (int j=0; j<N; j++)\n {\n if (G[k][j] == INF) continue;\n if (G[i][j] == INF || G[i][j] > G[i][k] + G[k][j])\n G[i][j] = G[i][k] + G[k][j];\n }\n }\n }\n}\n\n//------------------------------------------------------------------------------\nvoid solve(int N, int src)\n{\n //--------------------------------------------------------------------------\n // base cases:\n if (bellman_ford(N, src))\n {\n printf(\"NEGATIVE CYCLE\\n\");\n return;\n }\n //--------------------------------------------------------------------------\n // init:\n //--------------------------------------------------------------------------\n // compute:\n floyd_warshall(N);\n\n //--------------------------------------------------------------------------\n // report:\n for (int v=0; v<N; ++v)\n {\n if (G[src][v] == INF) printf(\"INF\\n\");\n else printf(\"%d\\n\", G[src][v]);\n }\n}\n\n//------------------------------------------------------------------------------\nvoid test()\n{\n\n}\n\n//------------------------------------------------------------------------------\nint main()\n{\n //test(); return 0;\n //DEBUG = true;\n //--------------------------------------------------------------------------\n int N, M, v, w, c, src, num;\n\n num = scanf(\"%d %d %d \", &N, &M, &src);\n for (int v=0; v<N; v++)\n {\n for (int w=0; w<N; w++)\n {\n if (v != w) G[v][w] = INF;\n else G[v][w] = 0;\n }\n }\n\n for (int m=0; m<M; ++m)\n {\n num = scanf(\"%d %d %d \", &v, &w, &c);\n G[v][w] = min(G[v][w], c);\n }\n solve(N, src);\n //--------------------------------------------------------------------------\n return 0;\n}\n//------------------------------------------------------------------------------", "accuracy": 1, "time_ms": 790, "memory_kb": 7316, "score_of_the_acc": -1.0573, "final_rank": 9 }, { "submission_id": "aoj_GRL_1_B_9965374", "code_snippet": "#include <bits/stdc++.h>\n\n\nusing namespace std;\n//make -f ../makefile SRC=\n/*\n*/\n\n\n//------------------------------------------------------------------------------\nbool DEBUG = false;\nconst int INF = 2147483647;\n\nconst int MAX_N = 1000;\nstatic int G[MAX_N][MAX_N];\nstatic int D[MAX_N];\n\n//------------------------------------------------------------------------------\nbool bellman_ford(int N, int src)\n{\n //--------------------------------------------------------------------------\n // init params:\n for (int n=0; n<=N; ++n) D[n] = INF;\n D[src] = 0;\n\n //--------------------------------------------------------------------------\n // do this N times:\n for (int unused=0; unused<N-1; ++unused)\n {\n // for each edge:\n for (int v=0; v<N; ++v)\n {\n if (D[v] == INF) continue;\n for (int w=0; w<N; ++w)\n {\n if (w == v || G[v][w] == INF) continue;\n // relax the edge:\n if (D[w] == INF || D[w] > D[v]+G[v][w]) D[w] = D[v] + G[v][w];\n }\n }\n }\n\n if (DEBUG) {for (int v=0; v<N; ++v) if (D[v] != INF) printf(\"v=%d, D=%d\\n\", v, D[v]);}\n\n for (int v=0; v<N; ++v)\n {\n for (int w=0; w<N; ++w)\n {\n if (w == v || G[v][w] == INF) continue;\n if (D[v] == INF) continue;\n if (D[w] > D[v] + G[v][w])\n {\n return true;\n }\n }\n }\n return false;\n}\n//------------------------------------------------------------------------------\nvoid floyd_warshall(int N)\n{\n for (int k=0; k<N; k++)\n {\n for (int i=0; i<N; i++)\n {\n if (G[i][k] == INF) continue;\n for (int j=0; j<N; j++)\n {\n if (G[k][j] == INF) continue;\n if (G[i][j] == INF || G[i][j] > G[i][k] + G[k][j])\n G[i][j] = G[i][k] + G[k][j];\n }\n }\n }\n}\n\n//------------------------------------------------------------------------------\nvoid solve(int N, int src)\n{\n //--------------------------------------------------------------------------\n // base cases:\n if (bellman_ford(N, src))\n {\n printf(\"NEGATIVE CYCLE\\n\");\n return;\n }\n //--------------------------------------------------------------------------\n // init:\n //--------------------------------------------------------------------------\n // compute:\n floyd_warshall(N);\n\n //--------------------------------------------------------------------------\n // report:\n for (int v=0; v<N; ++v)\n {\n if (G[src][v] == INF) printf(\"INF\\n\");\n else printf(\"%d\\n\", G[src][v]);\n }\n}\n\n//------------------------------------------------------------------------------\nvoid test()\n{\n\n}\n\n//------------------------------------------------------------------------------\nint main()\n{\n //test(); return 0;\n //DEBUG = true;\n //--------------------------------------------------------------------------\n int N, M, v, w, c, src, num;\n\n num = scanf(\"%d %d %d \", &N, &M, &src);\n for (int v=0; v<N; v++)\n {\n for (int w=0; w<N; w++)\n {\n if (v != w) G[v][w] = INF;\n else G[v][w] = 0;\n }\n }\n\n for (int m=0; m<M; ++m)\n {\n num = scanf(\"%d %d %d \", &v, &w, &c);\n G[v][w] = min(G[v][w], c);\n }\n solve(N, src);\n //--------------------------------------------------------------------------\n return 0;\n}\n//------------------------------------------------------------------------------", "accuracy": 0.975, "time_ms": 790, "memory_kb": 7448, "score_of_the_acc": -1.0592, "final_rank": 11 }, { "submission_id": "aoj_GRL_1_B_9753152", "code_snippet": "#include <bits/stdc++.h>\n#define rep(i,n) for(int i=0;i<(n);++i)\nusing namespace std;\nusing ll = long long;\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int n,m,s;\n cin >> n >> m >> s;\n\n vector<vector<int>> es(m);\n rep(i,m){\n int a,b,c;\n cin >> a >> b >> c;\n es[i] = {a,b,c};\n } \n\n vector<ll> dist(n,1e18);\n dist[s] = 0;\n\n\n rep(_,n-1){\n for(auto e:es){\n if(dist[e[0]]!=1e18 && dist[e[1]]>dist[e[0]]+e[2]){\n dist[e[1]] = dist[e[0]]+e[2];\n }\n }\n }\n rep(_,n-1){\n for(auto e: es){\n if(dist[e[0]]!=1e18 && dist[e[1]]>dist[e[0]]+e[2]){\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n }\n }\n\n rep(i,n) {\n if(dist[i]==1e18) cout << \"INF\" << endl;\n else cout << dist[i] << endl;\n }\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3464, "score_of_the_acc": -0.0513, "final_rank": 7 }, { "submission_id": "aoj_GRL_1_B_9731500", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define vi vector<int64_t>\n#define vvi vector<vi>\ntemplate<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }\nint main(){\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n\n int64_t v,e,r,sum=0;\n cin>>v>>e>>r;\n vector<vvi> a(v,vvi(0,vi(2)));\n vi kiro(v,INT_MAX);\n rep(i,e){\n int s,t,d;\n cin>>s>>t>>d;\n a[s].push_back({t,d});\n }\n queue<int> tan,sak;\n rep(i,a[r].size()){\n tan.push(r);\n }\n kiro[r]=0;\n while(tan.size()>0){\n if(sum>e*v)break;\n //cout<<\"ya\";\n int sou=tan.front();\n tan.pop();\n rep(i,a[sou].size()){\n if(kiro[a[sou][i][0]]>kiro[sou]+a[sou][i][1]){\n kiro[a[sou][i][0]]=kiro[sou]+a[sou][i][1];\n //cout<<kiro[a[sou][i][0]]<<\" \"<<sou<<\" \";\n tan.push(a[sou][i][0]);\n sum++;\n }\n }\n }\n if(sum>e*v){\n cout<<\"NEGATIVE CYCLE\"<<endl;\n return 0;\n }\n rep(i,v){\n if(kiro[i]!=INT_MAX){\n cout<<kiro[i]<<endl;\n }\n else cout<<\"INF\"<<endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3560, "score_of_the_acc": -0.0014, "final_rank": 2 }, { "submission_id": "aoj_GRL_1_B_9558932", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define all(a) (a).begin(), (a).end()\n#define pb push_back\n#define fi first\n#define se second\nmt19937_64 rng(chrono::system_clock::now().time_since_epoch().count());\nconst ll MOD1000000007 = 1000000007;\nconst ll MOD998244353 = 998244353;\nconst ll MOD[3] = {999727999, 1070777777, 1000000007};\nconst ll LINF = 1LL << 60LL;\nconst int IINF = (1 << 30) - 2;\n\n\ntemplate<typename T> \nstruct edge{\n int from;\n int to;\n T cost;\n int id;\n\n edge(){}\n edge(int to, T cost=1) : from(-1), to(to), cost(cost){}\n edge(int to, T cost, int id) : from(-1), to(to), cost(cost), id(id){}\n edge(int from, int to, T cost, int id) : from(from), to(to), cost(cost), id(id){}\n\n void reverse(){swap(from, to);}\n};\n\ntemplate<typename T>\nstruct edges : std::vector<edge<T>>{\n void sort(){\n std::sort(\n (*this).begin(),\n (*this).end(), \n [](const edge<T>& a, const edge<T>& b){\n return a.cost < b.cost;\n }\n );\n }\n};\n\ntemplate<typename T = bool>\nstruct graph : std::vector<edges<T>>{\nprivate:\n int n = 0;\n int m = 0;\n edges<T> es;\n bool dir;\n\npublic:\n graph(int n, bool dir) : n(n), dir(dir){\n (*this).resize(n);\n }\n\n void add_edge(int from, int to, T cost=1){\n if(dir){\n es.push_back(edge<T>(from, to, cost, m));\n (*this)[from].push_back(edge<T>(from, to, cost, m++));\n }else{\n if(from > to) swap(from, to);\n es.push_back(edge<T>(from, to, cost, m));\n (*this)[from].push_back(edge<T>(from, to, cost, m));\n (*this)[to].push_back(edge<T>(to, from, cost, m++));\n }\n }\n\n int get_vnum(){\n return n;\n }\n\n int get_enum(){\n return m;\n }\n\n bool get_dir(){\n return dir;\n }\n\n edge<T> get_edge(int i){\n return es[i];\n }\n\n edges<T> get_edge_set(){\n return es;\n }\n};\n\ntemplate<typename T>\nstruct redge{\n int from, to;\n T cap, cost;\n int rev;\n \n redge(int to, T cap, T cost=(T)(1)) : from(-1), to(to), cap(cap), cost(cost){}\n redge(int to, T cap, T cost, int rev) : from(-1), to(to), cap(cap), cost(cost), rev(rev){}\n};\n\ntemplate<typename T> using Edges = vector<edge<T>>;\ntemplate<typename T> using weighted_graph = vector<Edges<T>>;\ntemplate<typename T> using tree = vector<Edges<T>>;\nusing unweighted_graph = vector<vector<int>>;\ntemplate<typename T> using residual_graph = vector<vector<redge<T>>>;\n\n\nclass shortest_path{\npublic:\n template<typename T>\n static vector<T> dijkstra(graph<T> &G, int s){\n int n = G.get_vnum();\n const T TINF = numeric_limits<T>::max()/2;\n vector<T> dist(n, TINF);\n\n dist[s] = 0;\n priority_queue<pair<T, int>, vector<pair<T, int>>, greater<>> que;\n que.push({0, s});\n while(!que.empty()){\n auto [d, v] = que.top();\n que.pop();\n if(dist[v] < d) continue;\n\n for(auto e : G[v]){\n if(dist[v] + e.cost < dist[e.to]){\n dist[e.to] = dist[v] + e.cost;\n que.push({dist[e.to], e.to});\n }\n }\n }\n\n for(int v=0; v<n; v++) if(dist[v]==TINF) dist[v] = -1;\n\n return dist;\n }\n \n template<typename T>\n static vector<T> bellmanford(graph<T> &G, int s){\n int n = G.get_vnum();\n bool dir = G.get_dir();\n const T TINF = numeric_limits<T>::max()/2;\n edges<T> es = G.get_edge_set();\n vector<T> dist(n, TINF);\n vector<bool> flag(n, false);\n\n dist[s] = 0;\n for(int i=0; i<n; i++) for(auto e : es){\n if(dist[e.from]!=TINF && dist[e.from]+e.cost<dist[e.to]) dist[e.to] = dist[e.from] + e.cost;\n if(!dir && dist[e.to]!=TINF && dist[e.to]+e.cost<dist[e.from]) dist[e.from] = dist[e.to] + e.cost;\n }\n\n for(int i=0; i<n; i++) for(auto e : es){\n if(dist[e.from]!=TINF && dist[e.from]+e.cost<dist[e.to]) dist[e.to] = dist[e.from] + e.cost, flag[e.to]=true;\n if(!dir && dist[e.to]!=TINF && dist[e.to]+e.cost<dist[e.from]) dist[e.from] = dist[e.to] + e.cost, flag[e.from]=true;\n }\n\n for(int i=0; i<n; i++) for(auto e : es){\n flag[e.to] = flag[e.to] | flag[e.from];\n if(!dir) flag[e.from] = flag[e.from] | flag[e.to];\n }\n for(int v=0; v<n; v++) if(flag[v]) dist[v] = -TINF;\n\n return dist;\n }\n\n template<typename T>\n vector<vector<T>> warshall_floyd(graph<T> &G){\n int n = G.get_vnum();\n const T TINF = numeric_limits<T>::max()/2;\n vector<vector<T>> dist(n, vector<T>(n, TINF));\n \n for(int v=0; v<n; v++) for(auto e : G[v]) dist[v][e.to] = min(dist[v][e.to], e.cost);\n for(int k=0; k<n; k++) for(int i=0; i<n; i++) for(int j=0; j<n; j++) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n\n return dist;\n }\n\n template<typename T>\n vector<T> yen(graph<T> &G, int s, int t, int k){\n \n }\n};\n\n\nvoid solve(){\n int n, m, s; cin >> n >> m >> s;\n graph<int> G(n, true);\n for(int i=0; i<m; i++){\n int u, v, w; cin >> u >> v >> w;\n G.add_edge(u, v, w);\n }\n\n auto dist = shortest_path::bellmanford<int>(G, s);\n for(int v=0; v<n; v++) if(dist[v] <= -IINF){\n cout << \"NEGATIVE CYCLE\\n\";\n return;\n }\n for(int v=0; v<n; v++){\n if(IINF <= dist[v]) cout << \"INF\\n\";\n else cout << dist[v] << '\\n';\n }\n}\n\nint main(){\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n \n int T=1;\n //cin >> T;\n while(T--) solve();\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3500, "score_of_the_acc": -0.0005, "final_rank": 1 }, { "submission_id": "aoj_GRL_1_B_9438027", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef vector<ll> vi;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\ntypedef vector<bool> vb;\ntypedef vector<vb> vvb;\ntypedef vector<vvb> vvvb;\ntypedef vector<vvvb> vvvvb;\ntypedef pair<ll,ll> pi;\ntypedef pair<ll,pi> ppi;\n#define FOR(i,l,r) for(ll i=l;i<r;i++)\n#define REP(i,n) FOR(i,0,n)\n#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)\n#define RREP(i,n) RFOR(i,0,n)\n#define sz(A) (ll)(A.size())\n#define ALL(A) A.begin(),A.end()\n#define LB(A,x) (ll)(lower_bound(ALL(A),x)-A.begin())\n#define UB(A,x) (ll)(upper_bound(ALL(A),x)-A.begin())\n#define COU(A,x) (UB(A,x)-LB(A,x))\n#define F first\n#define S second\ntemplate<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;\ntemplate<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.F<<\" \"<<p.S;return os;}\ntemplate<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.F>>p.S;return is;}\ntemplate<typename T>ostream&operator<<(ostream&os,vector<T>&v){REP(i,sz(v))os<<v[i]<<(i+1!=sz(v)?\" \":\"\");return os;}\ntemplate<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}\ntemplate<class T>bool chmax(T&a,T b){if(a<b){a=b;return 1;}return 0;}\ntemplate<class T>bool chmin(T&a,T b){if(b<a){a=b;return 1;}return 0;}\nconst ll mod=998244353;\nint main(){\n ll N,M,r;cin>>N>>M>>r;\n vector<vector<pi>>E(N);\n REP(i,M){\n ll u,v,d;cin>>u>>v>>d;\n E[u].emplace_back(pi(v,d));\n }\n vi D(N,1e18);\n D[r]=0;\n min_priority_queue<pi>Q;\n Q.emplace(pi(0,r));\n while(sz(Q)){\n ll d=Q.top().F,v=Q.top().S;Q.pop();\n if(d!=D[v])continue;\n if(clock()>0.5*CLOCKS_PER_SEC){cout<<\"NEGATIVE CYCLE\"<<endl;return 0;}\n for(auto[u,c]:E[v])if(chmin(D[u],d+c)){\n Q.emplace(pi(d+c,u));\n }\n }\n REP(i,N){\n if(D[i]>1e17)cout<<\"INF\"<<endl;\n else cout<<D[i]<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 490, "memory_kb": 70716, "score_of_the_acc": -1.6154, "final_rank": 10 }, { "submission_id": "aoj_GRL_1_B_9254025", "code_snippet": "#include <bits/stdc++.h>\n//#include <atcoder/all>\n#define rep(i, n) for(int i = 0;i < (int)(n); i ++)\n#define REP(i, j, n) for (int i = (int)(j); i < (int)(n) ; i ++)\nusing namespace std;\n//using namespace atcoder;\n// atcoder::dsu uf(N);のように使う\n//コンパイルは下記のmain.cppをコンパイルしたいファイル名に書き換える\n//g++ main.cpp -std=c++14 -I . \n//閉路の個数はleader[i] == iでfor文して数える。\n//連結成分のノード数もsizeで検出可能 \n\ntypedef long long ll;\nconst ll LINF = numeric_limits<long long>::max();\ntemplate <typename T>\nbool chmax(T &a,const T &b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a,const T &b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nvoid print_map(const map<T, T> &dict) {\n for (auto itr = dict.begin();itr != dict.end(); itr++ ) {\n cout << itr->first << \": \" << itr->second << endl;\n }\n}\ntemplate <typename T>\nvoid print_set(const set<T> &ssss) {\n cout << \"set content: \" ;\n for (auto itt = ssss.begin(); itt != ssss.end() ; itt++) {\n cout << *itt << \" \" ;\n }\n cout << endl;\n}\nll power(ll radix, ll index2) {\n ll ans = 1;\n if (index2 == 0) return 1;\n while (index2 >= 1)\n {\n /* code */\n ans *= radix;\n index2 -= 1;\n }\n return ans;\n}\nll stol2 (string num) {\n ll ans = 0;\n rep(i, num.size()) {\n ans += (num[i] - '0') * power(10, num.size() - i -1);\n }\n return ans;\n}\nll gcd(ll m , ll n) {\n if (n == 0) return m;\n return gcd(n, m % n);\n}\n//二分探索で[50,50,50,51]のような同じものが複数個\n//あるようなとき左と右どちらに合わせるかで注意!!\nint main() {\n ll n, m ; cin >> n >> m;\n ll r ; cin >> r;\n map<pair<ll,ll>, ll> weight;\n vector<pair<ll,ll>> edge;\n if (n == 1) {\n cout << 0 << endl;\n exit(0);\n }\n rep(i, m) {\n ll v,v2, w; cin >> v >> v2 >> w;\n edge.push_back(make_pair(v, v2));\n weight[make_pair(v,v2)] = w;\n }\n vector<ll> dist(n, 100100100100);\n dist[r] = 0;\n int t = 1;\n ll count = 0;\n while ((t == 1) && (count <= n-1))\n {\n /* code */\n t = 0;\n rep(i, m) {\n ll now_node = edge[i].first;\n ll next_node = edge[i].second;\n ll cost = weight[make_pair(now_node, next_node)];\n //cout << cost << endl;\n if (dist[now_node] == 100100100100) continue;\n if (dist[now_node] + cost < dist[next_node]) {\n //cout << \"i; \" << i << \" now_node: \" << now_node << \" next_node: \" << next_node << endl; \n dist[next_node] = dist[now_node] +cost;\n t = 1;\n }\n } \n if (t) {\n count ++;\n if (count == n) {\n cout << \"NEGATIVE CYCLE\" << endl;\n exit(0);\n }\n }\n }\n rep(i, n) {\n if (dist[i] >= 10010010010) cout << \"INF\" << endl;\n else cout << dist[i] << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3508, "score_of_the_acc": -0.0263, "final_rank": 4 }, { "submission_id": "aoj_GRL_1_B_8795916", "code_snippet": "#ifdef DEBUG\n #define _GLIBCXX_DEBUG\n #define REPEAT_MAIN( BOUND ) START_MAIN; signal( SIGABRT , &AlertAbort ); AutoCheck( exec_mode , use_getline ); if( exec_mode == sample_debug_mode || exec_mode == submission_debug_mode || exec_mode == library_search_mode ){ return 0; } else if( exec_mode == experiment_mode ){ Experiment(); return 0; } else if( exec_mode == small_test_mode ){ SmallTest(); return 0; }; DEXPR( int , bound_test_case_num , BOUND , min( BOUND , 100 ) ); int test_case_num = 1; if( exec_mode == solve_mode ){ if constexpr( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } } else if( exec_mode == random_test_mode ){ CERR( \"ランダムテストを行う回数を指定してください。\" ); SET_LL( test_case_num ); } FINISH_MAIN\n #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , DEBUG_VALUE )\n #define ASSERT( A , MIN , MAX ) CERR( \"ASSERTチェック: \" , ( MIN ) , ( ( MIN ) <= A ? \"<=\" : \">\" ) , A , ( A <= ( MAX ) ? \"<=\" : \">\" ) , ( MAX ) ); assert( ( MIN ) <= A && A <= ( MAX ) )\n #define SET_ASSERT( A , MIN , MAX ) if( exec_mode == solve_mode ){ SET_LL( A ); ASSERT( A , MIN , MAX ); } else if( exec_mode == random_test_mode ){ CERR( #A , \" = \" , ( A = GetRand( MIN , MAX ) ) ); } else { assert( false ); }\n #define SOLVE_ONLY static_assert( __FUNCTION__[0] == 'S' )\n #define CERR( ... ) VariadicCout( cerr , __VA_ARGS__ ) << endl\n #define COUT( ... ) VariadicCout( cout << \"出力: \" , __VA_ARGS__ ) << endl\n #define CERR_A( A , N ) OUTPUT_ARRAY( cerr , A , N ) << endl\n #define COUT_A( A , N ) cout << \"出力: \"; OUTPUT_ARRAY( cout , A , N ) << endl\n #define CERR_ITR( A ) OUTPUT_ITR( cerr , A ) << endl\n #define COUT_ITR( A ) cout << \"出力: \"; OUTPUT_ITR( cout , A ) << endl\n#else\n #pragma GCC optimize ( \"O3\" )\n #pragma GCC optimize ( \"unroll-loops\" )\n #pragma GCC target ( \"sse4.2,fma,avx2,popcnt,lzcnt,bmi2\" )\n #define REPEAT_MAIN( BOUND ) START_MAIN; CEXPR( int , bound_test_case_num , BOUND ); int test_case_num = 1; if constexpr( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } FINISH_MAIN\n #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , VALUE )\n #define ASSERT( A , MIN , MAX ) assert( ( MIN ) <= A && A <= ( MAX ) )\n #define SET_ASSERT( A , MIN , MAX ) SET_LL( A ); ASSERT( A , MIN , MAX )\n #define SOLVE_ONLY \n #define CERR( ... ) \n #define COUT( ... ) VariadicCout( cout , __VA_ARGS__ ) << ENDL\n #define CERR_A( A , N ) \n #define COUT_A( A , N ) OUTPUT_ARRAY( cout , A , N ) << ENDL\n #define CERR_ITR( A ) \n #define COUT_ITR( A ) OUTPUT_ITR( cout , A ) << ENDL\n#endif\n#ifdef REACTIVE\n #define ENDL endl\n#else\n #define ENDL \"\\n\"\n#endif\n#ifdef USE_GETLINE\n #define SET_LL( A ) { GETLINE( A ## _str ); A = stoll( A ## _str ); }\n #define GETLINE_SEPARATE( SEPARATOR , ... ) SOLVE_ONLY; string __VA_ARGS__; VariadicGetline( cin , SEPARATOR , __VA_ARGS__ )\n #define GETLINE( ... ) SOLVE_ONLY; GETLINE_SEPARATE( '\\n' , __VA_ARGS__ )\n#else\n #define SET_LL( A ) cin >> A\n #define CIN( LL , ... ) SOLVE_ONLY; LL __VA_ARGS__; VariadicCin( cin , __VA_ARGS__ )\n #define SET_A( A , N ) SOLVE_ONLY; FOR( VARIABLE_FOR_CIN_A , 0 , N ){ cin >> A[VARIABLE_FOR_CIN_A]; }\n #define CIN_A( LL , A , N ) vector<LL> A( N ); SET_A( A , N );\n#endif\n#include <bits/stdc++.h>\nusing namespace std;\nusing uint = unsigned int;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing lld = __float128;\ntemplate <typename INT> using T2 = pair<INT,INT>;\ntemplate <typename INT> using T3 = tuple<INT,INT,INT>;\ntemplate <typename INT> using T4 = tuple<INT,INT,INT,INT>;\nusing path = pair<int,ll>;\n#define ATT __attribute__( ( target( \"sse4.2,fma,avx2,popcnt,lzcnt,bmi2\" ) ) )\n#define START_MAIN int main(){ ios_base::sync_with_stdio( false ); cin.tie( nullptr )\n#define FINISH_MAIN REPEAT( test_case_num ){ if constexpr( bound_test_case_num > 1 ){ CERR( \"testcase \" , VARIABLE_FOR_REPEAT_test_case_num , \":\" ); } Solve(); CERR( \"\" ); } }\n#define START_WATCH chrono::system_clock::time_point watch = chrono::system_clock::now()\n#define CURRENT_TIME static_cast<double>( chrono::duration_cast<chrono::microseconds>( chrono::system_clock::now() - watch ).count() / 1000.0 )\n#define CHECK_WATCH( TL_MS ) ( CURRENT_TIME < TL_MS - 100.0 )\n#define TYPE_OF( VAR ) decay_t<decltype( VAR )>\n#define CEXPR( LL , BOUND , VALUE ) constexpr LL BOUND = VALUE\n#define CIN_ASSERT( A , MIN , MAX ) TYPE_OF( MAX ) A; SET_ASSERT( A , MIN , MAX )\n#define FOR( VAR , INITIAL , FINAL_PLUS_ONE ) for( TYPE_OF( FINAL_PLUS_ONE ) VAR = INITIAL ; VAR < FINAL_PLUS_ONE ; VAR ++ )\n#define FOREQ( VAR , INITIAL , FINAL ) for( TYPE_OF( FINAL ) VAR = INITIAL ; VAR <= FINAL ; VAR ++ )\n#define FOREQINV( VAR , INITIAL , FINAL ) for( TYPE_OF( INITIAL ) VAR = INITIAL ; VAR + 1 > FINAL ; VAR -- )\n#define AUTO_ITR( ARRAY ) auto itr_ ## ARRAY = ARRAY .begin() , end_ ## ARRAY = ARRAY .end()\n#define FOR_ITR( ARRAY ) for( AUTO_ITR( ARRAY ) , itr = itr_ ## ARRAY ; itr_ ## ARRAY != end_ ## ARRAY ; itr_ ## ARRAY ++ , itr++ )\n#define REPEAT( HOW_MANY_TIMES ) FOR( VARIABLE_FOR_REPEAT_ ## HOW_MANY_TIMES , 0 , HOW_MANY_TIMES )\n#define SET_PRECISION( DECIMAL_DIGITS ) cout << fixed << setprecision( DECIMAL_DIGITS )\n#define OUTPUT_ARRAY( OS , A , N ) FOR( VARIABLE_FOR_OUTPUT_ARRAY , 0 , N ){ OS << A[VARIABLE_FOR_OUTPUT_ARRAY] << (VARIABLE_FOR_OUTPUT_ARRAY==N-1?\"\":\" \"); } OS\n#define OUTPUT_ITR( OS , A ) { auto ITERATOR_FOR_OUTPUT_ITR = A.begin() , END_FOR_OUTPUT_ITR = A.end(); bool VARIABLE_FOR_OUTPUT_ITR = ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR; while( VARIABLE_FOR_OUTPUT_ITR ){ OS << *ITERATOR_FOR_COUT_ITR; ( VARIABLE_FOR_OUTPUT_ITR = ++ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR ) ? OS : OS << \" \"; } } OS\n#define RETURN( ... ) SOLVE_ONLY; COUT( __VA_ARGS__ ); return\n#define COMPARE( ... ) auto naive = Naive( __VA_ARGS__ ); auto answer = Answer( __VA_ARGS__ ); bool match = naive == answer; COUT( \"(\" , #__VA_ARGS__ , \") == (\" , __VA_ARGS__ , \") : Naive == \" , naive , match ? \"==\" : \"!=\" , answer , \"== Answer\" ); if( !match ){ return; }\n\n// 入出力用\ntemplate <class Traits> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is ) { return is; }\ntemplate <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is , Arg& arg , ARGS&... args ) { return VariadicCin( is >> arg , args... ); }\ntemplate <class Traits> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator ) { return is; }\ntemplate <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator , Arg& arg , ARGS&... args ) { return VariadicGetline( getline( is , arg , separator ) , separator , args... ); }\ntemplate <class Traits , typename Arg> inline basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os , const vector<Arg>& arg ) { auto begin = arg.begin() , end = arg.end(); auto itr = begin; while( itr != end ){ ( itr == begin ? os : os << \" \" ) << *itr; itr++; } return os; }\ntemplate <class Traits , typename Arg> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg& arg ) { return os << arg; }\ntemplate <class Traits , typename Arg1 , typename Arg2 , typename... ARGS> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg1& arg1 , const Arg2& arg2 , const ARGS&... args ) { return VariadicCout( os << arg1 << \" \" , arg2 , args... ); }\n\n// デバッグ用\n#ifdef DEBUG\n inline void AlertAbort( int n ) { CERR( \"abort関数が呼ばれました。assertマクロのメッセージが出力されていない場合はオーバーフローの有無を確認をしてください。\" ); }\n void AutoCheck( int& exec_mode , const bool& use_getline );\n inline void Solve();\n inline void Experiment();\n inline void SmallTest();\n inline void RandomTest();\n ll GetRand( const ll& Rand_min , const ll& Rand_max );\n int exec_mode;\n CEXPR( int , solve_mode , 0 );\n CEXPR( int , sample_debug_mode , 1 );\n CEXPR( int , submission_debug_mode , 2 );\n CEXPR( int , library_search_mode , 3 );\n CEXPR( int , experiment_mode , 4 );\n CEXPR( int , small_test_mode , 5 );\n CEXPR( int , random_test_mode , 6 );\n #ifdef USE_GETLINE\n CEXPR( bool , use_getline , true );\n #else\n CEXPR( bool , use_getline , false );\n #endif\n#else\n ll GetRand( const ll& Rand_min , const ll& Rand_max ) { ll answer = time( NULL ); return answer * rand() % ( Rand_max + 1 - Rand_min ) + Rand_min; }\n#endif\n\n// 圧縮用\n#define TE template\n#define TY typename\n#define US using\n#define ST static\n#define IN inline\n#define CL class\n#define PU public\n#define OP operator\n#define CE constexpr\n#define CO const\n#define NE noexcept\n#define RE return \n#define WH while\n#define VO void\n#define VE vector\n#define LI list\n#define BE begin\n#define EN end\n#define SZ size\n#define MO move\n#define TH this\n#define CRI CO int&\n#define CRUI CO uint&\n#define CRL CO ll&\n\n// VVV 常設ライブラリは以下に挿入する。\n// Map\n// c:/Users/user/Documents/Programming/Mathematics/Function/Map\nCL is_ordered{PU:is_ordered()= delete;TE <TY T> ST CE auto Check(CO T& t)-> decltype(t < t,true_type());ST CE false_type Check(...);TE <TY T> ST CE CO bool value = is_same_v< decltype(Check(declval<T>())),true_type >;};\nTE <TY T , TY U>US Map = conditional_t<is_constructible_v<unordered_map<T,int>>,unordered_map<T,U>,conditional_t<is_ordered::value<T>,map<T,U>,void>>;\n// AAA 常設ライブラリは以上に挿入する。\n\n// グラフ用\ntemplate <typename PATH> vector<list<PATH> > gE;\ntemplate <typename T , template <typename...> typename V> inline auto Get( const V<T>& a ) { return [&]( const int& i ){ return a[i]; }; }\n\n\n// 圧縮時は中身だけ削除する。\ninline void Experiment()\n{\n}\n\n// 圧縮時は中身だけ削除する。\ninline void SmallTest()\n{\n}\n\n// VVV 常設でないライブラリは以下に挿入する。\n\ntemplate <typename U>\nclass VirtualPointedSet\n{\n\npublic:\n virtual const U& Point() const noexcept = 0;\n inline const U& Unit() const noexcept;\n inline const U& Zero() const noexcept;\n inline const U& One() const noexcept;\n inline const U& Infty() const noexcept;\n inline const U& size() const noexcept;\n\n};\n\ntemplate <typename U>\nclass PointedSet :\n virtual public VirtualPointedSet<U>\n{\n\nprivate:\n U m_b_U;\n\npublic:\n inline PointedSet( const U& b_u = U() );\n inline const U& Point() const noexcept;\n\n};\n\ntemplate <typename U>\nclass VirtualNSet\n{\n\npublic:\n virtual U Transfer( const U& u ) = 0;\n inline U Inverse( const U& u );\n\n};\n\ntemplate <typename U , typename F_U>\nclass AbstractNSet :\n virtual public VirtualNSet<U>\n{\n\nprivate:\n F_U m_f_U;\n\npublic:\n inline AbstractNSet( F_U f_U );\n inline U Transfer( const U& u );\n\n};\n\ntemplate <typename U>\nclass VirtualMagma\n{\n\npublic:\n virtual U Product( const U& u0 , const U& u1 ) = 0;\n inline U Sum( const U& u0 , const U& u1 );\n\n};\n\ntemplate <typename U , typename M_U>\nclass AbstractMagma :\n virtual public VirtualMagma<U>\n{\n\nprivate:\n M_U m_m_U;\n\npublic:\n inline AbstractMagma( M_U m_U );\n inline U Product( const U& u0 , const U& u1 );\n\n};\n\ntemplate <typename U> inline PointedSet<U>::PointedSet( const U& b_U ) : m_b_U( b_U ) {}\ntemplate <typename U> inline const U& PointedSet<U>::Point() const noexcept { return m_b_U; }\ntemplate <typename U> inline const U& VirtualPointedSet<U>::Unit() const noexcept { return Point(); }\ntemplate <typename U> inline const U& VirtualPointedSet<U>::Zero() const noexcept { return Point(); }\ntemplate <typename U> inline const U& VirtualPointedSet<U>::One() const noexcept { return Point(); }\ntemplate <typename U> inline const U& VirtualPointedSet<U>::Infty() const noexcept { return Point(); }\ntemplate <typename U> inline const U& VirtualPointedSet<U>::size() const noexcept { return Point(); }\n\ntemplate <typename U , typename F_U> inline AbstractNSet<U,F_U>::AbstractNSet( F_U f_U ) : m_f_U( move( f_U ) ) { static_assert( is_invocable_r_v<U,F_U,U> ); }\ntemplate <typename U , typename F_U> inline U AbstractNSet<U,F_U>::Transfer( const U& u ) { return m_f_U( u ); }\ntemplate <typename U> inline U VirtualNSet<U>::Inverse( const U& u ) { return Transfer( u ); }\n\ntemplate <typename U , typename M_U> inline AbstractMagma<U,M_U>::AbstractMagma( M_U m_U ) : m_m_U( move( m_U ) ) { static_assert( is_invocable_r_v<U,M_U,U,U> ); }\ntemplate <typename U , typename M_U> inline U AbstractMagma<U,M_U>::Product( const U& u0 , const U& u1 ) { return m_m_U( u0 , u1 ); }\ntemplate <typename U> inline U VirtualMagma<U>::Sum( const U& u0 , const U& u1 ) { return Product( u0 , u1 ); }\n\n\ntemplate <typename U>\nclass VirtualMonoid :\n virtual public VirtualMagma<U> ,\n virtual public VirtualPointedSet<U>\n{};\n\ntemplate <typename U = ll>\nclass AdditiveMonoid :\n virtual public VirtualMonoid<U> ,\n public PointedSet<U>\n{\n\npublic:\n inline U Product( const U& u0 , const U& u1 );\n static inline AdditiveMonoid<U>& Object();\n\n};\n\ntemplate <typename U = ll>\nclass MultiplicativeMonoid :\n virtual public VirtualMonoid<U> ,\n public PointedSet<U>\n{\n\npublic:\n inline MultiplicativeMonoid( const U& e_U );\n inline U Product( const U& u0 , const U& u1 );\n static inline MultiplicativeMonoid<U>& Object();\n\n};\n\ntemplate <typename U , typename M_U>\nclass AbstractMonoid :\n virtual public VirtualMonoid<U> ,\n public AbstractMagma<U,M_U> ,\n public PointedSet<U>\n{\n\npublic:\n inline AbstractMonoid( M_U m_U , const U& e_U );\n inline U Product( const U& u0 , const U& u1 );\n\n};\n\ntemplate <typename U> inline MultiplicativeMonoid<U>::MultiplicativeMonoid( const U& e_U ) : PointedSet<U>( e_U ) {}\ntemplate <typename U , typename M_U> inline AbstractMonoid<U,M_U>::AbstractMonoid( M_U m_U , const U& e_U ) : AbstractMagma<U,M_U>( move( m_U ) ) , PointedSet<U>( e_U ) {}\n\ntemplate <typename U> inline U AdditiveMonoid<U>::Product( const U& u0 , const U& u1 ) { return u0 + u1; }\ntemplate <typename U> inline U MultiplicativeMonoid<U>::Product( const U& u0 , const U& u1 ) { return u0 * u1; }\ntemplate <typename U , typename M_U> inline U AbstractMonoid<U,M_U>::Product( const U& u0 , const U& u1 ) { return m_m_U( u0 , u1 ); }\n\ntemplate <typename U> inline AdditiveMonoid<U>& AdditiveMonoid<U>::Object() { static AdditiveMonoid<U> obj{}; return obj; }\n\n\n#ifndef RET_TYPE\n #define RET_TYPE\n template <typename F , typename...Args> using ret_t = decltype( declval<F>()( declval<Args>()... ) );\n#endif\n#ifndef INNER_TYPE\n #define INNER_TYPE\n template <typename T> using inner_t = typename T::type;\n#endif\n#ifndef decldecay_t\n #define decldecay_t( VAR ) decay_t<decltype( VAR )>\n#endif\n\n// Enumeration:N->R1-->TとEnumeration_inv:T->R2-->Nは互いに逆写像である仮想関数。\ntemplate <typename T , typename R1 , typename R2 , typename E>\nclass VirtualGraph :\n public PointedSet<int>\n{\n\nprivate:\n E m_edge;\n\npublic:\n inline VirtualGraph( const int& size , E edge );\n virtual R1 Enumeration( const int& i ) = 0;\n virtual R2 Enumeration_inv( const T& t ) = 0;\n inline void Reset();\n ret_t<E,T> Edge( const T& t );\n using type = T;\n\n};\n\ntemplate <typename E>\nclass Graph :\n virtual public VirtualGraph<int,const int&,const int&,E>\n{\n \npublic:\n inline Graph( const int& size , E edge );\n inline const int& Enumeration( const int& i );\n inline const int& Enumeration_inv( const int& t );\n template <typename F> inline Graph<F> GetGraph( F edge ) const;\n\n};\n\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename E>\nclass EnumerationGraph :\n virtual public VirtualGraph<T,ret_t<Enum_T,int>,ret_t<Enum_T_inv,T>,E>\n{\n\nprivate:\n Enum_T m_enum_T;\n Enum_T_inv m_enum_T_inv;\n \npublic:\n inline EnumerationGraph( const int& size , Enum_T enum_T , Enum_T_inv enum_T_inv , E edge );\n inline ret_t<Enum_T,int> Enumeration( const int& i );\n inline ret_t<Enum_T_inv,T> Enumeration_inv( const T& t );\n template <typename F> inline EnumerationGraph<T,Enum_T,Enum_T_inv,F> GetGraph( F edge ) const;\n\n};\ntemplate <typename Enum_T , typename Enum_T_inv , typename E> EnumerationGraph( const int& size , Enum_T enum_T , Enum_T_inv enum_T_inv , E edge ) -> EnumerationGraph<decldecay_t(get<0>(declval<E>()(0).front())),Enum_T,Enum_T_inv,E>;\n\n// 推論補助のためにE::operator()はデフォルト引数が必要。\ntemplate <typename T , typename E>\nclass MemorisationGraph :\n virtual public VirtualGraph<T,T,const int&,E>\n{\n\nprivate:\n int m_length;\n vector<T> m_memory;\n Map<T,int> m_memory_inv;\n \npublic:\n inline MemorisationGraph( const int& size , E edge );\n // push_backする可能性のあるvectorなので参照にしないように注意\n inline T Enumeration( const int& i );\n inline const int& Enumeration_inv( const T& t );\n inline void Reset();\n template <typename F> inline MemorisationGraph<T,F> GetGraph( F edge ) const;\n\n};\ntemplate <typename E> MemorisationGraph( const int& size , E edge ) -> MemorisationGraph<decldecay_t(get<0>(declval<E>()().front())),E>;\n\ntemplate <typename T , typename R1 , typename R2 , typename E> inline VirtualGraph<T,R1,R2,E>::VirtualGraph( const int& size , E edge ) : PointedSet<int>( size ) , m_edge( move( edge ) ) { static_assert( is_constructible_v<T,R1> && is_constructible_v<int,R2> && is_invocable_v<E,T> ); }\ntemplate <typename E> inline Graph<E>::Graph( const int& size , E edge ) : VirtualGraph<int,const int&,const int&,E>( size , move( edge ) ) {}\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename E> inline EnumerationGraph<T,Enum_T,Enum_T_inv,E>::EnumerationGraph( const int& size , Enum_T enum_T , Enum_T_inv enum_T_inv , E edge ) : VirtualGraph<T,ret_t<Enum_T,int>,ret_t<Enum_T_inv,T>,E>( size , move( edge ) ) , m_enum_T( move( enum_T ) ) , m_enum_T_inv( move( enum_T_inv ) ) {}\ntemplate <typename T , typename E> inline MemorisationGraph<T,E>::MemorisationGraph( const int& size , E edge ) : VirtualGraph<T,T,const int&,E>( size , move( edge ) ) , m_length() , m_memory() , m_memory_inv() {}\n\ntemplate <typename T , typename R1 , typename R2 , typename E> inline ret_t<E,T> VirtualGraph<T,R1,R2,E>::Edge( const T& t ) { return m_edge( t ); }\n\ntemplate <typename E> inline const int& Graph<E>::Enumeration( const int& i ) { return i; }\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename E> inline ret_t<Enum_T,int> EnumerationGraph<T,Enum_T,Enum_T_inv,E>::Enumeration( const int& i ) { return m_enum_T( i ); }\ntemplate <typename T , typename E> inline T MemorisationGraph<T,E>::Enumeration( const int& i ) { assert( 0 <= i && i < m_length ); return m_memory[i]; }\n\ntemplate <typename E> inline const int& Graph<E>::Enumeration_inv( const int& i ) { return i; }\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename E> inline ret_t<Enum_T_inv,T> EnumerationGraph<T,Enum_T,Enum_T_inv,E>::Enumeration_inv( const T& t ) { return m_enum_T_inv( t ); }\ntemplate <typename T , typename E> inline const int& MemorisationGraph<T,E>::Enumeration_inv( const T& t )\n{\n\n if( m_memory_inv.count( t ) == 0 ){\n\n assert( m_length < this->size() );\n m_memory.push_back( t );\n return m_memory_inv[t] = m_length++;\n\n }\n \n return m_memory_inv[t];\n\n}\n\ntemplate <typename T , typename R1 , typename R2 , typename E> void VirtualGraph<T,R1,R2,E>::Reset() {}\ntemplate <typename T , typename E> inline void MemorisationGraph<T,E>::Reset() { m_length = 0; m_memory.clear(); m_memory_inv.clear(); }\n\ntemplate <typename E> template <typename F> inline Graph<F> Graph<E>::GetGraph( F edge ) const { return Graph<F>( this->size() , move( edge ) ); }\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename E> template <typename F> inline EnumerationGraph<T,Enum_T,Enum_T_inv,F> EnumerationGraph<T,Enum_T,Enum_T_inv,E>::GetGraph( F edge ) const { return EnumerationGraph( this->size() , m_enum_T , m_enum_T_inv , move( edge ) ); }\ntemplate <typename T , typename E> template <typename F> inline MemorisationGraph<T,F> MemorisationGraph<T,E>::GetGraph( F edge ) const { return MemorisationGraph( this->size() , move( edge ) ); }\n\n#define BELLMAN_FORD_BODY( INITIALISE_PREV , SET_PREV )\t\t\t\\\n const U& zero = m_M.Zero();\t\t\t\t\t\t\\\n const U& infty = this->Infty();\t\t\t\t\t\\\n assert( zero < infty );\t\t\t\t\t\t\\\n const int& size = m_G.size();\t\t\t\t\t\t\\\n auto&& i_start = m_G.Enumeration_inv( t_start );\t\t\t\\\n assert( 0 <= i_start && i_start < size );\t\t\t\t\\\n vector<bool> found( size );\t\t\t\t\t\t\\\n vector<U> weight( size , infty );\t\t\t\t\t\\\n found[i_start] = true;\t\t\t\t\t\t\\\n weight[i_start] = 0;\t\t\t\t\t\t\t\\\n INITIALISE_PREV;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( int length = 0 ; length < size ; length++ ){\t\t\t\\\n \t\t\t\t\t\t\t\t\t\\\n for( int i = 0 ; i < size ; i++ ){\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n if( found[i] ){\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tconst U& weight_i = weight[i];\t\t\t\t\t\\\n\tassert( weight_i != infty );\t\t\t\t\t\\\n\tauto&& edge_i = m_G.Edge( m_G.Enumeration( i ) );\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tfor( auto itr = edge_i.begin() , end = edge_i.end() ; itr != end ; itr++ ){ \\\n\t\t\t\t\t\t\t\t\t\\\n\t auto&& j = m_G.Enumeration_inv( itr->first );\t\t\t\\\n\t const U& edge_ij = itr->second;\t\t\t\t\\\n\t U temp = m_M.Sum( weight_i , edge_ij );\t\t\t\\\n\t U& weight_j = weight[j];\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t if( weight_j > temp ){\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t found[j] = true;\t\t\t\t\t\t\\\n\t weight_j = move( temp );\t\t\t\t\t\\\n\t SET_PREV;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t }\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n bool valid = true;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( int i = 0 ; i < size && valid ; i++ ){\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n if( found[i] ){\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n const U& weight_i = weight[i];\t\t\t\t\t\\\n auto&& edge_i = m_G.Edge( m_G.Enumeration( i ) );\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( auto itr = edge_i.begin() , end = edge_i.end() ; itr != end ; itr++ ){ \\\n\t\t\t\t\t\t\t\t\t\\\n\tauto&& j = m_G.Enumeration_inv( itr->first );\t\t\t\\\n\tconst U& edge_ij = itr->second;\t\t\t\t\t\\\n\tU& weight_j = weight[j];\t\t\t\t\t\\\n\tconst U temp = m_M.Sum( weight_i , edge_ij );\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tif( weight_j > temp ){\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t valid = false;\t\t\t\t\t\t\\\n\t break;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\n\n// GRAPHはグラフG=(V_G,E_G:T->(T \\times U)^{< \\omega})に相当する型。\n\n// 入力の範囲内で要件\n// (0) Mは全順序可換モノイド構造である。\n// (1) inftyがE_Gの値の各成分の第2成分|V_G|個以下の和で表せるいかなる数よりも大きい。\n// が成り立つ場合にのみサポート。\n\n// 単一始点全終点最短経路探索/経路復元なしO(|V_G| |E_G|)\n// 単一始点全終点最短経路探索/経路復元ありO(|V_G| |E_G|)\ntemplate <typename GRAPH , typename MONOID , typename U>\nclass AbstractBellmanFord :\n public PointedSet<U>\n{\n\nprivate:\n GRAPH m_G;\n MONOID m_M;\n\npublic:\n inline AbstractBellmanFord( GRAPH G , MONOID M , const U& infty );\n\n // 負の閉路が存在すればfalse、存在しなければtrueを第1成分に返す。\n tuple<bool,vector<U>> GetDistance( const inner_t<GRAPH>& t_start );\n tuple<bool,vector<U>,vector<list<inner_t<GRAPH>>>> GetPath( const inner_t<GRAPH>& t_start );\n \n};\n\ntemplate <typename GRAPH>\nclass BellmanFord :\n public AbstractBellmanFord<GRAPH,AdditiveMonoid<>,ll>\n{\n\npublic:\n inline BellmanFord( GRAPH G );\n \n};\n\ntemplate <typename GRAPH , typename MONOID , typename U> inline AbstractBellmanFord<GRAPH,MONOID,U>::AbstractBellmanFord( GRAPH G , MONOID M , const U& infty ) : PointedSet<U>( infty ) , m_G( move( G ) ) , m_M( move( M ) ) { static_assert( ! is_same_v<U,int> ); }\n\ntemplate <typename GRAPH> inline BellmanFord<GRAPH>::BellmanFord( GRAPH G ) : AbstractBellmanFord<GRAPH,AdditiveMonoid<>,ll>( move( G ) , AdditiveMonoid<>::Object() , 4611686018427387904 ) {}\n\ntemplate <typename GRAPH , typename MONOID , typename U>\ntuple<bool,vector<U>> AbstractBellmanFord<GRAPH,MONOID,U>::GetDistance( const inner_t<GRAPH>& t_start )\n{\n\n BELLMAN_FORD_BODY( , );\n m_G.Reset();\n return { valid , move( weight ) };\n\n}\n\ntemplate <typename GRAPH , typename MONOID , typename U>\ntuple<bool,vector<U>,vector<list<inner_t<GRAPH>>>> AbstractBellmanFord<GRAPH,MONOID,U>::GetPath( const inner_t<GRAPH>& t_start )\n{\n\n BELLMAN_FORD_BODY( vector<int> prev( size ) , prev[j] = i );\n vector<list<inner_t<GRAPH>>> path( valid ? size : 0 );\n\n if( valid ){\n \n for( int j = 0 ; j < size ; j++ ){\n\n auto& path_j = path[j];\n int i = j;\n\n while( i != i_start ){\n\n\tpath_j.push_front( m_G.Enumeration( i ) );\n\ti = prev[i];\n\n }\n\n path_j.push_front( t_start );\n\n }\n\n }\n\n m_G.Reset();\n return { valid , move( weight ) , move( path ) };\n\n}\n\n// AAA 常設でないライブラリは以上に挿入する。\n\ninline void Solve()\n{\n CIN( int , N , M , r );\n gE<path>.resize( N );\n FOR( j , 0 , M ){\n CIN( int , uj , vj );\n CIN( ll , wj );\n gE<path>[uj].push_back( { vj , wj } );\n }\n Graph graph{ N , Get( gE<path> ) };\n BellmanFord bf{ move( graph ) };\n auto [b,weight] = bf.GetDistance( r );\n if( b ){\n FOR( i , 0 , N ){\n if( weight[i] == bf.Infty() ){\n\tCOUT( \"INF\" );\n } else {\n\tCOUT( weight[i] );\n }\n }\n } else {\n COUT( \"NEGATIVE CYCLE\" );\n }\n}\nREPEAT_MAIN(1);", "accuracy": 1, "time_ms": 30, "memory_kb": 3592, "score_of_the_acc": -0.0275, "final_rank": 6 }, { "submission_id": "aoj_GRL_1_B_8779457", "code_snippet": "#ifdef DEBUG\n #define _GLIBCXX_DEBUG\n #define REPEAT_MAIN( BOUND ) START_MAIN; signal( SIGABRT , &AlertAbort ); AutoCheck( exec_mode , use_getline ); if( exec_mode == sample_debug_mode || exec_mode == submission_debug_mode || exec_mode == library_search_mode ){ return 0; } else if( exec_mode == experiment_mode ){ Experiment(); return 0; } else if( exec_mode == small_test_mode ){ SmallTest(); return 0; }; DEXPR( int , bound_test_case_num , BOUND , min( BOUND , 100 ) ); int test_case_num = 1; if( exec_mode == solve_mode ){ if constexpr( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } } else if( exec_mode == random_test_mode ){ CERR( \"ランダムテストを行う回数を指定してください。\" ); SET_LL( test_case_num ); } FINISH_MAIN\n #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , DEBUG_VALUE )\n #define ASSERT( A , MIN , MAX ) CERR( \"ASSERTチェック: \" , ( MIN ) , ( ( MIN ) <= A ? \"<=\" : \">\" ) , A , ( A <= ( MAX ) ? \"<=\" : \">\" ) , ( MAX ) ); assert( ( MIN ) <= A && A <= ( MAX ) )\n #define SET_ASSERT( A , MIN , MAX ) if( exec_mode == solve_mode ){ SET_LL( A ); ASSERT( A , MIN , MAX ); } else if( exec_mode == random_test_mode ){ CERR( #A , \" = \" , ( A = GetRand( MIN , MAX ) ) ); } else { assert( false ); }\n #define SOLVE_ONLY static_assert( __FUNCTION__[0] == 'S' )\n #define CERR( ... ) VariadicCout( cerr , __VA_ARGS__ ) << endl\n #define COUT( ... ) VariadicCout( cout << \"出力: \" , __VA_ARGS__ ) << endl\n #define CERR_A( A , N ) OUTPUT_ARRAY( cerr , A , N ) << endl\n #define COUT_A( A , N ) cout << \"出力: \"; OUTPUT_ARRAY( cout , A , N ) << endl\n #define CERR_ITR( A ) OUTPUT_ITR( cerr , A ) << endl\n #define COUT_ITR( A ) cout << \"出力: \"; OUTPUT_ITR( cout , A ) << endl\n#else\n #pragma GCC optimize ( \"O3\" )\n #pragma GCC optimize ( \"unroll-loops\" )\n #pragma GCC target ( \"sse4.2,fma,avx2,popcnt,lzcnt,bmi2\" )\n #define REPEAT_MAIN( BOUND ) START_MAIN; CEXPR( int , bound_test_case_num , BOUND ); int test_case_num = 1; if constexpr( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } FINISH_MAIN\n #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , VALUE )\n #define ASSERT( A , MIN , MAX ) assert( ( MIN ) <= A && A <= ( MAX ) )\n #define SET_ASSERT( A , MIN , MAX ) SET_LL( A ); ASSERT( A , MIN , MAX )\n #define SOLVE_ONLY \n #define CERR( ... ) \n #define COUT( ... ) VariadicCout( cout , __VA_ARGS__ ) << ENDL\n #define CERR_A( A , N ) \n #define COUT_A( A , N ) OUTPUT_ARRAY( cout , A , N ) << ENDL\n #define CERR_ITR( A ) \n #define COUT_ITR( A ) OUTPUT_ITR( cout , A ) << ENDL\n#endif\n#ifdef REACTIVE\n #define ENDL endl\n#else\n #define ENDL \"\\n\"\n#endif\n#ifdef USE_GETLINE\n #define SET_LL( A ) { GETLINE( A ## _str ); A = stoll( A ## _str ); }\n #define GETLINE_SEPARATE( SEPARATOR , ... ) SOLVE_ONLY; string __VA_ARGS__; VariadicGetline( cin , SEPARATOR , __VA_ARGS__ )\n #define GETLINE( ... ) SOLVE_ONLY; GETLINE_SEPARATE( '\\n' , __VA_ARGS__ )\n#else\n #define SET_LL( A ) cin >> A\n #define CIN( LL , ... ) SOLVE_ONLY; LL __VA_ARGS__; VariadicCin( cin , __VA_ARGS__ )\n #define SET_A( A , N ) SOLVE_ONLY; FOR( VARIABLE_FOR_CIN_A , 0 , N ){ cin >> A[VARIABLE_FOR_CIN_A]; }\n #define CIN_A( LL , A , N ) vector<LL> A( N ); SET_A( A , N );\n#endif\n#include <bits/stdc++.h>\nusing namespace std;\nusing uint = unsigned int;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing lld = __float128;\ntemplate <typename INT> using T2 = pair<INT,INT>;\ntemplate <typename INT> using T3 = tuple<INT,INT,INT>;\ntemplate <typename INT> using T4 = tuple<INT,INT,INT,INT>;\nusing path = pair<int,ll>;\n#define ATT __attribute__( ( target( \"sse4.2,fma,avx2,popcnt,lzcnt,bmi2\" ) ) )\n#define START_MAIN int main(){ ios_base::sync_with_stdio( false ); cin.tie( nullptr )\n#define FINISH_MAIN REPEAT( test_case_num ){ if constexpr( bound_test_case_num > 1 ){ CERR( \"testcase \" , VARIABLE_FOR_REPEAT_test_case_num , \":\" ); } Solve(); CERR( \"\" ); } }\n#define START_WATCH chrono::system_clock::time_point watch = chrono::system_clock::now()\n#define CURRENT_TIME static_cast<double>( chrono::duration_cast<chrono::microseconds>( chrono::system_clock::now() - watch ).count() / 1000.0 )\n#define CHECK_WATCH( TL_MS ) ( CURRENT_TIME < TL_MS - 100.0 )\n#define TYPE_OF( VAR ) decay_t<decltype( VAR )>\n#define CEXPR( LL , BOUND , VALUE ) constexpr LL BOUND = VALUE\n#define CIN_ASSERT( A , MIN , MAX ) TYPE_OF( MAX ) A; SET_ASSERT( A , MIN , MAX )\n#define FOR( VAR , INITIAL , FINAL_PLUS_ONE ) for( TYPE_OF( FINAL_PLUS_ONE ) VAR = INITIAL ; VAR < FINAL_PLUS_ONE ; VAR ++ )\n#define FOREQ( VAR , INITIAL , FINAL ) for( TYPE_OF( FINAL ) VAR = INITIAL ; VAR <= FINAL ; VAR ++ )\n#define FOREQINV( VAR , INITIAL , FINAL ) for( TYPE_OF( INITIAL ) VAR = INITIAL ; VAR + 1 > FINAL ; VAR -- )\n#define AUTO_ITR( ARRAY ) auto itr_ ## ARRAY = ARRAY .begin() , end_ ## ARRAY = ARRAY .end()\n#define FOR_ITR( ARRAY ) for( AUTO_ITR( ARRAY ) , itr = itr_ ## ARRAY ; itr_ ## ARRAY != end_ ## ARRAY ; itr_ ## ARRAY ++ , itr++ )\n#define REPEAT( HOW_MANY_TIMES ) FOR( VARIABLE_FOR_REPEAT_ ## HOW_MANY_TIMES , 0 , HOW_MANY_TIMES )\n#define SET_PRECISION( DECIMAL_DIGITS ) cout << fixed << setprecision( DECIMAL_DIGITS )\n#define OUTPUT_ARRAY( OS , A , N ) FOR( VARIABLE_FOR_OUTPUT_ARRAY , 0 , N ){ OS << A[VARIABLE_FOR_OUTPUT_ARRAY] << (VARIABLE_FOR_OUTPUT_ARRAY==N-1?\"\":\" \"); } OS\n#define OUTPUT_ITR( OS , A ) { auto ITERATOR_FOR_OUTPUT_ITR = A.begin() , END_FOR_OUTPUT_ITR = A.end(); bool VARIABLE_FOR_OUTPUT_ITR = ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR; while( VARIABLE_FOR_OUTPUT_ITR ){ OS << *ITERATOR_FOR_COUT_ITR; ( VARIABLE_FOR_OUTPUT_ITR = ++ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR ) ? OS : OS << \" \"; } } OS\n#define RETURN( ... ) SOLVE_ONLY; COUT( __VA_ARGS__ ); return\n#define COMPARE( ... ) auto naive = Naive( __VA_ARGS__ ); auto answer = Answer( __VA_ARGS__ ); bool match = naive == answer; COUT( \"(\" , #__VA_ARGS__ , \") == (\" , __VA_ARGS__ , \") : Naive == \" , naive , match ? \"==\" : \"!=\" , answer , \"== Answer\" ); if( !match ){ return; }\n\n// 入出力用\ntemplate <class Traits> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is ) { return is; }\ntemplate <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is , Arg& arg , ARGS&... args ) { return VariadicCin( is >> arg , args... ); }\ntemplate <class Traits> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator ) { return is; }\ntemplate <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator , Arg& arg , ARGS&... args ) { return VariadicGetline( getline( is , arg , separator ) , separator , args... ); }\ntemplate <class Traits , typename Arg> inline basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os , const vector<Arg>& arg ) { auto begin = arg.begin() , end = arg.end(); auto itr = begin; while( itr != end ){ ( itr == begin ? os : os << \" \" ) << *itr; itr++; } return os; }\ntemplate <class Traits , typename Arg> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg& arg ) { return os << arg; }\ntemplate <class Traits , typename Arg1 , typename Arg2 , typename... ARGS> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg1& arg1 , const Arg2& arg2 , const ARGS&... args ) { return VariadicCout( os << arg1 << \" \" , arg2 , args... ); }\n\n// デバッグ用\n#ifdef DEBUG\n inline void AlertAbort( int n ) { CERR( \"abort関数が呼ばれました。assertマクロのメッセージが出力されていない場合はオーバーフローの有無を確認をしてください。\" ); }\n void AutoCheck( int& exec_mode , const bool& use_getline );\n inline void Solve();\n inline void Experiment();\n inline void SmallTest();\n inline void RandomTest();\n ll GetRand( const ll& Rand_min , const ll& Rand_max );\n int exec_mode;\n CEXPR( int , solve_mode , 0 );\n CEXPR( int , sample_debug_mode , 1 );\n CEXPR( int , submission_debug_mode , 2 );\n CEXPR( int , library_search_mode , 3 );\n CEXPR( int , experiment_mode , 4 );\n CEXPR( int , small_test_mode , 5 );\n CEXPR( int , random_test_mode , 6 );\n #ifdef USE_GETLINE\n CEXPR( bool , use_getline , true );\n #else\n CEXPR( bool , use_getline , false );\n #endif\n#else\n ll GetRand( const ll& Rand_min , const ll& Rand_max ) { ll answer = time( NULL ); return answer * rand() % ( Rand_max + 1 - Rand_min ) + Rand_min; }\n#endif\n\n// 圧縮用\n#define TE template\n#define TY typename\n#define US using\n#define ST static\n#define IN inline\n#define CL class\n#define PU public\n#define OP operator\n#define CE constexpr\n#define CO const\n#define NE noexcept\n#define RE return \n#define WH while\n#define VO void\n#define VE vector\n#define LI list\n#define BE begin\n#define EN end\n#define SZ size\n#define MO move\n#define TH this\n#define CRI CO int&\n#define CRUI CO uint&\n#define CRL CO ll&\n\n// VVV 常設ライブラリは以下に挿入する。\n// Map\n// c:/Users/user/Documents/Programming/Mathematics/Function/Map\nCL is_ordered{PU:is_ordered()= delete;TE <TY T> ST CE auto Check(CO T& t)-> decltype(t < t,true_type());ST CE false_type Check(...);TE <TY T> ST CE CO bool value = is_same_v< decltype(Check(declval<T>())),true_type >;};\nTE <TY T , TY U>US Map = conditional_t<is_constructible_v<unordered_map<T,int>>,unordered_map<T,U>,conditional_t<is_ordered::value<T>,map<T,U>,void>>;\n// AAA 常設ライブラリは以上に挿入する。\n\n// グラフ用\ntemplate <typename PATH> vector<list<PATH> > gE;\ntemplate <typename T , template <typename...> typename V> inline auto Get( const V<T>& a ) { return [&]( const int& i ){ return a[i]; }; }\n\n\n// 圧縮時は中身だけ削除する。\ninline void Experiment()\n{\n}\n\n// 圧縮時は中身だけ削除する。\ninline void SmallTest()\n{\n}\n\n// VVV 常設でないライブラリは以下に挿入する。\n\ntemplate <typename U>\nclass VirtualMonoid\n{\n\npublic:\n virtual U Product( const U& u0 , const U& u1 ) = 0;\n virtual const U& Unit() = 0;\n\n};\n\n// 加法モノイド\ntemplate <typename U = ll>\nclass Monoid :\n virtual public VirtualMonoid<U>\n{\n\npublic:\n inline U Product( const U& u0 , const U& u1 );\n inline const U& Unit();\n\n static inline Monoid<U>& Object();\n\n};\n\ntemplate <typename U , typename M_U , typename E_U>\nclass AbstractMonoid :\n virtual public VirtualMonoid<U>\n{\n\nprivate:\n M_U m_m_U;\n E_U m_e_U;\n\npublic:\n inline AbstractMonoid( M_U m_U , E_U e_U );\n\n inline U Product( const U& u0 , const U& u1 );\n inline const U& Unit();\n\n};\n\ntemplate <typename U , typename M_U , typename E_U> inline AbstractMonoid<U,M_U,E_U>::AbstractMonoid( M_U m_U , E_U e_U ) : VirtualMonoid<U>() , m_m_U( m_U ) , m_e_U( e_U ) { static_assert( is_invocable_r_v<U,M_U,U,U> && is_invocable_r_v<const U&,E_U> ); }\n\ntemplate <typename U> inline U Monoid<U>::Product( const U& u0 , const U& u1 ) { return u0 + u1; }\ntemplate <typename U , typename M_U , typename E_U> inline U AbstractMonoid<U,M_U,E_U>::Product( const U& u0 , const U& u1 ) { return m_e_U( u0 , u1 ); }\n\ntemplate <typename U> inline const U& Monoid<U>::Unit() { static const U zero{}; return zero; }\ntemplate <typename U , typename M_U , typename E_U> inline const U& AbstractMonoid<U,M_U,E_U>::Unit() { return m_e_U(); }\n\ntemplate <typename U> inline Monoid<U>& Monoid<U>::Object() { static Monoid<U> obj{}; return obj; }\n\n\n// Eは写像edge:T->(T \\times ...)^{< omega}に相当するデータ。\n// Enumeration:N->R1-->TとEnumeration_inv:T->R2-->Nは互いに逆写像である仮想関数。\ntemplate <typename T , typename R1 , typename R2 , typename E>\nclass VirtualGraph\n{\n\nprotected:\n int m_size;\n E m_edge;\n\npublic:\n inline VirtualGraph( const int& size , E edge );\n\n inline const int& size() const noexcept;\n inline decltype(declval<E>()(declval<T>())) Edge( const T& );\n\n virtual R1 Enumeration( const int& i ) = 0;\n virtual R2 Enumeration_inv( const T& t ) = 0;\n virtual void Reset();\n\n};\n\n// 入力の範囲内で条件\n// (1) Enumeration:N->R1-->TとEnumeration_inv:T->R2-->Nが全単射。\n// を満たす場合にのみサポート。\ntemplate <typename E>\nclass Graph :\n virtual public VirtualGraph<int,const int&,const int&,E>\n{\n \npublic:\n inline Graph( const int& V , E edge );\n\n inline const int& Enumeration( const int& i );\n inline const int& Enumeration_inv( const int& t );\n\n};\n\ntemplate <typename T , typename R1 , typename Enum_T , typename R2 , typename Enum_T_inv , typename E>\nclass EnumerationGraph :\n virtual public VirtualGraph<T,R1,R2,E>\n{\n\nprivate:\n Enum_T m_enum_T;\n Enum_T_inv m_enum_T_inv;\n \npublic:\n inline EnumerationGraph( const int& V , Enum_T enum_T , Enum_T_inv enum_T_inv , E edge );\n\n inline R1 Enumeration( const int& i );\n inline R2 Enumeration_inv( const T& t );\n\n};\ntemplate <typename Enum_T , typename Enum_T_inv , typename E> EnumerationGraph( const int& V , Enum_T enum_T , Enum_T_inv enum_T_inv , E edge ) -> EnumerationGraph<decay_t<decltype(declval<Enum_T>()(0))>,decltype(declval<Enum_T>()(0)),Enum_T,decltype(declval<Enum_T_inv>()(declval<decay_t<decltype(declval<Enum_T>()(0))>>())),Enum_T_inv,E>;\n\ntemplate <typename T , typename E>\nclass MemorisationGraph :\n virtual public VirtualGraph<T,T,const int&,E>\n{\n\nprivate:\n int m_length;\n vector<T> m_memory;\n Map<T,int> m_memory_inv;\n \npublic:\n inline MemorisationGraph( const int& V , E edge );\n\n // push_backする可能性のあるvectorなので参照にしないように注意\n inline T Enumeration( const int& i );\n inline const int& Enumeration_inv( const T& t );\n inline void Reset();\n\n};\n\ntemplate <typename T , typename R1 , typename R2 , typename E> inline VirtualGraph<T,R1,R2,E>::VirtualGraph( const int& size , E edge ) : m_size( size ) , m_edge( move( edge ) ) { static_assert( is_invocable_v<E,T> && is_constructible_v<T,R1> && is_constructible_v<int,R2> ); }\ntemplate <typename E> inline Graph<E>::Graph( const int& V , E edge ) : VirtualGraph<int,const int&,const int&,E>( V , move( edge ) ) {}\ntemplate <typename T , typename R1 , typename Enum_T , typename R2 , typename Enum_T_inv , typename E> inline EnumerationGraph<T,R1,Enum_T,R2,Enum_T_inv,E>::EnumerationGraph( const int& V , Enum_T enum_T , Enum_T_inv enum_T_inv , E edge ) : VirtualGraph<int,R1,R2,E>( V , move( edge ) ) , m_enum_T( move( enum_T ) ) , m_enum_T_inv( move( enum_T_inv ) ) { static_assert( is_same_v<R1,decltype(declval<Enum_T>()(0))> && is_same_v<R2,decltype(declval<Enum_T_inv>()(declval<T>()))> && is_same_v<T,decay_t<R1>> ); }\ntemplate <typename T , typename E> inline MemorisationGraph<T,E>::MemorisationGraph( const int& V , E edge ) : VirtualGraph<T,T,const int&,E>( V , move( edge ) ) , m_length() , m_memory() , m_memory_inv() {}\n\ntemplate <typename T , typename R1 , typename R2 , typename E> inline const int& VirtualGraph<T,R1,R2,E>::size() const noexcept { return m_size; }\ntemplate <typename T , typename R1 , typename R2 , typename E> inline decltype(declval<E>()(declval<T>())) VirtualGraph<T,R1,R2,E>::Edge( const T& t ) { return m_edge( t ); }\n\ntemplate <typename E> inline const int& Graph<E>::Enumeration( const int& i ) { return i; }\ntemplate <typename T , typename R1 , typename Enum_T , typename R2 , typename Enum_T_inv , typename E> inline R1 EnumerationGraph<T,R1,Enum_T,R2,Enum_T_inv,E>::Enumeration( const int& i ) { return m_enum_T( i ); }\ntemplate <typename T , typename E> inline T MemorisationGraph<T,E>::Enumeration( const int& i ) { assert( 0 <= i && i < m_length ); return m_memory[i]; }\n\ntemplate <typename E> inline const int& Graph<E>::Enumeration_inv( const int& i ) { return i; }\ntemplate <typename T , typename R1 , typename Enum_T , typename R2 , typename Enum_T_inv , typename E> inline R2 EnumerationGraph<T,R1,Enum_T,R2,Enum_T_inv,E>::Enumeration_inv( const T& t ) { return m_enum_T_inv( t ); }\ntemplate <typename T , typename E> inline const int& MemorisationGraph<T,E>::Enumeration_inv( const T& t )\n{\n\n if( m_memory_inv.count( t ) == 0 ){\n\n assert( m_length < this->m_size );\n m_memory.push_back( t );\n return m_memory_inv[t] = m_length++;\n\n }\n \n return m_memory_inv[t];\n\n}\n\ntemplate <typename T , typename R1 , typename R2 , typename E> void VirtualGraph<T,R1,R2,E>::Reset() {}\ntemplate <typename T , typename E> inline void MemorisationGraph<T,E>::Reset() { m_length = 0; m_memory.clear(); m_memory_inv.clear(); }\n\n\n#define BELLMAN_FORD_BODY( INITIALISE_PREV , SET_PREV )\t\t\t\\\n const U& unit = m_p_M->Unit();\t\t\t\t\t\\\n assert( unit < m_infty );\t\t\t\t\t\t\\\n const int& size = m_p_G->size();\t\t\t\t\t\\\n auto&& i_start = m_p_G->Enumeration_inv( t_start );\t\t\t\\\n assert( 0 <= i_start && i_start < size );\t\t\t\t\\\n vector<bool> found( size );\t\t\t\t\t\t\\\n vector<U> weight( size , m_infty );\t\t\t\t\t\\\n found[i_start] = true;\t\t\t\t\t\t\\\n weight[i_start] = 0;\t\t\t\t\t\t\t\\\n INITIALISE_PREV;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( int length = 0 ; length < size ; length++ ){\t\t\t\\\n \t\t\t\t\t\t\t\t\t\\\n for( int i = 0 ; i < size ; i++ ){\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n if( found[i] ){\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tconst U& weight_i = weight[i];\t\t\t\t\t\\\n\tassert( weight_i != m_infty );\t\t\t\t\t\\\n\tauto&& edge_i = m_p_G->Edge( m_p_G->Enumeration( i ) );\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tfor( auto itr_edge_i = edge_i.begin() , end_edge_i = edge_i.end() ; itr_edge_i != end_edge_i ; itr_edge_i++ ){ \\\n\t\t\t\t\t\t\t\t\t\\\n\t auto&& j = m_p_G->Enumeration_inv( itr_edge_i->first );\t\\\n\t const U& edge_ij = itr_edge_i->second;\t\t\t\\\n\t U temp = m_p_M->Product( weight_i , edge_ij );\t\t\\\n\t U& weight_j = weight[j];\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t if( weight_j > temp ){\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t found[j] = true;\t\t\t\t\t\t\\\n\t weight_j = move( temp );\t\t\t\t\t\\\n\t SET_PREV;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t }\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n bool valid = true;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( int i = 0 ; i < size && valid ; i++ ){\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n if( found[i] ){\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n const U& weight_i = weight[i];\t\t\t\t\t\\\n auto&& edge_i = m_p_G->Edge( m_p_G->Enumeration( i ) ); \\\n\t\t\t\t\t\t\t\t\t\\\n for( auto itr_edge_i = edge_i.begin() , end_edge_i = edge_i.end() ; itr_edge_i != end_edge_i ; itr_edge_i++ ){ \\\n\t\t\t\t\t\t\t\t\t\\\n\tconst int& j = m_p_G->Enumeration_inv( itr_edge_i->first );\t\\\n\tconst U& edge_ij = itr_edge_i->second;\t\t\t\t\\\n\tU& weight_j = weight[j];\t\t\t\t\t\\\n\tconst U temp = m_p_M->Product( weight_i , edge_ij );\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tif( weight_j > temp ){\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t valid = false;\t\t\t\t\t\t\\\n\t break;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\n// Eは写像edge:T->(T \\times U)^{< \\omega}に相当する型。\n// メモリが不足する場合はEの定義を前計算しないでその都度計算させること。\n\n// 入力の範囲内で要件\n// (1) inftyがEの値の各成分の第2成分|V_G|個以下の和で表せるいかなる数よりも大きい。\n// (2) Vの各要素u,vに対し、辺u->vが複数存在する場合は重みが最小のものが前にpushされている。\n// が成り立つ場合にのみサポート。\n\n// 単一始点全終点最短経路探索/経路復元なしO(size |edge|)\n// 単一始点全終点最短経路探索/経路復元ありO(size |edge|)\ntemplate <typename T , typename U , typename R1 , typename R2 , typename E>\nclass AbstractBellmanFord\n{\n\nprivate:\n VirtualGraph<T,R1,R2,E>* m_p_G;\n VirtualMonoid<U>* m_p_M;\n U m_infty;\n\npublic:\n inline AbstractBellmanFord( VirtualGraph<T,R1,R2,E>& G , VirtualMonoid<U>& M , const U& infty );\n\n const U& Infty() const;\n \n // 負の閉路が存在すればfalse、存在しなければtrueを第1成分に返す。\n tuple<bool,vector<U>> GetDistance( const T& t_start );\n tuple<bool,vector<U>,vector<list<T>>> GetPath( const T& t_start );\n \n};\n\ntemplate <typename T , typename R1 , typename R2 , typename E>\nclass BellmanFord :\n public AbstractBellmanFord<T,ll,R1,R2,E>\n{\n\npublic:\n inline BellmanFord( VirtualGraph<T,R1,R2,E>& G );\n \n};\n\ntemplate <typename T , typename U , typename R1 , typename R2 , typename E> inline AbstractBellmanFord<T,U,R1,R2,E>::AbstractBellmanFord( VirtualGraph<T,R1,R2,E>& G , VirtualMonoid<U>& M , const U& infty ) : m_p_G( &G ) , m_p_M( &M ) , m_infty( infty ) { static_assert( ! is_same_v<U,int> && is_invocable_r_v<list<pair<T,U>>,E,T> ); }\ntemplate <typename T , typename R1 , typename R2 , typename E> inline BellmanFord<T,R1,R2,E>::BellmanFord( VirtualGraph<T,R1,R2,E>& G ) : AbstractBellmanFord<T,ll,R1,R2,E>( G , Monoid<>::Object() , 4611686018427387904 ) {}\n\ntemplate <typename T , typename U , typename R1 , typename R2 , typename E> const U& AbstractBellmanFord<T,U,R1,R2,E>::Infty() const { return m_infty; }\n\ntemplate <typename T , typename U , typename R1 , typename R2 , typename E>\ntuple<bool,vector<U>> AbstractBellmanFord<T,U,R1,R2,E>::GetDistance( const T& t_start )\n{\n\n BELLMAN_FORD_BODY( , );\n m_p_G->Reset();\n return { valid , move( weight ) };\n\n}\n\ntemplate <typename T , typename U , typename R1 , typename R2 , typename E>\ntuple<bool,vector<U>,vector<list<T>>> AbstractBellmanFord<T,U,R1,R2,E>::GetPath( const T& t_start )\n{\n\n BELLMAN_FORD_BODY( vector<int> prev( size ) , prev[j] = i );\n vector<list<T>> path( size );\n\n if( valid ){\n \n for( int j = 0 ; j < size ; j++ ){\n\n list<T>& path_j = path[j];\n int i = j;\n\n while( i != i_start ){\n\n\tpath_j.push_front( m_p_G->Enumeration( i ) );\n\ti = prev[i];\n\n }\n\n path_j.push_front( t_start );\n\n }\n\n }\n\n m_p_G->Reset();\n return { valid , move( weight ) , move( path ) };\n\n}\n\n// AAA 常設でないライブラリは以上に挿入する。\n\ninline void Solve()\n{\n CIN( int , N , M , r );\n gE<path>.resize( N );\n FOR( j , 0 , M ){\n CIN( int , uj , vj );\n CIN( ll , wj );\n gE<path>[uj].push_back( { vj , wj } );\n }\n Graph graph{ N , Get( gE<path> ) };\n BellmanFord bf{ graph };\n auto [b,weight] = bf.GetDistance( r );\n if( b ){\n FOR( i , 0 , N ){\n if( weight[i] == bf.Infty() ){\n\tCOUT( \"INF\" );\n } else {\n\tCOUT( weight[i] );\n }\n }\n } else {\n COUT( \"NEGATIVE CYCLE\" );\n }\n}\nREPEAT_MAIN(1);", "accuracy": 1, "time_ms": 30, "memory_kb": 3544, "score_of_the_acc": -0.0268, "final_rank": 5 }, { "submission_id": "aoj_GRL_1_B_8770002", "code_snippet": "#ifdef DEBUG\n #define _GLIBCXX_DEBUG\n #define REPEAT_MAIN( BOUND ) START_MAIN; signal( SIGABRT , &AlertAbort ); AutoCheck( exec_mode , use_getline ); if( exec_mode == sample_debug_mode || exec_mode == submission_debug_mode || exec_mode == library_search_mode ){ return 0; } else if( exec_mode == experiment_mode ){ Experiment(); return 0; } else if( exec_mode == small_test_mode ){ SmallTest(); return 0; }; DEXPR( int , bound_test_case_num , BOUND , min( BOUND , 100 ) ); int test_case_num = 1; if( exec_mode == solve_mode ){ if constexpr( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } } else if( exec_mode == random_test_mode ){ CERR( \"ランダムテストを行う回数を指定してください。\" ); SET_LL( test_case_num ); } FINISH_MAIN\n #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , DEBUG_VALUE )\n #define ASSERT( A , MIN , MAX ) CERR( \"ASSERTチェック: \" , ( MIN ) , ( ( MIN ) <= A ? \"<=\" : \">\" ) , A , ( A <= ( MAX ) ? \"<=\" : \">\" ) , ( MAX ) ); assert( ( MIN ) <= A && A <= ( MAX ) )\n #define SET_ASSERT( A , MIN , MAX ) if( exec_mode == solve_mode ){ SET_LL( A ); ASSERT( A , MIN , MAX ); } else if( exec_mode == random_test_mode ){ CERR( #A , \" = \" , ( A = GetRand( MIN , MAX ) ) ); } else { assert( false ); }\n #define SOLVE_ONLY static_assert( __FUNCTION__[0] == 'S' )\n #define CERR( ... ) VariadicCout( cerr , __VA_ARGS__ ) << endl\n #define COUT( ... ) VariadicCout( cout << \"出力: \" , __VA_ARGS__ ) << endl\n #define CERR_A( A , N ) OUTPUT_ARRAY( cerr , A , N ) << endl\n #define COUT_A( A , N ) cout << \"出力: \"; OUTPUT_ARRAY( cout , A , N ) << endl\n #define CERR_ITR( A ) OUTPUT_ITR( cerr , A ) << endl\n #define COUT_ITR( A ) cout << \"出力: \"; OUTPUT_ITR( cout , A ) << endl\n#else\n #pragma GCC optimize ( \"O3\" )\n #pragma GCC optimize ( \"unroll-loops\" )\n #pragma GCC target ( \"sse4.2,fma,avx2,popcnt,lzcnt,bmi2\" )\n #define REPEAT_MAIN( BOUND ) START_MAIN; CEXPR( int , bound_test_case_num , BOUND ); int test_case_num = 1; if constexpr( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } FINISH_MAIN\n #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , VALUE )\n #define ASSERT( A , MIN , MAX ) assert( ( MIN ) <= A && A <= ( MAX ) )\n #define SET_ASSERT( A , MIN , MAX ) SET_LL( A ); ASSERT( A , MIN , MAX )\n #define SOLVE_ONLY \n #define CERR( ... ) \n #define COUT( ... ) VariadicCout( cout , __VA_ARGS__ ) << ENDL\n #define CERR_A( A , N ) \n #define COUT_A( A , N ) OUTPUT_ARRAY( cout , A , N ) << ENDL\n #define CERR_ITR( A ) \n #define COUT_ITR( A ) OUTPUT_ITR( cout , A ) << ENDL\n#endif\n#ifdef REACTIVE\n #define ENDL endl\n#else\n #define ENDL \"\\n\"\n#endif\n#ifdef USE_GETLINE\n #define SET_LL( A ) { GETLINE( A ## _str ); A = stoll( A ## _str ); }\n #define GETLINE_SEPARATE( SEPARATOR , ... ) SOLVE_ONLY; string __VA_ARGS__; VariadicGetline( cin , SEPARATOR , __VA_ARGS__ )\n #define GETLINE( ... ) SOLVE_ONLY; GETLINE_SEPARATE( '\\n' , __VA_ARGS__ )\n#else\n #define SET_LL( A ) cin >> A\n #define CIN( LL , ... ) SOLVE_ONLY; LL __VA_ARGS__; VariadicCin( cin , __VA_ARGS__ )\n #define SET_A( A , N ) SOLVE_ONLY; FOR( VARIABLE_FOR_CIN_A , 0 , N ){ cin >> A[VARIABLE_FOR_CIN_A]; }\n #define CIN_A( LL , A , N ) vector<LL> A( N ); SET_A( A , N );\n#endif\n#include <bits/stdc++.h>\nusing namespace std;\nusing uint = unsigned int;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing lld = __float128;\ntemplate <typename INT> using T2 = pair<INT,INT>;\ntemplate <typename INT> using T3 = tuple<INT,INT,INT>;\ntemplate <typename INT> using T4 = tuple<INT,INT,INT,INT>;\nusing path = pair<int,ll>;\n#define ATT __attribute__( ( target( \"sse4.2,fma,avx2,popcnt,lzcnt,bmi2\" ) ) )\n#define START_MAIN int main(){ ios_base::sync_with_stdio( false ); cin.tie( nullptr )\n#define FINISH_MAIN REPEAT( test_case_num ){ if constexpr( bound_test_case_num > 1 ){ CERR( \"testcase \" , VARIABLE_FOR_REPEAT_test_case_num , \":\" ); } Solve(); CERR( \"\" ); } }\n#define START_WATCH chrono::system_clock::time_point watch = chrono::system_clock::now()\n#define CURRENT_TIME static_cast<double>( chrono::duration_cast<chrono::microseconds>( chrono::system_clock::now() - watch ).count() / 1000.0 )\n#define CHECK_WATCH( TL_MS ) ( CURRENT_TIME < TL_MS - 100.0 )\n#define TYPE_OF( VAR ) decay_t<decltype( VAR )>\n#define CEXPR( LL , BOUND , VALUE ) constexpr LL BOUND = VALUE\n#define CIN_ASSERT( A , MIN , MAX ) TYPE_OF( MAX ) A; SET_ASSERT( A , MIN , MAX )\n#define FOR( VAR , INITIAL , FINAL_PLUS_ONE ) for( TYPE_OF( FINAL_PLUS_ONE ) VAR = INITIAL ; VAR < FINAL_PLUS_ONE ; VAR ++ )\n#define FOREQ( VAR , INITIAL , FINAL ) for( TYPE_OF( FINAL ) VAR = INITIAL ; VAR <= FINAL ; VAR ++ )\n#define FOREQINV( VAR , INITIAL , FINAL ) for( TYPE_OF( INITIAL ) VAR = INITIAL ; VAR + 1 > FINAL ; VAR -- )\n#define AUTO_ITR( ARRAY ) auto itr_ ## ARRAY = ARRAY .begin() , end_ ## ARRAY = ARRAY .end()\n#define FOR_ITR( ARRAY ) for( AUTO_ITR( ARRAY ) , itr = itr_ ## ARRAY ; itr_ ## ARRAY != end_ ## ARRAY ; itr_ ## ARRAY ++ , itr++ )\n#define REPEAT( HOW_MANY_TIMES ) FOR( VARIABLE_FOR_REPEAT_ ## HOW_MANY_TIMES , 0 , HOW_MANY_TIMES )\n#define SET_PRECISION( DECIMAL_DIGITS ) cout << fixed << setprecision( DECIMAL_DIGITS )\n#define OUTPUT_ARRAY( OS , A , N ) FOR( VARIABLE_FOR_OUTPUT_ARRAY , 0 , N ){ OS << A[VARIABLE_FOR_OUTPUT_ARRAY] << (VARIABLE_FOR_OUTPUT_ARRAY==N-1?\"\":\" \"); } OS\n#define OUTPUT_ITR( OS , A ) { auto ITERATOR_FOR_OUTPUT_ITR = A.begin() , END_FOR_OUTPUT_ITR = A.end(); bool VARIABLE_FOR_OUTPUT_ITR = ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR; while( VARIABLE_FOR_OUTPUT_ITR ){ OS << *ITERATOR_FOR_COUT_ITR; ( VARIABLE_FOR_OUTPUT_ITR = ++ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR ) ? OS : OS << \" \"; } } OS\n#define RETURN( ... ) SOLVE_ONLY; COUT( __VA_ARGS__ ); return\n#define COMPARE( ... ) auto naive = Naive( __VA_ARGS__ ); auto answer = Answer( __VA_ARGS__ ); bool match = naive == answer; COUT( \"(\" , #__VA_ARGS__ , \") == (\" , __VA_ARGS__ , \") : Naive == \" , naive , match ? \"==\" : \"!=\" , answer , \"== Answer\" ); if( !match ){ return; }\n\n// 入出力用\ntemplate <class Traits> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is ) { return is; }\ntemplate <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is , Arg& arg , ARGS&... args ) { return VariadicCin( is >> arg , args... ); }\ntemplate <class Traits> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator ) { return is; }\ntemplate <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator , Arg& arg , ARGS&... args ) { return VariadicGetline( getline( is , arg , separator ) , separator , args... ); }\ntemplate <class Traits , typename Arg> inline basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os , const vector<Arg>& arg ) { auto begin = arg.begin() , end = arg.end(); auto itr = begin; while( itr != end ){ ( itr == begin ? os : os << \" \" ) << *itr; itr++; } return os; }\ntemplate <class Traits , typename Arg> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg& arg ) { return os << arg; }\ntemplate <class Traits , typename Arg1 , typename Arg2 , typename... ARGS> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg1& arg1 , const Arg2& arg2 , const ARGS&... args ) { return VariadicCout( os << arg1 << \" \" , arg2 , args... ); }\n\n// デバッグ用\n#ifdef DEBUG\n inline void AlertAbort( int n ) { CERR( \"abort関数が呼ばれました。assertマクロのメッセージが出力されていない場合はオーバーフローの有無を確認をしてください。\" ); }\n void AutoCheck( int& exec_mode , const bool& use_getline );\n inline void Solve();\n inline void Experiment();\n inline void SmallTest();\n inline void RandomTest();\n ll GetRand( const ll& Rand_min , const ll& Rand_max );\n int exec_mode;\n CEXPR( int , solve_mode , 0 );\n CEXPR( int , sample_debug_mode , 1 );\n CEXPR( int , submission_debug_mode , 2 );\n CEXPR( int , library_search_mode , 3 );\n CEXPR( int , experiment_mode , 4 );\n CEXPR( int , small_test_mode , 5 );\n CEXPR( int , random_test_mode , 6 );\n #ifdef USE_GETLINE\n CEXPR( bool , use_getline , true );\n #else\n CEXPR( bool , use_getline , false );\n #endif\n#else\n ll GetRand( const ll& Rand_min , const ll& Rand_max ) { ll answer = time( NULL ); return answer * rand() % ( Rand_max + 1 - Rand_min ) + Rand_min; }\n#endif\n\n// 圧縮用\n#define TE template\n#define TY typename\n#define US using\n#define ST static\n#define IN inline\n#define CL class\n#define PU public\n#define OP operator\n#define CE constexpr\n#define CO const\n#define NE noexcept\n#define RE return \n#define WH while\n#define VO void\n#define VE vector\n#define LI list\n#define BE begin\n#define EN end\n#define SZ size\n#define MO move\n#define TH this\n#define CRI CO int&\n#define CRUI CO uint&\n#define CRL CO ll&\n\n// VVV 常設ライブラリは以下に挿入する。\n// Map\n// c:/Users/user/Documents/Programming/Mathematics/Function/Map\nCL is_ordered{PU:is_ordered()= delete;TE <TY T> ST CE auto Check(CO T& t)-> decltype(t < t,true_type());ST CE false_type Check(...);TE <TY T> ST CE CO bool value = is_same_v< decltype(Check(declval<T>())),true_type >;};\nTE <TY T , TY U>US Map = conditional_t<is_constructible_v<unordered_map<T,int>>,unordered_map<T,U>,conditional_t<is_ordered::value<T>,map<T,U>,void>>;\n// AAA 常設ライブラリは以上に挿入する。\n\n// グラフ用\ntemplate <typename PATH> vector<list<PATH> > gE;\ntemplate <typename T , template <typename...> typename V> inline auto Get( const V<T>& a ) { return [&]( const int& i ){ return a[i]; }; }\n\n\n// 圧縮時は中身だけ削除する。\ninline void Experiment()\n{\n}\n\n// 圧縮時は中身だけ削除する。\ninline void SmallTest()\n{\n}\n\n// VVV 常設でないライブラリは以下に挿入する。\n\n#define BELLMAN_FORD_BODY( INITIALISE_PREV , SET_PREV )\t\t\t\\\n static const U& unit = Unit();\t\t\t\t\t\\\n assert( unit < m_infty );\t\t\t\t\\\n const int i_start = e_inv( t_start );\t\t\t\t\t\\\n vector<bool> found( m_size );\t\t\t\t\t\t\\\n weight = vector<U>( m_size , m_infty );\t\t\t\t\\\n found[i_start] = true;\t\t\t\t\t\t\\\n weight[i_start] = 0;\t\t\t\t\t\t\t\\\n INITIALISE_PREV;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( int length = 0 ; length < m_size ; length++ ){\t\t\t\\\n \t\t\t\t\t\t\t\t\t\\\n for( int i = 0 ; i < m_size ; i++ ){\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n if( found[i] ){\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tconst U& weight_i = weight[i];\t\t\t\t\t\\\n\tassert( weight_i != m_infty );\t\t\t\t\t\\\n\tlist<pair<int,U>> edge_i = m_edge( e( i ) );\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tfor( auto itr_edge_i = edge_i.begin() , end_edge_i = edge_i.end() ; itr_edge_i != end_edge_i ; itr_edge_i++ ){ \\\n\t\t\t\t\t\t\t\t\t\\\n\t const int& j = e_inv( itr_edge_i->first );\t\t\t\\\n\t const U& edge_ij = itr_edge_i->second;\t\t\t\\\n\t U& weight_j = weight[j];\t\t\t\t\t\\\n\t U temp = Addition( weight_i , edge_ij );\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t if( weight_j > temp ){\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t found[j] = true;\t\t\t\t\t\t\\\n\t weight_j = move( temp );\t\t\t\t\t\\\n\t SET_PREV;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t }\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n bool valid = true;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( int i = 0 ; i < m_size && valid ; i++ ){\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n if( found[i] ){\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n const U& weight_i = weight[i];\t\t\t\t\t\\\n list<pair<int,U>> edge_i = m_edge( e( i ) );\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n for( auto itr_edge_i = edge_i.begin() , end_edge_i = edge_i.end() ; itr_edge_i != end_edge_i ; itr_edge_i++ ){ \\\n\t\t\t\t\t\t\t\t\t\\\n\tconst int& j = e_inv( itr_edge_i->first );\t\t\t\\\n\tconst U& edge_ij = itr_edge_i->second;\t\t\t\t\\\n\tU& weight_j = weight[j];\t\t\t\t\t\\\n\tconst U temp = Addition( weight_i , edge_ij );\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tif( weight_j > temp ){\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t valid = false;\t\t\t\t\t\t\\\n\t break;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n\n// Eは写像edge:T->(T \\times U)^{< \\omega}に相当する型。\n// メモリが不足する場合はEの定義を前計算しないでその都度計算させること。\ntemplate <typename T , typename U , typename E>\nclass BellmanFord_Body\n{\n\nprotected:\n int m_size;\n\nprivate:\n U m_infty;\n E m_edge;\n\npublic:\n inline BellmanFord_Body( const int& size , const U& infty , E edge );\n // 負の閉路が存在すればfalse、存在しなければtrue\n bool Solve( const T& t_start , vector<U>& weight );\n bool Solve( const T& t_start , vector<U>& weight , vector<list<T>>& path );\n \n const U& Infty() const;\n \nprivate:\n virtual const U& Unit() const = 0;\n virtual U Addition( const U& , const U& ) const = 0;\n virtual T e( const int& i ) = 0;\n virtual int e_inv( const T& t ) = 0;\n virtual void Reset();\n\n};\n\n// 入力の範囲内で要件\n// (1) edgeの値の各成分の第2成分が0以上である。\n// (2) 2^{31}-1がEの値の各成分の第2成分size個以下の和で表せるいかなる数よりも大きい。\n// (6) Vの各要素u,vに対し、辺u->vが複数存在する場合は重みが最小のものが前にpushされている。\n// が成り立つ場合にのみサポート。\n\n// 単一始点全終点最短経路探索/経路復元なしO(size |edge|)\n// 単一始点全終点最短経路探索/経路復元ありO(size |edge|)\ntemplate <typename E>\nclass BellmanFord :\n public BellmanFord_Body<int,ll,E>\n{\n\npublic:\n inline BellmanFord( const int& size , E edge );\n \nprivate:\n inline const ll& Unit() const;\n inline ll Addition( const ll& , const ll& ) const;\n inline int e( const int& i );\n inline int e_inv( const int& t );\n\n};\n\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E>\nclass MonoidForBellmanFord :\n public BellmanFord_Body<T,U,E>\n{\n\nprivate:\n M_U m_m_U;\n E_U m_e_U;\n\npublic:\n inline MonoidForBellmanFord( const int& size , M_U m_U , E_U e_U , const U& infty , E edge );\n\nprivate:\n inline const U& Unit() const;\n inline U Addition( const U& , const U& ) const;\n\n};\n\n// 入力の範囲内で要件\n// (1) edgeの値の各成分の第2成分がe_U()以上である。\n// (2) inftyがEの値の各成分の第2成分size個以下の和で表せるいかなる項よりも大きい。\n// (3) foundがEの値の各成分の第2成分size個以下の和で表せず、inftyとも異なる。\n// (4) (U,m_U:U^2->U,e_U:1->U)がbool operator<(const U&,const U&)に関して全順序モノイドである。\n// (6) Vの各要素u,vに対し、辺u->vが複数存在する場合は重みが最小のものが前にpushされている。\n// (7) edgeはデフォルト引数による呼び出し可能(推論補助に用いる)\n// が成り立つ場合にのみサポート。\n\n// 単一始点全終点最短経路探索/経路復元なしO(size |edge| log size)\n// 単一始点全終点最短経路探索/経路復元ありO(size |edge| log size)\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E>\nclass MemorisationBellmanFord :\n public MonoidForBellmanFord<T,U,M_U,E_U,E>\n{\n\nprivate:\n int m_length;\n Map<T,int> m_memory;\n vector<T> m_memory_inv;\n\npublic:\n inline MemorisationBellmanFord( const int& size , M_U m_U , E_U e_U , const U& infty , E edge );\n \nprivate:\n inline T e( const int& i );\n inline int e_inv( const T& t );\n inline void Reset();\n\n};\ntemplate<typename U , typename M_U , typename E_U , typename E> MemorisationBellmanFord( const int& , M_U , E_U , const U& , E ) -> MemorisationBellmanFord<decltype(declval<E>()(0).front().first),U,M_U,E_U,E>;\n\n// 入力の範囲内で要件\n// (1) edgeの値の各成分の第2成分がe_U()以上である。\n// (2) inftyがEの値の各成分の第2成分size個以下の和で表せるいかなる項よりも大きい。\n// (3) foundがEの値の各成分の第2成分size個以下の和で表せず、inftyとも異なる。\n// (4) (U,m_U:U^2->U,e_U:1->U)がbool operator<(const U&,const U&)に関して全順序モノイドである。\n// (5) (enum_T,enum_T_inv)が互いに逆写像である。\n// (6) Vの各要素u,vに対し、辺u->vが複数存在する場合は重みが最小のものが前にpushされている。\n// が成り立つ場合にのみサポート。\n\n// 単一始点全終点最短経路探索/経路復元なしO(size |edge|)\n// 単一始点全終点最短経路探索/経路復元ありO(size |edge|)\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename U , typename M_U , typename E_U , typename E>\nclass EnumerationBellmanFord :\n public MonoidForBellmanFord<T,U,M_U,E_U,E>\n{\n\nprivate:\n Enum_T m_enum_T;\n Enum_T_inv m_enum_T_inv;\n \npublic:\n inline EnumerationBellmanFord( const int& size , Enum_T enum_T , Enum_T_inv enum_T_inv , M_U m_U , E_U e_U , const U& infty , E edge );\n \nprivate:\n inline T e( const int& i );\n inline int e_inv( const T& t );\n\n};\ntemplate<typename Enum_T , typename Enum_T_inv , typename U , typename M_U , typename E_U , typename E> EnumerationBellmanFord( const int& , Enum_T , Enum_T_inv , M_U , E_U , const U& , E ) -> EnumerationBellmanFord<decltype(declval<Enum_T>()(0)),Enum_T,Enum_T_inv,U,M_U,E_U,E>;\n\ntemplate <typename T , typename U , typename E> inline BellmanFord_Body<T,U,E>::BellmanFord_Body( const int& size , const U& infty , E edge ) : m_size( size ) , m_infty( infty ) , m_edge( move( edge ) ) { static_assert( ! is_same_v<U,int> && is_invocable_r_v<list<pair<T,U>>,E,T> ); }\ntemplate <typename E> inline BellmanFord<E>::BellmanFord( const int& size , E edge ) : BellmanFord_Body<int,ll,E>( size , 9223372036854775807 , move( edge ) ) {}\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E> inline MonoidForBellmanFord<T,U,M_U,E_U,E>::MonoidForBellmanFord( const int& size , M_U m_U , E_U e_U , const U& infty , E edge ) : BellmanFord_Body<T,U,E>( size , infty , move( edge ) ) , m_m_U( move( m_U ) ) , m_e_U( move( e_U ) ) {}\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E> inline MemorisationBellmanFord<T,U,M_U,E_U,E>::MemorisationBellmanFord( const int& size , M_U m_U , E_U e_U , const U& infty , E edge ) : MonoidForBellmanFord<T,U,M_U,E_U,E>( size , move( m_U ) , move( e_U ) , infty , move( edge ) ) , m_length() , m_memory() , m_memory_inv() {}\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename U , typename M_U , typename E_U , typename E> inline EnumerationBellmanFord<T,Enum_T,Enum_T_inv,U,M_U,E_U,E>::EnumerationBellmanFord( const int& size , Enum_T enum_T , Enum_T_inv enum_T_inv , M_U m_U , E_U e_U , const U& infty , E edge ) : MonoidForBellmanFord<T,U,M_U,E_U,E>( size , move( m_U ) , move( e_U ) , infty , move( edge ) ) , m_enum_T( move( enum_T ) ) , m_enum_T_inv( move( enum_T_inv ) ) {}\n\ntemplate <typename T , typename U , typename E>\nbool BellmanFord_Body<T,U,E>::Solve( const T& t_start , vector<U>& weight )\n{\n\n BELLMAN_FORD_BODY( , );\n Reset();\n return valid;\n\n}\n\ntemplate <typename T , typename U , typename E>\nbool BellmanFord_Body<T,U,E>::Solve( const T& t_start , vector<U>& weight , vector<list<T>>& path )\n{\n\n BELLMAN_FORD_BODY( vector<int> prev( m_size ) , prev[j] = i );\n\n if( valid ){\n \n for( int j = 0 ; j < m_size ; j++ ){\n\n list<T>& path_j = path[j];\n int i = j;\n\n while( i != i_start ){\n\n\tpath_j.push_front( e( i ) );\n\ti = prev[i];\n\n }\n\n path_j.push_front( t_start );\n\n }\n\n }\n\n Reset();\n return valid;\n\n}\n\ntemplate <typename T , typename U , typename E> const U& BellmanFord_Body<T,U,E>::Infty() const { return m_infty; }\n\ntemplate <typename E> inline const ll& BellmanFord<E>::Unit() const { static const ll unit = 0; return unit; }\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E> inline const U& MonoidForBellmanFord<T,U,M_U,E_U,E>::Unit() const { return m_e_U(); }\n\ntemplate <typename E> inline ll BellmanFord<E>::Addition( const ll& u0 , const ll& u1 ) const { return u0 + u1; }\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E> inline U MonoidForBellmanFord<T,U,M_U,E_U,E>::Addition( const U& u0 , const U& u1 ) const { return m_m_U( u0 , u1 ); }\n\ntemplate <typename E> inline int BellmanFord<E>::e( const int& i ) { return i; }\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E> inline T MemorisationBellmanFord<T,U,M_U,E_U,E>::e( const int& i ) { assert( i < m_length ); return m_memory_inv[i]; }\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename U , typename M_U , typename E_U , typename E> inline T EnumerationBellmanFord<T,Enum_T,Enum_T_inv,U,M_U,E_U,E>::e( const int& i ) { return m_enum_T( i ); }\n\ntemplate <typename E> inline int BellmanFord<E>::e_inv( const int& t ) { return t; }\n\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E> inline int MemorisationBellmanFord<T,U,M_U,E_U,E>::e_inv( const T& t )\n{\n\n using base = BellmanFord_Body<T,U,E>;\n \n if( m_memory.count( t ) == 0 ){\n\n assert( m_length < base::m_size );\n m_memory_inv.push_back( t );\n return m_memory[t] = m_length++;\n\n }\n \n return m_memory[t];\n\n}\n\ntemplate <typename T , typename Enum_T , typename Enum_T_inv , typename U , typename M_U , typename E_U , typename E> inline int EnumerationBellmanFord<T,Enum_T,Enum_T_inv,U,M_U,E_U,E>::e_inv( const T& t ) { return m_enum_T_inv( t ); }\n\ntemplate <typename T , typename U , typename E> inline void BellmanFord_Body<T,U,E>::Reset() {}\ntemplate <typename T , typename U , typename M_U , typename E_U , typename E> inline void MemorisationBellmanFord<T,U,M_U,E_U,E>::Reset() { m_length = 0; m_memory.clear(); m_memory_inv.clear(); }\n\n// AAA 常設でないライブラリは以上に挿入する。\n\ninline void Solve()\n{\n CIN( int , N , M , r );\n gE<path>.resize( N );\n FOR( j , 0 , M ){\n CIN( int , uj , vj );\n CIN( ll , wj );\n gE<path>[uj].push_back( { vj , wj } );\n }\n BellmanFord bf{ N , Get( gE<path> ) };\n vector<ll> weight;\n if( bf.Solve( r , weight ) ){\n FOR( i , 0 , N ){\n if( weight[i] == bf.Infty() ){\n\tCOUT( \"INF\" );\n } else {\n\tCOUT( weight[i] );\n }\n }\n } else {\n COUT( \"NEGATIVE CYCLE\" );\n }\n}\nREPEAT_MAIN(1);", "accuracy": 1, "time_ms": 30, "memory_kb": 3472, "score_of_the_acc": -0.0258, "final_rank": 3 } ]
aoj_DSL_3_B_cpp
The Smallest Window II For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0. Constraints $1 \leq N \leq 10^5$ $1 \leq K \leq 10^5$ $1 \leq a_i \leq 10^5$ Input The input is given in the following format. $N$ $K$ $a_1$ $a_2$ ... $a_N$ Output Print the smallest sub-array size in a line. Sample Input 1 6 2 4 1 2 1 3 5 Sample Output 1 2 Sample Input 2 6 3 4 1 2 1 3 5 Sample Output 2 3 Sample Input 3 3 4 1 2 3 Sample Output 3 0
[ { "submission_id": "aoj_DSL_3_B_10994705", "code_snippet": "///***....... In the name of Allah ......***////\n/*...Free Palestine..........Free Al_Aqsa.....*/\n#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define F first\n#define S second\n#define yes cout<<\"YES\"<<endl\n#define no cout<<\"NO\"<<endl\n#define pb push_back\n#define tt int t;cin>>t;while(t--)\n#define all(x) x.begin(),x.end()\n#define pii pair<int,int>\n#define loop(i,n) for(int i=0;i<n;i++)\n#define input(x) for(int i=0;i<n;i++)cin>>x[i]\n#define srt(x) sort(x.begin(),x.end())\n#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n#define endl '\\n' \nvoid solve()\n{\n int n,k;\n cin>>n>>k;\n vector<int>v(n);loop(i,n)cin>>v[i];\n map<int,int>ce;\n for(int i=1;i<=k;i++)\n {\n ce[i]++;\n }\n int cnt=0;\n int l=0;\n int r=0;\n int ans=n+1;\n map<int ,int>m;\n while(r<n)\n {\n m[v[r]]++;\n if(m[v[r]]==1&&ce[v[r]]==1)\n {\n cnt++;\n }\n if(cnt==k)\n {\n while(m[v[l]]>ce[v[l]])\n {\n m[v[l]]--;\n l++;\n }\n ans=min(ans,r-l+1);\n }\n r++;\n\n }\n if(ans==n+1)cout<<0<<endl;\n else cout<<ans<<endl;\n\n \n}\nsigned main()\n{\n optimize();\nsolve();\n\n \n \n}", "accuracy": 1, "time_ms": 60, "memory_kb": 12852, "score_of_the_acc": -1.8138, "final_rank": 18 }, { "submission_id": "aoj_DSL_3_B_10960354", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef pair<int, int> pii;\ntypedef pair<double, double> pdd;\ntypedef pair<ll, ll> pll;\ntypedef vector<pii> vpi;\ntypedef vector<pll> vpl;\ntypedef double dl;\n\n#define PB push_back\n#define F first\n#define S second\n#define MP make_pair\n#define endl '\\n'\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define sz(x) (ll) x.size()\n#define mid(l, r) ((r + l) / 2)\n#define left(node) (node * 2)\n#define right(node) (node * 2 + 1)\n#define mx_int_prime 999999937\n\nconst double PI = acos(-1);\nconst double eps = 1e-9;\nconst int infi = 2000000000;\nconst ll infLL = 9000000000000000000;\n#define MOD 1000000007\n\n#define mem(a, b) memset(a, b, sizeof(a))\n#define gcd(a, b) __gcd(a, b)\n#define sqr(a) ((a) * (a))\n\nvoid solve()\n{\n ll n, k;\n cin >> n >> k;\n\n vl v(n);\n for (ll i = 0; i < n; i++) cin >> v[i];\n\n\n ll l=0, r=0;\n ll ans = LLONG_MAX;\n set<ll>st;\n map<ll,ll>mp;\n\n while(r<n){\n if(v[r]<=k){\n mp[v[r]]++;\n st.insert(v[r]);\n }\n\n while(st.size()==k){\n ans = min(ans,(r-l)+1);\n if(v[l]<=k){\n mp[v[l]]--;\n if(mp[v[l]]==0){\n st.erase(v[l]);\n }\n }\n l++;\n }\n\n r++;\n }\n if(ans == LLONG_MAX){\n cout << 0 << endl;\n }\n else{\n cout << ans << endl;\n }\n\n}\n\nint main()\n{\n // ll t;\n // cin>>t;\n // while(t--){\n solve();\n // }\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 14728, "score_of_the_acc": -1.8, "final_rank": 17 }, { "submission_id": "aoj_DSL_3_B_10898339", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int n,k;cin>>n>>k;\n vector<int> a(n);\n for(auto &i:a)cin>>i;\n int r=0,ndis=0,ans=n+1;\n bool ok=1;\n map<int,int> freq;\n \n if(a[0]<=k && freq[a[0]]==0)ndis++;\n freq[a[0]]++;\n for(int i=0;i<n;i++){\n if(i>0){\n freq[a[i-1]]--;\n if(a[i-1]<=k && freq[a[i-1]]==0)ndis--;\n }\n while(ndis<k && r<n){\n r++;\n if(r<n && a[r]<=k && freq[a[r]]==0)ndis++;\n freq[a[r]]++;\n }\n if(ndis==k && r>=i){\n ans=min(ans,r-i+1);\n ok=0;\n }\n }\n\n if(ok)cout<<0<<'\\n';\n else cout<<ans<<'\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 8100, "score_of_the_acc": -1.3422, "final_rank": 15 }, { "submission_id": "aoj_DSL_3_B_10877538", "code_snippet": "//! https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_3_B\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n, k;\n cin >> n >> k;\n\n vector<int> v(n), cnt(k + 1, 0), vis(k + 1, 0);\n for (auto &x : v) cin >> x;\n\n int currK = 0, ans = INT_MAX;\n queue<int> q;\n for (int i = 0; i < n; i++) {\n q.push(v[i]);\n if (v[i] <= k) {\n cnt[v[i]]++;\n\n if (vis[v[i]] == 0) currK++;\n vis[v[i]] = 1;\n }\n\n while (!q.empty() && (q.front() > k || cnt[q.front()] > 1)) {\n if (q.front() <= k) cnt[q.front()]--;\n q.pop();\n }\n\n if (currK == k) ans = min(ans, (int)(q.size()));\n // cout << \"currK : \" << currK << ' ' << q.size() << endl;\n }\n if (ans == INT_MAX) ans = 0;\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4652, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DSL_3_B_10865193", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\nint n, k;\ncin >> n >> k;\n\nint arr[n];\n\nfor(int i=0; i<n; i++) cin >> arr[i];\n\nint ans = INT_MAX;\n\nint flag = 0;\n\nint l = 0, r = 0;\n\nmap<int,int>mp;\n\nwhile(r<n){\n\nif(arr[r]<=k) mp[arr[r]]++;\n\nif(mp.size()==k){\n\nflag = 1; \n\nwhile(mp.size()==k){\n\nans = min(ans, r-l+1);\n\nif(arr[l]<=k) mp[arr[l]]--;\n\nif(mp[arr[l]]==0) mp.erase(arr[l]);\n\nl++;\n\n}\n\n}\n\nr++;\n\n}\n\ncout<<(flag? ans : 0)<<'\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8420, "score_of_the_acc": -0.774, "final_rank": 11 }, { "submission_id": "aoj_DSL_3_B_10859782", "code_snippet": "/**\n Author: Md. Tanvir Ahmed rafi (Alraaafi)\n CF : https://codeforces.com/profile/Alraaafi\n**/\n \n /*\n \n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░█████████████████████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░██████░░░░░░░░░░░░░░░░░░░███░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░██░░░░░░░░░░░░░░░░░░░░░░░░░░█░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░██░░░░░░░░░░█░░░░░░░░░░░░░░░░█░░░\n███████████████████████████████████████░░░░░████████░░░░░░░\n░░░░░░░░░░░░░████░░░░█░░░░░█░░░░░░░░░██░░░░░█░░░░░░████░░░░\n░░░░░░░░░░░██░░░█░░░░██░░░░█░░░░░░░░██░░░░░░█░░░░░░░█░██░░░\n░░░░░░░░███░░░░░█░░░░░█░░░░██░░░░░██░░░░░░░░█░░░░░░░████░░░\n░░░░░░███░░░░░░░█░░░░░█░░░░░█░░░░░██████░░░░█░░░░░░░░░░░░░░\n░░░░░░░░█████░░░█░░░░░█░░░░░██░░░░░░░██░░░░░█░░░░░░░░░░░░░░\n░░░░░░░░░░░░░████░░░░░██░░░░░█░░░░████████████░░░░░░░░░░░░░\n░░░░░░██░██░░░░░░░░░░░░█░░░░░█░░░░██░░░░░░░░░█░░░░░░░░░░░░░\n░░░░░░█████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░█████╗░██╗░░░░░██████╗░░█████╗░░█████╗░░█████╗░███████╗██╗\n██╔══██╗██║░░░░░██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝██║\n███████║██║░░░░░██████╔╝███████║███████║███████║█████╗░░██║\n██╔══██║██║░░░░░██╔══██╗██╔══██║██╔══██║██╔══██║██╔══╝░░██║\n██║░░██║███████╗██║░░██║██║░░██║██║░░██║██║░░██║██║░░░░░██║\n╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░░░░╚═╝\n \n \n*/\n\n \n#include<bits/stdc++.h>\nusing namespace std;\n\n/*\n//Policy based Data structure\n//USE: ordered_set st;\n#include <ext/pb_ds/assoc_container.hpp> \n#include <ext/pb_ds/tree_policy.hpp> \nusing namespace __gnu_pbds; \n#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> \n*/\n \n \n//TYPEDEF\n#define HA printf(\"YES\\n\")\n#define NA printf(\"NO\\n\")\n#define F first\n#define S second\n\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef pair<int,int> pii;\ntypedef pair<double, double> pdd;\ntypedef pair<ll, ll> pll;\ntypedef vector<pii> vpi;\ntypedef vector<pll> vpll;\ntypedef double dl;\n#define testCase long long int TT,tc; cin>>TT; for(tc=1; tc<=TT; tc++)\n#define output(a,n) for(int i=0;i<n;i++) cout<<a[i]<<\" \"; \n#define endl \"\\n\" //not for interactive Problem...\ntypedef priority_queue<ll> PQ;\nint dx[] = {1,-1,0,0};\nint dy[] = {0,0,1,-1};\n#define FAST ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n#define POINT cout<<setprecision(10)<<fixed\n#define all(a) (a).begin(),(a).end()\n#define CASE cout<<\"Case \"<<tc<<\": \"\n#define PB push_back\n// Lamda Fn: auto fn_nm = [](var pera) { return expres; };\n\nll const md = 1e9 + 7;\n\n\nint main(){\n\n //FAST;\n ll i,j;\n\n // testCase\n // {\n // ll n,k;\n\n\n // }\n\n ll n,k;\n\n\n cin>>n>>k;\n\n ll a[n+4];\n\n for(i=1; i<=n; i++)\n {\n cin>>a[i];\n }\n\n map<ll,ll> mp;\n deque<ll> dq;\n\n ll jj;\n\n for(i=1; i<=n; i++)\n {\n if( a[i] <= k ) mp[ a[i] ]++;\n\n dq.push_back( a[i] );\n\n if( mp.size() == k ) \n {\n jj = i;\n break;\n }\n }\n\n if( mp.size() < k )\n {\n cout<<0<<endl;\n return 0;\n }\n\n\n ll ans = dq.size();\n ll pre,post;\n //post = a[jj+1];\n\n for(i = jj+1; ; )\n {\n \n \n pre = dq.front();\n\n dq.pop_front();\n if(pre<=k) mp[pre]--;\n\n if( ( i>n ) && (pre<=k) && (mp[pre]==0))\n break;\n\n //if( ( i>n) ) \n // break;\n\n j = i;\n while( mp[pre] == 0 && ( pre<=k ) && ( i<=n )){\n if(i>n) break;\n //cout<<j <<\" \"<<a[j]<<endl;\n post = a[j];\n dq.push_back( post );\n if(( post<=k )) mp[post]++;\n j++;\n if( j> n+1 ) break;\n }\n i = j;\n\n //if( ( i>n) ) \n // break;\n\n ll sz = dq.size();\n ans = min(ans, sz);\n\n\n if( i> n+1 ) break;\n\n //cout<<i<<\" \"<<sz<<\" \"<<pre<<\" \"<<post<<endl;\n }\n\n\n\n cout<<ans<<endl;\n\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 11296, "score_of_the_acc": -1.0594, "final_rank": 14 }, { "submission_id": "aoj_DSL_3_B_10859778", "code_snippet": "/**\n Author: Md. Tanvir Ahmed rafi (Alraaafi)\n CF : https://codeforces.com/profile/Alraaafi\n**/\n \n /*\n \n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░█████████████████████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░██████░░░░░░░░░░░░░░░░░░░███░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░██░░░░░░░░░░░░░░░░░░░░░░░░░░█░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░██░░░░░░░░░░█░░░░░░░░░░░░░░░░█░░░\n███████████████████████████████████████░░░░░████████░░░░░░░\n░░░░░░░░░░░░░████░░░░█░░░░░█░░░░░░░░░██░░░░░█░░░░░░████░░░░\n░░░░░░░░░░░██░░░█░░░░██░░░░█░░░░░░░░██░░░░░░█░░░░░░░█░██░░░\n░░░░░░░░███░░░░░█░░░░░█░░░░██░░░░░██░░░░░░░░█░░░░░░░████░░░\n░░░░░░███░░░░░░░█░░░░░█░░░░░█░░░░░██████░░░░█░░░░░░░░░░░░░░\n░░░░░░░░█████░░░█░░░░░█░░░░░██░░░░░░░██░░░░░█░░░░░░░░░░░░░░\n░░░░░░░░░░░░░████░░░░░██░░░░░█░░░░████████████░░░░░░░░░░░░░\n░░░░░░██░██░░░░░░░░░░░░█░░░░░█░░░░██░░░░░░░░░█░░░░░░░░░░░░░\n░░░░░░█████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░█████╗░██╗░░░░░██████╗░░█████╗░░█████╗░░█████╗░███████╗██╗\n██╔══██╗██║░░░░░██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝██║\n███████║██║░░░░░██████╔╝███████║███████║███████║█████╗░░██║\n██╔══██║██║░░░░░██╔══██╗██╔══██║██╔══██║██╔══██║██╔══╝░░██║\n██║░░██║███████╗██║░░██║██║░░██║██║░░██║██║░░██║██║░░░░░██║\n╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░░░░╚═╝\n \n \n*/\n\n \n#include<bits/stdc++.h>\nusing namespace std;\n\n/*\n//Policy based Data structure\n//USE: ordered_set st;\n#include <ext/pb_ds/assoc_container.hpp> \n#include <ext/pb_ds/tree_policy.hpp> \nusing namespace __gnu_pbds; \n#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> \n*/\n \n \n//TYPEDEF\n#define HA printf(\"YES\\n\")\n#define NA printf(\"NO\\n\")\n#define F first\n#define S second\n\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef pair<int,int> pii;\ntypedef pair<double, double> pdd;\ntypedef pair<ll, ll> pll;\ntypedef vector<pii> vpi;\ntypedef vector<pll> vpll;\ntypedef double dl;\n#define testCase long long int TT,tc; cin>>TT; for(tc=1; tc<=TT; tc++)\n#define output(a,n) for(int i=0;i<n;i++) cout<<a[i]<<\" \"; \n#define endl \"\\n\" //not for interactive Problem...\ntypedef priority_queue<ll> PQ;\nint dx[] = {1,-1,0,0};\nint dy[] = {0,0,1,-1};\n#define FAST ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n#define POINT cout<<setprecision(10)<<fixed\n#define all(a) (a).begin(),(a).end()\n#define CASE cout<<\"Case \"<<tc<<\": \"\n#define PB push_back\n// Lamda Fn: auto fn_nm = [](var pera) { return expres; };\n\nll const md = 1e9 + 7;\n\n\nint main(){\n\n //FAST;\n ll i,j;\n\n // testCase\n // {\n // ll n,k;\n\n\n // }\n\n ll n,k;\n\n\n cin>>n>>k;\n\n ll a[n+4];\n\n for(i=1; i<=n; i++)\n {\n cin>>a[i];\n }\n\n map<ll,ll> mp;\n deque<ll> dq;\n\n ll jj;\n\n for(i=1; i<=n; i++)\n {\n if( a[i] <= k ) mp[ a[i] ]++;\n\n dq.push_back( a[i] );\n\n if( mp.size() == k ) \n {\n jj = i;\n break;\n }\n }\n\n if( mp.size() < k )\n {\n cout<<0<<endl;\n return 0;\n }\n\n\n ll ans = dq.size();\n ll pre,post;\n //post = a[jj+1];\n\n for(i = jj+1; ; )\n {\n \n \n pre = dq.front();\n\n dq.pop_front();\n if(pre<=k) mp[pre]--;\n\n if( ( i>n ) && (pre<=k) && (mp[pre]==0))\n break;\n\n //if( ( i>n) ) \n // break;\n\n j = i;\n while( mp[pre] == 0 && ( pre<=k ) && ( i<=n )){\n if(i>n) break;\n //cout<<j <<\" \"<<a[j]<<endl;\n post = a[j];\n dq.push_back( post );\n if(( post<=k )) mp[post]++;\n j++;\n }\n i = j;\n\n //if( ( i>n) ) \n // break;\n\n ll sz = dq.size();\n ans = min(ans, sz);\n\n //cout<<i<<\" \"<<sz<<\" \"<<pre<<\" \"<<post<<endl;\n }\n\n\n\n cout<<ans<<endl;\n\n}", "accuracy": 0.7391304347826086, "time_ms": 20, "memory_kb": 5492, "score_of_the_acc": -0.2834, "final_rank": 19 }, { "submission_id": "aoj_DSL_3_B_10859748", "code_snippet": "/**\n Author: Md. Tanvir Ahmed rafi (Alraaafi)\n CF : https://codeforces.com/profile/Alraaafi\n**/\n \n /*\n \n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░█████████████████████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░██████░░░░░░░░░░░░░░░░░░░███░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░██░░░░░░░░░░░░░░░░░░░░░░░░░░█░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░██░░░░░░░░░░█░░░░░░░░░░░░░░░░█░░░\n███████████████████████████████████████░░░░░████████░░░░░░░\n░░░░░░░░░░░░░████░░░░█░░░░░█░░░░░░░░░██░░░░░█░░░░░░████░░░░\n░░░░░░░░░░░██░░░█░░░░██░░░░█░░░░░░░░██░░░░░░█░░░░░░░█░██░░░\n░░░░░░░░███░░░░░█░░░░░█░░░░██░░░░░██░░░░░░░░█░░░░░░░████░░░\n░░░░░░███░░░░░░░█░░░░░█░░░░░█░░░░░██████░░░░█░░░░░░░░░░░░░░\n░░░░░░░░█████░░░█░░░░░█░░░░░██░░░░░░░██░░░░░█░░░░░░░░░░░░░░\n░░░░░░░░░░░░░████░░░░░██░░░░░█░░░░████████████░░░░░░░░░░░░░\n░░░░░░██░██░░░░░░░░░░░░█░░░░░█░░░░██░░░░░░░░░█░░░░░░░░░░░░░\n░░░░░░█████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░█████╗░██╗░░░░░██████╗░░█████╗░░█████╗░░█████╗░███████╗██╗\n██╔══██╗██║░░░░░██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝██║\n███████║██║░░░░░██████╔╝███████║███████║███████║█████╗░░██║\n██╔══██║██║░░░░░██╔══██╗██╔══██║██╔══██║██╔══██║██╔══╝░░██║\n██║░░██║███████╗██║░░██║██║░░██║██║░░██║██║░░██║██║░░░░░██║\n╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░░░░╚═╝\n \n \n*/\n\n \n#include<bits/stdc++.h>\nusing namespace std;\n\n/*\n//Policy based Data structure\n//USE: ordered_set st;\n#include <ext/pb_ds/assoc_container.hpp> \n#include <ext/pb_ds/tree_policy.hpp> \nusing namespace __gnu_pbds; \n#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> \n*/\n \n \n//TYPEDEF\n#define HA printf(\"YES\\n\")\n#define NA printf(\"NO\\n\")\n#define F first\n#define S second\n\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef pair<int,int> pii;\ntypedef pair<double, double> pdd;\ntypedef pair<ll, ll> pll;\ntypedef vector<pii> vpi;\ntypedef vector<pll> vpll;\ntypedef double dl;\n#define testCase long long int TT,tc; cin>>TT; for(tc=1; tc<=TT; tc++)\n#define output(a,n) for(int i=0;i<n;i++) cout<<a[i]<<\" \"; \n#define endl \"\\n\" //not for interactive Problem...\ntypedef priority_queue<ll> PQ;\nint dx[] = {1,-1,0,0};\nint dy[] = {0,0,1,-1};\n#define FAST ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n#define POINT cout<<setprecision(10)<<fixed\n#define all(a) (a).begin(),(a).end()\n#define CASE cout<<\"Case \"<<tc<<\": \"\n#define PB push_back\n// Lamda Fn: auto fn_nm = [](var pera) { return expres; };\n\nll const md = 1e9 + 7;\n\n\nint main(){\n\n //FAST;\n ll i,j;\n\n // testCase\n // {\n // ll n,k;\n\n\n // }\n\n ll n,k;\n\n\n cin>>n>>k;\n\n ll a[n+4];\n\n for(i=1; i<=n; i++)\n {\n cin>>a[i];\n }\n\n map<ll,ll> mp;\n deque<ll> dq;\n\n ll jj;\n\n for(i=1; i<=n; i++)\n {\n if( a[i] <= k ) mp[ a[i] ]++;\n\n dq.push_back( a[i] );\n\n if( mp.size() == k ) \n {\n jj = i;\n break;\n }\n }\n\n if( mp.size() < k )\n {\n cout<<0<<endl;\n return 0;\n }\n\n\n ll ans = dq.size();\n ll pre,post;\n //post = a[jj+1];\n\n for(i = jj+1; ; )\n {\n \n \n pre = dq.front();\n\n dq.pop_front();\n if(pre<=k) mp[pre]--;\n\n if( ( i>n ) && (pre<=k) && (mp[pre]==0))\n break;\n\n j = i;\n while( mp[pre] == 0 && ( pre<=k ) ){\n \n post = a[j];\n dq.push_back( post );\n if(( post<=k )) mp[post]++;\n j++;\n }\n i = j;\n\n\n ll sz = dq.size();\n ans = min(ans, sz);\n\n //cout<<i<<\" \"<<sz<<\" \"<<pre<<\" \"<<post<<endl;\n }\n\n\n\n cout<<ans<<endl;\n\n}", "accuracy": 0.7391304347826086, "time_ms": 20, "memory_kb": 5524, "score_of_the_acc": -0.2865, "final_rank": 20 }, { "submission_id": "aoj_DSL_3_B_10843450", "code_snippet": "// \"Jai Shri Ram\"\n// author : himu_mojumder\n// \"Do more of what you enjoy most.\"\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// ---------------------- Macros ----------------------\n#define upar(value) upper_bound(v.begin(), v.end(), value) - v.begin();\n#define lower(value) lower_bound(v.begin(), v.end(), value) - v.begin();\n#define endl \"\\n\"\n#define yes cout << \"YES\\n\";\n#define no cout << \"NO\\n\";\n#define Yes cout << \"Yes\" << endl;\n#define No cout << \"No\" << endl;\n#define gcd __gcd\n#define pb push_back\n#define ll long long\n#define int long long\n\n#define lop(i, a, b) for (int i = a; i < b; ++i)\n#define rlop(i, a, b) for (int i = a; i >= b; --i)\n\n#define input(v) for (int i = 0; i < n; ++i) cin >> (v)[i];\n\n// ------------------ Sorting Macros ------------------\n#define srt(v) sort(v.begin(), v.end());\n#define rsrt(v) sort(v.rbegin(), v.rend());\n#define rev(v) reverse(v.begin(), v.end());\n#define uniq(v) srt(v); v.erase(unique(v.begin(), v.end()), v.end());\n\n// ------------------ Typedefs ------------------\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<pii> vpi;\ntypedef vector<vi> vvi;\ntypedef map<int, int> mii;\n\n// ------------------ Custom Comparator ------------------\nbool cmp(pair<int, int> &p1, pair<int, int> &p2)\n{\n if ((p1.first - p1.second) == (p2.first - p2.second))\n return (p1.first < p2.first);\n return ((p1.first - p1.second) > (p2.first - p2.second));\n // je vave cai shebabe return korbo\n}\n\n// ------------------ Algorithm Macros ------------------\n#define lcm(x, y) y * x / gcd(x, y)\n\n// ------------------ Testcase Macro ------------------\n#define test int tt; cin >> tt; while (tt--)\n\n// ------------------ Solve Function ------------------\nvoid solve()\n{\n int n,k;\n cin>>n>>k;\n vector<int>v(n);\n for(int i=0;i<n;i++)cin>>v[i];\n map<int,int>mp;\n int i=0;\n int j=0;\n int ans=INT_MAX;\n while(j<n){\n if(v[j]<=k)\n mp[v[j]]++;\n if(mp.size()>=k){\n while(v[i]>k || mp[v[i]]>1){\n if(v[i]>k);\n else{\n mp[v[i]]--;\n if(mp[v[i]]==0){\n mp.erase(mp[v[i]]);\n }\n }\n i++;\n }\n int tem=j-i+1;\n ans=min(tem,ans);\n }\n j++;\n }\n if(ans==INT_MAX)cout<<0<<endl;\n else cout<<ans<<endl;\n}\n// ------------------ Main Function ------------------\nsigned main()\n{\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n // test\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 10368, "score_of_the_acc": -0.7673, "final_rank": 9 }, { "submission_id": "aoj_DSL_3_B_10829882", "code_snippet": "// linK: https://onlinejudge.u-aizu.ac.jp/problems/DSL_3_B\n#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef double dl;\n\n#define endl \"\\n\"\n#define optimize() \\\n ios_base::sync_with_stdio(0); \\\n cin.tie(0); \\\n cout.tie(0);\n#define fraction() \\\n cout.unsetf(ios::floatfield); \\\n cout.precision(10); \\\n cout.setf(ios::fixed, ios::floatfield);\n\nvoid program()\n{\n int n, k;\n cin >> n >> k;\n\n vector<int> v(n);\n\n for (int &vi : v)\n cin >> vi;\n\n map<int, int> mp;\n\n int l = 0;\n int r = 0;\n bool found = false;\n int ans = n;\n\n while (r < n)\n {\n if (v[r] <= k)\n {\n mp[v[r]]++;\n }\n\n if (mp.size() < k)\n {\n r++;\n continue;\n }\n\n while (mp.size() == k)\n {\n found = true;\n\n if (v[l] <= k)\n {\n mp[v[l]]--;\n }\n\n if (mp[v[l]] == 0)\n {\n mp.erase(v[l]);\n }\n\n int len = r - l + 1;\n\n ans = min(ans, len);\n l++;\n }\n r++;\n }\n\n cout << (found ? ans : found) << endl;\n}\n\nint main()\n{\n optimize();\n program();\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8076, "score_of_the_acc": -0.5398, "final_rank": 2 }, { "submission_id": "aoj_DSL_3_B_10785460", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int n,k;\n cin>>n>>k;\n vector<int> v(n);\n for(int i=0;i<n;i++){\n\n \tcin>>v[i];\n }\n\n\n int res=INT_MAX;\n int l=0;\n int c=0;\n map<int,int>m;\n\n\n for(int r=0;r<n;r++){\n \tm[v[r]]++;\n \t if(v[r]>=1 && v[r]<=k && m[v[r]]==1){\n \t \tc++;\n \t }\n\n \t while(c==k){\n \t \tres=min(res,r-l+1);\n \t \tm[v[l]]--;\n \t \t if(v[l]>=1 && v[l]<=k && m[v[l]]==0){\n \t \tc--;\n \t }\n \t l++;\n\n \t }\n\n\n }\n if(res==INT_MAX){\n \tcout<<0<<endl;\n\n }\n else\n \tcout<<res<<endl;\n\n\n\n\n\n\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8132, "score_of_the_acc": -0.9454, "final_rank": 12 }, { "submission_id": "aoj_DSL_3_B_10782095", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n, k;\n cin >> n >> k;\n vector<int> a(n);\n for (int &x : a) cin >> x;\n\n map<int, int> freq;\n int have = 0, l = 0, r = 0, res = n + 1;\n\n while (r < n) {\n if (a[r] >= 1 && a[r] <= k) {\n freq[a[r]]++;\n if (freq[a[r]] == 1) have++;\n }\n while (have == k) {\n res = min(res, r - l + 1);\n if (a[l] >= 1 && a[l] <= k) {\n freq[a[l]]--;\n if (freq[a[l]] == 0) have--;\n }\n l++;\n }\n r++;\n }\n if (res == n + 1) cout << 0 << endl;\n else cout << res << endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8048, "score_of_the_acc": -0.737, "final_rank": 7 }, { "submission_id": "aoj_DSL_3_B_10775933", "code_snippet": "// Bismillahir Rahmanir Raheem\n\n\n\n#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef pair<int,int> pii;\ntypedef pair<double, double> pdd;\ntypedef pair<ll, ll> pll;\ntypedef vector<pii> vii;\ntypedef vector<pll> vll;\ntypedef double dl;\n\n\n#define endl '\\n'\n#define mx_int_prime 999999937\n#define tc int t;cin>>t;while(t--)\n#define yes cout<<\"YES\"<<endl;\n#define no cout<<\"NO\"<<endl;\n#define fr(i,a,n) for(int i=a;i<n;i++)\n\n\n\n\n\n#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n#define fraction() cout.unsetf(ios::floatfield); cout.precision(10); cout.setf(ios::fixed,ios::floatfield);\n#define file() freopen(\"input.txt\",\"r\",stdin);freopen(\"output.txt\",\"w\",stdout);\n\n\n\n\nvoid solve(){\n int n,k;\n cin>>n>>k;\n vi v(n);\n for(int i=0;i<n;i++){\n cin>>v[i];\n }\n int l=0,ans=INT_MAX,cnt=0;\n map<int,int>mp;\n for(int r=0;r<n;r++){\n if(v[r]>=1&&v[r]<=k){\n if(mp[v[r]] == 0) cnt++;\n mp[v[r]]++;\n\n }\n while(cnt==k){\n ans=min(ans,(r-l+1));\n\n if(v[l]>=1&&v[l]<=k){\n mp[v[l]]--;;\n if(mp[v[l]] == 0) cnt--;\n }\n l++;\n }\n }\n\n if(ans==INT_MAX)cout<<0<<endl;\n else cout<<ans<<endl;\n\n return ;\n\n\n }\n\n\n\nint main()\n{\n optimize();\n\n\n\n\n solve();\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8032, "score_of_the_acc": -0.7355, "final_rank": 6 }, { "submission_id": "aoj_DSL_3_B_10770367", "code_snippet": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\ntemplate <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\n\n#define ll long long\n#define double long double\n#define faster ios_base::sync_with_stdio(0);\n#define PI acos(-1.0)\n#define all(x) x.begin(),x.end()\n#define rall(x) x.rbegin(),x.rend()\n#define endl \"\\n\"\n#define PrintCase cout<<\"Case \"<<cs<<\": \"\n#define fraction(x) fixed<<setprecision(x)\n#define pinf INT_MAX\n#define minf INT_MIN\n\n//Debug\n#define DebugSingle(x) for(auto h: x){cout<<h<<\" \";}cout<<endl;\n#define DebugPair(x) for(auto h: x){cout<<h.first<<\" \"<<h.second<<endl;}\n\n#define vi vector<int>\n#define vvi vector<vi>\n#define vb vector<bool>\n#define pii pair<int, int>\n#define vpii vector<pii>\n#define vvpii vector<vpii>\n\n//input an array\n#define fin(a) for(auto &h: a){cin>> h;}\n\n\nvoid solve(){\n int n, k;\n cin>> n >> k;\n vector<int> a(n);\n set<int> st;\n for(int i = 0; i < n; i++){\n cin>> a[i];\n if(a[i] <= k)\n st.insert(a[i]);\n }\n if(st.size() < k){\n cout<< 0 <<endl;\n return;\n }\n\n map<int, int> mp;\n int ans = INT_MAX, j = 0;\n for(int i = 0; i < n; i++){\n if(a[i] <= k){\n mp[a[i]]++;\n }\n while(mp.size() == k){\n if(a[j] <= k){\n mp[a[j]]--;\n if(mp[a[j]] == 0){\n mp.erase(a[j]);\n }\n }\n ans = min(ans, i - j + 1);\n j++;\n if(j >= n){\n break;\n }\n }\n }\n cout<< ans <<endl;\n\n\n\n}\n\n\n\nint main()\n{\n faster\n solve();\n \n}", "accuracy": 1, "time_ms": 40, "memory_kb": 12856, "score_of_the_acc": -1.4142, "final_rank": 16 }, { "submission_id": "aoj_DSL_3_B_10770360", "code_snippet": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\ntemplate <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\n\n#define ll long long\n#define double long double\n#define faster ios_base::sync_with_stdio(0);\n#define PI acos(-1.0)\n#define all(x) x.begin(),x.end()\n#define rall(x) x.rbegin(),x.rend()\n#define endl \"\\n\"\n#define PrintCase cout<<\"Case \"<<cs<<\": \"\n#define fraction(x) fixed<<setprecision(x)\n#define pinf INT_MAX\n#define minf INT_MIN\n\n//Debug\n#define DebugSingle(x) for(auto h: x){cout<<h<<\" \";}cout<<endl;\n#define DebugPair(x) for(auto h: x){cout<<h.first<<\" \"<<h.second<<endl;}\n\n#define vi vector<int>\n#define vvi vector<vi>\n#define vb vector<bool>\n#define pii pair<int, int>\n#define vpii vector<pii>\n#define vvpii vector<vpii>\n\n//input an array\n#define fin(a) for(auto &h: a){cin>> h;}\n\n\nvoid solve(){\n ll n, k;\n cin>> n >> k;\n vector<ll> a(n);\n fin(a);\n map<int, int> mp;\n int id = -1;\n for(int i = 0; i < n; i++){\n if(a[i] <= k){\n mp[a[i]]++;\n }\n\n if(mp.size() == k){\n id = i;\n break;\n }\n }\n\n if(id == -1){\n cout<< 0 <<endl;\n return;\n }\n\n int j = id, ans = id + 1;\n\n for(int i = 0; i < n; i++){\n if(a[i] <= k and mp[a[i]] == 1){\n while(1){\n j++;\n if(j >= n){\n break;\n }\n if(a[j] <= k){\n mp[a[j]]++;\n }\n if(a[i] == a[j]){\n break;\n }\n }\n }\n if(a[i] <= k){\n mp[a[i]]--;\n if(mp[a[i]] == 0){\n break;\n }\n }\n if(j < n)\n ans = min(ans, j - i);\n }\n cout<< ans <<endl;\n \n\n\n\n}\n\n\n\nint main()\n{\n faster\n solve();\n \n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8632, "score_of_the_acc": -0.595, "final_rank": 4 }, { "submission_id": "aoj_DSL_3_B_10702919", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here \n\tint t,n,i,j,k,g,h,st,f;\n\tvector<int> v;\n\tmap<int,int> m;\n\tcin>>n>>k;\n\tfor(i=0;i<n;i++)\n\t{\n\t\tcin>>g;\n\t\tv.push_back(g);\n\t}\n\th=INT_MAX;\n\tst=0;\n\tfor(i=0;i<n;i++)\n\t{\n\t\tif(v[i]>k)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tm[v[i]]++;\n\t\t\twhile(st<i && m.size()==k && (v[st]>k || m[v[st]]>1))\n\t\t\t{\n\t\t\t\tif(v[st]<=k)\n\t\t\t\tm[v[st]]--;\n\t\t\t\tst++;\n\t\t\t}\n\t\t\tif(m.size()==k)\n\t\t\t{\n\t\t\t\tif(h>i-st+1)\n\t\t\t\th=i-st+1;\n\t\t\t}\n\t\t}\n\t}\n\tif(h==INT_MAX)\n\t{\n\t\tcout<<\"0\\n\";\n\t}\n\telse \n\t{\n\t\tcout<<h<<\"\\n\";\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8112, "score_of_the_acc": -0.7434, "final_rank": 8 }, { "submission_id": "aoj_DSL_3_B_10702893", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint n,k; cin>>n>>k;\n\tint arr[n];\n\tmap<int,int> mp;\n\tint e=0,f=0,min=n+1;\n\tfor(e=0;e<n;e++){\n\t\tcin>>arr[e];\n\t\tif(arr[e]<=k && arr[e]>=1){\n\t\t\tmp[arr[e]]++;\n\t\t}\n\t\tif(mp.size()==k){\n\t\t\tif(min>e-f+1) min=e-f+1;\n\t\t}\n\t\twhile(f<=e && mp.size()==k){\n\t\t\tif(mp.count(arr[f])){\n\t\t\t\tmp[arr[f]]--;\n\t\t\t\tif(mp[arr[f]]==0) mp.erase(arr[f]);\n\t\t\t}\n\t\t\tf++;\n\t\t\tif(mp.size()==k){\n\t\t\t\tif(min>e-f+1) min=e-f+1;\n\t\t\t}\n\t\t}\n\t}\n\tif(min==n+1) cout<<0<<\"\\n\";\n\telse cout<<min<<\"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8400, "score_of_the_acc": -0.772, "final_rank": 10 }, { "submission_id": "aoj_DSL_3_B_10663441", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n#define double long double\n#define faster ios_base::sync_with_stdio(0);\n#define PI acos(-1.0)\n#define all(x) x.begin(),x.end()\n#define rall(x) x.rbegin(),x.rend()\n#define endl \"\\n\"\n#define PrintCase cout<<\"Case \"<<cs<<\": \"\n#define fraction(x) fixed<<setprecision(x)\n#define pinf INT_MAX\n#define minf INT_MIN\n\n//Debug\n#define DebugSingle(x) for(auto h: x){cout<<h<<\" \";}cout<<endl;\n#define DebugPair(x) for(auto h: x){cout<<h.first<<\" \"<<h.second<<endl;}\n\n#define vi vector<int>\n#define vvi vector<vi>\n#define vb vector<bool>\n#define pii pair<int, int>\n#define vpii vector<pii>\n#define vvpii vector<vpii>\n\n//input an array\n#define fin(a) for(auto &h: a){cin>> h;}\n\n\nvoid solve(){\n int n, k;\n cin>> n >> k;\n vector<int> a(n);\n fin(a);\n map<int, int> mp;\n int id = -1;\n for(int i = 0; i < n; i++){\n if(a[i] <= k){\n mp[a[i]]++;\n }\n if(mp.size() == k){\n id = i;\n break;\n }\n }\n // cout<< id <<endl;\n if(id == -1){\n cout<< 0 <<endl;\n return;\n }\n\n int ans = id + 1, j = id;\n for(int i = 0; i < n; i++){\n if(a[i] <= k and mp[a[i]] == 1){\n while(1){\n j++;\n if(j >= n){\n break;\n }\n if(a[j] <= k){\n mp[a[j]]++;\n }\n if(a[j] == a[i]){\n break;\n } \n }\n }\n if(a[i] <= k){\n mp[a[i]]--;\n if(mp[a[i]] == 0){\n break;\n }\n }\n if(j < n){\n ans = min(ans, j - i);\n }\n // cout<< j << \" \" << i <<endl;\n }\n cout<< ans <<endl;\n\n\n\n}\n\n\n\nint main()\n{\n faster\n solve();\n \n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8100, "score_of_the_acc": -0.5422, "final_rank": 3 }, { "submission_id": "aoj_DSL_3_B_10594795", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n\tlong long n,k;\n\tcin>>n>>k;\n\tmap<long long,long long>cnt;\n\tdeque<long long>x;\n\tlong long mn=1e18;\n\tfor(long long i=0;i<n;i++){\n\t\tlong long c;\n\t\tcin>>c;\n\t\tif(c<k+1){\n\t\t\tcnt[c]+=1;\n\t\t}\n\t\tx.push_back(c);\n\t\tif(cnt.size()==k){\n\t\t\twhile(1){\n\t\t\t\tlong long v=x.front();\n\t\t\t\tif(v<k+1&&cnt[v]!=1){\n\t\t\t\t\tx.pop_front();\n\t\t\t\t\tcnt[v]-=1;\n\t\t\t\t}\n\t\t\t\telse if(v<k+1&&cnt[v]==1){\n\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tx.pop_front();\n\t\t\t\t}\n\t\t\t}\n\t\t\tmn=min(mn,(long long)x.size());\n\t\t}\n\t\t\n\n\t}\n\tif(cnt.size()==k){\n\t\tcout<<mn<<endl;\n\t}\n\telse{\n\t\t\n\t\tcout<<\"0\"<<endl;\n\t}\n\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 10508, "score_of_the_acc": -0.9812, "final_rank": 13 }, { "submission_id": "aoj_DSL_3_B_10538538", "code_snippet": "/*********************** In the Name of ALLAH ************************/\n#include<bits/stdc++.h>\n#include<ext/pb_ds/assoc_container.hpp>\n#include<ext/pb_ds/tree_policy.hpp>\n#define fl(n) for(ll i = 0; i < n;i++)\n#define flj(n) for(ll j = 0; j < n;j++)\n#define fastio ios_base::sync_with_stdio(false);\n#define ll long long\n#define endl \"\\n\"\nusing namespace std;\nusing namespace __gnu_pbds;\n#define MOD 1000000007\ntemplate<typename T> using ordered_set = tree < T, null_type,less<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\n//Comparator\n//bool cmp(const pair<ll,ll>&a,const pair<ll,ll>&b)\n//{\n// if(a.first < b.first) return 1;\n// else if(a.first == b.first) return (a.second > b.second);\n// return 0;\n//}\n\n\nint main()\n{\n fastio;\n int n,k;\n cin >> n >> k;\n int arr[n];\n fl(n)\n {\n cin >> arr[i];\n }\n map<int,int>mp;\n deque<int>dq;\n queue<int>q;\n for(auto i : arr) q.push(i);\n bool flag = false;\n fl(n)\n {\n if(arr[i] >= 1 && arr[i] <= k)\n {\n mp[arr[i]]++;\n }\n dq.push_back(arr[i]);\n q.pop();\n if(mp.size() == k)\n {\n flag = true;\n break;\n }\n }\n if(!flag)\n {\n cout << 0 << endl;\n return 0;\n }\n int mini = dq.size();\n while(true)\n {\n mini = min((int)dq.size(),mini);\n int x = dq.front();\n if(mp[x] == 1)\n {\n while(!q.empty())\n {\n int y = q.front();\n dq.push_back(y);\n if(y >= 1 && y <= k) mp[y]++;\n q.pop();\n if(mp[x] > 1) break;\n }\n }\n dq.pop_front();\n if(x >= 1 && x <= k)\n {\n mp[x]--;\n if(mp[x] < 1) break;\n }\n }\n cout << mini << endl;\n\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8904, "score_of_the_acc": -0.622, "final_rank": 5 } ]
aoj_GRL_1_C_cpp
All Pairs Shortest Path Input An edge-weighted graph G ( V , E ). | V | | E | s 0 t 0 d 0 s 1 t 1 d 1 : s |E|-1 t |E|-1 d |E|-1 |V| is the number of vertices and |E| is the number of edges in G . The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. s i and t i represent source and target vertices of i -th edge (directed) and d i represents the cost of the i -th edge. Output If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print NEGATIVE CYCLE in a line. Otherwise, print D 0,0 D 0,1 ... D 0,|V|-1 D 1,0 D 1,1 ... D 1,|V|-1 : D |V|-1,0 D 1,1 ... D |V|-1,|V|-1 The output consists of |V| lines. For each i th line, print the cost of the shortest path from vertex i to each vertex j ( j = 0, 1, ... |V|-1 ) respectively. If there is no path from vertex i to vertex j , print " INF ". Print a space between the costs. Constraints 1 ≤ |V| ≤ 100 0 ≤ |E| ≤ 9900 -2 × 10 7 ≤ d i ≤ 2 × 10 7 There are no parallel edges There are no self-loops Sample Input 1 4 6 0 1 1 0 2 5 1 2 2 1 3 4 2 3 1 3 2 7 Sample Output 1 0 1 3 4 INF 0 2 3 INF INF 0 1 INF INF 7 0 Sample Input 2 4 6 0 1 1 0 2 -5 1 2 2 1 3 4 2 3 1 3 2 7 Sample Output 2 0 1 -5 -4 INF 0 2 3 INF INF 0 1 INF INF 7 0 Sample Input 3 4 6 0 1 1 0 2 5 1 2 2 1 3 4 2 3 1 3 2 -7 Sample Output 3 NEGATIVE CYCLE
[ { "submission_id": "aoj_GRL_1_C_10776003", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/1/GRL_1_C\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <queue>\nusing namespace std;\n\nstruct Edge\n{\n int s = 0, t = 0;\n int d = 0;\n bool enabled = false;\n Edge() = default; // デフォルトコンストラクタを追加\n Edge(int s, int t, int d) : s(s), t(t), d(d), enabled(true) {}\n};\n\nstruct Route\n{\n int destination;\n int min_cost;\n size_t num_node;\n Route(int destination, int min_cost, size_t num_node) : destination(destination), min_cost(min_cost), num_node(num_node) {}\n};\n\nstruct ShortestPath\n{\n int destination;\n int cost;\n bool enabled = false;\n};\n\n// prim法を踏襲\nvoid get_distances_as_minimum_spannging_tree(int strat_id, const vector<vector<Edge>> &A, vector<ShortestPath> &d, bool &has_negative_cycle)\n{\n // 選択済みと隣接する経路(重みと頂点番号)のリスト\n struct Comp\n {\n bool operator()(const Route &a, const Route &b)\n {\n return a.min_cost > b.min_cost;\n }\n };\n priority_queue<Route, deque<Route>, Comp> routes; // 経路キュー\n\n routes.push(Route(strat_id, 0, 1)); // 出発点への最短コストは0としておく\n\n while (routes.empty() == false)\n {\n // 最も安い経路を得る\n auto route = routes.top();\n routes.pop();\n\n if (d[route.destination].enabled && d[route.destination].cost < route.min_cost)\n continue; // 既に経路が見つかっており、そのコストが新しい経路コストよりも小さいなら無視\n\n if (route.num_node > A.size()) // 経路に含まれる頂点数が総点数を超えている場合\n {\n has_negative_cycle = true; // NEGATIVE CYCLE\n return;\n }\n\n d[route.destination].cost = route.min_cost;\n d[route.destination].enabled = true;\n\n // その経路の行き先頂点から隣接する未選択頂点への経路をキューに追加する\n for (Edge edge : A[route.destination])\n {\n if (!edge.enabled)\n continue; // この辺が無効ならスキップ\n\n int cost = d[route.destination].cost + edge.d; // この経路+辺のコスト\n\n if (d[edge.t].enabled) // この辺の行き先の最短経路が見つかっている場合\n {\n if (d[edge.t].cost <= cost)\n {\n continue; // 既知の最短経路コストの方が新しい経路コスト以下ならスキップ\n }\n }\n\n // 経路をキューに追加\n routes.push(Route(edge.t, cost, route.num_node + 1));\n }\n }\n}\n\nint main()\n{\n int num_vertices; // 頂点数\n int num_edges; // 辺数\n cin >> num_vertices >> num_edges;\n vector<vector<Edge>> A(num_vertices, vector<Edge>(num_vertices)); // 隣接関係\n\n for (int i = 0; i < num_edges; ++i)\n {\n int s, t, d;\n cin >> s >> t >> d;\n A[s][t] = Edge(s, t, d);\n }\n\n vector<vector<ShortestPath>> D; // 最短距離行列\n for (int i = 0; i < num_vertices; ++i)\n {\n bool has_negative_cycle = false; // NegativeCycleかどうか\n vector<ShortestPath> d(num_vertices); // ノードiからの最短距離\n\n get_distances_as_minimum_spannging_tree(i, A, d, has_negative_cycle);\n\n if (has_negative_cycle)\n {\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n\n D.push_back(d);\n }\n\n // 結果を出力\n for (int i = 0; i < num_vertices; ++i)\n {\n for (int j = 0; j < num_vertices; ++j)\n {\n if (D[i][j].enabled)\n cout << D[i][j].cost;\n else\n cout << \"INF\";\n\n if (j != num_vertices - 1) // 最後の列以外ではスペースを出力\n cout << \" \";\n }\n cout << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3736, "score_of_the_acc": -0.3162, "final_rank": 1 }, { "submission_id": "aoj_GRL_1_C_10775881", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/1/GRL_1_C\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <queue>\nusing namespace std;\n\nstruct Edge\n{\n int s = 0, t = 0;\n int d = 0;\n bool enabled = false;\n Edge() = default; // デフォルトコンストラクタを追加\n Edge(int s, int t, int d) : s(s), t(t), d(d), enabled(true) {}\n};\n\nstruct Route\n{\n int destination;\n int min_cost;\n Route(int destination, int min_cost) : destination(destination), min_cost(min_cost) {}\n};\n\nstruct ShortestPath\n{\n int destination;\n int cost;\n bool enabled = false;\n};\n\n// prim法を踏襲\nvoid get_distances_as_minimum_spannging_tree(int strat_id, const vector<vector<Edge>> &A, vector<ShortestPath> &d, bool &has_negative_cycle)\n{\n // 選択済みと隣接する経路(重みと頂点番号)のリスト\n struct Comp\n {\n bool operator()(const Route &a, const Route &b)\n {\n return a.min_cost > b.min_cost;\n }\n };\n priority_queue<Route, deque<Route>, Comp> routes; // 経路キュー\n\n routes.emplace(strat_id, 0); // 出発点への最短コストは0としておく\n\n int cnt = 0;\n\n while (routes.empty() == false)\n {\n // 最も安い経路を得る\n auto route = routes.top();\n routes.pop();\n\n if (d[route.destination].enabled && d[route.destination].cost < route.min_cost)\n continue; // 既に経路が見つかっており、そのコストが新しい経路コストよりも小さいなら無視\n\n d[route.destination].cost = route.min_cost;\n d[route.destination].enabled = true;\n\n // その経路の行き先頂点から隣接する未選択頂点への経路をキューに追加する\n for (Edge edge : A[route.destination])\n {\n if (!edge.enabled)\n continue; // この辺が無効ならスキップ\n\n if (cnt > 99000)\n {\n // 辺の数は9900を超えない⇒超えたら負のループがある\n has_negative_cycle = true; // NegativeCycle判定\n return;\n }\n cnt++;\n\n int cost = d[route.destination].cost + edge.d; // この経路+辺のコスト\n\n if (d[edge.t].enabled) // この辺の行き先の最短経路が見つかっている場合\n {\n if (d[edge.t].cost <= cost)\n {\n continue; // 既知の最短経路コストの方が新しい経路コスト以下ならスキップ\n }\n }\n\n // 経路をキューに追加\n routes.emplace(edge.t, cost);\n }\n }\n}\n\nint main()\n{\n int num_vertices; // 頂点数\n int num_edges; // 辺数\n cin >> num_vertices >> num_edges;\n vector<vector<Edge>> A(num_vertices, vector<Edge>(num_vertices)); // 隣接関係\n\n for (int i = 0; i < num_edges; ++i)\n {\n int s, t, d;\n cin >> s >> t >> d;\n A[s][t] = Edge(s, t, d);\n }\n\n vector<vector<ShortestPath>> D; // 最短距離行列\n for (int i = 0; i < num_vertices; ++i)\n {\n bool has_negative_cycle = false; // NegativeCycleかどうか\n vector<ShortestPath> d(num_vertices); // ノードiからの最短距離\n\n get_distances_as_minimum_spannging_tree(i, A, d, has_negative_cycle);\n\n if (has_negative_cycle)\n {\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n\n D.push_back(d);\n }\n\n // 結果を出力\n for (int i = 0; i < num_vertices; ++i)\n {\n for (int j = 0; j < num_vertices; ++j)\n {\n if (D[i][j].enabled)\n cout << D[i][j].cost;\n else\n cout << \"INF\";\n\n if (j != num_vertices - 1) // 最後の列以外ではスペースを出力\n cout << \" \";\n }\n cout << endl;\n }\n\n return 0;\n}", "accuracy": 0.94, "time_ms": 50, "memory_kb": 3772, "score_of_the_acc": -0.3206, "final_rank": 9 }, { "submission_id": "aoj_GRL_1_C_10775826", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/1/GRL_1_C\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <queue>\nusing namespace std;\n\nstruct Edge\n{\n int s = 0, t = 0;\n int d = 0;\n bool enabled = false;\n Edge() = default; // デフォルトコンストラクタを追加\n Edge(int s, int t, int d) : s(s), t(t), d(d), enabled(true) {}\n};\n\nstruct Route\n{\n int destination;\n int min_cost;\n Route(int destination, int min_cost) : destination(destination), min_cost(min_cost) {}\n};\n\nstruct ShortestPath\n{\n int destination;\n int cost;\n bool enabled = false;\n};\n\n// prim法を踏襲\nvoid get_distances_as_minimum_spannging_tree(int strat_id, const vector<vector<Edge>> &A, vector<ShortestPath> &d, bool &has_negative_cycle)\n{\n // 選択済みと隣接する経路(重みと頂点番号)のリスト\n struct Comp\n {\n bool operator()(const Route &a, const Route &b)\n {\n return a.min_cost > b.min_cost;\n }\n };\n priority_queue<Route, deque<Route>, Comp> routes; // 経路キュー\n\n routes.emplace(strat_id, 0); // 出発点への最短コストは0としておく\n\n int cnt = 0;\n\n while (routes.empty() == false)\n {\n // 最も安い経路を得る\n auto route = routes.top();\n routes.pop();\n\n if (d[route.destination].enabled && d[route.destination].cost < route.min_cost)\n continue; // 既に経路が見つかっており、そのコストが新しい経路コストよりも小さいなら無視\n\n d[route.destination].cost = route.min_cost;\n d[route.destination].enabled = true;\n\n // その経路の行き先頂点から隣接する未選択頂点への経路をキューに追加する\n for (Edge edge : A[route.destination])\n {\n if (!edge.enabled)\n continue; // この辺が無効ならスキップ\n\n if (cnt > 9900)\n {\n // 辺の数は9900を超えない⇒超えたら負のループがある\n has_negative_cycle = true; // NegativeCycle判定\n return;\n }\n cnt++;\n\n int cost = d[route.destination].cost + edge.d; // この経路+辺のコスト\n\n if (d[edge.t].enabled) // この辺の行き先の最短経路が見つかっている場合\n {\n if (d[edge.t].cost <= cost)\n {\n continue; // 既知の最短経路コストの方が新しい経路コスト以下ならスキップ\n }\n }\n\n // 経路をキューに追加\n routes.emplace(edge.t, cost);\n }\n }\n}\n\nint main()\n{\n int num_vertices; // 頂点数\n int num_edges; // 辺数\n cin >> num_vertices >> num_edges;\n vector<vector<Edge>> A(num_vertices, vector<Edge>(num_vertices)); // 隣接関係\n\n for (int i = 0; i < num_edges; ++i)\n {\n int s, t, d;\n cin >> s >> t >> d;\n A[s][t] = Edge(s, t, d);\n }\n\n vector<vector<ShortestPath>> D; // 最短距離行列\n for (int i = 0; i < num_vertices; ++i)\n {\n bool has_negative_cycle = false; // NegativeCycleかどうか\n vector<ShortestPath> d(num_vertices); // ノードiからの最短距離\n\n get_distances_as_minimum_spannging_tree(i, A, d, has_negative_cycle);\n\n if (has_negative_cycle)\n {\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n\n D.push_back(d);\n }\n\n // 結果を出力\n for (int i = 0; i < num_vertices; ++i)\n {\n for (int j = 0; j < num_vertices; ++j)\n {\n if (D[i][j].enabled)\n cout << D[i][j].cost;\n else\n cout << \"INF\";\n\n if (j != num_vertices - 1) // 最後の列以外ではスペースを出力\n cout << \" \";\n }\n cout << endl;\n }\n\n return 0;\n}", "accuracy": 0.66, "time_ms": 20, "memory_kb": 3656, "score_of_the_acc": -0.0921, "final_rank": 10 }, { "submission_id": "aoj_GRL_1_C_10711784", "code_snippet": "#include<iostream>\n#include<cstdio>\nusing namespace std;\nconst int INF=1e12;\nint e,v,r;\nlong long int to[100000],from[100000],w[1000000],d[1000][1000];\nbool relax(int e){\n\tif(d[r][to[e]]>d[r][from[e]]+w[e] && d[r][from[e]]!=INF){\n\t\td[r][to[e]]=d[r][from[e]]+w[e];\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint main(){\n\tcin>>v>>e;\n\tfor(int i=0;i<e;i++){\n\t\tcin>>to[i]>>from[i]>>w[i];\n\t}\n\tfor(int i=0;i<v+10;i++){\n\t\tfill(d[i],d[i]+v+10,INF);\n\t}\n\tfor(r=0;r<v;r++){\n\t\td[r][r]=0;\n\t\tfor(int i=0;i<v;i++){\n\t\t\tfor(int j=0;j<e;j++){\n\t\t\t\tbool o=relax(j);\n\t\t\t\tif(i==v-1 && o==true){\n\t\t\t\t\tcout<<\"NEGATIVE CYCLE\"<<endl;\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0;i<v;i++){\n\t\tfor(int j=0;j<v;j++){\n\t\t\tif(d[j][i]!=INF){\n\t\t\t\tcout<<d[j][i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcout<<\"INF\";\n\t\t\t}\n\t\t\tif(j!=v-1){\n\t\t\t\tcout<<\" \";\n\t\t\t}\n\t\t}\n\t\tcout<<endl;\n\t}\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 8156, "score_of_the_acc": -1.1446, "final_rank": 8 }, { "submission_id": "aoj_GRL_1_C_10546308", "code_snippet": "//// From algorithms repository `template.cpp`\n// Based on Competitive Programming Book by Steve Halim\n// Also has some snippets from previous codes I've written\n\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<long, long> pll;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n#define FAST_IO() \\\n ios_base::sync_with_stdio(false); \\\n cin.tie(NULL)\n\n// 2**6 = 64 // 4! = 24\n// 2**8 = 256 // 5! = 120\n// 2**10 = 1,024 ~= 10^3 // 6! = 720\n// 2**15 = 32,768 // 7! = 5,040\n// 2**20 = 1,048,576 ~= 10^6 // 8! = 40,320\n// 2**25 = 33,554,432 // 9! = 362,880\n// 2**30 = 1,073,741,824 // 10! = 3,628,800 ~= 3*10^6\n// 2**32 = 4,294,967,296 // 11! = 39,916,800 ~= 4*10^7\n// // 12! = 479,001,600\n// // 14! = 87,178,291,200\n// int up to 2*10^9 (2^31-1) // 16! = 20,922,789,888,000\n// ll up to 9*10^18 (2^63 -1) // 18! = 6,402,373,705,728,000\n// ull up to 18*10^18 (2^64-1)/ // 20! = 2,432,902,008,176,640,000\n// ld up to 10*10^307\n\n// 1 sec is ~10^8 operations\n\n// n Worst AC algorithm\n// <=[10..11] O(n!), O(n^6)\n// <=[17..19] O(2^n * n^2)\n// <=[18..22] O(2^n * n)\n// <=[24..26] O(2^n)\n// <=100 O(n^4)\n// <=450 O(n^3)\n// <=1.5*10^3 O(n^2.5)\n// <=2.5*10^3 O(n^2 * log(n))\n// <=10^4 O(n^2)\n// <=2*10^5 O(n^1.5)\n// <=4.5*10^6 O(n * log(n))\n// <=10^7 O(n * log(log(n)))\n// <=10^8 O(n), O(log(n)), O(1)\n\n#define INF 1e11\n\n// O(VE)\nvoid bellman_ford(int source, int V, const vector<vector<pair<int, ll>>> &neighbors, vector<ll> &distance, vector<int> &predecessor)\n{\n // vector<int> distance(V, INF);\n // vector<int> predecessor(V, -1);\n\n distance[source] = 0;\n\n for (int i = 0; i < V - 1; i++) // relax all E edges V−1 times\n for (int u = 0; u < V; u++) // these next two loops = O(E), overall O(VE)\n if (distance[u] != INF)\n for (int j = 0; j < (int)neighbors[u].size(); j++)\n {\n pair<int, ll> v = neighbors[u][j];\n if (distance[u] + v.second < distance[v.first])\n {\n distance[v.first] = distance[u] + v.second; // relax\n predecessor[v.first] = u; // save predecessor\n }\n }\n}\n\nbool has_negative_cycle(int V, const vector<vector<pair<int, ll>>> &neighbors, const vector<ll> &distance)\n{\n // after running the O(VE) Bellman Ford’s algorithm\n bool hasNegativeCycle = false;\n\n for (int u = 0; u < V; u++) // one more pass to check\n if (distance[u] != INF)\n for (int i = 0; i < (int)neighbors[u].size(); i++)\n {\n pair<int, ll> v = neighbors[u][i];\n if (distance[v.first] > distance[u] + v.second) // if this is still possible\n hasNegativeCycle = true; // then negative cycle exists!\n }\n\n return hasNegativeCycle;\n}\n\nint main()\n{\n FAST_IO();\n\n#ifdef DEBUG\n freopen(\"input.txt\", \"r\", stdin);\n freopen(\"error.txt\", \"w\", stderr);\n freopen(\"output.txt\", \"w\", stdout);\n#endif\n\n int V, E;\n cin >> V >> E;\n\n vector<vector<pair<int, ll>>> neighbors(V, vector<pair<int, ll>>());\n\n for (int i = 0; i < E; i++)\n {\n int u, v;\n ll w;\n cin >> u >> v >> w;\n\n neighbors[u].push_back(make_pair(v, w));\n }\n\n vector<vector<ll>> distance(V, vector<ll>());\n\n for (int i = 0; i < V; i++)\n {\n int source = i;\n vector<ll> current_distance(V, INF);\n vector<int> predecessor(V, -1);\n\n bellman_ford(source, V, neighbors, current_distance, predecessor);\n\n if (has_negative_cycle(V, neighbors, current_distance))\n {\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n else\n {\n distance[source] = current_distance;\n }\n }\n\n for (int i = 0; i < V; i++)\n {\n for (int j = 0; j < V; j++)\n {\n if (distance[i][j] == INF)\n cout << \"INF\";\n else\n cout << distance[i][j];\n\n if (j < V - 1)\n cout << \" \";\n }\n cout << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3684, "score_of_the_acc": -0.4526, "final_rank": 2 }, { "submission_id": "aoj_GRL_1_C_10514250", "code_snippet": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <list>\n#include <queue>\n#include <climits>\n#include <sstream>\n#include <tuple>\n\nusing Path = std::tuple<int, int, int>; // 経路。cost, s, t. 頂点indexから頂点secondを経由した頂点thirdまでの距離はfirst\nusing Edge = std::pair<int, int>; // 辺。ある点から頂点番号firstまでの距離はsecond\nusing Graph = std::vector<std::list<Edge>>;\n\nbool isLoop(const std::vector<int>& P, int u) {\n for (int v = P[u]; v >= 0; v = P[v]) if (v == u) return true;\n return false;\n}\nstd::vector<int> sssp(const Graph& G, int index) {\n int n = G.size();\n std::vector<int> D(n, INT_MIN); // 始点から各頂点までの距離、負数は距離未確定\n std::vector<int> P(n, -1); // 各頂点の親 流入元\n\n // 始点からの距離が近い順に、距離・頂点番号ペアを保持する\n std::priority_queue<Path, std::deque<Path>, std::greater<Path>> paths;\n paths.emplace(0, -1, index); // 始点から始点までの距離は0\n\n while(paths.empty() == false) {\n // 始点からの最も近い点を得る\n const auto [d, s, t] = paths.top(); paths.pop();\n if (D[t] != INT_MIN && D[t] <= d) continue; // 高いルートは無視\n\n // もし、tの親を辿って自身が居たら負の閉路\n P[t] = s;\n D[t] = d;\n if (isLoop(P, t)) return std::vector<int>();\n\n // 新たな頂点に隣接する頂点の経路を追加する\n for (const auto& [v, c] : G[t]) {\n paths.emplace(D[t] + c, t, v);\n }\n }\n return D;\n}\n\nint main() {\n int v, e;\n std::cin >> v >> e;\n Graph G(v);\n for (int i = 0; i < e; ++i) {\n int s, t, d;\n std::cin >> s >> t >> d;\n G[s].emplace_back(t, d);\n }\n std::stringstream ans; \n for (int i = 0; i < v; ++i) {\n const auto& d = sssp(G, i);\n if (d.empty()) {\n std::cout << \"NEGATIVE CYCLE\" << std::endl;\n return 0;\n }\n for (int j = 0; j < d.size(); ++j) {\n if (j) ans << \" \";\n if (d[j] == INT_MIN) ans << \"INF\";\n else ans << d[j];\n }\n ans << \"\\n\";\n }\n std::cout << ans.str();\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 3856, "score_of_the_acc": -1.0452, "final_rank": 7 }, { "submission_id": "aoj_GRL_1_C_10514231", "code_snippet": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <list>\n#include <queue>\n#include <climits>\n#include <sstream>\n#include <tuple>\n\nusing Path = std::tuple<int, int, int>; // 経路。cost, s, t. 頂点indexから頂点secondを経由した頂点thirdまでの距離はfirst\nusing Edge = std::pair<int, int>; // 辺。ある点から頂点番号firstまでの距離はsecond\nusing Graph = std::vector<std::list<Edge>>;\n\nbool isLoop(const std::vector<int>& P, int u) {\n for (int v = P[u]; v >= 0; v = P[v]) {\n if (v == u) {\n return true;\n }\n }\n return false;\n}\nstd::vector<int> sssp(const Graph& G, int index) {\n int n = G.size();\n std::vector<int> D(n, INT_MIN); // 始点から各頂点までの距離、負数は距離未確定\n std::vector<int> P(n, -1); // 各頂点の親 流入元\n\n // 始点からの距離が近い順に、距離・頂点番号ペアを保持する\n std::priority_queue<Path, std::deque<Path>, std::greater<Path>> paths;\n paths.emplace(0, -1, index); // 始点から始点までの距離は0\n\n while(paths.empty() == false) {\n // 始点からの最も近い点を得る\n const auto [d, s, t] = paths.top(); paths.pop();\n if (D[t] != INT_MIN && D[t] <= d) continue; // 高いルートは無視\n\n // もし、tの親を辿って自身が居たら負の閉路\n P[t] = s;\n D[t] = d;\n if (isLoop(P, t)) return std::vector<int>();\n\n // 新たな頂点に隣接する頂点の経路を追加する\n for (const auto& [v, c] : G[t]) {\n paths.emplace(D[t] + c, t, v);\n }\n }\n return D;\n}\n\nint main() {\n int v, e;\n std::cin >> v >> e;\n Graph G(v);\n for (int i = 0; i < e; ++i) {\n int s, t, d;\n std::cin >> s >> t >> d;\n G[s].emplace_back(t, d);\n }\n std::stringstream ans; \n for (int i = 0; i < v; ++i) {\n const auto& d = sssp(G, i);\n if (d.empty()) {\n std::cout << \"NEGATIVE CYCLE\" << std::endl;\n return 0;\n }\n for (int j = 0; j < d.size(); ++j) {\n if (j) ans << \" \";\n if (d[j] == INT_MIN) ans << \"INF\";\n else ans << d[j];\n }\n ans << \"\\n\";\n }\n std::cout << ans.str();\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 3752, "score_of_the_acc": -1.0324, "final_rank": 6 }, { "submission_id": "aoj_GRL_1_C_10362476", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing VI = vector<int>;\nusing P = pair<int, int>;\nconstexpr int INF = 2001001001;\nconstexpr ll LINF = 1001001001001001001ll;\n#define rep(i, n) for (ll i = 0; i < (int)(n); i++)\n#define rep2(i, k, n) for (ll i = k; i < (int)(n); i++)\n//ワーシャルフロイドは盤面(n^2)をn回修正することで回り道ルートの長さが1つずつ減り、最終的にその回り道が全部つながって1本の辺になるイメージ\n//または頂点s,tのみに着目するとそれ以外の頂点を1つずつ消して回り道ルートの長さを1つずつ減らしていくイメージ\n//だから極論一回当たりの盤面の修正はどこから行っても結局min値をとるだけなので上手くいく\nint main(){\n\n // int ans = 0;\n int n, e;\n cin >> n >> e;\n // vector<vector<int>> v(n, vector<int>(m));\n vector<vector<int>> edge(n, vector<int>(n, INF));\n \n rep(i, n) edge[i][i] = 0;\n rep(i, e){\n int s, t, d;\n cin >> s >> t >> d;\n edge[s][t] = d;//有向辺の場合\n }\n rep(cnt, n) rep(i, n) rep(j, n) rep(k, n) {\n if(edge[i][k] == INF || edge[k][j] == INF) continue;\n edge[i][j] = min(edge[i][j], edge[i][k] + edge[k][j]);\n }\n \n rep(i, n){\n if(edge[i][i] < 0) {\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n }\n rep(i, n) {\n rep(j, n){\n if(edge[i][j] == INF) cout << \"INF\";\n else cout << edge[i][j];\n if(j != n-1) cout << ' ';\n }\n cout << \"\\n\";\n } \n \n \n \n\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 3488, "score_of_the_acc": -0.7143, "final_rank": 4 }, { "submission_id": "aoj_GRL_1_C_10338876", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n\nvector<long long> bellman_ford(int v,int r,const vector<vector<pair<int,long long>>>& graph,bool& has_negative_cycle){\n const long long INF=LLONG_MAX;\n vector<long long> dist(v,INF);\n dist[r]=0;\n\n for(int i=0;i<v-1;i++){\n for(int u=0;u<v;u++){\n for(auto& [to,weight]:graph[u]){\n if(dist[u]!=INF && dist[u]+weight<dist[to]){\n dist[to]=dist[u]+weight;\n }\n }\n }\n }\n for(int u=0;u<v;u++){\n for(auto& [to,weight]:graph[u]){\n if(dist[u]!=INF && dist[u]+weight<dist[to]){\n has_negative_cycle=true;\n return {};\n }\n }\n }\n return dist;\n}\n\nint main(){\n int v,e;\n cin >> v >> e;\n \n vector<vector<pair<int,long long>>> graph(v);\n rep(i,e){\n int s,t,d;\n cin >> s >> t >> d;\n graph[s].push_back({t,d});\n }\n\n rep(i,v){\n bool has_negative_cycle=false;\n vector<long long> dist = bellman_ford(v,i,graph,has_negative_cycle);\n if(has_negative_cycle){\n cout << \"NEGATIVE CYCLE\" << endl;\n return 0;\n }\n rep(j,v){\n if(dist[j]==LLONG_MAX){\n cout << \"INF\";\n }\n else{\n cout << dist[j];\n }\n if(j<v-1){\n cout << \" \";\n }\n }\n cout << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 3560, "score_of_the_acc": -0.5803, "final_rank": 3 }, { "submission_id": "aoj_GRL_1_C_10093407", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nstruct Edge{\n\n int to;\n ll cost;\n\n Edge( int _to, ll _cost ){\n\n to = _to;\n cost = _cost;\n\n }\n\n};\n\nstruct Graph{\n\n int size;\n vector< vector<Edge> > adj;\n\n Graph( int _size ){\n\n size = _size;\n for( int i = 0 ; i < size ; i++ ){\n vector<Edge> tmp;\n adj.push_back( tmp );\n }\n\n }\n\n void dijkstra( int origin ){\n\n vector<ll> dist( size, INF );\n priority_queue<P> pq;\n\n dist[origin] = 0;\n pq.push( make_pair( 0, origin ) );\n while( !pq.empty() ){\n P next = pq.top(); pq.pop();\n ll cost = -next.first;\n int to = next.second;\n if( dist[to] < cost ) continue;\n for( int i = 0 ; i < adj[to].size() ; i++ ){\n if( dist[adj[to][i].to] > dist[to] + adj[to][i].cost ){\n dist[adj[to][i].to] = dist[to] + adj[to][i].cost;\n pq.push( make_pair( -dist[adj[to][i].to], adj[to][i].to ) );\n }\n }\n }\n for( int i = 0 ; i < size ; i++ ){\n if( dist[i] == INF )\n cout << \"INF\" << endl;\n else\n cout << dist[i] << endl;\n }\n\n }\n\n void bellman_ford( int origin ){\n\n vector<ll> dist;\n\n for( int i = 0 ; i < size ; i++ )\n dist.push_back( INF );\n dist[origin] = 0LL;\n for( int i = 0 ; i < size ; i++ ){\n for( int j = 0 ; j < size ; j++ ){\n for( int k = 0 ; k < adj[j].size() ; k++ ){\n if( dist[j] == INF ) continue;\n if( i == size - 1 && dist[j] + adj[j][k].cost < dist[adj[j][k].to] ){\n cout << \"NEGATIVE CYCLE\" << endl;\n return;\n }\n dist[adj[j][k].to] = min( dist[adj[j][k].to], dist[j] + adj[j][k].cost );\n }\n }\n }\n for( int i = 0 ; i < size ; i++ ){\n if( dist[i] == INF )\n cout << \"INF\" << endl;\n else\n cout << dist[i] << endl;\n }\n }\n\n void warshall_floyd(){\n\n vector<vector<vector<ll>>> dist;\n\n for( int i = 0 ; i <= size ; i++ ){\n vector<vector<ll>> v1;\n for( int j = 0 ; j < size ; j++ ){\n vector<ll> v2;\n for( int k = 0 ; k < size ; k++ )\n v2.push_back( INF );\n v1.push_back( v2 );\n }\n dist.push_back( v1 );\n }\n for( int i = 0 ; i < size ; i++ )\n dist[0][i][i] = 0LL;\n for( int i = 0 ; i < size ; i++ ){\n for( int j = 0 ; j < adj[i].size() ; j++ )\n dist[0][i][adj[i][j].to] = adj[i][j].cost;\n }\n for( int i = 1 ; i <= size ; i++ ){\n for( int j = 0 ; j < size ; j++ ){\n for( int k = 0 ; k < size ; k++ ){\n if( dist[i-1][j][i-1] != INF && dist[i-1][i-1][k] != INF )\n dist[i][j][k] = min( dist[i-1][j][k], dist[i-1][j][i-1] + dist[i-1][i-1][k] );\n else \n dist[i][j][k] = dist[i-1][j][k];\n }\n }\n }\n for( int i = 0 ; i < size ; i++ ){\n if( dist[size][i][i] < 0 ){\n cout << \"NEGATIVE CYCLE\" << endl;\n return;\n }\n }\n for( int i = 0 ; i < size ; i++ ){\n for( int j = 0 ; j < size - 1; j++ ){\n if( dist[size][i][j] == INF )\n cout << \"INF\" << \" \";\n else\n cout << dist[size][i][j] << \" \";\n }\n if( dist[size][i][size-1] == INF )\n cout << \"INF\" << endl;\n else\n cout << dist[size][i][size-1] << endl;\n }\n\n }\n \n};\n\nint main(){\n\n int V, E, s, t;\n ll d;\n\n cin >> V >> E;\n Graph g( V );\n for( int i = 0 ; i < E ; i++ ){\n cin >> s >> t >> d;\n Edge e( t, d );\n g.adj[s].push_back( e );\n }\n g.warshall_floyd();\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11632, "score_of_the_acc": -1, "final_rank": 5 } ]
aoj_DSL_3_A_cpp
The Smallest Window I For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $S$, find the smallest sub-array size (smallest window length) where the sum of the sub-array is greater than or equal to $S$. If there is not such sub-array, report 0. Constraints $1 \leq N \leq 10^5$ $1 \leq S \leq 10^9$ $1 \leq a_i \leq 10^4$ Input The input is given in the following format. $N$ $S$ $a_1$ $a_2$ ... $a_N$ Output Print the smallest sub-array size in a line. Sample Input 1 6 4 1 2 1 2 3 2 Sample Output 1 2 Sample Input 2 6 6 1 2 1 2 3 2 Sample Output 2 3 Sample Input 3 3 7 1 2 3 Sample Output 3 0
[ { "submission_id": "aoj_DSL_3_A_10929127", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n int N, S;\n cin >> N >> S;\n vector<int> a(N);\n for(auto& i : a) cin >> i;\n int ans = 1000000000;\n for(int s = 0, t = 0, sum = 0; t < N;){\n sum += a[t];\n if(sum < N) t++;\n else{\n while(s < t && sum >= N) sum -= a[s++];\n ans = min(ans, t - s + 2);\n }\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 0.02, "time_ms": 670, "memory_kb": 3456, "score_of_the_acc": -1.2015, "final_rank": 20 }, { "submission_id": "aoj_DSL_3_A_10738757", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint smallSubArray(int a[],int n, int s)\n{\n\tint ans=INT_MAX,start=0,sum=0;\n\tfor(int end=0;end<n; end++)\n\t{\n\t\tsum+=a[end];\n\t\twhile(sum-a[start]>=s) \n\t\t{\n\t\t\tsum-=a[start];\n\t\t\tstart++;\n\t\t}\n\t\tif(sum>=s) \n\t\t ans=min(ans,end-start+1);\n\t}\n\tif(ans==INT_MAX)\n\t return 0;\n\treturn ans; \n}\n\nint main() {\n\t// your code goes here\n\tint n, s; \n\tcin>>n>>s; \n\tint a[n];\n\tfor(int i=0;i<n;i++)\n\t cin>>a[i];\n\tcout<<smallSubArray(a,n,s)<<endl;;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3824, "score_of_the_acc": -0.4303, "final_rank": 12 }, { "submission_id": "aoj_DSL_3_A_10738750", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int n,m; cin>>n>>m;\n int a[n];\n for(int i=0;i<n;i++)\n {\n cin>>a[i];\n }\n \n queue<int> q;\n int sum=0,i,minsize=n,flag=0;\n \n for(i=0;i<n;i++)\n {\n q.push(a[i]);\n sum+=a[i];\n while(sum>=m)\n {\n flag=1;\n if(q.size()<=minsize)\n {\n minsize=q.size();\n }\n sum=sum-q.front();\n q.pop();\n }\n }\n \n if(flag==1)\n {\n cout<<minsize;\n }\n else\n {\n cout<<0;\n }\n\n cout<<endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4148, "score_of_the_acc": -0.6318, "final_rank": 15 }, { "submission_id": "aoj_DSL_3_A_10738741", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int n,m; cin>>n>>m;\n int a[n];\n for(int i=0;i<n;i++)\n {\n cin>>a[i];\n }\n queue<int> q;\n int sum=0,i,minsize=INT_MAX,flag=0;\n for(i=0;i<n;i++)\n {\n q.push(a[i]);\n sum+=a[i];\n while(sum>=m)\n {\n flag=1;\n if(q.size()<=minsize)\n {\n minsize=q.size();\n }\n sum=sum-q.front();\n q.pop();\n }\n }\n if(flag==1)\n {\n cout<<minsize;\n }\n else\n {\n cout<<0;\n }\n\n cout<<endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4244, "score_of_the_acc": -0.6915, "final_rank": 16 }, { "submission_id": "aoj_DSL_3_A_10364665", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntemplate<class T,T(*op)(T,T),T(*e)()>\nstruct fenwick{\n\tint n;vector<T>d;\n\tfenwick(int n):n(n),d(n,e()){}\n\ttemplate<class U>fenwick(vector<U>a):fenwick(a.size()){\n\t\tfor(int i=0;i<n;i++){\n\t\t\td[i]=op(d[i],a[i]);\n\t\t\tint j=i|i+1;\n\t\t\tif(j<n)d[j]=op(d[j],d[i]);\n\t\t}\n\t}\n\tvoid apply(int i,T x){\n\t\tassert(0<=i);\n\t\twhile(i<n)d[i]=op(d[i],x),i|=i+1;\n\t}\n\tT operator[](int i){\n\t\tassert(i<n);\n\t\tT y{};while(i>=0)y=op(y,d[i]),i&=i+1,i--;return y;\n\t}\n\ttemplate<class F>int max_right(F ok){\n\t\tassert(ok(e()));\n\t\tT y=e();int i=0,w=1;while(w<=n)w<<=1;\n\t\twhile(w>>=1)if(i+w<=n&&ok(op(y,d[i+w-1])))y=op(y,d[(i+=w)-1]);\n\t\treturn i;\n\t}\n};\nint op(int x,int y){return x+y;}\nint e(){return 0;}\nint main(){\n\tios::sync_with_stdio(0),cin.tie(0);\n\tint n,k;\n\tcin>>n>>k;\n\tvector<int>a(n);\n\tfor(int i=0;i<n;i++)cin>>a[i];\n\tfenwick<int,op,e>s(a);\n\tint ans=n+1;\n\tfor(int i=0;i<n;i++){\n\t\tint r=s.max_right([&](int x){return x<k+s[i-1];});\n\t\tif(r==n)break;\n\t\tans=min(ans,r-i+1);\n\t}\n\tif(ans==n+1)ans=0;\n\tcout<<ans<<'\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4400, "score_of_the_acc": -0.7886, "final_rank": 17 }, { "submission_id": "aoj_DSL_3_A_10364655", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntemplate<class T,T(*op)(T,T),T(*e)()>\nstruct fenwick{\n\tint n;vector<T>d;\n\tfenwick(int n):n(n),d(n,e()){}\n\ttemplate<class U>fenwick(vector<U>a):fenwick(a.size()){\n\t\tfor(int i=0;i<n;i++){\n\t\t\td[i]=op(d[i],a[i]);\n\t\t\tint j=i|i+1;\n\t\t\tif(j<n)d[j]=op(d[j],d[i]);\n\t\t}\n\t}\n\tvoid apply(int i,T x){\n\t\tassert(0<=i);\n\t\twhile(i<n)d[i]=op(d[i],x),i|=i+1;\n\t}\n\tT operator[](int i){\n\t\tassert(i<n);\n\t\tT y{};while(i>=0)y=op(y,d[i]),i&=i+1,i--;return y;\n\t}\n\ttemplate<class F>int max_right(F ok){\n\t\tT y=e();int i=0,w=1;while(w<=n)w<<=1;\n\t\twhile(w>>=1)if(i+w<=n&&ok(op(y,d[i+w-1])))y=op(y,d[(i+=w)-1]);\n\t\treturn i;\n\t}\n};\nint op(int x,int y){return x+y;}\nint e(){return 0;}\nint main(){\n\tios::sync_with_stdio(0),cin.tie(0);\n\tint n,k;\n\tcin>>n>>k;\n\tvector<int>a(n);\n\tfor(int i=0;i<n;i++)cin>>a[i];\n\tfenwick<int,op,e>s(a);\n\tint ans=n+1;\n\tfor(int i=0;i<n;i++){\n\t\tint r=s.max_right([&](int x){return x<k+s[i-1];});\n\t\tif(r==n)break;\n\t\tans=min(ans,r-i+1);\n\t}\n\tif(ans==n+1)ans=0;\n\tcout<<ans<<'\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4400, "score_of_the_acc": -0.7886, "final_rank": 17 }, { "submission_id": "aoj_DSL_3_A_10363195", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntemplate<class T>\nstruct fenwick{\n\tint n;vector<T>d;\n\tfenwick(int n):n(n),d(n){}\n\ttemplate<class U>fenwick(vector<U>a):fenwick(a.size()){\n\t\tfor(int i=0;i<n;i++){d[i]+=a[i];if((i|i+1)<n)d[i|i+1]+=d[i];}\n\t}\n\tvoid add(int i,T x){while(i<n)d[i]+=x,i|=i+1;}\n\tT operator[](int i){T y{};while(i>=0)y+=d[i],i&=i+1,i--;return y;}\n\tint lower_bound(T x){\n\t\tint i=0,w=1;while(w<=n)w<<=1;\n\t\twhile(w>>=1)if(i+w<=n&&d[i+w-1]<x)x-=d[(i+=w)-1];\n\t\treturn i;\n\t}\n};\nint main(){\n\tint n,S;\n\tcin>>n>>S;\n\tvector<int>a(n);for(int i=0;i<n;i++)cin>>a[i];\n\tfenwick<int>s(a);\n\tint ans=n+1;\n\tfor(int i=0;i<n;i++){\n\t\tint r=s.lower_bound(S+s[i-1]);\n\t\tif(r==n)break;\n\t\tans=min(ans,r-i+1);\n\t}\n\tif(ans==n+1)ans=0;\n\tcout<<ans<<'\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4136, "score_of_the_acc": -0.6244, "final_rank": 14 }, { "submission_id": "aoj_DSL_3_A_10363149", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntemplate<class T>\nstruct fenwick{\n\tint n;vector<T>d;\n\tfenwick(int n):n(n),d(n){}\n\tvoid add(int i,T x){while(i<n)d[i]+=x,i|=i+1;}\n\tT operator[](int i){T y{};while(i>=0)y+=d[i],i&=i+1,i--;return y;}\n\tint lower_bound(T x){\n\t\tint i=0,w=1;while(w<=n)w<<=1;\n\t\twhile(w>>=1)if(i+w<=n&&d[i+w-1]<x)x-=d[(i+=w)-1];\n\t\treturn i;\n\t}\n};\nint main(){\n\tint n,S;\n\tcin>>n>>S;\n\tfenwick<int>s(n);\n\tfor(int i=0;i<n;i++){\n\t\tint a;cin>>a;s.add(i,a);\n\t}\n\tint ans=n+1;\n\tfor(int i=0;i<n;i++){\n\t\tint r=s.lower_bound(S+s[i-1]);\n\t\tif(r==n)break;\n\t\tans=min(ans,r-i+1);\n\t}\n\tif(ans==n+1)ans=0;\n\tcout<<ans<<'\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3596, "score_of_the_acc": -0.2886, "final_rank": 2 }, { "submission_id": "aoj_DSL_3_A_10073561", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nint smallest_window( ll S, const vector<ll> &number ){\n\n int left = 0, right = 0, res = number.size() + 1;\n ll sum = 0;\n\n while( left < number.size() ){\n while( right < number.size() && sum < S )\n sum += number[right++];\n if( sum >= S )\n res = min( res, right - left );\n sum -= number[left++];\n }\n return ( res <= number.size() ? res : 0 );\n\n}\n\nint main(){\n\n int N;\n ll S, a;\n vector<ll> number;\n\n cin >> N >> S;\n for( int i = 0 ; i < N ; i++ ){\n cin >> a;\n number.push_back( a );\n }\n cout << smallest_window( S, number ) << endl;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4132, "score_of_the_acc": -0.6219, "final_rank": 13 }, { "submission_id": "aoj_DSL_3_A_10059180", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\nusing namespace std;\ntypedef long long ll;\n// const ll INF64 = 1LL << 60;\nconst ll INF64 = ((1LL<<62)-(1LL<<31)); // 10^18より大きく、かつ2倍しても負にならない数\nconst int INF32 = 0x3FFFFFFF; // =(2^30)-1 10^9より大きく、かつ2倍しても負にならない数\ntemplate<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; }\n#define YesNo(T) cout << ((T) ? \"Yes\" : \"No\") << endl; // T:bool\n\n// AOJ DSL_3_A\n// https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/3/DSL_3_A\n\n// 尺取り法の練習問題\n\nint main(void)\n{\n\tint i;\n\tint N, S; cin >> N >> S;\n\tvector<int> a(N); for(i = 0; i < N; i++) {cin >> a[i];}\n\n\tint l, r;\n\tr = 0;\n\tint ans = INF32;\n\tint sum = 0;\n\tfor(l = 0; l < N; l++) // [l,r)\n\t{\n\t\twhile(r < N && sum < S) // 条件を満たすまで移動\n\t\t{\n\t\t\tsum += a[r];\n\t\t\tr++;\n\t\t}\n\t\tif(sum >= S)\n\t\t{\n\t\t\tchmin(ans, r-l);\n\t\t}\n\t\tsum -= a[l];\n\t\t// lがrを超えることは無い\n\t}\n\tif(ans == INF32) ans = 0;\n\tcout << ans << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3640, "score_of_the_acc": -0.3159, "final_rank": 6 }, { "submission_id": "aoj_DSL_3_A_10059175", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\nusing namespace std;\ntypedef long long ll;\n// const ll INF64 = 1LL << 60;\nconst ll INF64 = ((1LL<<62)-(1LL<<31)); // 10^18より大きく、かつ2倍しても負にならない数\nconst int INF32 = 0x3FFFFFFF; // =(2^30)-1 10^9より大きく、かつ2倍しても負にならない数\ntemplate<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; }\n#define YesNo(T) cout << ((T) ? \"Yes\" : \"No\") << endl; // T:bool\n\n// AOJ DSL_3_A\n// https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/3/DSL_3_A\n\n/*\n * \n * \n */\n\nint main(void)\n{\n\tint i;\n\tint N, S; cin >> N >> S;\n\tvector<int> a(N); for(i = 0; i < N; i++) {cin >> a[i];}\n\n\tint l, r;\n\tr = 0;\n\tint ans = INF32;\n\tint sum = 0;\n\tfor(l = 0; l < N; l++) // [l,r)\n\t{\n\t\twhile(r < N && sum < S) // 条件を満たすまで移動\n\t\t{\n\t\t\tsum += a[r];\n\t\t\tr++;\n\t\t}\n\t\tif(sum >= S)\n\t\t{\n\t\t\tchmin(ans, r-l);\n\t\t}\n\t\tsum -= a[l];\n\t}\n\tif(ans == INF32) ans = 0;\n\tcout << ans << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3632, "score_of_the_acc": -0.3109, "final_rank": 5 }, { "submission_id": "aoj_DSL_3_A_10006931", "code_snippet": "#include <algorithm>\n#include <array>\n#include <bit>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <clocale>\n#include <cmath>\n#include <complex>\n#include <concepts>\n#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <deque>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <list>\n#include <map>\n#include <numbers>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <ranges>\n#include <regex>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nconstexpr int MOD{1'000'000'007};\nconstexpr int MOD2{998'244'353};\nconstexpr int INF{1'000'000'000}; //1e9\nconstexpr int NIL{-1};\nconstexpr long long LINF{1'000'000'000'000'000'000}; // 1e18\nconstexpr long double EPS{1E-10L};\nusing namespace std::literals;\nnamespace ranges = std::ranges;\nnamespace views = ranges::views;\n\ntemplate<class T, class S> bool chmax(T &a, const S &b){\n if(a < b){a = b; return true;}\n return false;\n}\ntemplate<class T, class S> bool chmin(T &a, const S &b){\n if(b < a){a = b; return true;}\n return false;\n}\ntemplate<class T> bool inside(T x, T lx, T rx){ //semi-open\n return (ranges::clamp(x, lx, rx-1) == x);\n}\ntemplate<class T> bool inside(T x, T y, T lx, T rx, T ly, T ry){\n return inside(x, lx, rx) && inside(y, ly, ry);\n}\ntemplate<class T, class S> std::istream &operator>>(std::istream &is, std::pair<T, S> &p){\n return is >> p.first >> p.second;\n}\ntemplate<class T, class S> std::ostream &operator<<(std::ostream &os, const std::pair<T, S> &p){\n return os << p.first << \" \" << p.second;\n}\ntemplate<class T> std::istream &operator>>(std::istream &is, std::vector<T> &v){\n {for(auto &e: v) is >> e;} return is;\n}\ntemplate<class Container> void print_container(const Container &c, std::string sep = \" \"s, std::string end = \"\\n\"s){\n for(int i{int(std::size(c))}; auto e: c) std::cout << e << (--i ? sep : end);\n}\nstd::string yesno(bool x){return x ? \"Yes\"s : \"No\"s;}\n\n\n\nint main(){\n std::cout << [](){\n int N, S, s{}; std::cin >> N >> S;\n std::vector<int> a(N);\n for(int &e: a){\n std::cin >> e; s += e;\n }\n if(s < S) return 0;\n int ans{INF}; s = 0;\n for(int i{0}, j{-1}; i < N; ++i){\n while(j < N-1 && s < S) s += a[++j];\n if(s >= S) chmin(ans, j - i + 1);\n s -= a[i];\n }\n return ans;\n }() << std::endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3712, "score_of_the_acc": -0.3607, "final_rank": 7 }, { "submission_id": "aoj_DSL_3_A_10006623", "code_snippet": "#include <algorithm>\n#include <array>\n#include <bit>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <clocale>\n#include <cmath>\n#include <complex>\n#include <concepts>\n#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <deque>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <list>\n#include <map>\n#include <numbers>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <ranges>\n#include <regex>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nconstexpr int MOD{1'000'000'007};\nconstexpr int MOD2{998'244'353};\nconstexpr int INF{1'000'000'000}; //1e9\nconstexpr int NIL{-1};\nconstexpr long long LINF{1'000'000'000'000'000'000}; // 1e18\nconstexpr long double EPS{1E-10L};\nusing namespace std::literals;\nnamespace ranges = std::ranges;\nnamespace views = ranges::views;\n\ntemplate<class T, class S> bool chmax(T &a, const S &b){\n if(a < b){a = b; return true;}\n return false;\n}\ntemplate<class T, class S> bool chmin(T &a, const S &b){\n if(b < a){a = b; return true;}\n return false;\n}\ntemplate<class T> bool inside(T x, T lx, T rx){ //semi-open\n return (ranges::clamp(x, lx, rx-1) == x);\n}\ntemplate<class T> bool inside(T x, T y, T lx, T rx, T ly, T ry){\n return inside(x, lx, rx) && inside(y, ly, ry);\n}\ntemplate<class T, class S> std::istream &operator>>(std::istream &is, std::pair<T, S> &p){\n return is >> p.first >> p.second;\n}\ntemplate<class T, class S> std::ostream &operator<<(std::ostream &os, const std::pair<T, S> &p){\n return os << p.first << \" \" << p.second;\n}\ntemplate<class T> std::istream &operator>>(std::istream &is, std::vector<T> &v){\n {for(auto &e: v) is >> e;} return is;\n}\ntemplate<class Container> void print_container(const Container &c, std::string sep = \" \"s, std::string end = \"\\n\"s){\n for(int i{int(std::size(c))}; auto e: c) std::cout << e << (--i ? sep : end);\n}\nstd::string yesno(bool x){return x ? \"Yes\"s : \"No\"s;}\n\n\n\nint main(){\n std::cout << [](){\n int N, S, s{}; std::cin >> N >> S;\n std::vector<int> a(N);\n for(int &e: a){\n std::cin >> e; s += e;\n }\n if(s < S) return 0;\n int ans{INF}, j{-1}; s = 0;\n for(int i{0}; i < N; ++i){\n while(j < N-1 && s < S) s += a[++j];\n if(s >= S) chmin(ans, j - i + 1);\n s -= a[i];\n }\n return ans;\n }() << std::endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3712, "score_of_the_acc": -0.3607, "final_rank": 7 }, { "submission_id": "aoj_DSL_3_A_10006605", "code_snippet": "#include <algorithm>\n#include <array>\n#include <bit>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <clocale>\n#include <cmath>\n#include <complex>\n#include <concepts>\n#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <deque>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <list>\n#include <map>\n#include <numbers>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <ranges>\n#include <regex>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nconstexpr int MOD{1'000'000'007};\nconstexpr int MOD2{998'244'353};\nconstexpr int INF{1'000'000'000}; //1e9\nconstexpr int NIL{-1};\nconstexpr long long LINF{1'000'000'000'000'000'000}; // 1e18\nconstexpr long double EPS{1E-10L};\nusing namespace std::literals;\nnamespace ranges = std::ranges;\nnamespace views = ranges::views;\n\ntemplate<class T, class S> bool chmax(T &a, const S &b){\n if(a < b){a = b; return true;}\n return false;\n}\ntemplate<class T, class S> bool chmin(T &a, const S &b){\n if(b < a){a = b; return true;}\n return false;\n}\ntemplate<class T> bool inside(T x, T lx, T rx){ //semi-open\n return (ranges::clamp(x, lx, rx-1) == x);\n}\ntemplate<class T> bool inside(T x, T y, T lx, T rx, T ly, T ry){\n return inside(x, lx, rx) && inside(y, ly, ry);\n}\ntemplate<class T, class S> std::istream &operator>>(std::istream &is, std::pair<T, S> &p){\n return is >> p.first >> p.second;\n}\ntemplate<class T, class S> std::ostream &operator<<(std::ostream &os, const std::pair<T, S> &p){\n return os << p.first << \" \" << p.second;\n}\ntemplate<class T> std::istream &operator>>(std::istream &is, std::vector<T> &v){\n {for(auto &e: v) is >> e;} return is;\n}\ntemplate<class Container> void print_container(const Container &c, std::string sep = \" \"s, std::string end = \"\\n\"s){\n for(int i{int(std::size(c))}; auto e: c) std::cout << e << (--i ? sep : end);\n}\nstd::string yesno(bool x){return x ? \"Yes\"s : \"No\"s;}\n\n\n\nint main(){\n std::cout << [](){\n int N, S, s{}; std::cin >> N >> S;\n std::vector<int> a(N);\n for(int &e: a){\n std::cin >> e; s += e;\n }\n if(s < S) return 0;\n int ans{INF}, j{-1}; s = 0;\n for(int i{0}; i < N; ++i){\n if(j < i){\n j = i; s = a[i];\n }\n while(j < N-1 && s < S) s += a[++j];\n if(s >= S) chmin(ans, j - i + 1);\n s -= a[i];\n }\n return ans;\n }() << std::endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3712, "score_of_the_acc": -0.3607, "final_rank": 7 }, { "submission_id": "aoj_DSL_3_A_9953236", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\nint main(){\n int n,s;\n cin>>n>>s;\n vector<int>a(n);\n for(int i=0;i<n;i++)cin>>a[i];\n int ans=n+1;\n for(int l=0,r=0,sum=0;r<=n;){\n if(l>r)r=l,sum=0;\n while(r<n&&sum<s)sum+=a[r++];\n if(sum>=s)if(ans>r-l)ans=r-l;\n sum-=a[l++];\n }\n if(ans==n+1)ans=0;\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3712, "score_of_the_acc": -0.3607, "final_rank": 7 }, { "submission_id": "aoj_DSL_3_A_9749531", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int n,s;\n cin>>n>>s;\n vector<int> a(n);\n for(auto &e:a)cin>>e;\n int r=0;\n long sum=0;\n int ans=1<<30;\n for(int l=0;l<n;l++){\n while(r!=n and sum<s){\n sum+=a[r++];\n }\n int val=r-l;\n if(sum>=s and ans>val) ans=val;\n sum-=a[l];\n }\n cout<<(ans!=1<<30?ans:0)<<'\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3712, "score_of_the_acc": -0.3607, "final_rank": 7 }, { "submission_id": "aoj_DSL_3_A_9495878", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n// long longの省略\ntypedef long long ll;\n\n// rep(先頭にRで逆からループ、末尾にSで「1~n」となる)\n#define rep(i, a, n) for(int i = a; i < n; i++)\n#define reps(i, a, n) for(int i = a; i <= n; i++)\n#define rrep(i, a, n) for(int i = n - 1; i >= a; i--)\n#define rreps(i, a, n) for(int i = n; i >= a; i--)\n\n// ソートなどに対象を入れる場合\n#define all(x) (x).begin(),(x).end()\n\n// ソートされた配列から重複を削除して詰めなおす\n#define UNIQUE(x) x.erase( unique(x.begin(), x.end()), x.end() );\n\nint d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nint __gcd(int a, int b){\n\tint c;\n\n\twhile((c = a % b) != 0){\n\t\ta = b;\n\t\tb = c;\n\t}\n\n\treturn b;\n}\n\n// 「number」の「n」ビット目が「1」であるか「0」か\n// ビット目の数え方は配列の添え字と同じ\nbool __bit(int number, int n){\n\tif(number & (1 << n))\n\t\treturn true;\n\n\treturn false;\n}\n\n// aよりもbが大きいならばaをbで更新する\n// (更新されたならばtrueを返す)\ntemplate <typename T>\nbool chmax(T &a, const T& b) {\n\tif (a < b) {\n\t\ta = b; // aをbで更新\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n// aよりもbが小さいならばaをbで更新する\n// (更新されたならばtrueを返す)\ntemplate <typename T>\nbool chmin(T &a, const T& b) {\n\tif (a > b) {\n\t\ta = b; // aをbで更新\n\treturn true;\n\t}\n\n\treturn false;\n}\n\nll mod_pow(ll a, ll n, ll mod) {\n\tll res = 1;\n\t// n を 2進数に変換して考える\n\twhile (n > 0) {\n\t\tif (n & 1) res = res * a % mod;\n\t\ta = a * a % mod;\n\t\tn >>= 1;\n\t}\n\treturn res;\n}\n\nint main(){\n\tll N, S; cin >> N >> S;\n\n\tvector<ll> A(N);\n\trep(i, 0, N) cin >> A[i];\n\n\tvector<ll> psum(N + 1);\n\treps(i, 1, N) psum[i] = psum[i - 1] + A[i - 1];\n\n\tint ans = INT_MAX, r = 0;\n\trep(l, 0, N){\n\t\twhile(r < N && psum[r + 1] - psum[l] < S)\n\t\t\tr++;\n\n\t\tif(r < N && S <= psum[r + 1] - psum[l])\n\t\t\tchmin(ans, r - l + 1);\n\t}\n\n\tcout << (ans == INT_MAX ? 0 : ans) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4740, "score_of_the_acc": -1, "final_rank": 19 }, { "submission_id": "aoj_DSL_3_A_9469018", "code_snippet": "#include <iostream>\n#include <vector>\n#include <climits>\n\nusing namespace std;\n\nint smallestSubarrayWithGivenSum(int N, int S, vector<int>& arr) {\n int current_sum = 0;\n int min_length = INT_MAX;\n int start = 0;\n\n for (int end = 0; end < N; ++end) {\n current_sum += arr[end];\n\n while (current_sum >= S) {\n min_length = min(min_length, end - start + 1);\n current_sum -= arr[start];\n ++start;\n }\n }\n\n return (min_length == INT_MAX) ? 0 : min_length;\n}\n\nint main() {\n int N, S;\n cin >> N >> S;\n vector<int> arr(N);\n\n for (int i = 0; i < N; ++i) {\n cin >> arr[i];\n }\n\n int result = smallestSubarrayWithGivenSum(N, S, arr);\n cout << result << endl;\n\n return 0;\n}\n//sonia", "accuracy": 1, "time_ms": 10, "memory_kb": 3608, "score_of_the_acc": -0.296, "final_rank": 3 }, { "submission_id": "aoj_DSL_3_A_9467663", "code_snippet": "#include <iostream>\n#include <vector>\n#include <climits>\nusing namespace std;\n\nint main() {\n int N, S;\n cin >> N >> S;\n vector<int> a(N);\n for (int i = 0; i < N; ++i) {\n cin >> a[i];\n }\n\n int start = 0, current_sum = 0, min_length = INT_MAX;\n\n for (int i = 0; i< N; ++i) {\n current_sum += a[i];\n\n while (current_sum >= S) {\n min_length = min(min_length, i - start + 1);\n current_sum -= a[start];\n start++;\n }\n }\n\n if (min_length == INT_MAX) {\n cout << 0 << endl;\n } else {\n cout << min_length << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3608, "score_of_the_acc": -0.296, "final_rank": 3 }, { "submission_id": "aoj_DSL_3_A_9465141", "code_snippet": "#include<iostream>\n#include<vector>\n#include<climits>\nusing namespace std;\nint main(){\nint n;\nint s;\ncin>>n>>s;\nvector<int>v(n);\nfor(int i=0; i<n;i++){\ncin>>v[i];\n}\nint l=0, r=0, sum=0,mini=INT_MAX;\nwhile(r<n){\nsum+=v[r];\nwhile(sum>=s){\nmini=min(mini,r-l+1);\nsum-=v[l];\nl++;\n}\nr++;\n}\nif(mini==INT_MAX){\ncout<<0<<endl;\n}\nelse{\ncout<<mini<<endl;\n}\nreturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3132, "score_of_the_acc": 0, "final_rank": 1 } ]
aoj_GRL_1_A_cpp
Single Source Shortest Path For a given weighted graph G(V, E) and a source r , find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path). Input An edge-weighted graph G ( V , E ) and the source r . | V | | E | r s 0 t 0 d 0 s 1 t 1 d 1 : s |E|-1 t |E|-1 d |E|-1 |V| is the number of vertices and |E| is the number of edges in G . The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph. s i and t i represent source and target vertices of i -th edge (directed) and d i represents the cost of the i -th edge. Output Print the costs of SSSP in the following format. c 0 c 1 : c |V|-1 The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF . Constraints 1 ≤ |V| ≤ 100000 0 ≤ d i ≤ 10000 0 ≤ |E| ≤ 500000 There are no parallel edges There are no self-loops Sample Input 1 4 5 0 0 1 1 0 2 4 1 2 2 2 3 1 1 3 5 Sample Output 1 0 1 3 4 Sample Input 2 4 6 1 0 1 1 0 2 4 2 0 1 1 2 2 3 1 1 3 2 5 Sample Output 2 3 0 2 INF
[ { "submission_id": "aoj_GRL_1_A_11064891", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nusing P=pair<ll,int>;\n\nint main(){\n int V, E, r;\n cin >> V >> E >> r;\n vector<vector<P>> G(V,vector<P>(0));\n for(int i=0; i<E; i++){\n int s, t;\n ll d;\n cin >> s >> t >> d;\n G[s].push_back({d,t});\n }\n\n ll INF=1e18;\n vector<ll> dist(V,INF);\n priority_queue<P, vector<P>, greater<P>> q;\n dist[r]=0;\n q.push({0,r});\n\n while(q.size()){\n auto [td,tv]=q.top();\n q.pop();\n if(td!=dist[tv]) continue;\n for( P p : G[tv]){\n ll nd=p.first;\n int nv=p.second;\n if(nd+dist[tv]>=dist[nv]) continue;\n dist[nv]=nd+dist[tv];\n q.push({dist[nv],nv});\n }\n }\n\n for(int i=0; i<V; i++){\n if(dist[i]==INF){\n cout << \"INF\" << endl;\n }\n else{\n cout << dist[i] << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 19464, "score_of_the_acc": -0.3782, "final_rank": 10 }, { "submission_id": "aoj_GRL_1_A_11063121", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nstruct Edge{\n int from;\n int to;\n int d;\n};\n\nstruct Node{\n int index;\n int cost;\n};\n\nint main(){\n int V, E, start;\n cin >> V >> E >> start;\n vector<vector<Edge>> G(V);\n for (int i=0; i<E; i++){\n int s,t,d;\n Edge e;\n cin >> s >> t >> d;\n e.from = s;\n e.to = t;\n e.d = d;\n G[s].push_back(e);\n }\n\n int INF = 1<<30;\n auto comp = [] (Node a, Node b){\n return a.cost > b.cost;\n };\n priority_queue<Node, vector<Node>, decltype(comp)> q{comp};\n q.push(Node{start, 0});\n vector<int> minCost(V, INF);\n minCost[start] = 0;\n\n while(!q.empty()){\n Node n = q.top();\n int now = n.index;\n int cost = n.cost;\n q.pop();\n // 既に最短経路が見つかっている場合\n if (cost > minCost[now]) continue;\n for (Edge e: G[now]){\n int newCost = cost + e.d;\n // より短い経路を見つけられなかった場合\n if (newCost > minCost[e.to]) continue;\n // 暫定の最短経路を更新し、さらに探索。\n minCost[e.to] = newCost;\n q.push(Node{e.to, newCost});\n }\n }\n\n for (int i=0; i<V; i++){\n if (minCost[i] == INF) cout << \"INF\" << endl;\n else cout << minCost[i] << endl;\n }\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 15420, "score_of_the_acc": -0.2734, "final_rank": 7 }, { "submission_id": "aoj_GRL_1_A_11063033", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nint main(){\n long long int V, E, r;\n cin >> V >> E >> r;\n vector<vector<pair<int,int>>> G(V);\n for (int i=0; i<E; i++){\n int s, t, d;\n cin >> s >> t >> d;\n G[s].push_back({t,d});\n // G[t].push_back({s,d});\n }\n priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;\n q.push({0,r});\n long long int INF = 1<<30;\n vector<long long int> distance(V, INF);\n distance[r] = 0;\n\n while(!q.empty()){\n auto top = q.top();\n q.pop();\n int d = top.first;\n int now = top.second;\n if (d > distance[now]) continue;\n for(auto next: G[now]){\n int nextIndex = next.first; \n int nextDistance = next.second; \n int nextAllDistance = d + nextDistance;\n if (nextAllDistance > distance[nextIndex]) continue;\n distance[nextIndex] = nextAllDistance;\n q.push({nextAllDistance, nextIndex});\n }\n }\n\n for (int i=0; i<V; i++){\n if (distance[i] == INF) cout << \"INF\" << endl;\n else cout << distance[i] << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 13540, "score_of_the_acc": -0.2417, "final_rank": 5 }, { "submission_id": "aoj_GRL_1_A_11056498", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pl = pair<ll, ll>;\n\n#define rep(i, x) for (int i = 0; i < (x); ++i)\n#define reps(i, pr, x) for (int i = (pr); i <= (x); ++i)\n#define vl vector<ll>\n#define fore(i, m2) for (auto &i : m2)\n#define all(X) (X).begin(), (X).end()\n#define out(X) std::cout << (X) << endl\n\ntemplate <class T> inline bool chmax(T &x, T y) {\n if (x < y) {\n x = y;\n return true;\n }\n return false;\n}\ntemplate <class T> inline bool chmin(T &x, T y) {\n if (x > y) {\n x = y;\n return true;\n }\n return false;\n}\n\nconst ll INF = (1LL << 62);\nconst ll MAX = (1e5 + 5);\nconst ll MOD = (1e9 + 7);\n\nll n, m;\nvl dsts;\nvector<vector<pl>> G;\n\nvoid Dijkstra(ll st) {\n\n priority_queue<pl, vector<pl>, greater<pl>> q;\n q.emplace((dsts[st] = 0), st);\n\n while (!q.empty()) {\n const ll dst = q.top().first;\n const int from = q.top().second;\n q.pop();\n\n if (dsts[from] < dst) {\n continue;\n }\n\n for (const pl &nd : G[from]) {\n ll cost = nd.second, to = nd.first;\n const long long d = (dsts[from] + cost);\n\n if (d < dsts[to]) {\n q.emplace((dsts[to] = d), to);\n }\n }\n }\n}\n\nint main() {\n\n ll s;\n cin >> n >> m >> s;\n\n dsts.assign(n, INF);\n G.assign(n, vector<pl>());\n\n ll a, b, c;\n rep(i, m) {\n cin >> a >> b >> c;\n\n G[a].push_back({b, c});\n }\n\n Dijkstra(s);\n\n rep(i, n) {\n if (dsts[i] == INF) out(\"INF\");\n else out(dsts[i]);\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 19620, "score_of_the_acc": -0.3818, "final_rank": 11 }, { "submission_id": "aoj_GRL_1_A_11053458", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n// #include \"all.h\"\n\n#define int long long\n#define uint unsigned int\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define is2pow(n) (n && (!(n & (n - 1))))\n#define OPTIMIZE \\\n ios_base::sync_with_stdio(false); \\\n cin.tie(nullptr); \\\n cout.tie(nullptr);\n\nusing ld = long double;\nconstexpr int maxn = 2e5;\nconstexpr int maxk = 305;\nconstexpr long long inf = 1e18;\nconstexpr ld eps = 1e-8L;\nconstexpr long long mod = 998244353;\n\n\nusing pii = pair<int,int>;\nvector<vector<pii>> graph;\nvector<int> dist;\n\n\nvoid solve() {\n int n,m,s; cin >> n >> m >> s;\n graph.assign(n, vector<pii>());\n dist.assign(n,1e9);\n\n for (int i = 0; i < m; i++) {\n int u,v,w; cin >> u >> v >> w;\n graph[u].emplace_back(v,w);\n }\n set<pii> q;\n q.emplace(0,s);\n dist[s] = 0;\n while (!q.empty()) {\n auto [d, u] = *q.begin();\n q.erase(q.begin());\n if (dist[u] != d) continue;\n for (auto& edge : graph[u]) {\n if (dist[edge.first] > d + edge.second) {\n dist[edge.first] = d + edge.second;\n q.emplace(dist[edge.first], edge.first);\n }\n }\n }\n for (auto d : dist) {\n if (d!=1e9) cout << d << \"\\n\";\n else cout << \"INF\\n\";\n }\n\n\n}\n\n#define TES\n#define LOCA\n#define FIL\n\nint32_t main() {\n OPTIMIZE;\n\n#ifdef FILE\n freopen(\"coins.in\", \"r\", stdin);\n freopen(\"coins.out\", \"w\", stdout);\n#endif\n#ifdef LOCAL\n freopen(\"/home/sq/CLionProjects/graph/input.txt\", \"r\", stdin);\n#endif\n int tt = 1;\n#ifdef TEST\n cin >> tt;\n#endif\n while (tt--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 21680, "score_of_the_acc": -0.2083, "final_rank": 3 }, { "submission_id": "aoj_GRL_1_A_11050457", "code_snippet": "#include <bits/stdc++.h>\n#pragma GCC target(\"avx2\")\n#ifndef LOCAL\n#pragma GCC optimize(\"O3\")\n#endif\n#pragma GCC optimize(\"unroll-loops\")\n\n#ifdef ONLINE_JUDGE\n#include <boost/multiprecision/cpp_int.hpp>\n#include <atcoder/all>\n#endif\n#ifdef LOCAL\n#define GLIBCXX_DEBUG\n#define endl endl<<flush\n#else\n#define endl \"\\n\"\n#endif\nusing namespace std;using ll=long long;using ull=unsigned long long;using dl=long double;\n#define rep(i,n) for(ll i=0; i<(n); i++)\n#define rrep(i,n) for(ll i=1; i<=(n); i++)\n#define drep(i,n) for(ll i=(n)-1; i>=0; i--)\n#define xfor(i,s,e) for(ll i=(s); i<(e); i++)\n#define rxfor(i,s,e) for(ll i=(s); i<=(e); i++)\n#define dfor(i,s,e) for(ll i=(s)-1; i>=(e); i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define chmax(x,y) x = max(x,y)\n#define chmin(x,y) x = min(x,y)\n#define popcnt(s) ll(__popcount<ull>(uint64_t(s)))\ntemplate<typename T>istream&operator>>(istream&is,pair<T,T>&v){is>>v.first>>v.second;return is;}\ntemplate<typename T>istream&operator>>(istream&is,vector<T>&v){for(auto&in:v)is>>in;return is;}\ntemplate<typename T, typename U>ostream&operator<<(ostream&os,pair<T,U>&v){os<<v.first<<\" \"<<v.second;return os;}\ntemplate<typename T>ostream&operator<<(ostream&os,vector<T>&v){for(auto&in:v)os<<in<<' ';return os;}\nll modpow(ll a, ll b, ll mod) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a) % mod;a = (a * a) % mod;b >>= 1;}return res;}\nll powl(ll a, ll b) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a);a = (a * a);b >>= 1;}return res;}\n#define pow2(a) (a)*(a)\n/*MOD MUST BE A PRIME NUMBER!!*/ll moddiv(const ll a, const ll b, const ll mod) {ll modinv = modpow(b, mod-2, mod);return (a * modinv) % mod;}\nconstexpr ll INF = 2e15;\nll nC2(const ll i){return i>2?i*(i-1)/2:0;}ll nC3(const ll i){return i>3?i*(i-1)*(i-2)/6:0;}ll nC4(const ll i){return i>4?i*(i-1)*(i-2)*(i-3)/24:0;}ll nC5(const ll i){return i>5?i*(i-1)*(i-2)*(i-3)*(i-4)/120:0;}ll nC6(const ll i){return i>6?i*(i-1)*(i-2)*(i-3)*(i-4)*(i-5)/720:0;}\nvoid warshall_floyd(vector<vector<ll>>& dist) {const ull n = dist.size();rep(k, n) rep(i, n) rep(j, n) {dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j]);}}\n#define YES {cout<<\"Yes\\n\";return;}\n#define NO {cout<<\"No\\n\";return;}\n#define yn YES else NO\n#ifdef ONLINE_JUDGE\nusing lll = boost::multiprecision::cpp_int;\n//using lll = boost::multiprecision::int128_t;\nusing namespace atcoder;\n//using mint = modint1000000007;\nusing mint = modint998244353;\n//using mint = modint; // custom mod\n//atcoder::modint::set_mod(m);\n// DSU == UnionFind\n#endif\n#define vc vector\nusing P = pair<ll, ll>;using vl = vc<ll>;using vb=vc<bool>;using vs=vc<string>;using vvl=vc<vl>;using vp=vc<P>;\n#define pq priority_queue\ntemplate<typename T>void cs(vector<T>&v){xfor(i,1,v.size())v[i]+=v[i-1];}\n\nvl dx = {-1, 1, 0, 0, -1, 1, -1, 1};\nvl dy = {0, 0, 1, -1, -1, -1, 1, 1};\n\nconstexpr ll mod = 998244353;\n\nvoid solve() {\n ll V, E, r;\n cin >> V >> E >> r;\n vc<vc<P>> nexts(V);\n rep(i, E) {\n ll s,t,d;\n cin>>s>>t>>d;\n nexts[s].emplace_back(t,d);\n }\n\n vl dijkstra(V, INF);\n dijkstra[r] = 0;\n\n pq<P, vector<P>, greater<>> q; // make_pair( 重みの総和, 頂点番号 )\n q.emplace(0, r);\n\n while (!q.empty()) {\n auto [_, vert] = q.top(); q.pop();\n\n for (auto [next, weight] : nexts[vert]) {\n if (dijkstra[next] > dijkstra[vert] + weight) {\n dijkstra[next] = dijkstra[vert] + weight;\n q.emplace(dijkstra[next], next);\n }\n }\n }\n\n rep(i,V)cout<<(dijkstra[i]==INF?\"INF\":to_string(dijkstra[i]))<<endl;\n}\n\nint main() {\n ios_base::sync_with_stdio(false);\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n cout << fixed << setprecision(50);\n\n ll n = 1;\n //cin >> n;\n while (n--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 19536, "score_of_the_acc": -0.1473, "final_rank": 1 }, { "submission_id": "aoj_GRL_1_A_11037051", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n int n;\n cin >> n;\n int m;\n cin >> m;\n int k;\n cin >> k;\n k++;\n vector<vector<pair<int,int>>> adj(n+1);\n for(int i=0;i<m;i++){\n int a,b,w;\n cin >> a >> b >> w;\n a++; b++;\n adj[a].push_back({b,w});\n }\n priority_queue<pair<int,int>> q;\n vector<int> d(n+1, INT_MAX);\n q.push({0,k});\n d[k]=0;\n while(!q.empty()){\n int a=q.top().first, b=q.top().second;\n q.pop();\n if(d[b]!=INT_MAX && b!=k) continue;\n d[b]=-a;\n for(auto nxt:adj[b]){\n if(d[nxt.first]==INT_MAX) q.push({-(-a+nxt.second),nxt.first});\n }\n }\n for(int i=1;i<=n;i++){\n if(d[i]!=INT_MAX) cout << d[i] << '\\n';\n else cout << \"INF\\n\";\n }\n}", "accuracy": 1, "time_ms": 260, "memory_kb": 14160, "score_of_the_acc": -0.1978, "final_rank": 2 }, { "submission_id": "aoj_GRL_1_A_11030972", "code_snippet": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n#include <queue>\n#include <stack>\nusing namespace std;\nusing ll = long long;\nstruct Edge {\n\tint to;\n\tint cost;\n};\nusing Graph = vector<vector<Edge>>;\nint main() {\n\tint N, M, r;cin >> N >> M >>r;\n\tGraph G(N);\n\tfor (int i = 0;i < M;i++) {\n\t\tint a, b, c;cin >> a >> b >> c;\n\t\tG[a].push_back({b, c});\n\t}\n\tll inf = (1LL << 60);\n\tvector<ll> dist(N, inf);\n\tpriority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n\tdist[r] = 0;\n\tpq.push({0, r});\n\twhile (!pq.empty()) {\n\t\tauto tp = pq.top();\n\t\tpq.pop();\n\t\tint v = tp.second;\n\t\tll d = tp.first;\n\t\tif (dist[v] < d) continue;\n\t\tfor (auto nv : G[v]) {\n\t\t\tif (nv.cost+d < dist[nv.to]) {\n\t\t\t\tdist[nv.to] = d + nv.cost;\n\t\t\t\tpq.push({dist[nv.to], nv.to});\n\t\t\t}\n\t\t}\n\t}\n\tfor (int v = 0;v < N;v++) {\n\t\tif (dist[v] == inf) {\n\t\t\tcout << \"INF\" << endl;\n\t\t} else {\n\t\t\tcout << dist[v] << endl;\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 14492, "score_of_the_acc": -0.2636, "final_rank": 6 }, { "submission_id": "aoj_GRL_1_A_11029714", "code_snippet": "#line 1 \"src/main.cpp\"\n#include <bits/stdc++.h>\n\n#line 2 \"library/newlib/src/Functional.hpp\"\n#include <type_traits>\n#line 5 \"library/newlib/src/Functional.hpp\"\n\nnamespace gandalfr {\n\nnamespace internal {\ntemplate <typename T>\nbool chmin(T &a, const T &b) {\n return b < a ? (a = b, true) : false;\n}\ntemplate <typename T>\nbool chmax(T &a, const T &b) {\n return a < b ? (a = b, true) : false;\n}\n} // namespace internal\n\nnamespace mixin {\nstruct HasFrom {\n int _from;\n HasFrom() = default;\n HasFrom(int from) : _from(from) {}\n int from() const { return _from; }\n};\nstruct HasTo {\n int _to;\n HasTo() = default;\n HasTo(int to) : _to(to) {}\n int to() const { return _to; }\n};\nstruct HasOther {\n int _xor;\n HasOther() = default;\n HasOther(int xor_val) : _xor(xor_val) {}\n int other(int from) const { return from ^ _xor; }\n};\ntemplate <typename WeightType>\nstruct WithCost {\n using W = WeightType;\n WeightType _cost;\n WithCost() = default;\n WithCost(WeightType cost) : _cost(cost) {}\n WeightType cost() const { return _cost; }\n};\ntemplate <typename WeightType = int>\nstruct HasConstCost {\n using W = WeightType;\n HasConstCost() = default;\n HasConstCost(WeightType) {} // dummy\n WeightType cost() const { return 1; }\n};\ntemplate <typename InfoType>\nstruct WithInfo {\n InfoType _info;\n WithInfo() = default;\n WithInfo(InfoType info) : _info(info) {}\n InfoType info() const { return _info; }\n};\n} // namespace mixin\n\nnamespace detail {\ntemplate <typename T>\nstruct cost_type_of {\n using type = void;\n};\ntemplate <typename WeightType>\nstruct cost_type_of<mixin::WithCost<WeightType>> {\n using type = WeightType;\n};\ntemplate <typename WeightType>\nstruct cost_type_of<mixin::HasConstCost<WeightType>> {\n using type = WeightType;\n};\n\ntemplate <typename... Ts>\nstruct find_cost_type_helper;\ntemplate <>\nstruct find_cost_type_helper<> {\n using type = void;\n};\ntemplate <typename Head, typename... Tail>\nstruct find_cost_type_helper<Head, Tail...>\n : std::conditional_t<\n !std::is_same_v<typename cost_type_of<Head>::type, void>,\n cost_type_of<Head>, find_cost_type_helper<Tail...>> {};\n} // namespace detail\n\ntemplate <typename... OptionalProperties>\nstruct Edge : public OptionalProperties... {\n using W =\n typename detail::find_cost_type_helper<OptionalProperties...>::type;\n\n Edge() = default;\n Edge(const Edge &) = default;\n Edge(Edge &&) = default;\n Edge &operator=(const Edge &) = default;\n Edge &operator=(Edge &&) = default;\n\n template <typename... Args>\n Edge(Args &&...args) : OptionalProperties(std::forward<Args>(args))... {}\n};\nnamespace edge {\nusing UnweightedEdge = Edge<mixin::HasOther, mixin::HasConstCost<>>;\ntemplate <typename InfoType>\nusing UnweightedEdgeWithInfo =\n Edge<mixin::HasOther, mixin::HasConstCost<>, mixin::WithInfo<InfoType>>;\ntemplate <typename WeightType>\nusing WeightedEdge = Edge<mixin::HasOther, mixin::WithCost<WeightType>>;\ntemplate <typename WeightType, typename InfoType>\nusing WeightedEdgeWithInfo = Edge<mixin::HasOther, mixin::WithCost<WeightType>,\n mixin::WithInfo<InfoType>>;\n} // namespace edge\n\ntemplate <typename E, bool is_directed>\nstruct General {\n using W = typename E::W;\n static_assert(std::is_base_of_v<mixin::HasOther, E>,\n \"E must have to(int) method\");\n static_assert(std::is_base_of_v<mixin::HasConstCost<W>, E> ^\n std::is_base_of_v<mixin::WithCost<W>, E>,\n \"E must have either HasConstCost or WithCost mixin\");\n\n int _n = 0;\n std::vector<int> _idx, _ptr;\n std::vector<E> _edges;\n\n template <typename Iterator>\n class IndexRange {\n private:\n Iterator _begin_it;\n Iterator _end_it;\n\n public:\n IndexRange(Iterator begin_it, Iterator end_it)\n : _begin_it(begin_it), _end_it(end_it) {}\n Iterator begin() const { return _begin_it; }\n Iterator end() const { return _end_it; }\n };\n IndexRange<typename std::vector<int>::const_iterator> operator[](\n int v) const {\n auto begin_it = _idx.cbegin() + _ptr[v];\n auto end_it = _idx.cbegin() + _ptr[v + 1];\n return {begin_it, end_it};\n }\n\n General(int n) : _n(n) {}\n\n void build(const std::vector<int> &from_v, const std::vector<E> &e_v) {\n assert(from_v.size() == e_v.size());\n int m = e_v.size();\n _edges = e_v;\n _ptr.assign(_n + 1, 0);\n for (int i = 0; i < m; i++) {\n int from = from_v[i];\n int to = e_v[i].other(from);\n _ptr[from + 1]++;\n if (!is_directed && from != to) _ptr[to + 1]++;\n }\n for (int v = 0; v < _n; v++) _ptr[v + 1] += _ptr[v];\n\n int idx_size = is_directed ? m : 2 * m;\n _idx.assign(idx_size, -1);\n std::vector<int> counter = _ptr;\n for (int i = 0; i < m; i++) {\n int from = from_v[i];\n int to = e_v[i].other(from);\n int dest_idx = counter[from]++;\n _idx[dest_idx] = i;\n if (!is_directed && from != to) {\n int rev_dest_idx = counter[to]++;\n _idx[rev_dest_idx] = i;\n }\n }\n }\n\n int vertex_count() const { return _n; }\n int edge_count() const { return (int)_edges.size(); }\n\n const E &edge_at(int i) const { return _edges[i]; }\n E &edge_at(int i) { return _edges[i]; }\n\n template <bool D = std::is_base_of_v<mixin::WithCost<W>, E>>\n auto dijkstra(int s) -> std::enable_if_t<D, std::vector<W>> {\n const W INF = std::numeric_limits<W>::max();\n std::vector<W> dist(_n, INF);\n using P = std::pair<W, int>;\n std::priority_queue<P, std::vector<P>, std::greater<P>> pq;\n dist[s] = W(0);\n pq.push({dist[s], s});\n while (!pq.empty()) {\n auto [d, v] = pq.top();\n pq.pop();\n if (dist[v] < d) continue;\n for (int ei : (*this)[v]) {\n const E &e = edge_at(ei);\n int to = e.other(v);\n W nd = d + e.cost();\n if (internal::chmin(dist[to], nd)) pq.push({nd, to});\n }\n }\n return dist;\n }\n\n template <bool D = std::is_base_of_v<mixin::HasConstCost<W>, E>>\n auto bfs(int s) -> std::enable_if_t<D, std::vector<W>> {\n std::vector<W> dist(_n, W(std::numeric_limits<W>::max()));\n std::queue<int> q;\n dist[s] = W(0);\n q.push(s);\n while (!q.empty()) {\n int v = q.front();\n q.pop();\n for (int ei : (*this)[v]) {\n const E &e = edge_at(ei);\n int to = e.other(v);\n W nd = dist[v] + e.cost();\n if (internal::chmin(dist[to], nd)) q.push(to);\n }\n }\n return dist;\n }\n};\n\n} // namespace gandalfr\n#line 4 \"src/main.cpp\"\n\nusing namespace std;\n#pragma GCC target(\"avx2\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n\n#define rep(i, n) for (int i = 0; i < (n); i++)\n#define all(a) (a).begin(), (a).end()\nusing ll = long long;\n\nusing namespace gandalfr;\n\nint main() {\n int n, m, s;\n cin >> n >> m >> s;\n General<edge::WeightedEdge<int>, true> graph(n);\n vector<int> froms;\n vector<edge::WeightedEdge<int>> edges;\n for (int i = 0; i < m; i++) {\n int from, to, cost;\n cin >> from >> to >> cost;\n edges.push_back({from ^ to, cost});\n froms.push_back(from);\n }\n graph.build(froms, edges);\n\n auto dist = graph.dijkstra(s);\n for (int v = 0; v < graph.vertex_count(); v++) {\n if (dist[v] == std::numeric_limits<int>::max()) {\n cout << \"INF\" << endl;\n continue;\n }\n cout << dist[v] << endl;\n }\n}", "accuracy": 1, "time_ms": 290, "memory_kb": 17240, "score_of_the_acc": -0.3037, "final_rank": 8 }, { "submission_id": "aoj_GRL_1_A_11026300", "code_snippet": "#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"inline\",\"fast-math\",\"unroll-loops\",\"no-stack-protector\")\n#include <iostream>\n#include<vector>\n#include<list>\n#include<utility>\n#include<limits>\n#include<set>\n#include<iostream>\n#include<queue>\n#include<unordered_map>\n#include<unordered_set>\n#include<random>\n#include<ext/pb_ds/assoc_container.hpp>\n\nusing T = long long;\nnamespace spp {\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntemplate<typename K, typename V>\nusing hash_map = unordered_map<K, V>;\ntemplate<typename K>\nusing hash_set = unordered_set<K>;\n\ntemplate<typename uniqueDistT>\nstruct batchPQ { // batch priority queue, implemented as in Lemma 3.3\n using elementT = pair<int,uniqueDistT>;\n \n struct CompareUB {\n template <typename It>\n bool operator()(const pair<uniqueDistT, It>& a, const pair<uniqueDistT, It>& b) const {\n if (a.first != b.first) return a.first < b.first;\n return addressof(*a.second) < addressof(*b.second);\n }\n };\n \n typename list<list<elementT>>::iterator it_min;\n \n list<list<elementT>> D0,D1;\n set<pair<uniqueDistT,typename list<list<elementT>>::iterator>,CompareUB> UBs; // (UB, it_block)\n \n int M,size_;\n uniqueDistT B;\n \n hash_map<int, uniqueDistT> actual_value;\n hash_map<int, pair< typename list<list<elementT>>::iterator , typename list<elementT>::iterator> > where_is[2];\n \n // Initialize\n batchPQ(int M_, uniqueDistT B_): M(M_), B(B_) { // O(1)\n D1.push_back(list<elementT>());\n UBs.insert({B_,D1.begin()});\n size_ = 0;\n }\n \n int size(){\n return size_;\n }\n \n inline void erase(int key) {\n if(actual_value.find(key) != actual_value.end())\n delete_({-1, -1, key, -1});\n }\n void delete_(uniqueDistT x){ \n int a = get<2>(x);\n uniqueDistT b = actual_value[a];\n \n auto it_w = where_is[1].find(a);\n if((it_w != where_is[1].end())){\n auto [it_block,it] = it_w->second;\n \n (*it_block).erase(it);\n where_is[1].erase(a);\n \n if((*it_block).size() == 0){\n auto it_UB_block = UBs.lower_bound({b,it_block}); \n \n if((*it_UB_block).first != B){\n UBs.erase(it_UB_block);\n D1.erase(it_block);\n }\n }\n }else{\n auto [it_block,it] = where_is[0][a];\n (*it_block).erase(it);\n where_is[0].erase(a);\n if((*it_block).size() == 0) D0.erase(it_block); \n }\n \n actual_value.erase(a);\n size_--;\n }\n \n void insert(uniqueDistT x){ // O(lg(Block Numbers)) \n uniqueDistT b = x;\n int a = get<2>(b);\n \n // checking if exists\n auto it_exist = actual_value.find(a);\n int exist = (it_exist != actual_value.end()); \n \n if(exist && it_exist->second > b){\n delete_(x);\n }else if(exist){\n return;\n }\n \n // Searching for the first block with UB which is > \n auto it_UB_block = UBs.lower_bound({b,it_min});\n auto [ub,it_block] = (*it_UB_block);\n \n // Inserting key/value (a,b)\n auto it = it_block->insert(it_block->end(),{a,b});\n where_is[1][a] = {it_block, it};\n actual_value[a] = b;\n \n size_++;\n \n // Checking if exceeds the sixe limit M\n if((*it_block).size() > M){\n split(it_block);\n }\n }\n\n uniqueDistT medianOfMedians(vector<elementT>::iterator bg, vector<elementT>::iterator en) {\n vector<elementT> l(bg, en);\n while (true) {\n int n = l.size();\n\n if (n <= 5) {\n sort(l.begin(), l.end(), [](const auto& a, const auto& b) {\n return a.second < b.second;\n });\n return l[l.size() / 2].second;\n }\n\n vector<elementT> medians;\n medians.reserve((n + 4) / 5);\n\n auto it = l.begin();\n while (it != l.end()) {\n vector<elementT> group;\n group.reserve(5);\n for (int j = 0; j < 5 && it != l.end(); ++j, ++it)\n group.push_back(*it);\n\n sort(group.begin(), group.end(), [](const auto& a, const auto& b) {\n return a.second < b.second;\n });\n\n medians.push_back(group[group.size() / 2]);\n }\n\n l = move(medians);\n }\n }\n \n uniqueDistT selectKth(vector<elementT> &v, int k) { \n using std::swap;\n int l=0, r=v.size()-1;\n \n for(;l<=r;){\n uniqueDistT p = medianOfMedians(v.begin() + l, v.begin() + r + 1);\n \n int i = l, j = r, m = l;\n \n while(m <= j){\n if(v[m].second < p) {\n swap(v[m++],v[i++]);\n }else if(v[m].second > p){\n swap(v[m],v[j--]);\n }else{\n m++;\n }\n }\n \n if (k < i) r = i - 1; // k está na parte menor\n else if (k > j) l = j + 1; // k está na parte maior\n else return v[k].second; // k está entre os iguais ao pivot\n } \n \n return v[k].second;\n }\n\n \n void split(list<list<elementT>>::iterator it_block){ // O(M) + O(lg(Block Numbers))\n int sz = (*it_block).size();\n \n vector<elementT> v((*it_block).begin() , (*it_block).end());\n uniqueDistT med = selectKth(v,(sz/2)); // O(M)\n \n auto pos = it_block;\n pos++;\n\n\n auto new_block = D1.insert(pos,list<elementT>());\n auto it = (*it_block).begin();\n \n while(it != (*it_block).end()){ // O(M)\n if((*it).second >= med){\n // (*new_block).push_back((*it));\n (*new_block).push_back(move(*it));\n auto it_new = (*new_block).end(); it_new--;\n where_is[1][(*it).first] = {new_block, it_new};\n \n it = (*it_block).erase(it);\n }else{\n it++;\n }\n }\n \n\n // Updating UBs \n // O(lg(Block Numbers))\n uniqueDistT UB1 = {get<0>(med),get<1>(med),get<2>(med),get<3>(med)-1};\n auto it_lb = UBs.lower_bound({UB1,it_min});\n auto [UB2,aux] = (*it_lb);\n \n UBs.insert({UB1,it_block});\n UBs.insert({UB2,new_block});\n \n UBs.erase(it_lb);\n }\n \n void batchPrepend(const list<elementT> &l) { // O(|l| log(|l|/M) ) \n int sz = l.size();\n \n if(sz == 0) return;\n if(sz <= M){\n \n D0.push_front(list<elementT>());\n auto new_block = D0.begin();\n \n for(auto &x : l){ \n auto it = actual_value.find(x.first);\n int exist = (it != actual_value.end()); \n \n if(exist && it->second > x.second){\n delete_(x.second);\n }else if(exist){\n continue;\n }\n \n (*new_block).push_back(x);\n auto it_new = (*new_block).end(); it_new--;\n where_is[0][x.first] = {new_block, it_new};\n actual_value[x.first] = x.second;\n size_++;\n }\n if(new_block->size() == 0) D0.erase(new_block);\n return;\n }\n\n vector<elementT> v(l.begin(), l.end());\n uniqueDistT med = selectKth(v, sz/2);\n \n list<elementT> less,great;\n for(auto [a,b]: l){\n if(b < med){\n less.push_back({a,b});\n }else if(b > med){\n great.push_back({a,b});\n }\n }\n \n great.push_back({get<2>(med),med});\n\n batchPrepend(great);\n batchPrepend(less);\n }\n \n void batchPrepend(const vector<uniqueDistT> &v){\n list<elementT> l;\n for(auto x: v){\n l.push_back({get<2>(x),x});\n }\n batchPrepend(l);\n }\n \n pair<uniqueDistT, vector<int>> pull(){ // O(M)\n vector<elementT> s0,s1;\n s0.reserve(2 * M); s1.reserve(M);\n \n auto it_block = D0.begin();\n while(it_block != D0.end() && s0.size() <= M){ // O(M) \n for (const auto& x : *it_block) s0.push_back(x);\n it_block++;\n }\n \n it_block = D1.begin();\n while(it_block != D1.end() && s1.size() <= M){ //O(M)\n for (const auto& x : *it_block) s1.push_back(x);\n it_block++;\n }\n \n if(s1.size() + s0.size() <= M){\n vector<int> ret;\n ret.reserve(s1.size()+s0.size());\n for(auto [a,b] : s0) {\n ret.push_back(a);\n delete_({b});\n }\n for(auto [a,b] : s1){\n ret.push_back(a);\n delete_({b});\n } \n \n return {B, ret};\n }else{ \n vector<elementT> &l = s0;\n l.insert(l.end(), s1.begin(), s1.end());\n\n uniqueDistT med = selectKth(l, M);\n vector<int> ret;\n ret.reserve(M);\n for(auto [a,b]: l){\n if(b < med) {\n ret.push_back(a);\n delete_({b});\n }\n }\n \n return {med,ret};\n }\n }\n};\n\ntemplate<typename wT>\nstruct bmssp { // bmssp class\n int n, k, t;\n const wT oo = numeric_limits<wT>::max() / 10;\n \n vector<vector<pair<int, wT>>> ori_adj;\n vector<vector<pair<int, wT>>> adj;\n vector<wT> d;\n vector<int> pred, path_sz;\n vector<int> rev_map;\n vector<short int> last_complete_lvl;\n \n vector<hash_map<int, int>> neig;\n bmssp(int n_): n(n_) {\n ori_adj.assign(n, {});\n neig.assign(n, {});\n }\n bmssp(const auto &adj) {\n n = adj.size();\n ori_adj = adj;\n neig.assign(n, {});\n }\n void addEdge(int a, int b, wT w) {\n ori_adj[a].emplace_back(b, w);\n }\n\n // if the graph already has constant degree, prepage_graph(false)\n // else, prepage_graph(true)\n void prepare_graph(bool exec_constant_degree_trasnformation = false) {\n // erase duplicated edges\n vector<pair<int, int>> tmp_edges(n, {-1, -1});\n for(int i = 0; i < n; i++) {\n vector<pair<int, wT>> nw_adj;\n nw_adj.reserve(ori_adj[i].size());\n for(auto [j, w]: ori_adj[i]) {\n if(tmp_edges[j].first != i) {\n nw_adj.emplace_back(j, w);\n tmp_edges[j] = {i, nw_adj.size() - 1};\n } else {\n int id = tmp_edges[j].second;\n nw_adj[id].second = min(nw_adj[id].second, w);\n }\n }\n ori_adj[i] = move(nw_adj);\n }\n tmp_edges.clear();\n\n if(exec_constant_degree_trasnformation == false) {\n adj = move(ori_adj);\n ori_adj.clear();\n d.resize(n);\n root.resize(n);\n pred.resize(n);\n treesz.resize(n);\n rev_map.resize(n);\n path_sz.resize(n, 0);\n last_complete_lvl.resize(n);\n \n for(int i = 0; i < n; i++) {\n neig[i][i] = i;\n rev_map[i] = i;\n }\n\n k = floor(pow(log2(n), 1.0 / 3.0));\n t = floor(pow(log2(n), 2.0 / 3.0));\n } else {\n // Make the graph become constant degree\n int cnt = 0;\n for(int i = 0; i < n; i++) {\n for(auto [j, w]: ori_adj[i]) {\n if(neig[i].find(j) == neig[i].end()) {\n neig[i][j] = cnt++;\n neig[j][i] = cnt++;\n }\n }\n }\n\n cnt++;\n adj.assign(cnt, {});\n \n d.resize(cnt);\n root.resize(cnt);\n pred.resize(cnt);\n treesz.resize(cnt);\n rev_map.resize(cnt);\n path_sz.resize(cnt, 0);\n last_complete_lvl.resize(cnt);\n \n for(int i = 0; i < n; i++) { // create 0-weight cycles\n for(auto cur = neig[i].begin(); cur != neig[i].end(); cur++) {\n auto nxt = next(cur);\n if(nxt == neig[i].end()) nxt = neig[i].begin();\n adj[cur->second].emplace_back(nxt->second, wT());\n rev_map[cur->second] = i;\n }\n }\n for(int i = 0; i < n; i++) { // add edges\n for(auto [j, w]: ori_adj[i]) {\n adj[neig[i][j]].emplace_back(neig[j][i], w);\n }\n if(neig[i].size() == 0) { // for vertices without edges\n neig[i][n] = cnt - 1;\n }\n }\n k = floor(pow(log2(cnt), 1.0 / 3.0));\n t = floor(pow(log2(cnt), 2.0 / 3.0));\n \n ori_adj.clear();\n }\n }\n \n int toAnyCustomNode(int real_id) {\n return neig[real_id].begin()->second;\n }\n int customToReal(int id) {\n return rev_map[id];\n }\n \n vector<wT> execute(int s) {\n fill(d.begin(), d.end(), oo);\n fill(path_sz.begin(), path_sz.end(), oo);\n fill(last_complete_lvl.begin(), last_complete_lvl.end(), -1);\n for(int i = 0; i < pred.size(); i++) pred[i] = i;\n \n s = toAnyCustomNode(s);\n d[s] = 0;\n path_sz[s] = 0;\n \n const int l = ceil(log2(adj.size()) / t);\n const uniqueDistT inf_dist = make_tuple(oo, 0, 0, 0);\n bmsspRec(l, inf_dist, {s});\n \n vector<wT> res(n);\n for(int i = 0; i < n; i++) res[i] = d[toAnyCustomNode(i)];\n return res;\n }\n \n // ===================================================================\n \n // set stuff\n // template<typename T>\n // void removeDuplicates(vector<T> &v) { // sort is faster\n // hash_set<T> s(v.begin(), v.end());\n // v = vector<T>(s.begin(), s.end());\n // // sort(v.begin(), v.end());\n // // v.erase(unique(v.begin(), v.end()), v.end());\n // }\n template<typename T>\n bool isUnique(const vector<T> &v) {\n auto v2 = v;\n sort(v2.begin(), v2.end());\n v2.erase(unique(v2.begin(), v2.end()), v2.end());\n return v2.size() == v.size();\n }\n\n using uniqueDistT = tuple<wT, int, int, int>;\n inline uniqueDistT getDist(int u, int v, int w) {\n return {d[u] + w, path_sz[u] + 1, v, u};\n }\n inline uniqueDistT getDist(int u) {\n return {d[u], path_sz[u], u, pred[u]};\n }\n void updateDist(int u, int v, wT w) {\n pred[v] = u;\n d[v] = d[u] + w;\n path_sz[v] = path_sz[u] + 1;\n }\n // ===================================================================\n vector<int> root;\n vector<short int> treesz;\n pair<vector<int>, hash_set<int>> findPivots(uniqueDistT B, const vector<int> &S) { // Algorithm 1\n hash_set<int> vis;\n vis.reserve(S.size() * k);\n vis.insert(S.begin(), S.end());\n\n vector<int> active = S;\n for(int x: S) root[x] = x, treesz[x] = 0;\n for(int i = 1; i <= k; i++) {\n vector<int> nw_active;\n nw_active.reserve(active.size() * 4);\n for(int u: active) {\n for(auto [v, w]: adj[u]) {\n if(getDist(u, v, w) <= getDist(v)) {\n updateDist(u, v, w);\n if(getDist(v) < B) {\n root[v] = root[u];\n nw_active.push_back(v);\n }\n }\n }\n }\n for(const auto &x: nw_active) {\n vis.insert(x);\n }\n if(vis.size() > k * S.size()) {\n return {S, vis};\n }\n active = move(nw_active);\n }\n\n vector<int> P;\n P.reserve(vis.size() / k);\n for(int u: vis) treesz[root[u]]++;\n for(int u: S) if(treesz[u] >= k) P.push_back(u);\n \n // assert(P.size() <= vis.size() / k);\n return {P, vis};\n }\n \n pair<uniqueDistT, vector<int>> baseCase(uniqueDistT B, int x) { // Algorithm 2\n vector<int> complete;\n complete.reserve(k + 1);\n \n priority_queue<uniqueDistT, vector<uniqueDistT>, greater<uniqueDistT>> heap;\n heap.push(getDist(x));\n while(heap.empty() == false && complete.size() < k + 1) {\n int u = get<2>(heap.top());\n int du = get<0>(heap.top());\n heap.pop();\n if(du > d[u]) continue;\n\n complete.push_back(u);\n for(auto [v, w]: adj[u]) {\n auto new_dist = getDist(u, v, w);\n auto old_dist = getDist(v);\n if(new_dist <= old_dist && new_dist < B) {\n updateDist(u, v, w);\n heap.push(new_dist);\n }\n }\n }\n if(complete.size() <= k) return {B, complete};\n \n uniqueDistT nB = getDist(complete.back());\n // { // sanity check\n // int cntbig = 0;\n // for(int u: complete) if(getDist(u) >= nB) cntbig++;\n // assert(cntbig == 1);\n // for(int u: complete) assert(getDist(u) < B);\n // assert(complete.size() == k + 1);\n // }\n complete.pop_back();\n return {nB, complete};\n }\n \n pair<uniqueDistT, vector<int>> bmsspRec(short int l, uniqueDistT B, const vector<int> &S) { // Algorithm 3\n if(l == 0) return baseCase(B, S[0]);\n \n auto [P, bellman_vis] = findPivots(B, S);\n \n const long long batch_size = (1ll << ((l - 1) * t));\n batchPQ<uniqueDistT> D(batch_size, B);\n for(int p: P) D.insert(getDist(p));\n \n uniqueDistT last_complete_B = B;\n for(int p: P) last_complete_B = min(last_complete_B, getDist(p));\n \n vector<int> complete;\n const long long quota = k * (1ll << (l * t));\n complete.reserve(quota + bellman_vis.size());\n while(complete.size() < quota && D.size()) {\n auto [trying_B, miniS] = D.pull();\n // all with dist < trying_B, can be reached by miniS <= req 2, alg 3\n \n auto [complete_B, nw_complete] = bmsspRec(l - 1, trying_B, miniS);\n \n // all new complete_B are greater than the old ones <= point 6, page 10\n // assert(last_complete_B < complete_B);\n \n complete.insert(complete.end(), nw_complete.begin(), nw_complete.end());\n // point 6, page 10 => complete does not intersect with nw_complete\n // assert(isUnique(complete));\n \n vector<uniqueDistT> can_prepend;\n can_prepend.reserve(nw_complete.size() * 5 + miniS.size());\n for(int u: nw_complete) {\n D.erase(u); // priority queue fix\n last_complete_lvl[u] = l;\n for(auto [v, w]: adj[u]) {\n auto new_dist = getDist(u, v, w);\n if(new_dist <= getDist(v)) {\n updateDist(u, v, w);\n if(trying_B <= new_dist && new_dist < B) {\n D.insert(new_dist); // d[v] can be greater equal than min(D), occur 1x per vertex\n } else if(complete_B <= new_dist && new_dist < trying_B) {\n can_prepend.emplace_back(new_dist); // d[v] is less than all in D, can occur 1x at each level per vertex\n }\n }\n }\n }\n for(int x: miniS) {\n if(complete_B <= getDist(x)) can_prepend.emplace_back(getDist(x));\n // second condition is not necessary\n }\n // can_prepend is not necessarily all unique\n D.batchPrepend(can_prepend);\n \n last_complete_B = complete_B;\n }\n uniqueDistT retB;\n if(D.size() == 0) retB = B; // successful\n else retB = last_complete_B; // partial\n \n for(int x: bellman_vis) if(last_complete_lvl[x] != l && getDist(x) < retB) complete.push_back(x); // this get the completed vertices from bellman-ford, it has P in it as well\n // get only the ones not in complete already, for it to become disjoint\n \n return {retB, complete};\n }\n};\n}\n\nint main() {\n int n, m, s;\n std::cin >> n >> m >> s;\n std::vector<std::tuple<int, int, T>> edges;\n while (m --)\n {\n int u, v, w;\n std::cin >> u >> v >> w;\n edges.push_back({u, v, w});\n }\n \n // std::vector<std::tuple<int, int, T>> edges = {\n // {0, 1, 10}, {0, 2, 3}, {1, 3, 2}, {2, 1, 4},\n // {2, 3, 8}, {2, 4, 2}, {3, 4, 5}\n // };\n int source_node = s;\n\n // 2. Initialize and build the graph\n spp::bmssp<T> solver(n);\n for (const auto& [u, v, weight] : edges) {\n solver.addEdge(u, v, weight);\n }\n\n // 3. Prepare the graph (must be called once)\n solver.prepare_graph(false);\n // use solver.prepare_graph(true) if the graph does not have contant out-degree\n\n // 4. Compute shortest paths\n std::vector<T> distances = solver.execute(source_node);\n\n // 5. Print results\n // std::cout << \"Shortest paths from source \" << source_node << \":\" << std::endl;\n for (int i = 0; i < n; ++i) {\n if (distances[i] == solver.oo) {\n std::cout << \"INF\" << '\\n';\n } else {\n std::cout << distances[i] << '\\n';\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 290, "memory_kb": 56536, "score_of_the_acc": -1.2093, "final_rank": 18 }, { "submission_id": "aoj_GRL_1_A_11026296", "code_snippet": "#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"inline\",\"fast-math\",\"unroll-loops\",\"no-stack-protector\")\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <map>\n#include <algorithm>\n#include <cassert>\n\nusing Vertex = int;\nusing Length = long long;\nconst Length INF = std::numeric_limits<long long>::max();\nusing Edge = std::pair<Vertex, Length>;\nusing Graph = std::vector<std::vector<Edge>>;\n\nclass BlockHeap {\n public:\n BlockHeap(int M, Length B);\n void insert(Vertex v, Length l);\n void batch_prepend(const std::vector<std::pair<Vertex, Length>>& L);\n std::pair<Length ,std::vector<Vertex>> pull();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n\n std::unordered_map<Vertex, Length> d_;\n std::vector<std::pair<Length, Vertex>> buffer_;\n std::vector<std::pair<Length, Vertex>> prepend_;\n std::set<std::pair<Length, Vertex>> active_;\n Length buffer_min_ = INF;\n Length prepend_min_ = INF;\n};\n\nBlockHeap::BlockHeap(int M, Length B) {\n M_ = M;\n B_ = B;\n}\n\nstd::pair<Length, std::vector<Vertex>> BlockHeap::pull() {\n std::vector<Vertex> S;\n\n if(active_.empty()) {\n if(!prepend_.empty()) {\n for(auto &p : prepend_) {\n Length l = p.first; Vertex v = p.second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n prepend_.clear();\n prepend_min_ = INF;\n }\n\n if(active_.empty() && !buffer_.empty()) {\n int take = std::min((int)buffer_.size(), M_);\n std::nth_element(buffer_.begin(), buffer_.begin() + take, buffer_.end(),\n [](const std::pair<Length, Vertex>& a, const std::pair<Length, Vertex>& b){\n return a.first < b.first;\n });\n for(int i = 0; i < take; ++i) {\n Length l = buffer_[i].first; Vertex v = buffer_[i].second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n\n std::vector<std::pair<Length, Vertex>> newbuf;\n newbuf.reserve(buffer_.size() - take);\n for(size_t i = take; i < buffer_.size(); ++i) newbuf.push_back(buffer_[i]);\n buffer_.swap(newbuf);\n buffer_min_ = INF;\n for(auto &p : buffer_) buffer_min_ = std::min(buffer_min_, p.first);\n }\n }\n\n for(int i = 0; i < M_; ++i) {\n if(active_.empty()) break;\n auto p = *active_.begin();\n active_.erase(active_.begin());\n Vertex v = p.second; Length l = p.first;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n S.push_back(v);\n d_.erase(it);\n }\n }\n\n Length next_min = INF;\n if(!active_.empty()) next_min = std::min(next_min, active_.begin()->first);\n if(buffer_min_ < next_min) next_min = buffer_min_;\n if(prepend_min_ < next_min) next_min = prepend_min_;\n if(next_min == INF) return std::make_pair(B_, S);\n return std::make_pair(next_min, S);\n}\n\nvoid BlockHeap::batch_prepend(const std::vector<std::pair<Vertex, Length>>& L) {\n for(const auto &p : L) {\n Vertex v = p.first; Length l = p.second;\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) continue;\n it->second = l;\n } else {\n d_[v] = l;\n }\n prepend_.push_back(std::make_pair(l, v));\n if(l < prepend_min_) prepend_min_ = l;\n }\n}\n\nvoid BlockHeap::insert(Vertex v, Length l) {\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) return;\n it->second = l;\n } else {\n d_[v] = l;\n }\n buffer_.push_back(std::make_pair(l, v));\n if(l < buffer_min_) buffer_min_ = l;\n}\n\nbool BlockHeap::empty() {\n return d_.empty();\n}\n\nvoid BlockHeap::debug() {\n std::cout << \"D(active)= [\";\n for(auto p: active_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(prepend)= [\";\n for(auto &p: prepend_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(buffer)= [\";\n for(auto &p: buffer_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass Heap {\n public:\n void push(Vertex v, Length l);\n std::pair<Vertex, Length> top();\n void pop();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n std::set<std::pair<Length, Vertex>> que_;\n std::unordered_map<Vertex, Length> d_;\n\n};\n\nvoid Heap::push(Vertex v, Length l) {\n if(d_.count(v) != 0 && d_[v] < l) {\n return;\n } else if (d_.count(v) != 0 && d_[v] >= l) {\n que_.erase(std::make_pair(d_[v], v));\n }\n que_.insert(std::make_pair(l, v));\n d_[v] = l;\n}\n\nstd::pair<Vertex, Length> Heap::top() {\n auto p = *que_.begin();\n return std::make_pair(p.second, p.first);\n}\n\nvoid Heap::pop() {\n d_.erase(top().second);\n que_.erase(que_.begin());\n}\n\nbool Heap::empty() {\n return que_.empty();\n}\n\nvoid Heap::debug() {\n std::cout << \"H= [\";\n for(auto p: que_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass ShortestPath {\n public:\n ShortestPath(Vertex s, const Graph& G);\n std::pair<Length, std::vector<Vertex>> BMSSP(int l, Length B, const std::vector<Vertex>& S);\n std::pair<std::vector<Vertex>, std::vector<Vertex>> find_pivots(Length B, const std::vector<Vertex>& S);\n void print_dhat();\n\n private:\n int t_;\n int k_;\n std::vector<Length> dhat_;\n Graph G_;\n\n std::pair<Length, std::vector<Vertex>> base_case(Length B, const std::vector<Vertex>& S);\n\n std::vector<Vertex> prev_;\n std::vector<int> tree_size_;\n std::vector<std::vector<Vertex>> F_;\n};\n\nShortestPath::ShortestPath(Vertex s, const Graph& G) {\n G_ = G;\n int N = G_.size();\n k_ = std::ceil(pow(std::log2(N), 1.0 / 3.0));\n t_ = std::floor(pow(std::log2(N), 2.0 / 3.0));\n dhat_ = std::vector<Length>(N, INF);\n dhat_[s] = 0;\n prev_ = std::vector<Vertex>(N, -1);\n tree_size_ = std::vector<Vertex>(N, -1);\n F_ = std::vector<std::vector<Vertex>>(N, std::vector<Vertex>());\n}\n\nnamespace {\n int find_tree_size(int u, std::vector<int>& tree_size, const std::vector<std::vector<Vertex>>& F) {\n if(tree_size[u] != -1) return tree_size[u];\n int res = 1;\n for(int i = 0; i < (int)F[u].size(); i++) {\n Vertex v = F[u][i];\n res += find_tree_size(v, tree_size, F);\n }\n return tree_size[u] = res;\n }\n\n void debug_vertex_set(std::vector<Vertex> S) {\n std::cout << \"[\";\n for(int i = 0; i < (int)S.size(); i++) {\n std::cout << S[i] << \", \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nvoid ShortestPath::print_dhat() {\n for(int i = 0; i < (int)dhat_.size(); i++) {\n if(dhat_[i] == INF) {\n std::cout << \"INF\" << '\\n';\n } else {\n std::cout << dhat_[i] << '\\n';\n }\n }\n // std::cout << \"[\";\n // for(int i = 0; i < (int)dhat_.size(); i++) {\n // if(dhat_[i] == INF) {\n // std::cout << \"INF\" << \", \";\n // } else {\n // std::cout << dhat_[i] << \", \";\n // }\n // }\n // std::cout << \"]\" << std::endl;\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::BMSSP(int l, Length B, const std::vector<Vertex>& S) {\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", S=\";\n // debug_vertex_set(S);\n // print_dhat();\n if(l == 0) {\n return base_case(B, S);\n }\n auto pw = find_pivots(B, S);\n std::vector<Vertex> P = pw.first; std::vector<Vertex> W = pw.second;\n // std::cout << \"P= \"; debug_vertex_set(P);\n // std::cout << \"W= \"; debug_vertex_set(W);\n\n int M = std::pow(2, (l - 1) * t_);\n BlockHeap D(M, B);\n Length Bd = INF;\n for(int i = 0; i < (int)P.size(); i++) {\n Vertex u = P[i];\n D.insert(u, dhat_[u]);\n Bd = std::min(Bd, dhat_[u]);\n }\n // D.debug();\n std::unordered_set<Vertex> U;\n\n while((int)U.size() < k_ * std::pow(2, l * t_) && !D.empty()) {\n auto bs = D.pull();\n Length Bi = bs.first; std::vector<Vertex> Si = bs.second;\n if (Si.empty()) {\n continue; \n }\n \n auto bu = BMSSP(l - 1, Bi, Si);\n Length Bid = bu.first; std::vector<Vertex> Ui = bu.second;\n // std::cout << \"Bid=\" << Bid << std::endl;\n // std::cout << \"Ui=\"; debug_vertex_set(Ui);\n // std::cout << \"U=\"; debug_vertex_set(std::vector<Vertex>(U.begin(), U.end()));\n for(int j = 0; j < (int)Ui.size(); j++) {\n // if(U.count(Ui[j]) != 0) {\n // std::cout << \"Ufound\" << \" \" << Ui[j] << \" \" << dhat_[Ui[j]] << \" \" << Bi << \" \" << Bid << std::endl;\n // }\n U.insert(Ui[j]);\n }\n\n std::vector<std::pair<Vertex, Length>> K;\n for(int j = 0; j < (int)Ui.size(); j++) {\n Vertex u = Ui[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n Length new_dist = dhat_[u] + w;\n dhat_[v] = new_dist;\n if(Bi <= new_dist && new_dist < B) {\n D.insert(v, new_dist);\n } else if(Bid <= new_dist && new_dist < Bi) {\n K.push_back(std::make_pair(v, new_dist));\n }\n }\n }\n }\n for(int i = 0; i < (int)Si.size(); i++) {\n int u = Si[i];\n if(Bid <= dhat_[u] && dhat_[u] < Bi) K.push_back(std::make_pair(u, dhat_[u]));\n }\n D.batch_prepend(K);\n Bd = Bid;\n }\n Bd = std::min(Bd, B);\n for(int i = 0; i < (int)W.size(); i++) {\n Vertex u = W[i];\n if(dhat_[u] < Bd) U.insert(u);\n }\n if(l == 3) {\n for(int i = 0; i < (int)G_.size(); i++) {\n // if(!U.count(i) && dhat_[i] != INF) {\n // std::cout << \"found: \" << i << \" \" << dhat_[i] << std::endl;\n // }\n }\n }\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", Bd=\" << Bd << std::endl;\n // std::cout << \"U size:=\" << U.size() << \" \" << (D.empty() ? \"empty\" : \"notempty\") << std::endl;\n return std::make_pair(Bd, std::vector<Vertex>(U.begin(), U.end()));\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::base_case(Length B, const std::vector<Vertex>& S) {\n assert(S.size() == 1);\n\n Vertex x = S[0];\n // std::cout << \"base_case k=\" << k_ << \", t=\" << t_ << \", B=\" << B << \", x=\" << x << std::endl; \n\n std::unordered_set<Vertex> U0(S.begin(), S.end());\n Heap H;\n H.push(x, dhat_[x]);\n\n while(!H.empty() && (int)U0.size() < k_ + 1) {\n auto p = H.top(); H.pop();\n Vertex u = p.first; Length d = p.second;\n U0.insert(u);\n\n for(int i = 0; i < (int)G_[u].size(); i++) {\n int v = G_[u][i].first; Length w = G_[u][i].second;\n if(dhat_[v] >= dhat_[u] + w && dhat_[u] + w < B) {\n dhat_[v] = dhat_[u] + w;\n H.push(v, dhat_[v]);\n }\n }\n // H.debug();\n }\n\n if((int)U0.size() <= k_) {\n return make_pair(B, std::vector<Vertex>(U0.begin(), U0.end()));\n } else {\n Length Bd = -INF;\n std::vector<Vertex> U;\n for(auto u: U0) {\n Bd = std::max(Bd, dhat_[u]);\n }\n for(auto u: U0) {\n if(dhat_[u] < Bd) {\n U.push_back(u);\n }\n }\n return make_pair(Bd, U);\n }\n}\n\n\nstd::pair<std::vector<Vertex>, std::vector<Vertex>> ShortestPath::find_pivots(Length B, const std::vector<Vertex>& S) {\n std::unordered_set<Vertex> W(S.begin(), S.end());\n std::vector<Vertex> Wp = S;\n\n for(auto v: W) {\n prev_[v] = -1;\n }\n\n for(int i = 0; i < k_; i++) {\n std::vector<Vertex> Wi; \n for(int j = 0; j < (int)Wp.size(); j++) {\n Vertex u = Wp[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n dhat_[v] = dhat_[u] + w;\n prev_[v] = u;\n // if(dhat_[u] + w < B) {\n Wi.push_back(v);\n // }\n }\n }\n }\n for(int k = 0; k < (int)Wi.size(); k++) {\n W.insert(Wi[k]);\n }\n if((int)W.size() >= k_ * (int)S.size()) {\n return std::make_pair(S, std::vector<Vertex>(W.begin(), W.end()));\n }\n Wp = Wi;\n // std::cout << \"Wp =\"; debug_vertex_set(Wp);\n }\n\n for(auto v: W) {\n tree_size_[v] = -1;\n F_[v].clear();\n }\n for(auto v: W) {\n Vertex u = prev_[v];\n if(u == -1) continue;\n F_[u].push_back(v);\n }\n std::vector<Vertex> P;\n for(int i = 0; i < (int)S.size(); i++) {\n Vertex u = S[i];\n // std::cout << \"find_tree_size: \" << u << \" \" << find_tree_size(u, tree_size_, F_) << std::endl;\n if(find_tree_size(u, tree_size_, F_) >= k_ && prev_[u] == -1) {\n P.push_back(u);\n }\n }\n return std::make_pair(P, std::vector<Vertex>(W.begin(), W.end()));\n}\n\n\n\n\nvoid find_shortest_path(int s, const Graph& G) {\n int N = (int)G.size();\n double t = std::floor(std::pow(std::log2(N), 2.0 / 3.0));\n double l = std::ceil(std::log2(N) / t);\n ShortestPath shortest_path(s, G);\n std::vector<Vertex> S;\n S.push_back(s);\n auto bu = shortest_path.BMSSP(l, INF, S);\n // std::cout << \"Bfinal:=\" << bu.first << std::endl;\n shortest_path.print_dhat();\n}\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n int N, M, s;\n std::cin >> N >> M >> s;\n Graph G(N);\n for(int i = 0; i < M; i++) {\n int a, b; Length c;\n std::cin >> a >> b >> c;\n G[a].push_back(std::make_pair(b, c));\n }\n find_shortest_path(s, G);\n return 0;\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 42216, "score_of_the_acc": -0.8095, "final_rank": 13 }, { "submission_id": "aoj_GRL_1_A_11026292", "code_snippet": "#include <iostream>\n#include<vector>\n#include<list>\n#include<utility>\n#include<limits>\n#include<set>\n#include<iostream>\n#include<queue>\n#include<unordered_map>\n#include<unordered_set>\n#include<random>\n#include<ext/pb_ds/assoc_container.hpp>\n\nusing T = long long;\nnamespace spp {\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntemplate<typename K, typename V>\nusing hash_map = unordered_map<K, V>;\ntemplate<typename K>\nusing hash_set = unordered_set<K>;\n\ntemplate<typename uniqueDistT>\nstruct batchPQ { // batch priority queue, implemented as in Lemma 3.3\n using elementT = pair<int,uniqueDistT>;\n \n struct CompareUB {\n template <typename It>\n bool operator()(const pair<uniqueDistT, It>& a, const pair<uniqueDistT, It>& b) const {\n if (a.first != b.first) return a.first < b.first;\n return addressof(*a.second) < addressof(*b.second);\n }\n };\n \n typename list<list<elementT>>::iterator it_min;\n \n list<list<elementT>> D0,D1;\n set<pair<uniqueDistT,typename list<list<elementT>>::iterator>,CompareUB> UBs; // (UB, it_block)\n \n int M,size_;\n uniqueDistT B;\n \n hash_map<int, uniqueDistT> actual_value;\n hash_map<int, pair< typename list<list<elementT>>::iterator , typename list<elementT>::iterator> > where_is[2];\n \n // Initialize\n batchPQ(int M_, uniqueDistT B_): M(M_), B(B_) { // O(1)\n D1.push_back(list<elementT>());\n UBs.insert({B_,D1.begin()});\n size_ = 0;\n }\n \n int size(){\n return size_;\n }\n \n inline void erase(int key) {\n if(actual_value.find(key) != actual_value.end())\n delete_({-1, -1, key, -1});\n }\n void delete_(uniqueDistT x){ \n int a = get<2>(x);\n uniqueDistT b = actual_value[a];\n \n auto it_w = where_is[1].find(a);\n if((it_w != where_is[1].end())){\n auto [it_block,it] = it_w->second;\n \n (*it_block).erase(it);\n where_is[1].erase(a);\n \n if((*it_block).size() == 0){\n auto it_UB_block = UBs.lower_bound({b,it_block}); \n \n if((*it_UB_block).first != B){\n UBs.erase(it_UB_block);\n D1.erase(it_block);\n }\n }\n }else{\n auto [it_block,it] = where_is[0][a];\n (*it_block).erase(it);\n where_is[0].erase(a);\n if((*it_block).size() == 0) D0.erase(it_block); \n }\n \n actual_value.erase(a);\n size_--;\n }\n \n void insert(uniqueDistT x){ // O(lg(Block Numbers)) \n uniqueDistT b = x;\n int a = get<2>(b);\n \n // checking if exists\n auto it_exist = actual_value.find(a);\n int exist = (it_exist != actual_value.end()); \n \n if(exist && it_exist->second > b){\n delete_(x);\n }else if(exist){\n return;\n }\n \n // Searching for the first block with UB which is > \n auto it_UB_block = UBs.lower_bound({b,it_min});\n auto [ub,it_block] = (*it_UB_block);\n \n // Inserting key/value (a,b)\n auto it = it_block->insert(it_block->end(),{a,b});\n where_is[1][a] = {it_block, it};\n actual_value[a] = b;\n \n size_++;\n \n // Checking if exceeds the sixe limit M\n if((*it_block).size() > M){\n split(it_block);\n }\n }\n\n uniqueDistT medianOfMedians(vector<elementT>::iterator bg, vector<elementT>::iterator en) {\n vector<elementT> l(bg, en);\n while (true) {\n int n = l.size();\n\n if (n <= 5) {\n sort(l.begin(), l.end(), [](const auto& a, const auto& b) {\n return a.second < b.second;\n });\n return l[l.size() / 2].second;\n }\n\n vector<elementT> medians;\n medians.reserve((n + 4) / 5);\n\n auto it = l.begin();\n while (it != l.end()) {\n vector<elementT> group;\n group.reserve(5);\n for (int j = 0; j < 5 && it != l.end(); ++j, ++it)\n group.push_back(*it);\n\n sort(group.begin(), group.end(), [](const auto& a, const auto& b) {\n return a.second < b.second;\n });\n\n medians.push_back(group[group.size() / 2]);\n }\n\n l = move(medians);\n }\n }\n \n uniqueDistT selectKth(vector<elementT> &v, int k) { \n using std::swap;\n int l=0, r=v.size()-1;\n \n for(;l<=r;){\n uniqueDistT p = medianOfMedians(v.begin() + l, v.begin() + r + 1);\n \n int i = l, j = r, m = l;\n \n while(m <= j){\n if(v[m].second < p) {\n swap(v[m++],v[i++]);\n }else if(v[m].second > p){\n swap(v[m],v[j--]);\n }else{\n m++;\n }\n }\n \n if (k < i) r = i - 1; // k está na parte menor\n else if (k > j) l = j + 1; // k está na parte maior\n else return v[k].second; // k está entre os iguais ao pivot\n } \n \n return v[k].second;\n }\n\n \n void split(list<list<elementT>>::iterator it_block){ // O(M) + O(lg(Block Numbers))\n int sz = (*it_block).size();\n \n vector<elementT> v((*it_block).begin() , (*it_block).end());\n uniqueDistT med = selectKth(v,(sz/2)); // O(M)\n \n auto pos = it_block;\n pos++;\n\n\n auto new_block = D1.insert(pos,list<elementT>());\n auto it = (*it_block).begin();\n \n while(it != (*it_block).end()){ // O(M)\n if((*it).second >= med){\n // (*new_block).push_back((*it));\n (*new_block).push_back(move(*it));\n auto it_new = (*new_block).end(); it_new--;\n where_is[1][(*it).first] = {new_block, it_new};\n \n it = (*it_block).erase(it);\n }else{\n it++;\n }\n }\n \n\n // Updating UBs \n // O(lg(Block Numbers))\n uniqueDistT UB1 = {get<0>(med),get<1>(med),get<2>(med),get<3>(med)-1};\n auto it_lb = UBs.lower_bound({UB1,it_min});\n auto [UB2,aux] = (*it_lb);\n \n UBs.insert({UB1,it_block});\n UBs.insert({UB2,new_block});\n \n UBs.erase(it_lb);\n }\n \n void batchPrepend(const list<elementT> &l) { // O(|l| log(|l|/M) ) \n int sz = l.size();\n \n if(sz == 0) return;\n if(sz <= M){\n \n D0.push_front(list<elementT>());\n auto new_block = D0.begin();\n \n for(auto &x : l){ \n auto it = actual_value.find(x.first);\n int exist = (it != actual_value.end()); \n \n if(exist && it->second > x.second){\n delete_(x.second);\n }else if(exist){\n continue;\n }\n \n (*new_block).push_back(x);\n auto it_new = (*new_block).end(); it_new--;\n where_is[0][x.first] = {new_block, it_new};\n actual_value[x.first] = x.second;\n size_++;\n }\n if(new_block->size() == 0) D0.erase(new_block);\n return;\n }\n\n vector<elementT> v(l.begin(), l.end());\n uniqueDistT med = selectKth(v, sz/2);\n \n list<elementT> less,great;\n for(auto [a,b]: l){\n if(b < med){\n less.push_back({a,b});\n }else if(b > med){\n great.push_back({a,b});\n }\n }\n \n great.push_back({get<2>(med),med});\n\n batchPrepend(great);\n batchPrepend(less);\n }\n \n void batchPrepend(const vector<uniqueDistT> &v){\n list<elementT> l;\n for(auto x: v){\n l.push_back({get<2>(x),x});\n }\n batchPrepend(l);\n }\n \n pair<uniqueDistT, vector<int>> pull(){ // O(M)\n vector<elementT> s0,s1;\n s0.reserve(2 * M); s1.reserve(M);\n \n auto it_block = D0.begin();\n while(it_block != D0.end() && s0.size() <= M){ // O(M) \n for (const auto& x : *it_block) s0.push_back(x);\n it_block++;\n }\n \n it_block = D1.begin();\n while(it_block != D1.end() && s1.size() <= M){ //O(M)\n for (const auto& x : *it_block) s1.push_back(x);\n it_block++;\n }\n \n if(s1.size() + s0.size() <= M){\n vector<int> ret;\n ret.reserve(s1.size()+s0.size());\n for(auto [a,b] : s0) {\n ret.push_back(a);\n delete_({b});\n }\n for(auto [a,b] : s1){\n ret.push_back(a);\n delete_({b});\n } \n \n return {B, ret};\n }else{ \n vector<elementT> &l = s0;\n l.insert(l.end(), s1.begin(), s1.end());\n\n uniqueDistT med = selectKth(l, M);\n vector<int> ret;\n ret.reserve(M);\n for(auto [a,b]: l){\n if(b < med) {\n ret.push_back(a);\n delete_({b});\n }\n }\n \n return {med,ret};\n }\n }\n};\n\ntemplate<typename wT>\nstruct bmssp { // bmssp class\n int n, k, t;\n const wT oo = numeric_limits<wT>::max() / 10;\n \n vector<vector<pair<int, wT>>> ori_adj;\n vector<vector<pair<int, wT>>> adj;\n vector<wT> d;\n vector<int> pred, path_sz;\n vector<int> rev_map;\n vector<short int> last_complete_lvl;\n \n vector<hash_map<int, int>> neig;\n bmssp(int n_): n(n_) {\n ori_adj.assign(n, {});\n neig.assign(n, {});\n }\n bmssp(const auto &adj) {\n n = adj.size();\n ori_adj = adj;\n neig.assign(n, {});\n }\n void addEdge(int a, int b, wT w) {\n ori_adj[a].emplace_back(b, w);\n }\n\n // if the graph already has constant degree, prepage_graph(false)\n // else, prepage_graph(true)\n void prepare_graph(bool exec_constant_degree_trasnformation = false) {\n // erase duplicated edges\n vector<pair<int, int>> tmp_edges(n, {-1, -1});\n for(int i = 0; i < n; i++) {\n vector<pair<int, wT>> nw_adj;\n nw_adj.reserve(ori_adj[i].size());\n for(auto [j, w]: ori_adj[i]) {\n if(tmp_edges[j].first != i) {\n nw_adj.emplace_back(j, w);\n tmp_edges[j] = {i, nw_adj.size() - 1};\n } else {\n int id = tmp_edges[j].second;\n nw_adj[id].second = min(nw_adj[id].second, w);\n }\n }\n ori_adj[i] = move(nw_adj);\n }\n tmp_edges.clear();\n\n if(exec_constant_degree_trasnformation == false) {\n adj = move(ori_adj);\n ori_adj.clear();\n d.resize(n);\n root.resize(n);\n pred.resize(n);\n treesz.resize(n);\n rev_map.resize(n);\n path_sz.resize(n, 0);\n last_complete_lvl.resize(n);\n \n for(int i = 0; i < n; i++) {\n neig[i][i] = i;\n rev_map[i] = i;\n }\n\n k = floor(pow(log2(n), 1.0 / 3.0));\n t = floor(pow(log2(n), 2.0 / 3.0));\n } else {\n // Make the graph become constant degree\n int cnt = 0;\n for(int i = 0; i < n; i++) {\n for(auto [j, w]: ori_adj[i]) {\n if(neig[i].find(j) == neig[i].end()) {\n neig[i][j] = cnt++;\n neig[j][i] = cnt++;\n }\n }\n }\n\n cnt++;\n adj.assign(cnt, {});\n \n d.resize(cnt);\n root.resize(cnt);\n pred.resize(cnt);\n treesz.resize(cnt);\n rev_map.resize(cnt);\n path_sz.resize(cnt, 0);\n last_complete_lvl.resize(cnt);\n \n for(int i = 0; i < n; i++) { // create 0-weight cycles\n for(auto cur = neig[i].begin(); cur != neig[i].end(); cur++) {\n auto nxt = next(cur);\n if(nxt == neig[i].end()) nxt = neig[i].begin();\n adj[cur->second].emplace_back(nxt->second, wT());\n rev_map[cur->second] = i;\n }\n }\n for(int i = 0; i < n; i++) { // add edges\n for(auto [j, w]: ori_adj[i]) {\n adj[neig[i][j]].emplace_back(neig[j][i], w);\n }\n if(neig[i].size() == 0) { // for vertices without edges\n neig[i][n] = cnt - 1;\n }\n }\n k = floor(pow(log2(cnt), 1.0 / 3.0));\n t = floor(pow(log2(cnt), 2.0 / 3.0));\n \n ori_adj.clear();\n }\n }\n \n int toAnyCustomNode(int real_id) {\n return neig[real_id].begin()->second;\n }\n int customToReal(int id) {\n return rev_map[id];\n }\n \n vector<wT> execute(int s) {\n fill(d.begin(), d.end(), oo);\n fill(path_sz.begin(), path_sz.end(), oo);\n fill(last_complete_lvl.begin(), last_complete_lvl.end(), -1);\n for(int i = 0; i < pred.size(); i++) pred[i] = i;\n \n s = toAnyCustomNode(s);\n d[s] = 0;\n path_sz[s] = 0;\n \n const int l = ceil(log2(adj.size()) / t);\n const uniqueDistT inf_dist = make_tuple(oo, 0, 0, 0);\n bmsspRec(l, inf_dist, {s});\n \n vector<wT> res(n);\n for(int i = 0; i < n; i++) res[i] = d[toAnyCustomNode(i)];\n return res;\n }\n \n // ===================================================================\n \n // set stuff\n // template<typename T>\n // void removeDuplicates(vector<T> &v) { // sort is faster\n // hash_set<T> s(v.begin(), v.end());\n // v = vector<T>(s.begin(), s.end());\n // // sort(v.begin(), v.end());\n // // v.erase(unique(v.begin(), v.end()), v.end());\n // }\n template<typename T>\n bool isUnique(const vector<T> &v) {\n auto v2 = v;\n sort(v2.begin(), v2.end());\n v2.erase(unique(v2.begin(), v2.end()), v2.end());\n return v2.size() == v.size();\n }\n\n using uniqueDistT = tuple<wT, int, int, int>;\n inline uniqueDistT getDist(int u, int v, int w) {\n return {d[u] + w, path_sz[u] + 1, v, u};\n }\n inline uniqueDistT getDist(int u) {\n return {d[u], path_sz[u], u, pred[u]};\n }\n void updateDist(int u, int v, wT w) {\n pred[v] = u;\n d[v] = d[u] + w;\n path_sz[v] = path_sz[u] + 1;\n }\n // ===================================================================\n vector<int> root;\n vector<short int> treesz;\n pair<vector<int>, hash_set<int>> findPivots(uniqueDistT B, const vector<int> &S) { // Algorithm 1\n hash_set<int> vis;\n vis.reserve(S.size() * k);\n vis.insert(S.begin(), S.end());\n\n vector<int> active = S;\n for(int x: S) root[x] = x, treesz[x] = 0;\n for(int i = 1; i <= k; i++) {\n vector<int> nw_active;\n nw_active.reserve(active.size() * 4);\n for(int u: active) {\n for(auto [v, w]: adj[u]) {\n if(getDist(u, v, w) <= getDist(v)) {\n updateDist(u, v, w);\n if(getDist(v) < B) {\n root[v] = root[u];\n nw_active.push_back(v);\n }\n }\n }\n }\n for(const auto &x: nw_active) {\n vis.insert(x);\n }\n if(vis.size() > k * S.size()) {\n return {S, vis};\n }\n active = move(nw_active);\n }\n\n vector<int> P;\n P.reserve(vis.size() / k);\n for(int u: vis) treesz[root[u]]++;\n for(int u: S) if(treesz[u] >= k) P.push_back(u);\n \n // assert(P.size() <= vis.size() / k);\n return {P, vis};\n }\n \n pair<uniqueDistT, vector<int>> baseCase(uniqueDistT B, int x) { // Algorithm 2\n vector<int> complete;\n complete.reserve(k + 1);\n \n priority_queue<uniqueDistT, vector<uniqueDistT>, greater<uniqueDistT>> heap;\n heap.push(getDist(x));\n while(heap.empty() == false && complete.size() < k + 1) {\n int u = get<2>(heap.top());\n int du = get<0>(heap.top());\n heap.pop();\n if(du > d[u]) continue;\n\n complete.push_back(u);\n for(auto [v, w]: adj[u]) {\n auto new_dist = getDist(u, v, w);\n auto old_dist = getDist(v);\n if(new_dist <= old_dist && new_dist < B) {\n updateDist(u, v, w);\n heap.push(new_dist);\n }\n }\n }\n if(complete.size() <= k) return {B, complete};\n \n uniqueDistT nB = getDist(complete.back());\n // { // sanity check\n // int cntbig = 0;\n // for(int u: complete) if(getDist(u) >= nB) cntbig++;\n // assert(cntbig == 1);\n // for(int u: complete) assert(getDist(u) < B);\n // assert(complete.size() == k + 1);\n // }\n complete.pop_back();\n return {nB, complete};\n }\n \n pair<uniqueDistT, vector<int>> bmsspRec(short int l, uniqueDistT B, const vector<int> &S) { // Algorithm 3\n if(l == 0) return baseCase(B, S[0]);\n \n auto [P, bellman_vis] = findPivots(B, S);\n \n const long long batch_size = (1ll << ((l - 1) * t));\n batchPQ<uniqueDistT> D(batch_size, B);\n for(int p: P) D.insert(getDist(p));\n \n uniqueDistT last_complete_B = B;\n for(int p: P) last_complete_B = min(last_complete_B, getDist(p));\n \n vector<int> complete;\n const long long quota = k * (1ll << (l * t));\n complete.reserve(quota + bellman_vis.size());\n while(complete.size() < quota && D.size()) {\n auto [trying_B, miniS] = D.pull();\n // all with dist < trying_B, can be reached by miniS <= req 2, alg 3\n \n auto [complete_B, nw_complete] = bmsspRec(l - 1, trying_B, miniS);\n \n // all new complete_B are greater than the old ones <= point 6, page 10\n // assert(last_complete_B < complete_B);\n \n complete.insert(complete.end(), nw_complete.begin(), nw_complete.end());\n // point 6, page 10 => complete does not intersect with nw_complete\n // assert(isUnique(complete));\n \n vector<uniqueDistT> can_prepend;\n can_prepend.reserve(nw_complete.size() * 5 + miniS.size());\n for(int u: nw_complete) {\n D.erase(u); // priority queue fix\n last_complete_lvl[u] = l;\n for(auto [v, w]: adj[u]) {\n auto new_dist = getDist(u, v, w);\n if(new_dist <= getDist(v)) {\n updateDist(u, v, w);\n if(trying_B <= new_dist && new_dist < B) {\n D.insert(new_dist); // d[v] can be greater equal than min(D), occur 1x per vertex\n } else if(complete_B <= new_dist && new_dist < trying_B) {\n can_prepend.emplace_back(new_dist); // d[v] is less than all in D, can occur 1x at each level per vertex\n }\n }\n }\n }\n for(int x: miniS) {\n if(complete_B <= getDist(x)) can_prepend.emplace_back(getDist(x));\n // second condition is not necessary\n }\n // can_prepend is not necessarily all unique\n D.batchPrepend(can_prepend);\n \n last_complete_B = complete_B;\n }\n uniqueDistT retB;\n if(D.size() == 0) retB = B; // successful\n else retB = last_complete_B; // partial\n \n for(int x: bellman_vis) if(last_complete_lvl[x] != l && getDist(x) < retB) complete.push_back(x); // this get the completed vertices from bellman-ford, it has P in it as well\n // get only the ones not in complete already, for it to become disjoint\n \n return {retB, complete};\n }\n};\n}\n\nint main() {\n int n, m, s;\n std::cin >> n >> m >> s;\n std::vector<std::tuple<int, int, T>> edges;\n while (m --)\n {\n int u, v, w;\n std::cin >> u >> v >> w;\n edges.push_back({u, v, w});\n }\n \n // std::vector<std::tuple<int, int, T>> edges = {\n // {0, 1, 10}, {0, 2, 3}, {1, 3, 2}, {2, 1, 4},\n // {2, 3, 8}, {2, 4, 2}, {3, 4, 5}\n // };\n int source_node = s;\n\n // 2. Initialize and build the graph\n spp::bmssp<T> solver(n);\n for (const auto& [u, v, weight] : edges) {\n solver.addEdge(u, v, weight);\n }\n\n // 3. Prepare the graph (must be called once)\n solver.prepare_graph(false);\n // use solver.prepare_graph(true) if the graph does not have contant out-degree\n\n // 4. Compute shortest paths\n std::vector<T> distances = solver.execute(source_node);\n\n // 5. Print results\n // std::cout << \"Shortest paths from source \" << source_node << \":\" << std::endl;\n for (int i = 0; i < n; ++i) {\n if (distances[i] == solver.oo) {\n std::cout << \"INF\" << '\\n';\n } else {\n std::cout << distances[i] << '\\n';\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 56532, "score_of_the_acc": -1.2208, "final_rank": 19 }, { "submission_id": "aoj_GRL_1_A_11025123", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define oke cout << \"Yes\" << '\\n';\n#define dame cout << \"No\" << '\\n';\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\nusing Hai2 = vector<vector<ll>>;\nusing HaiW = vector<vector<pair<ll,ll>>>;\nusing HaiB = vector<vector<bool>>;\nusing Hai3 = vector<vector<vector<ll>>>;\n\n\nint main() {\n\tcout << fixed << setprecision(15);\n ll N,M,R;\n cin>>N>>M>>R;\n vector<vector<pair<ll,ll>>> G(N);\n rep(i,M){\n ll a,b,c;\n cin>>a>>b>>c;\n G[a].push_back({b,c});\n }\n\n queue<int>Q;\n vector<ll>dist(N,1e9);\n\n Q.push(R);\n dist[R]=0;\n\n while(!Q.empty()){\n int v = Q.front();\n Q.pop();\n for(auto x:G[v]){\n if(dist[x.first]>dist[v]+x.second){\n dist[x.first]=dist[v]+x.second;\n Q.push(x.first);\n }\n }\n }\n\n rep(i,N){\n if(dist[i]!=1e9){\n cout<<dist[i]<<endl;\n }else{\n cout<<\"INF\"<<endl;\n }\n }\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 17756, "score_of_the_acc": -0.3272, "final_rank": 9 }, { "submission_id": "aoj_GRL_1_A_10999121", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\nusing ll=long long;\nconst ll INF=1ll<<60;\nint main(){\n int v,e,r;\n cin>>v>>e>>r;\n vector<vector<pair<int,int>>>g(v,vector<pair<int,int>>());\n rep(i,e){\n int s,t,d;\n cin>>s>>t>>d;\n g[s].push_back({t,d});\n }\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>q;\n q.push({0,r});\n vector<int>dist(v,2e9);\n dist[r]=0;\n while(!q.empty()){\n auto [a,v]=q.top();\n q.pop();\n for(auto [next_v,cost]:g[v]){\n if(dist[next_v]>dist[v]+cost){\n dist[next_v]=dist[v]+cost;\n q.push({dist[next_v],next_v});\n }\n }\n }\n for(auto p:dist){\n if(p!=2e9)cout<<p<<endl;\n else cout<<\"INF\"<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 13144, "score_of_the_acc": -0.2209, "final_rank": 4 }, { "submission_id": "aoj_GRL_1_A_10989458", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n\nstruct Edge\n{\n\tint to; // 接続先ノードのID\n\tlong long cost; // 接続先ノードまでのコスト\n\n\tEdge(int to, long long cost)\n\t{\n\t\tthis->to = to;\n\t\tthis->cost = cost;\n\t}\n\n\tbool operator>(const Edge& other) const\n\t{\n\t\treturn this->cost > other.cost;\n\t}\n};\n\nusing Graph = std::vector<std::vector<Edge>>;\nconstexpr long long INF = 1LL << 60;\n\nvoid Dijkstra(const Graph& graph, std::vector<long long>& dist, int start)\n{\n\tstd::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> queue;\n\tdist.assign(graph.size(), INF);\n\n\tdist[start] = 0;\n\tqueue.push({start, 0});\n\n\twhile (!queue.empty()) {\n\t\tEdge edge = queue.top();\n\t\tqueue.pop();\n\t\tif (edge.cost > dist[edge.to]) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const Edge& e : graph[edge.to]) {\n\t\t\tlong long nextDist = dist[edge.to] + e.cost;\n\t\t\tif (nextDist < dist[e.to]) {\n\t\t\t\tdist[e.to] = nextDist;\n\t\t\t\tqueue.push({e.to, nextDist});\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main()\n{\n\tint V, E, r;\n\tstd::cin >> V >> E >> r;\n\tGraph graph(V);\n\tfor (int i = 0; i < E; ++i) {\n\t\tint from, to, cost;\n\t\tstd::cin >> from >> to >> cost;\n\t\tgraph[from].push_back({to, cost});\n\t}\n\n\tstd::vector<long long> dist;\n\tDijkstra(graph, dist, r);\n\n\tfor (int i = 0; i < V; ++i) {\n\t\tif (dist[i] == INF) {\n\t\t\tstd::cout << \"INF\" << std::endl;\n\n\t\t}\n\t\telse {\n\t\t\tstd::cout << dist[i] << std::endl;\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 19672, "score_of_the_acc": -0.383, "final_rank": 12 }, { "submission_id": "aoj_GRL_1_A_10989435", "code_snippet": "#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"inline\",\"fast-math\",\"unroll-loops\",\"no-stack-protector\")\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <map>\n#include <algorithm>\n#include <cassert>\n\nusing Vertex = int;\nusing Length = long long;\nconst Length INF = std::numeric_limits<long long>::max();\nusing Edge = std::pair<Vertex, Length>;\nusing Graph = std::vector<std::vector<Edge>>;\n\nclass BlockHeap {\n public:\n BlockHeap(int M, Length B);\n void insert(Vertex v, Length l);\n void batch_prepend(const std::vector<std::pair<Vertex, Length>>& L);\n std::pair<Length ,std::vector<Vertex>> pull();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n std::set<std::pair<Length, Vertex>> que_;\n std::unordered_map<Vertex, Length> d_;\n};\n\nBlockHeap::BlockHeap(int M, Length B) {\n M_ = M;\n B_ = B;\n}\n\nstd::pair<Length, std::vector<Vertex>> BlockHeap::pull() {\n std::vector<Vertex> S;\n for(int i = 0; i < M_; i++) {\n if(que_.empty()) {\n break;\n }\n std::pair<Length, Vertex> p = *que_.begin();\n que_.erase(p);\n d_.erase(p.second);\n S.push_back(p.second);\n }\n if(que_.empty()) {\n return std::make_pair(B_, S);\n } else {\n return std::make_pair(que_.begin()->first, S);\n }\n}\n\nvoid BlockHeap::batch_prepend(const std::vector<std::pair<Vertex, Length>>& L) {\n for(int i = 0; i < (int)L.size(); i++) {\n insert(L[i].first, L[i].second);\n }\n}\n\nvoid BlockHeap::insert(Vertex v, Length l) {\n if(d_.count(v) != 0 && d_[v] < l) {\n return;\n } else if (d_.count(v) != 0 && d_[v] >= l) {\n que_.erase(std::make_pair(d_[v], v));\n }\n que_.insert(std::make_pair(l, v));\n d_[v] = l;\n}\n\nbool BlockHeap::empty() {\n return que_.empty();\n}\n\nvoid BlockHeap::debug() {\n std::cout << \"D= [\";\n for(auto p: que_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass Heap {\n public:\n void push(Vertex v, Length l);\n std::pair<Vertex, Length> top();\n void pop();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n std::set<std::pair<Length, Vertex>> que_;\n std::unordered_map<Vertex, Length> d_;\n\n};\n\nvoid Heap::push(Vertex v, Length l) {\n if(d_.count(v) != 0 && d_[v] < l) {\n return;\n } else if (d_.count(v) != 0 && d_[v] >= l) {\n que_.erase(std::make_pair(d_[v], v));\n }\n que_.insert(std::make_pair(l, v));\n d_[v] = l;\n}\n\nstd::pair<Vertex, Length> Heap::top() {\n auto p = *que_.begin();\n return std::make_pair(p.second, p.first);\n}\n\nvoid Heap::pop() {\n d_.erase(top().second);\n que_.erase(que_.begin());\n}\n\nbool Heap::empty() {\n return que_.empty();\n}\n\nvoid Heap::debug() {\n std::cout << \"H= [\";\n for(auto p: que_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass ShortestPath {\n public:\n ShortestPath(Vertex s, const Graph& G);\n std::pair<Length, std::vector<Vertex>> BMSSP(int l, Length B, const std::vector<Vertex>& S);\n std::pair<std::vector<Vertex>, std::vector<Vertex>> find_pivots(Length B, const std::vector<Vertex>& S);\n void print_dhat();\n\n private:\n int t_;\n int k_;\n std::vector<Length> dhat_;\n Graph G_;\n\n std::pair<Length, std::vector<Vertex>> base_case(Length B, const std::vector<Vertex>& S);\n\n std::vector<Vertex> prev_;\n std::vector<int> tree_size_;\n std::vector<std::vector<Vertex>> F_;\n};\n\nShortestPath::ShortestPath(Vertex s, const Graph& G) {\n G_ = G;\n int N = G_.size();\n k_ = std::ceil(pow(std::log2(N), 1.0 / 3.0));\n t_ = std::floor(pow(std::log2(N), 2.0 / 3.0));\n dhat_ = std::vector<Length>(N, INF);\n dhat_[s] = 0;\n prev_ = std::vector<Vertex>(N, -1);\n tree_size_ = std::vector<Vertex>(N, -1);\n F_ = std::vector<std::vector<Vertex>>(N, std::vector<Vertex>());\n}\n\nnamespace {\n int find_tree_size(int u, std::vector<int>& tree_size, const std::vector<std::vector<Vertex>>& F) {\n if(tree_size[u] != -1) return tree_size[u];\n int res = 1;\n for(int i = 0; i < (int)F[u].size(); i++) {\n Vertex v = F[u][i];\n res += find_tree_size(v, tree_size, F);\n }\n return tree_size[u] = res;\n }\n\n void debug_vertex_set(std::vector<Vertex> S) {\n std::cout << \"[\";\n for(int i = 0; i < (int)S.size(); i++) {\n std::cout << S[i] << \", \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nvoid ShortestPath::print_dhat() {\n for(int i = 0; i < (int)dhat_.size(); i++) {\n if(dhat_[i] == INF) {\n std::cout << \"INF\" << '\\n';\n } else {\n std::cout << dhat_[i] << '\\n';\n }\n }\n // std::cout << \"[\";\n // for(int i = 0; i < (int)dhat_.size(); i++) {\n // if(dhat_[i] == INF) {\n // std::cout << \"INF\" << \", \";\n // } else {\n // std::cout << dhat_[i] << \", \";\n // }\n // }\n // std::cout << \"]\" << std::endl;\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::BMSSP(int l, Length B, const std::vector<Vertex>& S) {\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", S=\";\n // debug_vertex_set(S);\n // print_dhat();\n if(l == 0) {\n return base_case(B, S);\n }\n auto pw = find_pivots(B, S);\n std::vector<Vertex> P = pw.first; std::vector<Vertex> W = pw.second;\n // std::cout << \"P= \"; debug_vertex_set(P);\n // std::cout << \"W= \"; debug_vertex_set(W);\n\n int M = std::pow(2, (l - 1) * t_);\n BlockHeap D(M, B);\n Length Bd = INF;\n for(int i = 0; i < (int)P.size(); i++) {\n Vertex u = P[i];\n D.insert(u, dhat_[u]);\n Bd = std::min(Bd, dhat_[u]);\n }\n // D.debug();\n std::unordered_set<Vertex> U;\n\n while((int)U.size() < k_ * std::pow(2, l * t_) && !D.empty()) {\n auto bs = D.pull();\n Length Bi = bs.first; std::vector<Vertex> Si = bs.second;\n auto bu = BMSSP(l - 1, Bi, Si);\n Length Bid = bu.first; std::vector<Vertex> Ui = bu.second;\n // std::cout << \"Bid=\" << Bid << std::endl;\n // std::cout << \"Ui=\"; debug_vertex_set(Ui);\n // std::cout << \"U=\"; debug_vertex_set(std::vector<Vertex>(U.begin(), U.end()));\n for(int j = 0; j < (int)Ui.size(); j++) {\n // if(U.count(Ui[j]) != 0) {\n // std::cout << \"Ufound\" << \" \" << Ui[j] << \" \" << dhat_[Ui[j]] << \" \" << Bi << \" \" << Bid << std::endl;\n // }\n U.insert(Ui[j]);\n }\n\n std::vector<std::pair<Vertex, Length>> K;\n for(int j = 0; j < (int)Ui.size(); j++) {\n Vertex u = Ui[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n Length new_dist = dhat_[u] + w;\n dhat_[v] = new_dist;\n if(Bi <= new_dist && new_dist < B) {\n D.insert(v, new_dist);\n } else if(Bid <= new_dist && new_dist < Bi) {\n K.push_back(std::make_pair(v, new_dist));\n }\n }\n }\n }\n for(int i = 0; i < (int)Si.size(); i++) {\n int u = Si[i];\n if(Bid <= dhat_[u] && dhat_[u] < Bi) K.push_back(std::make_pair(u, dhat_[u]));\n }\n D.batch_prepend(K);\n Bd = Bid;\n }\n Bd = std::min(Bd, B);\n for(int i = 0; i < (int)W.size(); i++) {\n Vertex u = W[i];\n if(dhat_[u] < Bd) U.insert(u);\n }\n if(l == 3) {\n for(int i = 0; i < (int)G_.size(); i++) {\n // if(!U.count(i) && dhat_[i] != INF) {\n // std::cout << \"found: \" << i << \" \" << dhat_[i] << std::endl;\n // }\n }\n }\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", Bd=\" << Bd << std::endl;\n // std::cout << \"U size:=\" << U.size() << \" \" << (D.empty() ? \"empty\" : \"notempty\") << std::endl;\n return std::make_pair(Bd, std::vector<Vertex>(U.begin(), U.end()));\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::base_case(Length B, const std::vector<Vertex>& S) {\n assert(S.size() == 1);\n\n Vertex x = S[0];\n // std::cout << \"base_case k=\" << k_ << \", t=\" << t_ << \", B=\" << B << \", x=\" << x << std::endl; \n\n std::unordered_set<Vertex> U0(S.begin(), S.end());\n Heap H;\n H.push(x, dhat_[x]);\n\n while(!H.empty() && (int)U0.size() < k_ + 1) {\n auto p = H.top(); H.pop();\n Vertex u = p.first; Length d = p.second;\n U0.insert(u);\n\n for(int i = 0; i < (int)G_[u].size(); i++) {\n int v = G_[u][i].first; Length w = G_[u][i].second;\n if(dhat_[v] >= dhat_[u] + w && dhat_[u] + w < B) {\n dhat_[v] = dhat_[u] + w;\n H.push(v, dhat_[v]);\n }\n }\n // H.debug();\n }\n\n if((int)U0.size() <= k_) {\n return make_pair(B, std::vector<Vertex>(U0.begin(), U0.end()));\n } else {\n Length Bd = -INF;\n std::vector<Vertex> U;\n for(auto u: U0) {\n Bd = std::max(Bd, dhat_[u]);\n }\n for(auto u: U0) {\n if(dhat_[u] < Bd) {\n U.push_back(u);\n }\n }\n return make_pair(Bd, U);\n }\n}\n\n\nstd::pair<std::vector<Vertex>, std::vector<Vertex>> ShortestPath::find_pivots(Length B, const std::vector<Vertex>& S) {\n std::unordered_set<Vertex> W(S.begin(), S.end());\n std::vector<Vertex> Wp = S;\n\n for(auto v: W) {\n prev_[v] = -1;\n }\n\n for(int i = 0; i < k_; i++) {\n std::vector<Vertex> Wi; \n for(int j = 0; j < (int)Wp.size(); j++) {\n Vertex u = Wp[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n dhat_[v] = dhat_[u] + w;\n prev_[v] = u;\n // if(dhat_[u] + w < B) {\n Wi.push_back(v);\n // }\n }\n }\n }\n for(int k = 0; k < (int)Wi.size(); k++) {\n W.insert(Wi[k]);\n }\n if((int)W.size() >= k_ * (int)S.size()) {\n return std::make_pair(S, std::vector<Vertex>(W.begin(), W.end()));\n }\n Wp = Wi;\n // std::cout << \"Wp =\"; debug_vertex_set(Wp);\n }\n\n for(auto v: W) {\n tree_size_[v] = -1;\n F_[v].clear();\n }\n for(auto v: W) {\n Vertex u = prev_[v];\n if(u == -1) continue;\n F_[u].push_back(v);\n }\n std::vector<Vertex> P;\n for(int i = 0; i < (int)S.size(); i++) {\n Vertex u = S[i];\n // std::cout << \"find_tree_size: \" << u << \" \" << find_tree_size(u, tree_size_, F_) << std::endl;\n if(find_tree_size(u, tree_size_, F_) >= k_ && prev_[u] == -1) {\n P.push_back(u);\n }\n }\n return std::make_pair(P, std::vector<Vertex>(W.begin(), W.end()));\n}\n\n\n\n\nvoid find_shortest_path(int s, const Graph& G) {\n int N = (int)G.size();\n double t = std::floor(std::pow(std::log2(N), 2.0 / 3.0));\n double l = std::ceil(std::log2(N) / t);\n ShortestPath shortest_path(s, G);\n std::vector<Vertex> S;\n S.push_back(s);\n auto bu = shortest_path.BMSSP(l, INF, S);\n // std::cout << \"Bfinal:=\" << bu.first << std::endl;\n shortest_path.print_dhat();\n}\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n int N, M, s;\n std::cin >> N >> M >> s;\n Graph G(N);\n for(int i = 0; i < M; i++) {\n int a, b; Length c;\n std::cin >> a >> b >> c;\n G[a].push_back(std::make_pair(b, c));\n }\n find_shortest_path(s, G);\n return 0;\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 39840, "score_of_the_acc": -0.8362, "final_rank": 14 }, { "submission_id": "aoj_GRL_1_A_10989429", "code_snippet": "#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"inline\",\"fast-math\",\"unroll-loops\",\"no-stack-protector\")\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <map>\n#include <algorithm>\n#include <cassert>\n\nusing Vertex = int;\nusing Length = long long;\nconst Length INF = std::numeric_limits<long long>::max();\nusing Edge = std::pair<Vertex, Length>;\nusing Graph = std::vector<std::vector<Edge>>;\n\nclass BlockHeap {\n public:\n BlockHeap(int M, Length B);\n void insert(Vertex v, Length l);\n void batch_prepend(const std::vector<std::pair<Vertex, Length>>& L);\n std::pair<Length ,std::vector<Vertex>> pull();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n // We implement a buffered block-heap: new inserts go to an append buffer (buffer_),\n // batch_prepend items go to a prepend buffer (prepend_), and we maintain a small\n // active sorted set (active_) from which we pop up to M elements per pull.\n // We keep a map d_ of current best distances for vertices; entries in buffers\n // may be stale and are validated against d_ on extraction.\n\n std::unordered_map<Vertex, Length> d_;\n std::vector<std::pair<Length, Vertex>> buffer_; // append-only buffer (length, vertex)\n std::vector<std::pair<Length, Vertex>> prepend_; // items to prioritize\n std::set<std::pair<Length, Vertex>> active_; // sorted active set\n Length buffer_min_ = INF;\n Length prepend_min_ = INF;\n};\n\nBlockHeap::BlockHeap(int M, Length B) {\n M_ = M;\n B_ = B;\n}\n\nstd::pair<Length, std::vector<Vertex>> BlockHeap::pull() {\n std::vector<Vertex> S;\n\n // Ensure active_ has elements to pop, preferring prepend_ then buffer_.\n if(active_.empty()) {\n // Move all prepend_ items into active_\n if(!prepend_.empty()) {\n for(auto &p : prepend_) {\n Length l = p.first; Vertex v = p.second;\n // only insert if this entry is current\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n prepend_.clear();\n prepend_min_ = INF;\n }\n // If still empty, move up to M_ smallest from buffer_\n if(active_.empty() && !buffer_.empty()) {\n int take = std::min((int)buffer_.size(), M_);\n // partial sort: nth_element to partition smallest 'take' elements\n std::nth_element(buffer_.begin(), buffer_.begin() + take, buffer_.end(),\n [](const std::pair<Length, Vertex>& a, const std::pair<Length, Vertex>& b){\n return a.first < b.first;\n });\n // move the first 'take' items into active_\n for(int i = 0; i < take; ++i) {\n Length l = buffer_[i].first; Vertex v = buffer_[i].second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n // rebuild buffer_ with remaining items\n std::vector<std::pair<Length, Vertex>> newbuf;\n newbuf.reserve(buffer_.size() - take);\n for(size_t i = take; i < buffer_.size(); ++i) newbuf.push_back(buffer_[i]);\n buffer_.swap(newbuf);\n // recompute buffer_min_\n buffer_min_ = INF;\n for(auto &p : buffer_) buffer_min_ = std::min(buffer_min_, p.first);\n }\n }\n\n // Pop up to M_ items from active_\n for(int i = 0; i < M_; ++i) {\n if(active_.empty()) break;\n auto p = *active_.begin();\n active_.erase(active_.begin());\n Vertex v = p.second; Length l = p.first;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n // valid\n S.push_back(v);\n d_.erase(it);\n }\n // otherwise stale, skip\n }\n\n // compute next threshold Bi\n Length next_min = INF;\n if(!active_.empty()) next_min = std::min(next_min, active_.begin()->first);\n if(buffer_min_ < next_min) next_min = buffer_min_;\n if(prepend_min_ < next_min) next_min = prepend_min_;\n if(next_min == INF) return std::make_pair(B_, S);\n return std::make_pair(next_min, S);\n}\n\nvoid BlockHeap::batch_prepend(const std::vector<std::pair<Vertex, Length>>& L) {\n // batch prepend: add items to prepend_ (higher priority than buffer_)\n for(const auto &p : L) {\n Vertex v = p.first; Length l = p.second;\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) continue;\n // update to better value\n it->second = l;\n } else {\n d_[v] = l;\n }\n prepend_.push_back(std::make_pair(l, v));\n if(l < prepend_min_) prepend_min_ = l;\n }\n}\n\nvoid BlockHeap::insert(Vertex v, Length l) {\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) return; // no improvement\n it->second = l;\n } else {\n d_[v] = l;\n }\n buffer_.push_back(std::make_pair(l, v));\n if(l < buffer_min_) buffer_min_ = l;\n}\n\nbool BlockHeap::empty() {\n return d_.empty();\n}\n\nvoid BlockHeap::debug() {\n std::cout << \"D(active)= [\";\n for(auto p: active_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(prepend)= [\";\n for(auto &p: prepend_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(buffer)= [\";\n for(auto &p: buffer_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass Heap {\n public:\n void push(Vertex v, Length l);\n std::pair<Vertex, Length> top();\n void pop();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n std::set<std::pair<Length, Vertex>> que_;\n std::unordered_map<Vertex, Length> d_;\n\n};\n\nvoid Heap::push(Vertex v, Length l) {\n if(d_.count(v) != 0 && d_[v] < l) {\n return;\n } else if (d_.count(v) != 0 && d_[v] >= l) {\n que_.erase(std::make_pair(d_[v], v));\n }\n que_.insert(std::make_pair(l, v));\n d_[v] = l;\n}\n\nstd::pair<Vertex, Length> Heap::top() {\n auto p = *que_.begin();\n return std::make_pair(p.second, p.first);\n}\n\nvoid Heap::pop() {\n d_.erase(top().second);\n que_.erase(que_.begin());\n}\n\nbool Heap::empty() {\n return que_.empty();\n}\n\nvoid Heap::debug() {\n std::cout << \"H= [\";\n for(auto p: que_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass ShortestPath {\n public:\n ShortestPath(Vertex s, const Graph& G);\n std::pair<Length, std::vector<Vertex>> BMSSP(int l, Length B, const std::vector<Vertex>& S);\n std::pair<std::vector<Vertex>, std::vector<Vertex>> find_pivots(Length B, const std::vector<Vertex>& S);\n void print_dhat();\n\n private:\n int t_;\n int k_;\n std::vector<Length> dhat_;\n Graph G_;\n\n std::pair<Length, std::vector<Vertex>> base_case(Length B, const std::vector<Vertex>& S);\n\n std::vector<Vertex> prev_;\n std::vector<int> tree_size_;\n std::vector<std::vector<Vertex>> F_;\n};\n\nShortestPath::ShortestPath(Vertex s, const Graph& G) {\n G_ = G;\n int N = G_.size();\n k_ = std::ceil(pow(std::log2(N), 1.0 / 3.0));\n t_ = std::floor(pow(std::log2(N), 2.0 / 3.0));\n dhat_ = std::vector<Length>(N, INF);\n dhat_[s] = 0;\n prev_ = std::vector<Vertex>(N, -1);\n tree_size_ = std::vector<Vertex>(N, -1);\n F_ = std::vector<std::vector<Vertex>>(N, std::vector<Vertex>());\n}\n\nnamespace {\n int find_tree_size(int u, std::vector<int>& tree_size, const std::vector<std::vector<Vertex>>& F) {\n if(tree_size[u] != -1) return tree_size[u];\n int res = 1;\n for(int i = 0; i < (int)F[u].size(); i++) {\n Vertex v = F[u][i];\n res += find_tree_size(v, tree_size, F);\n }\n return tree_size[u] = res;\n }\n\n void debug_vertex_set(std::vector<Vertex> S) {\n std::cout << \"[\";\n for(int i = 0; i < (int)S.size(); i++) {\n std::cout << S[i] << \", \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nvoid ShortestPath::print_dhat() {\n for(int i = 0; i < (int)dhat_.size(); i++) {\n if(dhat_[i] == INF) {\n std::cout << \"INF\" << '\\n';\n } else {\n std::cout << dhat_[i] << '\\n';\n }\n }\n // std::cout << \"[\";\n // for(int i = 0; i < (int)dhat_.size(); i++) {\n // if(dhat_[i] == INF) {\n // std::cout << \"INF\" << \", \";\n // } else {\n // std::cout << dhat_[i] << \", \";\n // }\n // }\n // std::cout << \"]\" << std::endl;\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::BMSSP(int l, Length B, const std::vector<Vertex>& S) {\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", S=\";\n // debug_vertex_set(S);\n // print_dhat();\n if(l == 0) {\n return base_case(B, S);\n }\n auto pw = find_pivots(B, S);\n std::vector<Vertex> P = pw.first; std::vector<Vertex> W = pw.second;\n // std::cout << \"P= \"; debug_vertex_set(P);\n // std::cout << \"W= \"; debug_vertex_set(W);\n\n int M = std::pow(2, (l - 1) * t_);\n BlockHeap D(M, B);\n Length Bd = INF;\n for(int i = 0; i < (int)P.size(); i++) {\n Vertex u = P[i];\n D.insert(u, dhat_[u]);\n Bd = std::min(Bd, dhat_[u]);\n }\n // D.debug();\n std::unordered_set<Vertex> U;\n\n while((int)U.size() < k_ * std::pow(2, l * t_) && !D.empty()) {\n auto bs = D.pull();\n Length Bi = bs.first; std::vector<Vertex> Si = bs.second;\n if (Si.empty()) {\n continue; \n }\n \n auto bu = BMSSP(l - 1, Bi, Si);\n Length Bid = bu.first; std::vector<Vertex> Ui = bu.second;\n // std::cout << \"Bid=\" << Bid << std::endl;\n // std::cout << \"Ui=\"; debug_vertex_set(Ui);\n // std::cout << \"U=\"; debug_vertex_set(std::vector<Vertex>(U.begin(), U.end()));\n for(int j = 0; j < (int)Ui.size(); j++) {\n // if(U.count(Ui[j]) != 0) {\n // std::cout << \"Ufound\" << \" \" << Ui[j] << \" \" << dhat_[Ui[j]] << \" \" << Bi << \" \" << Bid << std::endl;\n // }\n U.insert(Ui[j]);\n }\n\n std::vector<std::pair<Vertex, Length>> K;\n for(int j = 0; j < (int)Ui.size(); j++) {\n Vertex u = Ui[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n Length new_dist = dhat_[u] + w;\n dhat_[v] = new_dist;\n if(Bi <= new_dist && new_dist < B) {\n D.insert(v, new_dist);\n } else if(Bid <= new_dist && new_dist < Bi) {\n K.push_back(std::make_pair(v, new_dist));\n }\n }\n }\n }\n for(int i = 0; i < (int)Si.size(); i++) {\n int u = Si[i];\n if(Bid <= dhat_[u] && dhat_[u] < Bi) K.push_back(std::make_pair(u, dhat_[u]));\n }\n D.batch_prepend(K);\n Bd = Bid;\n }\n Bd = std::min(Bd, B);\n for(int i = 0; i < (int)W.size(); i++) {\n Vertex u = W[i];\n if(dhat_[u] < Bd) U.insert(u);\n }\n if(l == 3) {\n for(int i = 0; i < (int)G_.size(); i++) {\n // if(!U.count(i) && dhat_[i] != INF) {\n // std::cout << \"found: \" << i << \" \" << dhat_[i] << std::endl;\n // }\n }\n }\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", Bd=\" << Bd << std::endl;\n // std::cout << \"U size:=\" << U.size() << \" \" << (D.empty() ? \"empty\" : \"notempty\") << std::endl;\n return std::make_pair(Bd, std::vector<Vertex>(U.begin(), U.end()));\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::base_case(Length B, const std::vector<Vertex>& S) {\n assert(S.size() == 1);\n\n Vertex x = S[0];\n // std::cout << \"base_case k=\" << k_ << \", t=\" << t_ << \", B=\" << B << \", x=\" << x << std::endl; \n\n std::unordered_set<Vertex> U0(S.begin(), S.end());\n Heap H;\n H.push(x, dhat_[x]);\n\n while(!H.empty() && (int)U0.size() < k_ + 1) {\n auto p = H.top(); H.pop();\n Vertex u = p.first; Length d = p.second;\n U0.insert(u);\n\n for(int i = 0; i < (int)G_[u].size(); i++) {\n int v = G_[u][i].first; Length w = G_[u][i].second;\n if(dhat_[v] >= dhat_[u] + w && dhat_[u] + w < B) {\n dhat_[v] = dhat_[u] + w;\n H.push(v, dhat_[v]);\n }\n }\n // H.debug();\n }\n\n if((int)U0.size() <= k_) {\n return make_pair(B, std::vector<Vertex>(U0.begin(), U0.end()));\n } else {\n Length Bd = -INF;\n std::vector<Vertex> U;\n for(auto u: U0) {\n Bd = std::max(Bd, dhat_[u]);\n }\n for(auto u: U0) {\n if(dhat_[u] < Bd) {\n U.push_back(u);\n }\n }\n return make_pair(Bd, U);\n }\n}\n\n\nstd::pair<std::vector<Vertex>, std::vector<Vertex>> ShortestPath::find_pivots(Length B, const std::vector<Vertex>& S) {\n std::unordered_set<Vertex> W(S.begin(), S.end());\n std::vector<Vertex> Wp = S;\n\n for(auto v: W) {\n prev_[v] = -1;\n }\n\n for(int i = 0; i < k_; i++) {\n std::vector<Vertex> Wi; \n for(int j = 0; j < (int)Wp.size(); j++) {\n Vertex u = Wp[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n dhat_[v] = dhat_[u] + w;\n prev_[v] = u;\n // if(dhat_[u] + w < B) {\n Wi.push_back(v);\n // }\n }\n }\n }\n for(int k = 0; k < (int)Wi.size(); k++) {\n W.insert(Wi[k]);\n }\n if((int)W.size() >= k_ * (int)S.size()) {\n return std::make_pair(S, std::vector<Vertex>(W.begin(), W.end()));\n }\n Wp = Wi;\n // std::cout << \"Wp =\"; debug_vertex_set(Wp);\n }\n\n for(auto v: W) {\n tree_size_[v] = -1;\n F_[v].clear();\n }\n for(auto v: W) {\n Vertex u = prev_[v];\n if(u == -1) continue;\n F_[u].push_back(v);\n }\n std::vector<Vertex> P;\n for(int i = 0; i < (int)S.size(); i++) {\n Vertex u = S[i];\n // std::cout << \"find_tree_size: \" << u << \" \" << find_tree_size(u, tree_size_, F_) << std::endl;\n if(find_tree_size(u, tree_size_, F_) >= k_ && prev_[u] == -1) {\n P.push_back(u);\n }\n }\n return std::make_pair(P, std::vector<Vertex>(W.begin(), W.end()));\n}\n\n\n\n\nvoid find_shortest_path(int s, const Graph& G) {\n int N = (int)G.size();\n double t = std::floor(std::pow(std::log2(N), 2.0 / 3.0));\n double l = std::ceil(std::log2(N) / t);\n ShortestPath shortest_path(s, G);\n std::vector<Vertex> S;\n S.push_back(s);\n auto bu = shortest_path.BMSSP(l, INF, S);\n // std::cout << \"Bfinal:=\" << bu.first << std::endl;\n shortest_path.print_dhat();\n}\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n int N, M, s;\n std::cin >> N >> M >> s;\n Graph G(N);\n for(int i = 0; i < M; i++) {\n int a, b; Length c;\n std::cin >> a >> b >> c;\n G[a].push_back(std::make_pair(b, c));\n }\n find_shortest_path(s, G);\n return 0;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 40512, "score_of_the_acc": -0.8633, "final_rank": 15 }, { "submission_id": "aoj_GRL_1_A_10989422", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <map>\n#include <algorithm>\n#include <cassert>\n\nusing Vertex = int;\nusing Length = long long;\nconst Length INF = std::numeric_limits<long long>::max();\nusing Edge = std::pair<Vertex, Length>;\nusing Graph = std::vector<std::vector<Edge>>;\n\nclass BlockHeap {\n public:\n BlockHeap(int M, Length B);\n void insert(Vertex v, Length l);\n void batch_prepend(const std::vector<std::pair<Vertex, Length>>& L);\n std::pair<Length ,std::vector<Vertex>> pull();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n // We implement a buffered block-heap: new inserts go to an append buffer (buffer_),\n // batch_prepend items go to a prepend buffer (prepend_), and we maintain a small\n // active sorted set (active_) from which we pop up to M elements per pull.\n // We keep a map d_ of current best distances for vertices; entries in buffers\n // may be stale and are validated against d_ on extraction.\n\n std::unordered_map<Vertex, Length> d_;\n std::vector<std::pair<Length, Vertex>> buffer_; // append-only buffer (length, vertex)\n std::vector<std::pair<Length, Vertex>> prepend_; // items to prioritize\n std::set<std::pair<Length, Vertex>> active_; // sorted active set\n Length buffer_min_ = INF;\n Length prepend_min_ = INF;\n};\n\nBlockHeap::BlockHeap(int M, Length B) {\n M_ = M;\n B_ = B;\n}\n\nstd::pair<Length, std::vector<Vertex>> BlockHeap::pull() {\n std::vector<Vertex> S;\n\n // Ensure active_ has elements to pop, preferring prepend_ then buffer_.\n if(active_.empty()) {\n // Move all prepend_ items into active_\n if(!prepend_.empty()) {\n for(auto &p : prepend_) {\n Length l = p.first; Vertex v = p.second;\n // only insert if this entry is current\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n prepend_.clear();\n prepend_min_ = INF;\n }\n // If still empty, move up to M_ smallest from buffer_\n if(active_.empty() && !buffer_.empty()) {\n int take = std::min((int)buffer_.size(), M_);\n // partial sort: nth_element to partition smallest 'take' elements\n std::nth_element(buffer_.begin(), buffer_.begin() + take, buffer_.end(),\n [](const std::pair<Length, Vertex>& a, const std::pair<Length, Vertex>& b){\n return a.first < b.first;\n });\n // move the first 'take' items into active_\n for(int i = 0; i < take; ++i) {\n Length l = buffer_[i].first; Vertex v = buffer_[i].second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n // rebuild buffer_ with remaining items\n std::vector<std::pair<Length, Vertex>> newbuf;\n newbuf.reserve(buffer_.size() - take);\n for(size_t i = take; i < buffer_.size(); ++i) newbuf.push_back(buffer_[i]);\n buffer_.swap(newbuf);\n // recompute buffer_min_\n buffer_min_ = INF;\n for(auto &p : buffer_) buffer_min_ = std::min(buffer_min_, p.first);\n }\n }\n\n // Pop up to M_ items from active_\n for(int i = 0; i < M_; ++i) {\n if(active_.empty()) break;\n auto p = *active_.begin();\n active_.erase(active_.begin());\n Vertex v = p.second; Length l = p.first;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n // valid\n S.push_back(v);\n d_.erase(it);\n }\n // otherwise stale, skip\n }\n\n // compute next threshold Bi\n Length next_min = INF;\n if(!active_.empty()) next_min = std::min(next_min, active_.begin()->first);\n if(buffer_min_ < next_min) next_min = buffer_min_;\n if(prepend_min_ < next_min) next_min = prepend_min_;\n if(next_min == INF) return std::make_pair(B_, S);\n return std::make_pair(next_min, S);\n}\n\nvoid BlockHeap::batch_prepend(const std::vector<std::pair<Vertex, Length>>& L) {\n // batch prepend: add items to prepend_ (higher priority than buffer_)\n for(const auto &p : L) {\n Vertex v = p.first; Length l = p.second;\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) continue;\n // update to better value\n it->second = l;\n } else {\n d_[v] = l;\n }\n prepend_.push_back(std::make_pair(l, v));\n if(l < prepend_min_) prepend_min_ = l;\n }\n}\n\nvoid BlockHeap::insert(Vertex v, Length l) {\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) return; // no improvement\n it->second = l;\n } else {\n d_[v] = l;\n }\n buffer_.push_back(std::make_pair(l, v));\n if(l < buffer_min_) buffer_min_ = l;\n}\n\nbool BlockHeap::empty() {\n return d_.empty();\n}\n\nvoid BlockHeap::debug() {\n std::cout << \"D(active)= [\";\n for(auto p: active_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(prepend)= [\";\n for(auto &p: prepend_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(buffer)= [\";\n for(auto &p: buffer_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass Heap {\n public:\n void push(Vertex v, Length l);\n std::pair<Vertex, Length> top();\n void pop();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n std::set<std::pair<Length, Vertex>> que_;\n std::unordered_map<Vertex, Length> d_;\n\n};\n\nvoid Heap::push(Vertex v, Length l) {\n if(d_.count(v) != 0 && d_[v] < l) {\n return;\n } else if (d_.count(v) != 0 && d_[v] >= l) {\n que_.erase(std::make_pair(d_[v], v));\n }\n que_.insert(std::make_pair(l, v));\n d_[v] = l;\n}\n\nstd::pair<Vertex, Length> Heap::top() {\n auto p = *que_.begin();\n return std::make_pair(p.second, p.first);\n}\n\nvoid Heap::pop() {\n auto t = top();\n Vertex v = t.first;\n d_.erase(v);\n que_.erase(que_.begin());\n}\n\nbool Heap::empty() {\n return que_.empty();\n}\n\nvoid Heap::debug() {\n std::cout << \"H= [\";\n for(auto p: que_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass ShortestPath {\n public:\n ShortestPath(Vertex s, const Graph& G);\n std::pair<Length, std::vector<Vertex>> BMSSP(int l, Length B, const std::vector<Vertex>& S);\n std::pair<std::vector<Vertex>, std::vector<Vertex>> find_pivots(Length B, const std::vector<Vertex>& S);\n void print_dhat();\n\n private:\n int t_;\n int k_;\n std::vector<Length> dhat_;\n Graph G_;\n\n std::pair<Length, std::vector<Vertex>> base_case(Length B, const std::vector<Vertex>& S);\n\n std::vector<Vertex> prev_;\n std::vector<int> tree_size_;\n std::vector<std::vector<Vertex>> F_;\n};\n\nShortestPath::ShortestPath(Vertex s, const Graph& G) {\n G_ = G;\n int N = G_.size();\n k_ = std::ceil(pow(std::log2(N), 1.0 / 3.0));\n t_ = std::floor(pow(std::log2(N), 2.0 / 3.0));\n dhat_ = std::vector<Length>(N, INF);\n dhat_[s] = 0;\n prev_ = std::vector<Vertex>(N, -1);\n tree_size_ = std::vector<Vertex>(N, -1);\n F_ = std::vector<std::vector<Vertex>>(N, std::vector<Vertex>());\n}\n\nnamespace {\n int find_tree_size(int u, std::vector<int>& tree_size, const std::vector<std::vector<Vertex>>& F) {\n if(tree_size[u] != -1) return tree_size[u];\n int res = 1;\n for(int i = 0; i < (int)F[u].size(); i++) {\n Vertex v = F[u][i];\n res += find_tree_size(v, tree_size, F);\n }\n return tree_size[u] = res;\n }\n\n void debug_vertex_set(std::vector<Vertex> S) {\n std::cout << \"[\";\n for(int i = 0; i < (int)S.size(); i++) {\n std::cout << S[i] << \", \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nvoid ShortestPath::print_dhat() {\n for(int i = 0; i < (int)dhat_.size(); i++) {\n if(dhat_[i] == INF) {\n std::cout << \"INF\" << std::endl;\n } else {\n std::cout << dhat_[i] << std::endl;\n }\n }\n // std::cout << \"[\";\n // for(int i = 0; i < (int)dhat_.size(); i++) {\n // if(dhat_[i] == INF) {\n // std::cout << \"INF\" << \", \";\n // } else {\n // std::cout << dhat_[i] << \", \";\n // }\n // }\n // std::cout << \"]\" << std::endl;\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::BMSSP(int l, Length B, const std::vector<Vertex>& S) {\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", S=\";\n // debug_vertex_set(S);\n // print_dhat();\n if(l == 0) {\n return base_case(B, S);\n }\n auto pw = find_pivots(B, S);\n std::vector<Vertex> P = pw.first; std::vector<Vertex> W = pw.second;\n // std::cout << \"P= \"; debug_vertex_set(P);\n // std::cout << \"W= \"; debug_vertex_set(W);\n\n int M = std::pow(2, (l - 1) * t_);\n BlockHeap D(M, B);\n Length Bd = INF;\n for(int i = 0; i < (int)P.size(); i++) {\n Vertex u = P[i];\n D.insert(u, dhat_[u]);\n Bd = std::min(Bd, dhat_[u]);\n }\n // D.debug();\n std::unordered_set<Vertex> U;\n\n while((int)U.size() < k_ * std::pow(2, l * t_) && !D.empty()) {\n auto bs = D.pull();\n Length Bi = bs.first; std::vector<Vertex> Si = bs.second;\n if (Si.empty()) {\n continue; \n }\n \n auto bu = BMSSP(l - 1, Bi, Si);\n Length Bid = bu.first; std::vector<Vertex> Ui = bu.second;\n // std::cout << \"Bid=\" << Bid << std::endl;\n // std::cout << \"Ui=\"; debug_vertex_set(Ui);\n // std::cout << \"U=\"; debug_vertex_set(std::vector<Vertex>(U.begin(), U.end()));\n for(int j = 0; j < (int)Ui.size(); j++) {\n // if(U.count(Ui[j]) != 0) {\n // std::cout << \"Ufound\" << \" \" << Ui[j] << \" \" << dhat_[Ui[j]] << \" \" << Bi << \" \" << Bid << std::endl;\n // }\n U.insert(Ui[j]);\n }\n\n std::vector<std::pair<Vertex, Length>> K;\n for(int j = 0; j < (int)Ui.size(); j++) {\n Vertex u = Ui[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n Length new_dist = dhat_[u] + w;\n dhat_[v] = new_dist;\n if(Bi <= new_dist && new_dist < B) {\n D.insert(v, new_dist);\n } else if(Bid <= new_dist && new_dist < Bi) {\n K.push_back(std::make_pair(v, new_dist));\n }\n }\n }\n }\n for(int i = 0; i < (int)Si.size(); i++) {\n int u = Si[i];\n if(Bid <= dhat_[u] && dhat_[u] < Bi) K.push_back(std::make_pair(u, dhat_[u]));\n }\n D.batch_prepend(K);\n Bd = Bid;\n }\n Bd = std::min(Bd, B);\n for(int i = 0; i < (int)W.size(); i++) {\n Vertex u = W[i];\n if(dhat_[u] < Bd) U.insert(u);\n }\n if(l == 3) {\n for(int i = 0; i < (int)G_.size(); i++) {\n // if(!U.count(i) && dhat_[i] != INF) {\n // std::cout << \"found: \" << i << \" \" << dhat_[i] << std::endl;\n // }\n }\n }\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", Bd=\" << Bd << std::endl;\n // std::cout << \"U size:=\" << U.size() << \" \" << (D.empty() ? \"empty\" : \"notempty\") << std::endl;\n return std::make_pair(Bd, std::vector<Vertex>(U.begin(), U.end()));\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::base_case(Length B, const std::vector<Vertex>& S) {\n assert(S.size() == 1);\n\n Vertex x = S[0];\n // std::cout << \"base_case k=\" << k_ << \", t=\" << t_ << \", B=\" << B << \", x=\" << x << std::endl; \n\n std::unordered_set<Vertex> U0(S.begin(), S.end());\n Heap H;\n H.push(x, dhat_[x]);\n\n while(!H.empty() && (int)U0.size() < k_ + 1) {\n auto p = H.top(); H.pop();\n Vertex u = p.first; Length d = p.second;\n U0.insert(u);\n\n for(int i = 0; i < (int)G_[u].size(); i++) {\n int v = G_[u][i].first; Length w = G_[u][i].second;\n if(dhat_[v] >= dhat_[u] + w && dhat_[u] + w < B) {\n dhat_[v] = dhat_[u] + w;\n H.push(v, dhat_[v]);\n }\n }\n // H.debug();\n }\n\n if((int)U0.size() <= k_) {\n return make_pair(B, std::vector<Vertex>(U0.begin(), U0.end()));\n } else {\n Length Bd = -INF;\n std::vector<Vertex> U;\n for(auto u: U0) {\n Bd = std::max(Bd, dhat_[u]);\n }\n for(auto u: U0) {\n if(dhat_[u] < Bd) {\n U.push_back(u);\n }\n }\n return make_pair(Bd, U);\n }\n}\n\n\nstd::pair<std::vector<Vertex>, std::vector<Vertex>> ShortestPath::find_pivots(Length B, const std::vector<Vertex>& S) {\n std::unordered_set<Vertex> W(S.begin(), S.end());\n std::vector<Vertex> Wp = S;\n\n for(auto v: W) {\n prev_[v] = -1;\n }\n\n for(int i = 0; i < k_; i++) {\n std::vector<Vertex> Wi; \n for(int j = 0; j < (int)Wp.size(); j++) {\n Vertex u = Wp[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n dhat_[v] = dhat_[u] + w;\n prev_[v] = u;\n // if(dhat_[u] + w < B) {\n Wi.push_back(v);\n // }\n }\n }\n }\n for(int k = 0; k < (int)Wi.size(); k++) {\n W.insert(Wi[k]);\n }\n if((int)W.size() >= k_ * (int)S.size()) {\n return std::make_pair(S, std::vector<Vertex>(W.begin(), W.end()));\n }\n Wp = Wi;\n // std::cout << \"Wp =\"; debug_vertex_set(Wp);\n }\n\n for(auto v: W) {\n tree_size_[v] = -1;\n F_[v].clear();\n }\n for(auto v: W) {\n Vertex u = prev_[v];\n if(u == -1) continue;\n F_[u].push_back(v);\n }\n std::vector<Vertex> P;\n for(int i = 0; i < (int)S.size(); i++) {\n Vertex u = S[i];\n // std::cout << \"find_tree_size: \" << u << \" \" << find_tree_size(u, tree_size_, F_) << std::endl;\n if(find_tree_size(u, tree_size_, F_) >= k_ && prev_[u] == -1) {\n P.push_back(u);\n }\n }\n return std::make_pair(P, std::vector<Vertex>(W.begin(), W.end()));\n}\n\n\n\n\nvoid find_shortest_path(int s, const Graph& G) {\n int N = (int)G.size();\n double t = std::floor(std::pow(std::log2(N), 2.0 / 3.0));\n double l = std::ceil(std::log2(N) / t);\n ShortestPath shortest_path(s, G);\n std::vector<Vertex> S;\n S.push_back(s);\n auto bu = shortest_path.BMSSP(l, INF, S);\n // std::cout << \"Bfinal:=\" << bu.first << std::endl;\n shortest_path.print_dhat();\n}\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n int N, M, s;\n std::cin >> N >> M >> s;\n Graph G(N);\n for(int i = 0; i < M; i++) {\n int a, b; Length c;\n std::cin >> a >> b >> c;\n G[a].push_back(std::make_pair(b, c));\n }\n find_shortest_path(s, G);\n return 0;\n}", "accuracy": 1, "time_ms": 380, "memory_kb": 40596, "score_of_the_acc": -0.9466, "final_rank": 17 }, { "submission_id": "aoj_GRL_1_A_10989421", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <map>\n#include <algorithm>\n#include <cassert>\n\nusing Vertex = int;\nusing Length = long long;\nconst Length INF = std::numeric_limits<long long>::max();\nusing Edge = std::pair<Vertex, Length>;\nusing Graph = std::vector<std::vector<Edge>>;\n\nclass BlockHeap {\n public:\n BlockHeap(int M, Length B);\n void insert(Vertex v, Length l);\n void batch_prepend(const std::vector<std::pair<Vertex, Length>>& L);\n std::pair<Length ,std::vector<Vertex>> pull();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n // We implement a buffered block-heap: new inserts go to an append buffer (buffer_),\n // batch_prepend items go to a prepend buffer (prepend_), and we maintain a small\n // active sorted set (active_) from which we pop up to M elements per pull.\n // We keep a map d_ of current best distances for vertices; entries in buffers\n // may be stale and are validated against d_ on extraction.\n\n std::unordered_map<Vertex, Length> d_;\n std::vector<std::pair<Length, Vertex>> buffer_; // append-only buffer (length, vertex)\n std::vector<std::pair<Length, Vertex>> prepend_; // items to prioritize\n std::set<std::pair<Length, Vertex>> active_; // sorted active set\n Length buffer_min_ = INF;\n Length prepend_min_ = INF;\n};\n\nBlockHeap::BlockHeap(int M, Length B) {\n M_ = M;\n B_ = B;\n}\n\nstd::pair<Length, std::vector<Vertex>> BlockHeap::pull() {\n std::vector<Vertex> S;\n\n // Ensure active_ has elements to pop, preferring prepend_ then buffer_.\n if(active_.empty()) {\n // Move all prepend_ items into active_\n if(!prepend_.empty()) {\n for(auto &p : prepend_) {\n Length l = p.first; Vertex v = p.second;\n // only insert if this entry is current\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n prepend_.clear();\n prepend_min_ = INF;\n }\n // If still empty, move up to M_ smallest from buffer_\n if(active_.empty() && !buffer_.empty()) {\n int take = std::min((int)buffer_.size(), M_);\n // partial sort: nth_element to partition smallest 'take' elements\n std::nth_element(buffer_.begin(), buffer_.begin() + take, buffer_.end(),\n [](const std::pair<Length, Vertex>& a, const std::pair<Length, Vertex>& b){\n return a.first < b.first;\n });\n // move the first 'take' items into active_\n for(int i = 0; i < take; ++i) {\n Length l = buffer_[i].first; Vertex v = buffer_[i].second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n active_.insert(std::make_pair(l, v));\n }\n }\n // rebuild buffer_ with remaining items\n std::vector<std::pair<Length, Vertex>> newbuf;\n newbuf.reserve(buffer_.size() - take);\n for(size_t i = take; i < buffer_.size(); ++i) newbuf.push_back(buffer_[i]);\n buffer_.swap(newbuf);\n // recompute buffer_min_\n buffer_min_ = INF;\n for(auto &p : buffer_) buffer_min_ = std::min(buffer_min_, p.first);\n }\n }\n\n // Pop up to M_ items from active_\n for(int i = 0; i < M_; ++i) {\n if(active_.empty()) break;\n auto p = *active_.begin();\n active_.erase(active_.begin());\n Vertex v = p.second; Length l = p.first;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n // valid\n S.push_back(v);\n d_.erase(it);\n }\n // otherwise stale, skip\n }\n\n // compute next threshold Bi\n Length next_min = INF;\n if(!active_.empty()) next_min = std::min(next_min, active_.begin()->first);\n if(buffer_min_ < next_min) next_min = buffer_min_;\n if(prepend_min_ < next_min) next_min = prepend_min_;\n if(next_min == INF) return std::make_pair(B_, S);\n return std::make_pair(next_min, S);\n}\n\nvoid BlockHeap::batch_prepend(const std::vector<std::pair<Vertex, Length>>& L) {\n // batch prepend: add items to prepend_ (higher priority than buffer_)\n for(const auto &p : L) {\n Vertex v = p.first; Length l = p.second;\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) continue;\n // update to better value\n it->second = l;\n } else {\n d_[v] = l;\n }\n prepend_.push_back(std::make_pair(l, v));\n if(l < prepend_min_) prepend_min_ = l;\n }\n}\n\nvoid BlockHeap::insert(Vertex v, Length l) {\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) return; // no improvement\n it->second = l;\n } else {\n d_[v] = l;\n }\n buffer_.push_back(std::make_pair(l, v));\n if(l < buffer_min_) buffer_min_ = l;\n}\n\nbool BlockHeap::empty() {\n return d_.empty();\n}\n\nvoid BlockHeap::debug() {\n std::cout << \"D(active)= [\";\n for(auto p: active_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(prepend)= [\";\n for(auto &p: prepend_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(buffer)= [\";\n for(auto &p: buffer_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass Heap {\n public:\n void push(Vertex v, Length l);\n std::pair<Vertex, Length> top();\n void pop();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n std::set<std::pair<Length, Vertex>> que_;\n std::unordered_map<Vertex, Length> d_;\n\n};\n\nvoid Heap::push(Vertex v, Length l) {\n if(d_.count(v) != 0 && d_[v] < l) {\n return;\n } else if (d_.count(v) != 0 && d_[v] >= l) {\n que_.erase(std::make_pair(d_[v], v));\n }\n que_.insert(std::make_pair(l, v));\n d_[v] = l;\n}\n\nstd::pair<Vertex, Length> Heap::top() {\n auto p = *que_.begin();\n return std::make_pair(p.second, p.first);\n}\n\nvoid Heap::pop() {\n d_.erase(top().second);\n que_.erase(que_.begin());\n}\n\nbool Heap::empty() {\n return que_.empty();\n}\n\nvoid Heap::debug() {\n std::cout << \"H= [\";\n for(auto p: que_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass ShortestPath {\n public:\n ShortestPath(Vertex s, const Graph& G);\n std::pair<Length, std::vector<Vertex>> BMSSP(int l, Length B, const std::vector<Vertex>& S);\n std::pair<std::vector<Vertex>, std::vector<Vertex>> find_pivots(Length B, const std::vector<Vertex>& S);\n void print_dhat();\n\n private:\n int t_;\n int k_;\n std::vector<Length> dhat_;\n Graph G_;\n\n std::pair<Length, std::vector<Vertex>> base_case(Length B, const std::vector<Vertex>& S);\n\n std::vector<Vertex> prev_;\n std::vector<int> tree_size_;\n std::vector<std::vector<Vertex>> F_;\n};\n\nShortestPath::ShortestPath(Vertex s, const Graph& G) {\n G_ = G;\n int N = G_.size();\n k_ = std::ceil(pow(std::log2(N), 1.0 / 3.0));\n t_ = std::floor(pow(std::log2(N), 2.0 / 3.0));\n dhat_ = std::vector<Length>(N, INF);\n dhat_[s] = 0;\n prev_ = std::vector<Vertex>(N, -1);\n tree_size_ = std::vector<Vertex>(N, -1);\n F_ = std::vector<std::vector<Vertex>>(N, std::vector<Vertex>());\n}\n\nnamespace {\n int find_tree_size(int u, std::vector<int>& tree_size, const std::vector<std::vector<Vertex>>& F) {\n if(tree_size[u] != -1) return tree_size[u];\n int res = 1;\n for(int i = 0; i < (int)F[u].size(); i++) {\n Vertex v = F[u][i];\n res += find_tree_size(v, tree_size, F);\n }\n return tree_size[u] = res;\n }\n\n void debug_vertex_set(std::vector<Vertex> S) {\n std::cout << \"[\";\n for(int i = 0; i < (int)S.size(); i++) {\n std::cout << S[i] << \", \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nvoid ShortestPath::print_dhat() {\n for(int i = 0; i < (int)dhat_.size(); i++) {\n if(dhat_[i] == INF) {\n std::cout << \"INF\" << std::endl;\n } else {\n std::cout << dhat_[i] << std::endl;\n }\n }\n // std::cout << \"[\";\n // for(int i = 0; i < (int)dhat_.size(); i++) {\n // if(dhat_[i] == INF) {\n // std::cout << \"INF\" << \", \";\n // } else {\n // std::cout << dhat_[i] << \", \";\n // }\n // }\n // std::cout << \"]\" << std::endl;\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::BMSSP(int l, Length B, const std::vector<Vertex>& S) {\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", S=\";\n // debug_vertex_set(S);\n // print_dhat();\n if(l == 0) {\n return base_case(B, S);\n }\n auto pw = find_pivots(B, S);\n std::vector<Vertex> P = pw.first; std::vector<Vertex> W = pw.second;\n // std::cout << \"P= \"; debug_vertex_set(P);\n // std::cout << \"W= \"; debug_vertex_set(W);\n\n int M = std::pow(2, (l - 1) * t_);\n BlockHeap D(M, B);\n Length Bd = INF;\n for(int i = 0; i < (int)P.size(); i++) {\n Vertex u = P[i];\n D.insert(u, dhat_[u]);\n Bd = std::min(Bd, dhat_[u]);\n }\n // D.debug();\n std::unordered_set<Vertex> U;\n\n while((int)U.size() < k_ * std::pow(2, l * t_) && !D.empty()) {\n auto bs = D.pull();\n Length Bi = bs.first; std::vector<Vertex> Si = bs.second;\n if (Si.empty()) {\n continue; \n }\n \n auto bu = BMSSP(l - 1, Bi, Si);\n Length Bid = bu.first; std::vector<Vertex> Ui = bu.second;\n // std::cout << \"Bid=\" << Bid << std::endl;\n // std::cout << \"Ui=\"; debug_vertex_set(Ui);\n // std::cout << \"U=\"; debug_vertex_set(std::vector<Vertex>(U.begin(), U.end()));\n for(int j = 0; j < (int)Ui.size(); j++) {\n // if(U.count(Ui[j]) != 0) {\n // std::cout << \"Ufound\" << \" \" << Ui[j] << \" \" << dhat_[Ui[j]] << \" \" << Bi << \" \" << Bid << std::endl;\n // }\n U.insert(Ui[j]);\n }\n\n std::vector<std::pair<Vertex, Length>> K;\n for(int j = 0; j < (int)Ui.size(); j++) {\n Vertex u = Ui[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n Length new_dist = dhat_[u] + w;\n dhat_[v] = new_dist;\n if(Bi <= new_dist && new_dist < B) {\n D.insert(v, new_dist);\n } else if(Bid <= new_dist && new_dist < Bi) {\n K.push_back(std::make_pair(v, new_dist));\n }\n }\n }\n }\n for(int i = 0; i < (int)Si.size(); i++) {\n int u = Si[i];\n if(Bid <= dhat_[u] && dhat_[u] < Bi) K.push_back(std::make_pair(u, dhat_[u]));\n }\n D.batch_prepend(K);\n Bd = Bid;\n }\n Bd = std::min(Bd, B);\n for(int i = 0; i < (int)W.size(); i++) {\n Vertex u = W[i];\n if(dhat_[u] < Bd) U.insert(u);\n }\n if(l == 3) {\n for(int i = 0; i < (int)G_.size(); i++) {\n // if(!U.count(i) && dhat_[i] != INF) {\n // std::cout << \"found: \" << i << \" \" << dhat_[i] << std::endl;\n // }\n }\n }\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", Bd=\" << Bd << std::endl;\n // std::cout << \"U size:=\" << U.size() << \" \" << (D.empty() ? \"empty\" : \"notempty\") << std::endl;\n return std::make_pair(Bd, std::vector<Vertex>(U.begin(), U.end()));\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::base_case(Length B, const std::vector<Vertex>& S) {\n assert(S.size() == 1);\n\n Vertex x = S[0];\n // std::cout << \"base_case k=\" << k_ << \", t=\" << t_ << \", B=\" << B << \", x=\" << x << std::endl; \n\n std::unordered_set<Vertex> U0(S.begin(), S.end());\n Heap H;\n H.push(x, dhat_[x]);\n\n while(!H.empty() && (int)U0.size() < k_ + 1) {\n auto p = H.top(); H.pop();\n Vertex u = p.first; Length d = p.second;\n U0.insert(u);\n\n for(int i = 0; i < (int)G_[u].size(); i++) {\n int v = G_[u][i].first; Length w = G_[u][i].second;\n if(dhat_[v] >= dhat_[u] + w && dhat_[u] + w < B) {\n dhat_[v] = dhat_[u] + w;\n H.push(v, dhat_[v]);\n }\n }\n // H.debug();\n }\n\n if((int)U0.size() <= k_) {\n return make_pair(B, std::vector<Vertex>(U0.begin(), U0.end()));\n } else {\n Length Bd = -INF;\n std::vector<Vertex> U;\n for(auto u: U0) {\n Bd = std::max(Bd, dhat_[u]);\n }\n for(auto u: U0) {\n if(dhat_[u] < Bd) {\n U.push_back(u);\n }\n }\n return make_pair(Bd, U);\n }\n}\n\n\nstd::pair<std::vector<Vertex>, std::vector<Vertex>> ShortestPath::find_pivots(Length B, const std::vector<Vertex>& S) {\n std::unordered_set<Vertex> W(S.begin(), S.end());\n std::vector<Vertex> Wp = S;\n\n for(auto v: W) {\n prev_[v] = -1;\n }\n\n for(int i = 0; i < k_; i++) {\n std::vector<Vertex> Wi; \n for(int j = 0; j < (int)Wp.size(); j++) {\n Vertex u = Wp[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n dhat_[v] = dhat_[u] + w;\n prev_[v] = u;\n // if(dhat_[u] + w < B) {\n Wi.push_back(v);\n // }\n }\n }\n }\n for(int k = 0; k < (int)Wi.size(); k++) {\n W.insert(Wi[k]);\n }\n if((int)W.size() >= k_ * (int)S.size()) {\n return std::make_pair(S, std::vector<Vertex>(W.begin(), W.end()));\n }\n Wp = Wi;\n // std::cout << \"Wp =\"; debug_vertex_set(Wp);\n }\n\n for(auto v: W) {\n tree_size_[v] = -1;\n F_[v].clear();\n }\n for(auto v: W) {\n Vertex u = prev_[v];\n if(u == -1) continue;\n F_[u].push_back(v);\n }\n std::vector<Vertex> P;\n for(int i = 0; i < (int)S.size(); i++) {\n Vertex u = S[i];\n // std::cout << \"find_tree_size: \" << u << \" \" << find_tree_size(u, tree_size_, F_) << std::endl;\n if(find_tree_size(u, tree_size_, F_) >= k_ && prev_[u] == -1) {\n P.push_back(u);\n }\n }\n return std::make_pair(P, std::vector<Vertex>(W.begin(), W.end()));\n}\n\n\n\n\nvoid find_shortest_path(int s, const Graph& G) {\n int N = (int)G.size();\n double t = std::floor(std::pow(std::log2(N), 2.0 / 3.0));\n double l = std::ceil(std::log2(N) / t);\n ShortestPath shortest_path(s, G);\n std::vector<Vertex> S;\n S.push_back(s);\n auto bu = shortest_path.BMSSP(l, INF, S);\n // std::cout << \"Bfinal:=\" << bu.first << std::endl;\n shortest_path.print_dhat();\n}\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n int N, M, s;\n std::cin >> N >> M >> s;\n Graph G(N);\n for(int i = 0; i < M; i++) {\n int a, b; Length c;\n std::cin >> a >> b >> c;\n G[a].push_back(std::make_pair(b, c));\n }\n find_shortest_path(s, G);\n return 0;\n}", "accuracy": 1, "time_ms": 380, "memory_kb": 40532, "score_of_the_acc": -0.9451, "final_rank": 16 }, { "submission_id": "aoj_GRL_1_A_10989406", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <map>\n#include <algorithm>\n#include <cassert>\n\nusing Vertex = int;\nusing Length = long long;\nconst Length INF = std::numeric_limits<long long>::max();\nusing Edge = std::pair<Vertex, Length>;\nusing Graph = std::vector<std::vector<Edge>>;\n\nclass BlockHeap {\n public:\n BlockHeap(int M, Length B);\n void insert(Vertex v, Length l);\n void batch_prepend(const std::vector<std::pair<Vertex, Length>>& L);\n std::pair<Length ,std::vector<Vertex>> pull();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n // We implement a buffered block-heap: new inserts go to an append buffer (buffer_),\n // batch_prepend items go to a prepend buffer (prepend_), and we maintain a small\n // active sorted set (active_) from which we pop up to M elements per pull.\n // We keep a map d_ of current best distances for vertices; entries in buffers\n // may be stale and are validated against d_ on extraction.\n\n std::unordered_map<Vertex, Length> d_;\n std::vector<std::pair<Length, Vertex>> buffer_; // append-only buffer (length, vertex)\n std::vector<std::pair<Length, Vertex>> prepend_; // items to prioritize\n std::set<std::pair<Length, Vertex>> active_; // sorted active set\n Length buffer_min_ = INF;\n Length prepend_min_ = INF;\n};\n\nBlockHeap::BlockHeap(int M, Length B) {\n M_ = M;\n B_ = B;\n}\n\nstd::pair<Length, std::vector<Vertex>> BlockHeap::pull() {\n std::vector<Vertex> S;\n // debug trace disabled\n\n // Ensure active_ has elements to pop, preferring prepend_ then buffer_.\n if(active_.empty()) {\n // Move all prepend_ items into active_\n if(!prepend_.empty()) {\n // Use current d_ values for prepend_ entries and deduplicate by vertex\n for(auto &p : prepend_) {\n Vertex v = p.second;\n auto it = d_.find(v);\n if(it != d_.end()) {\n active_.insert(std::make_pair(it->second, v));\n }\n }\n prepend_.clear();\n prepend_min_ = INF;\n }\n // If still empty, move up to M_ smallest from buffer_\n if(active_.empty() && !buffer_.empty()) {\n // Collapse buffer_ by vertex to current d_ values to avoid stale entries\n std::unordered_map<Vertex, Length> cur;\n cur.reserve(buffer_.size()*2);\n for(auto &p : buffer_) {\n Vertex v = p.second;\n auto it = d_.find(v);\n if(it != d_.end()) cur[v] = it->second;\n }\n std::vector<std::pair<Length, Vertex>> candidates;\n candidates.reserve(cur.size());\n for(auto &kv : cur) candidates.emplace_back(kv.second, kv.first);\n int take = std::min((int)candidates.size(), M_);\n // If take equals full buffer size, move all items; otherwise use nth_element\n if(take >= (int)candidates.size()) {\n for(auto &c : candidates) active_.insert(c);\n // all candidates moved\n buffer_.clear();\n } else {\n std::nth_element(candidates.begin(), candidates.begin() + take, candidates.end(),\n [](const std::pair<Length, Vertex>& a, const std::pair<Length, Vertex>& b){\n return a.first < b.first;\n });\n std::unordered_set<Vertex> moved;\n moved.reserve(take*2 + 1);\n for(int i = 0; i < take; ++i) {\n active_.insert(candidates[i]);\n moved.insert(candidates[i].second);\n }\n // rebuild buffer_ from remaining candidates (store current values)\n std::vector<std::pair<Length, Vertex>> newbuf;\n newbuf.reserve(candidates.size() - take);\n for(auto &c : candidates) {\n if(moved.count(c.second) == 0) newbuf.push_back(c);\n }\n buffer_.swap(newbuf);\n }\n // recompute buffer_min_\n buffer_min_ = INF;\n for(auto &p : buffer_) buffer_min_ = std::min(buffer_min_, p.first);\n }\n }\n\n // Pop up to M_ items from active_\n // (internal) active_ contents debug removed\n // Pop until we collected up to M_ valid items (skip stale entries)\n while((int)S.size() < M_ && !active_.empty()) {\n auto p = *active_.begin();\n active_.erase(active_.begin());\n Vertex v = p.second; Length l = p.first;\n auto it = d_.find(v);\n if(it != d_.end() && it->second == l) {\n // valid\n S.push_back(v);\n d_.erase(it);\n }\n // otherwise stale, skip and continue popping\n }\n\n // compute next threshold Bi\n Length next_min = INF;\n if(!active_.empty()) next_min = std::min(next_min, active_.begin()->first);\n if(buffer_min_ < next_min) next_min = buffer_min_;\n if(prepend_min_ < next_min) next_min = prepend_min_;\n // If we didn't collect any valid items but there are still candidates in buffers,\n // pick one current-min candidate as a fallback (to avoid returning empty S when\n // the structure was considered non-empty).\n if(S.empty()) {\n Vertex pick = -1; Length pick_len = INF;\n // check active_ (their lengths may be stale, but prefer matching current d_)\n for(auto &p : active_) {\n Vertex v = p.second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second < pick_len) { pick_len = it->second; pick = v; }\n }\n // check prepend_\n for(auto &p : prepend_) {\n Vertex v = p.second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second < pick_len) { pick_len = it->second; pick = v; }\n }\n // check buffer_\n for(auto &p : buffer_) {\n Vertex v = p.second;\n auto it = d_.find(v);\n if(it != d_.end() && it->second < pick_len) { pick_len = it->second; pick = v; }\n }\n if(pick != -1) {\n // remove pick from data structures\n d_.erase(pick);\n // remove from active_\n for(auto it = active_.begin(); it != active_.end();) {\n if(it->second == pick) it = active_.erase(it);\n else ++it;\n }\n // remove from prepend_\n std::vector<std::pair<Length, Vertex>> np;\n for(auto &p: prepend_) if(p.second != pick) np.push_back(p);\n prepend_.swap(np);\n // remove from buffer_\n std::vector<std::pair<Length, Vertex>> nb;\n for(auto &p: buffer_) if(p.second != pick) nb.push_back(p);\n buffer_.swap(nb);\n // recompute mins\n buffer_min_ = INF; for(auto &p: buffer_) buffer_min_ = std::min(buffer_min_, p.first);\n prepend_min_ = INF; for(auto &p: prepend_) prepend_min_ = std::min(prepend_min_, p.first);\n S.push_back(pick);\n }\n }\n\n if(next_min == INF) return std::make_pair(B_, S);\n return std::make_pair(next_min, S);\n}\n\nvoid BlockHeap::batch_prepend(const std::vector<std::pair<Vertex, Length>>& L) {\n // batch prepend: add items to prepend_ (higher priority than buffer_)\n for(const auto &p : L) {\n Vertex v = p.first; Length l = p.second;\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) continue;\n // update to better value\n it->second = l;\n } else {\n d_[v] = l;\n }\n prepend_.push_back(std::make_pair(l, v));\n if(l < prepend_min_) prepend_min_ = l;\n }\n}\n\nvoid BlockHeap::insert(Vertex v, Length l) {\n auto it = d_.find(v);\n if(it != d_.end()) {\n if(it->second <= l) return; // no improvement\n it->second = l;\n } else {\n d_[v] = l;\n }\n buffer_.push_back(std::make_pair(l, v));\n if(l < buffer_min_) buffer_min_ = l;\n}\n\nbool BlockHeap::empty() {\n // Non-empty when there are any extractable (current) items in the active set or buffers.\n if(!active_.empty()) return false;\n for(auto &p: prepend_) {\n if(d_.count(p.second) != 0) return false;\n }\n for(auto &p: buffer_) {\n if(d_.count(p.second) != 0) return false;\n }\n return true;\n}\n\nvoid BlockHeap::debug() {\n std::cout << \"D(active)= [\";\n for(auto p: active_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(prepend)= [\";\n for(auto &p: prepend_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\\n\";\n std::cout << \"D(buffer)= [\";\n for(auto &p: buffer_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass Heap {\n public:\n void push(Vertex v, Length l);\n std::pair<Vertex, Length> top();\n void pop();\n bool empty();\n void debug();\n\n private:\n int M_;\n Length B_;\n\n std::set<std::pair<Length, Vertex>> que_;\n std::unordered_map<Vertex, Length> d_;\n\n};\n\nvoid Heap::push(Vertex v, Length l) {\n if(d_.count(v) != 0 && d_[v] < l) {\n return;\n } else if (d_.count(v) != 0 && d_[v] >= l) {\n que_.erase(std::make_pair(d_[v], v));\n }\n que_.insert(std::make_pair(l, v));\n d_[v] = l;\n}\n\nstd::pair<Vertex, Length> Heap::top() {\n auto p = *que_.begin();\n return std::make_pair(p.second, p.first);\n}\n\nvoid Heap::pop() {\n d_.erase(top().second);\n que_.erase(que_.begin());\n}\n\nbool Heap::empty() {\n return que_.empty();\n}\n\nvoid Heap::debug() {\n std::cout << \"H= [\";\n for(auto p: que_) {\n std::cout << \"(V=\" << p.second << \", v=\" << p.first << \"), \";\n }\n std::cout << \"]\" << std::endl;\n}\n\nclass ShortestPath {\n public:\n ShortestPath(Vertex s, const Graph& G);\n std::pair<Length, std::vector<Vertex>> BMSSP(int l, Length B, const std::vector<Vertex>& S);\n std::pair<std::vector<Vertex>, std::vector<Vertex>> find_pivots(Length B, const std::vector<Vertex>& S);\n void print_dhat();\n\n private:\n int t_;\n int k_;\n std::vector<Length> dhat_;\n Graph G_;\n\n std::pair<Length, std::vector<Vertex>> base_case(Length B, const std::vector<Vertex>& S);\n\n std::vector<Vertex> prev_;\n std::vector<int> tree_size_;\n std::vector<std::vector<Vertex>> F_;\n};\n\nShortestPath::ShortestPath(Vertex s, const Graph& G) {\n G_ = G;\n int N = G_.size();\n k_ = std::ceil(pow(std::log2(N), 1.0 / 3.0));\n t_ = std::floor(pow(std::log2(N), 2.0 / 3.0));\n dhat_ = std::vector<Length>(N, INF);\n dhat_[s] = 0;\n prev_ = std::vector<Vertex>(N, -1);\n tree_size_ = std::vector<Vertex>(N, -1);\n F_ = std::vector<std::vector<Vertex>>(N, std::vector<Vertex>());\n}\n\nnamespace {\n int find_tree_size(int u, std::vector<int>& tree_size, const std::vector<std::vector<Vertex>>& F) {\n if(tree_size[u] != -1) return tree_size[u];\n int res = 1;\n for(int i = 0; i < (int)F[u].size(); i++) {\n Vertex v = F[u][i];\n res += find_tree_size(v, tree_size, F);\n }\n return tree_size[u] = res;\n }\n\n void debug_vertex_set(std::vector<Vertex> S) {\n std::cout << \"[\";\n for(int i = 0; i < (int)S.size(); i++) {\n std::cout << S[i] << \", \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nvoid ShortestPath::print_dhat() {\n for(int i = 0; i < (int)dhat_.size(); i++) {\n if(dhat_[i] == INF) {\n std::cout << \"INF\" << std::endl;\n } else {\n std::cout << dhat_[i] << std::endl;\n }\n }\n // std::cout << \"[\";\n // for(int i = 0; i < (int)dhat_.size(); i++) {\n // if(dhat_[i] == INF) {\n // std::cout << \"INF\" << \", \";\n // } else {\n // std::cout << dhat_[i] << \", \";\n // }\n // }\n // std::cout << \"]\" << std::endl;\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::BMSSP(int l, Length B, const std::vector<Vertex>& S) {\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", S=\";\n // debug_vertex_set(S);\n // print_dhat();\n if(l == 0) {\n return base_case(B, S);\n }\n auto pw = find_pivots(B, S);\n std::vector<Vertex> P = pw.first; std::vector<Vertex> W = pw.second;\n // std::cout << \"P= \"; debug_vertex_set(P);\n // std::cout << \"W= \"; debug_vertex_set(W);\n\n int M = std::pow(2, (l - 1) * t_);\n BlockHeap D(M, B);\n Length Bd = INF;\n for(int i = 0; i < (int)P.size(); i++) {\n Vertex u = P[i];\n D.insert(u, dhat_[u]);\n Bd = std::min(Bd, dhat_[u]);\n }\n // D.debug();\n std::unordered_set<Vertex> U;\n\n while((int)U.size() < k_ * std::pow(2, l * t_) && !D.empty()) {\n auto bs = D.pull();\n Length Bi = bs.first; std::vector<Vertex> Si = bs.second;\n auto bu = BMSSP(l - 1, Bi, Si);\n Length Bid = bu.first; std::vector<Vertex> Ui = bu.second;\n // std::cout << \"Bid=\" << Bid << std::endl;\n // std::cout << \"Ui=\"; debug_vertex_set(Ui);\n // std::cout << \"U=\"; debug_vertex_set(std::vector<Vertex>(U.begin(), U.end()));\n for(int j = 0; j < (int)Ui.size(); j++) {\n // if(U.count(Ui[j]) != 0) {\n // std::cout << \"Ufound\" << \" \" << Ui[j] << \" \" << dhat_[Ui[j]] << \" \" << Bi << \" \" << Bid << std::endl;\n // }\n U.insert(Ui[j]);\n }\n\n std::vector<std::pair<Vertex, Length>> K;\n for(int j = 0; j < (int)Ui.size(); j++) {\n Vertex u = Ui[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n Length new_dist = dhat_[u] + w;\n dhat_[v] = new_dist;\n if(Bi <= new_dist && new_dist < B) {\n D.insert(v, new_dist);\n } else if(Bid <= new_dist && new_dist < Bi) {\n K.push_back(std::make_pair(v, new_dist));\n }\n }\n }\n }\n for(int i = 0; i < (int)Si.size(); i++) {\n int u = Si[i];\n if(Bid <= dhat_[u] && dhat_[u] < Bi) K.push_back(std::make_pair(u, dhat_[u]));\n }\n D.batch_prepend(K);\n Bd = Bid;\n }\n Bd = std::min(Bd, B);\n for(int i = 0; i < (int)W.size(); i++) {\n Vertex u = W[i];\n if(dhat_[u] < Bd) U.insert(u);\n }\n if(l == 3) {\n for(int i = 0; i < (int)G_.size(); i++) {\n // if(!U.count(i) && dhat_[i] != INF) {\n // std::cout << \"found: \" << i << \" \" << dhat_[i] << std::endl;\n // }\n }\n }\n // std::cout << \"BMSSP k=\" << k_ << \", t=\" << t_ << \", l=\" << l << \", B=\" << B << \", Bd=\" << Bd << std::endl;\n // std::cout << \"U size:=\" << U.size() << \" \" << (D.empty() ? \"empty\" : \"notempty\") << std::endl;\n return std::make_pair(Bd, std::vector<Vertex>(U.begin(), U.end()));\n}\n\nstd::pair<Length, std::vector<Vertex>> ShortestPath::base_case(Length B, const std::vector<Vertex>& S) {\n assert(S.size() == 1);\n\n Vertex x = S[0];\n // std::cout << \"base_case k=\" << k_ << \", t=\" << t_ << \", B=\" << B << \", x=\" << x << std::endl; \n\n std::unordered_set<Vertex> U0(S.begin(), S.end());\n Heap H;\n H.push(x, dhat_[x]);\n\n while(!H.empty() && (int)U0.size() < k_ + 1) {\n auto p = H.top(); H.pop();\n Vertex u = p.first; Length d = p.second;\n U0.insert(u);\n\n for(int i = 0; i < (int)G_[u].size(); i++) {\n int v = G_[u][i].first; Length w = G_[u][i].second;\n if(dhat_[v] >= dhat_[u] + w && dhat_[u] + w < B) {\n dhat_[v] = dhat_[u] + w;\n H.push(v, dhat_[v]);\n }\n }\n // H.debug();\n }\n\n if((int)U0.size() <= k_) {\n return make_pair(B, std::vector<Vertex>(U0.begin(), U0.end()));\n } else {\n Length Bd = -INF;\n std::vector<Vertex> U;\n for(auto u: U0) {\n Bd = std::max(Bd, dhat_[u]);\n }\n for(auto u: U0) {\n if(dhat_[u] < Bd) {\n U.push_back(u);\n }\n }\n return make_pair(Bd, U);\n }\n}\n\n\nstd::pair<std::vector<Vertex>, std::vector<Vertex>> ShortestPath::find_pivots(Length B, const std::vector<Vertex>& S) {\n std::unordered_set<Vertex> W(S.begin(), S.end());\n std::vector<Vertex> Wp = S;\n\n for(auto v: W) {\n prev_[v] = -1;\n }\n\n for(int i = 0; i < k_; i++) {\n std::vector<Vertex> Wi; \n for(int j = 0; j < (int)Wp.size(); j++) {\n Vertex u = Wp[j];\n for(int k = 0; k < (int)G_[u].size(); k++) {\n Vertex v = G_[u][k].first; Length w = G_[u][k].second;\n if(dhat_[v] >= dhat_[u] + w) {\n dhat_[v] = dhat_[u] + w;\n prev_[v] = u;\n // if(dhat_[u] + w < B) {\n Wi.push_back(v);\n // }\n }\n }\n }\n for(int k = 0; k < (int)Wi.size(); k++) {\n W.insert(Wi[k]);\n }\n if((int)W.size() >= k_ * (int)S.size()) {\n return std::make_pair(S, std::vector<Vertex>(W.begin(), W.end()));\n }\n Wp = Wi;\n // std::cout << \"Wp =\"; debug_vertex_set(Wp);\n }\n\n for(auto v: W) {\n tree_size_[v] = -1;\n F_[v].clear();\n }\n for(auto v: W) {\n Vertex u = prev_[v];\n if(u == -1) continue;\n F_[u].push_back(v);\n }\n std::vector<Vertex> P;\n for(int i = 0; i < (int)S.size(); i++) {\n Vertex u = S[i];\n // std::cout << \"find_tree_size: \" << u << \" \" << find_tree_size(u, tree_size_, F_) << std::endl;\n if(find_tree_size(u, tree_size_, F_) >= k_ && prev_[u] == -1) {\n P.push_back(u);\n }\n }\n return std::make_pair(P, std::vector<Vertex>(W.begin(), W.end()));\n}\n\n\n\n\nvoid find_shortest_path(int s, const Graph& G) {\n int N = (int)G.size();\n double t = std::floor(std::pow(std::log2(N), 2.0 / 3.0));\n double l = std::ceil(std::log2(N) / t);\n ShortestPath shortest_path(s, G);\n std::vector<Vertex> S;\n S.push_back(s);\n auto bu = shortest_path.BMSSP(l, INF, S);\n // std::cout << \"Bfinal:=\" << bu.first << std::endl;\n shortest_path.print_dhat();\n}\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n int N, M, s;\n std::cin >> N >> M >> s;\n Graph G(N);\n for(int i = 0; i < M; i++) {\n int a, b; Length c;\n std::cin >> a >> b >> c;\n G[a].push_back(std::make_pair(b, c));\n }\n find_shortest_path(s, G);\n return 0;\n}", "accuracy": 1, "time_ms": 970, "memory_kb": 41816, "score_of_the_acc": -1.6608, "final_rank": 20 } ]
aoj_GRL_2_A_cpp
Minimum Spanning Tree Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = ( V , E ). Input |V| |E| s 0 t 0 w 0 s 1 t 1 w 1 : s |E|-1 t |E|-1 w |E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V| -1 respectively. s i and t i represent source and target verticess of i -th edge (undirected) and w i represents the weight of the i -th edge. Output Print the sum of the weights of the Minimum Spanning Tree. Constraints 1 ≤ |V| ≤ 10,000 0 ≤ |E| ≤ 100,000 0 ≤ w i ≤ 10,000 The graph is connected There are no parallel edges There are no self-loops Sample Input 1 4 6 0 1 2 1 2 1 2 3 1 3 0 1 0 2 3 1 3 5 Sample Output 1 3 Sample Input 2 6 9 0 1 1 0 2 3 1 2 1 1 3 7 2 4 1 1 4 3 3 4 1 3 5 1 4 5 6 Sample Output 2 5
[ { "submission_id": "aoj_GRL_2_A_11063691", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint MAX_WEIGHT = 10000;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, weight\n};\n\nvoid tmp(const vector<Node> &nodes, vector<int> &weights, int current)\n{\n for (pair<int, int> p : nodes[current].children)\n {\n int d = p.first;\n int w = p.second;\n\n if (w < weights[d])\n {\n weights[d] = w;\n tmp(nodes, weights, d);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n\n vector<Node> nodes(vertexN);\n for (int i = 0; i < edgeN; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.emplace_back(t, w);\n nodes[t].children.emplace_back(s, w);\n }\n\n vector<int> weights(vertexN, MAX_WEIGHT);\n weights[0] = 0;\n tmp(nodes, weights, 0);\n\n int sum = 0;\n for (int w : weights)\n {\n sum += w;\n }\n cout << sum << endl;\n}\n\n// 各点から最短距離を求め続ける、始点から始める\n// 未探索 or 最短になる場合はその点にアクセス\n// アクセスした点から別の点にアクセス、これを繰り返す\n// 未探索の点がある場合はその点から最短距離を求める\n// ↑ここ要修正\n// なんか似たことやったことある気がするなぁ", "accuracy": 0.25, "time_ms": 30, "memory_kb": 4840, "score_of_the_acc": -0.2521, "final_rank": 20 }, { "submission_id": "aoj_GRL_2_A_11063686", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint MAX_WEIGHT = 10000;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, weight\n};\n\nvoid tmp(const vector<Node> &nodes, vector<int> &weights, int current)\n{\n for (pair<int, int> p : nodes[current].children)\n {\n int d = p.first;\n int w = p.second;\n\n if (w < weights[d])\n {\n weights[d] = w;\n tmp(nodes, weights, d);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n\n vector<Node> nodes(vertexN);\n for (int i = 0; i < edgeN; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.emplace_back(t, w);\n nodes[t].children.emplace_back(s, w);\n }\n\n vector<int> weights(vertexN, MAX_WEIGHT);\n weights[0] = 0;\n tmp(nodes, weights, 0);\n for (int i = 1; i < vertexN; i++)\n {\n if (weights[i] == MAX_WEIGHT)\n {\n tmp(nodes, weights, i);\n }\n }\n\n int sum = 0;\n for (int w : weights)\n {\n sum += w;\n }\n cout << sum << endl;\n}\n\n// 各点から最短距離を求め続ける、始点から始める\n// 未探索 or 最短になる場合はその点にアクセス\n// アクセスした点から別の点にアクセス、これを繰り返す\n// 未探索の点がある場合はその点から最短距離を求める\n// ↑ここ要修正\n// なんか似たことやったことある気がするなぁ", "accuracy": 0.25, "time_ms": 30, "memory_kb": 4748, "score_of_the_acc": -0.243, "final_rank": 19 }, { "submission_id": "aoj_GRL_2_A_11055716", "code_snippet": "#include <bits/stdc++.h>\n#pragma GCC target(\"avx2\")\n#ifndef LOCAL\n#pragma GCC optimize(\"O3\")\n#endif\n#pragma GCC optimize(\"unroll-loops\")\n\n/// @brief Union-Find 木\n/// @note 1.4 高速化 + 省メモリ化\n/// @see https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/viewer/union-find\nclass UnionFind\n{\npublic:\n\n\tUnionFind() = default;\n\n\t/// @brief Union-Find 木を構築します。\n\t/// @param n 要素数\n\texplicit UnionFind(size_t n)\n\t\t: m_parentsOrSize(n, -1) {}\n\n\t/// @brief 頂点 i の root のインデックスを返します。\n\t/// @param i 調べる頂点のインデックス\n\t/// @return 頂点 i の root のインデックス\n\tint find(int i)\n\t{\n\t\tif (m_parentsOrSize[i] < 0)\n\t\t{\n\t\t\treturn i;\n\t\t}\n\n\t\t// 経路圧縮\n\t\treturn (m_parentsOrSize[i] = find(m_parentsOrSize[i]));\n\t}\n\n\t/// @brief a のグループと b のグループを統合します。\n\t/// @param a 一方のインデックス\n\t/// @param b 他方のインデックス\n\tvoid merge(int a, int b)\n\t{\n\t\ta = find(a);\n\t\tb = find(b);\n\n\t\tif (a != b)\n\t\t{\n\t\t\t// union by size (小さいほうが子になる)\n\t\t\tif (-m_parentsOrSize[a] < -m_parentsOrSize[b])\n\t\t\t{\n\t\t\t\tstd::swap(a, b);\n\t\t\t}\n\n\t\t\tm_parentsOrSize[a] += m_parentsOrSize[b];\n\t\t\tm_parentsOrSize[b] = a;\n\t\t}\n\t}\n\n\t/// @brief a と b が同じグループに属すかを返します。\n\t/// @param a 一方のインデックス\n\t/// @param b 他方のインデックス\n\t/// @return a と b が同じグループに属す場合 true, それ以外の場合は false\n\tbool connected(int a, int b)\n\t{\n\t\treturn (find(a) == find(b));\n\t}\n\n\t/// @brief i が属するグループの要素数を返します。\n\t/// @param i インデックス\n\t/// @return i が属するグループの要素数\n\tint size(int i)\n\t{\n\t\treturn -m_parentsOrSize[find(i)];\n\t}\n\nprivate:\n\n\t// m_parentsOrSize[i] は i の 親,\n\t// ただし root の場合は (-1 * そのグループに属する要素数)\n\tstd::vector<int> m_parentsOrSize;\n};\n\n#ifdef ONLINE_JUDGE\n#include <atcoder/all>\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n#ifdef LOCAL\n#define GLIBCXX_DEBUG\n#else\n#define endl \"\\n\"\n#endif\nusing namespace std;using ll=long long;using ull=unsigned long long;using dl=long double;\n#define rep(i,n) for(ll i=0; i<(n); i++)\n#define rrep(i,n) for(ll i=1; i<=(n); i++)\n#define drep(i,n) for(ll i=(n)-1; i>=0; i--)\n#define xfor(i,s,e) for(ll i=(s); i<(e); i++)\n#define rxfor(i,s,e) for(ll i=(s); i<=(e); i++)\n#define dfor(i,s,e) for(ll i=(s)-1; i>=(e); i--)\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define chmax(x,y) x = max((x),(y))\n#define chmin(x,y) x = min((x),(y))\n#define popcnt(s) ll(__popcount<ull>(uint64_t(s)))\ntemplate<typename T>istream&operator>>(istream&is,vector<T>&v){for(auto&in:v)is>>in;return is;}\ntemplate<typename T, typename U>ostream&operator<<(ostream&os,const pair<T,U>&v){os<<v.first<<\" \"<<v.second;return os;}\ntemplate<typename T>ostream&operator<<(ostream&os,const vector<T>&v){for(auto&in:v)os<<in<<' ';return os;}\ntemplate<typename T>ostream&operator<<(ostream&os,const vector<vector<T>>&v){for(auto&in:v)os<<in<<endl;return os;}\nll modpow(ll a, ll b, ll mod) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a) % mod;a = (a * a) % mod;b >>= 1;}return res;}\nll powl(ll a, ll b) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a);a = (a * a);b >>= 1;}return res;}\n#define pow2(a) (a)*(a)\n/*MOD MUST BE A PRIME NUMBER!!*/ll moddiv(const ll a, const ll b, const ll mod) {ll modinv = modpow(b, mod-2, mod);return (a * modinv) % mod;}\nconst ll INF = 2e15;\nll nC2(const ll i){return i>2?i*(i-1)/2:0;}ll nC3(const ll i){return i>3?i*(i-1)*(i-2)/6:0;}ll nC4(const ll i){return i>4?i*(i-1)*(i-2)*(i-3)/24:0;}ll nC5(const ll i){return i>5?i*(i-1)*(i-2)*(i-3)*(i-4)/120:0;}ll nC6(const ll i){return i>6?i*(i-1)*(i-2)*(i-3)*(i-4)*(i-5)/720:0;}\nvoid warshall_floyd(vector<vector<ll>>& dist) {const ull n = dist.size();rep(k, n) rep(i, n) rep(j, n) {dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j]);}}\n#define YES {cout<<\"Yes\\n\";return;}\n#define NO {cout<<\"No\\n\";return;}\n#define yn YES else NO\n#ifdef ONLINE_JUDGE\nusing lll = boost::multiprecision::cpp_int;\n//using lll = boost::multiprecision::int128_t;\nusing namespace atcoder;\n//using mint = modint1000000007;\nusing mint = modint998244353;\n//using mint = modint; // custom mod\n//atcoder::modint::set_mod(m);\n// DSU == UnionFind\n#endif\n#define vc vector\nusing P = pair<ll, ll>;using vl = vc<ll>;using vb=vc<bool>;using vs=vc<string>;using vvl=vc<vl>;using vp=vc<P>;\n#define pq priority_queue\ntemplate<typename T>void cs(vector<T>&v){xfor(i,1,v.size())v[i]+=v[i-1];}\n\nvl dx = {-1, 1, 0, 0, -1, 1, -1, 1};\nvl dy = {0, 0, 1, -1, -1, -1, 1, 1};\n\nconst ll mod = 998244353;\n\nvoid solve() {\n ll V, E;\n cin >> V >> E;\n \n pq<tuple<ll,ll,ll>, vector<tuple<ll,ll,ll>>, greater<>> q;\n rep(i, E) {\n ll s, t, w;\n cin >> s >> t >> w;\n q.emplace(w, s, t);\n }\n\n UnionFind tree(V);\n\n ll res = 0;\n while (!q.empty()) {\n auto [w,s,t] = q.top(); q.pop();\n if (!tree.connected(s,t)) {\n tree.merge(s,t);\n res += w;\n }\n }\n\n cout << res << endl;\n}\n\nint main() {\n ios_base::sync_with_stdio(false);\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n cout << fixed << setprecision(50);\n\n ll n = 1;\n //cin >> n;\n while (n--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7660, "score_of_the_acc": -0.33, "final_rank": 2 }, { "submission_id": "aoj_GRL_2_A_11053534", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n// #include \"all.h\"\n\n#define int long long\n#define uint unsigned int\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define is2pow(n) (n && (!(n & (n - 1))))\n#define OPTIMIZE \\\n ios_base::sync_with_stdio(false); \\\n cin.tie(nullptr); \\\n cout.tie(nullptr);\n\nusing ld = long double;\nconstexpr int maxn = 2e5;\nconstexpr int maxk = 305;\nconstexpr long long inf = 1e18;\nconstexpr ld eps = 1e-8L;\nconstexpr long long mod = 998244353;\n\n\nstruct DSU {\n vector<int> parent;\n vector<int> rank;\n\n DSU(int n) : parent(n), rank(n,0) {\n iota(all(parent),0);\n }\n\n int find_set(int u) {\n if (u==parent[u]) return u;\n return parent[u] = find_set(parent[u]);\n }\n\n void union_set(int u, int v) {\n u = find_set(u);\n v = find_set(v);\n if (u==v) return;\n if (rank[u] < rank[v]) swap(u, v);\n parent[v] = u;\n if (rank[u] == rank[v]) rank[u]++;\n }\n};\n\n\nstruct Edge {\n int from,to,weight;\n Edge(int from, int to, int weight) : from(from), to(to), weight(weight) {}\n\n bool operator<(const Edge& e) const {\n return weight < e.weight;\n }\n};\n\nvector<Edge> edges;\n\nvoid solve() {\n int n,m; cin >> n >> m;\n DSU dsu(n);\n for (int i = 0; i < m; i++) {\n int u,v,w; cin >> u >> v >> w;\n edges.emplace_back(u,v,w);\n }\n sort(all(edges));\n int res= 0;\n for (auto& edge : edges) {\n auto [from,to,weight] = edge;\n if (dsu.find_set(from) != dsu.find_set(to)) {\n dsu.union_set(from,to);\n res+=weight;\n }\n }\n cout << res <<\"\\n\";\n}\n\n#define TES\n#define LOCA\n#define FIL\n\nint32_t main() {\n OPTIMIZE;\n\n#ifdef FILE\n freopen(\"coins.in\", \"r\", stdin);\n freopen(\"coins.out\", \"w\", stdout);\n#endif\n#ifdef LOCAL\n freopen(\"/home/sq/CLionProjects/graph/input.txt\", \"r\", stdin);\n#endif\n int tt = 1;\n#ifdef TEST\n cin >> tt;\n#endif\n while (tt--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7784, "score_of_the_acc": -0.3423, "final_rank": 3 }, { "submission_id": "aoj_GRL_2_A_11024351", "code_snippet": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nstruct Edge {\n int weight;\n int endA;\n int endB;\n Edge(int w, int a, int b) : weight(w), endA(a), endB(b) {}\n};\n\nint main() {\n int V, E;\n std::cin >> V >> E;\n std::vector<Edge> G;\n for (int i = 0; i < E; ++i) {\n int s, t, w;\n std::cin >> s >> t >> w;\n G.emplace_back(w, s, t);\n }\n std::vector<int> table(V); // 各頂点が属する木の番号表\n std::iota(table.begin(), table.end(), 0); // 最初は頂点毎に異なる木\n int sum = 0;\n int count = 0;\n \n // 辺を安い順に見る\n std::sort(G.begin(), G.end(), [](const Edge& a, const Edge& b) {\n return a.weight < b.weight;\n });\n for (Edge e : G) {\n // 辺を結んで循環するなら使わない\n if (table[e.endA] == table[e.endB]) continue;\n\n // 異なる木を結んだら、同じ木にする\n // 変更対象範囲の値を参照渡ししないようにコピーをとる\n std::replace(table.begin(), table.end(), int(table[e.endA]), int(table[e.endB]));\n\n // 辺を加える\n sum += e.weight;\n if (++count == V - 1) break; // 全ての頂点を結べば終了(全て結んだあとは循環になるのでこの判定は無くてもいい)\n }\n\n std::cout << sum << std::endl;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5076, "score_of_the_acc": -1.0753, "final_rank": 16 }, { "submission_id": "aoj_GRL_2_A_11012538", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\n#include <random>\n#include <chrono>\nusing namespace std;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 5000010;\nconst int MAX_W = 100002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\nconst int INF = 2147483647;\n//using ll = long long;\n\n// kruskal\nstruct edge { long long u, v; long long cost; };\nlong long V, E;\nedge es[MAX_W];\nlong long par[MAX_N];\nlong long rank1[MAX_N];\nlong long siz[MAX_N];\n\nvoid init(long long n) {\n\tfor (long long i = 0; i < n; i++) {\n\t\tpar[i] = i;\n\t\trank1[i] = 0;\n\t\tsiz[i] = 1;\n\t}\n}\n\nlong long find(long long x) {\n\tif (par[x] == x) {\n\t\treturn x;\n\t}\n\telse {\n\t\treturn par[x] = find(par[x]);\n\t}\n}\n\nvoid unite(long long x, long long y) {\n\tx = find(x);\n\ty = find(y);\n\tif (x == y) return;\n\n\tif (rank1[x] < rank1[y]) {\n\t\tpar[x] = y;\n\t\tsiz[y] += siz[x];\n\t}\n\telse {\n\t\tpar[y] = x;\n\t\tsiz[x] += siz[y];\n\t\tif (rank1[x] == rank1[y]) rank1[x]++;\n\t}\n}\n\nbool same(long long x, long long y) {\n\treturn find(x) == find(y);\n}\n\nlong long usize(long long x) {\n\treturn siz[find(x)];\n}\n\nbool comp(const edge& e1, const edge& e2) {\n\treturn e1.cost < e2.cost;\n}\n\nlong long kruskal() {\n\tsort(es, es + E, comp);\n\tinit(V);\n\tlong long res = 0;\n\tfor (long long i = 0; i < E; i++) {\n\t\tedge e = es[i];\n\t\tif (!same(e.u, e.v)) {\n\t\t\tunite(e.u, e.v);\n\t\t\tres += e.cost;\n\t\t}\n\t}\n\treturn res;\n}\n\n\n\n\nint main() {\n\n\tcin >> V >> E;\n\tfor (long long e = 0; e < E; e++) {\n\t\tlong long u, v, cost;\n\t\tcin >> u >> v >> cost;\n\t\tes[e].u = u;\n\t\tes[e].v = v;\n\t\tes[e].cost = cost;\n\t}\n\n\tcout << kruskal() << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 10312, "score_of_the_acc": -0.9915, "final_rank": 14 }, { "submission_id": "aoj_GRL_2_A_11011008", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\nstruct Edge{\n int from;\n int to;\n ll cost;\n Edge(int from, int to, ll cost=1): from(from), to(to), cost(cost){}\n};\nusing Graph = vvc<Edge>;\n\n/* Prim :プリム法でMSTの重みの総和を求める\n Prim(g,r=0): 無向グラフgからrを根とするMSTをつくる\n 計算量: O(|E|log|V|)\n*/\nll Prim(const Graph &g, int r=0){\n\tll sum=0; // 最小全域木の重みの総和\n vb flag(sz(g));\n using P=pair<ll,int>;\n pqg<P> q;\n q.emplace(0,0);\n while(sz(q)){\n auto [c,u]=q.top(); q.pop();\n if(flag[u]) continue;\n flag[u]=true;\n sum+=c;\n for(auto [from,to,cost]: g[u]){\n if(flag[to]) continue;\n q.emplace(cost,to);\n }\n }\n return sum;\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n,m; cin >> n >> m;\n Graph g(n);\n rep(i,m){\n int s,t; ll c; cin >> s >> t >> c;\n g[s].eb(s,t,c);\n g[t].eb(t,s,c);\n }\n cout << Prim(g) << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 10620, "score_of_the_acc": -0.8218, "final_rank": 12 }, { "submission_id": "aoj_GRL_2_A_11011004", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* UnionFind\n root(x): xの根。O(α(n))\n size(x): x を含む集合の要素数。\n same(x, y): x と y が同じ集合にいるか。O(α(n))\n merge(x, y): x と y を同じ集合にする。 O(α(n))\n*/\nstruct UF{\n int _n;\n vi par;\n UF(): _n(0){}\n UF(int n): _n(n),par(n,-1){}\n int root(int x){\n if(par[x] < 0) return x;\n return par[x] = root(par[x]); //経路圧縮\n }\n int size(int x){\n return -par[root(x)];\n }\n bool same(int x, int y){\n return root(x) == root(y);\n }\n bool merge(int x, int y){\n int rx = root(x), ry = root(y);\n if(rx == ry) return false;\n if(-par[rx]<-par[ry]) swap(rx,ry);\n par[rx] += par[ry];\n par[ry] = rx;\n return true;\n }\n};\n\nstruct Edge{\n int from;\n int to;\n ll cost;\n Edge(int from, int to, ll cost=1): from(from), to(to), cost(cost){}\n};\nusing Graph = vvc<Edge>;\n\n/* Kruskal :クラスカル法で minimum spanning tree を求める構造体\n Kruskal(g): 無向グラフgからMSTをつくる\n sum: MSTの重みの総和\n 計算量: O(|E|log|V|)\n*/\nll kruskal(const Graph &g){\n\tvc<Edge> edges;\n\tint n=sz(g);\n\tll sum=0; // 最小全域木の重みの総和\n\trep(i,n) for(auto &e: g[i]) edges.pb(e);\n\tsort(all(edges), [&](Edge a, Edge b){ return a.cost < b.cost; });\n\tUF uf(n);\n\tfor (auto &e : edges) {\n\t\tif (!uf.same(e.from, e.to)) {\n\t\t\tuf.merge(e.from, e.to);\n\t\t\tsum += e.cost;\n\t\t}\n\t}\n return sum;\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n,m; cin >> n >> m;\n Graph g(n);\n rep(i,m){\n int s,t; ll c; cin >> s >> t >> c;\n g[s].eb(s,t,c);\n g[t].eb(t,s,c);\n }\n cout << kruskal(g) << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 14252, "score_of_the_acc": -1.1799, "final_rank": 17 }, { "submission_id": "aoj_GRL_2_A_11010813", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* UnionFind\n root(x): xの根。O(α(n))\n size(x): x を含む集合の要素数。\n same(x, y): x と y が同じ集合にいるか。O(α(n))\n merge(x, y): x と y を同じ集合にする。 O(α(n))\n*/\nstruct UF{\n int _n;\n vi par;\n UF(): _n(0){}\n UF(int n): _n(n),par(n,-1){}\n int root(int x){\n if(par[x] < 0) return x;\n return par[x] = root(par[x]); //経路圧縮\n }\n int size(int x){\n return -par[root(x)];\n }\n bool same(int x, int y){\n return root(x) == root(y);\n }\n bool merge(int x, int y){\n int rx = root(x), ry = root(y);\n if(rx == ry) return false;\n if(-par[rx]<-par[ry]) swap(rx,ry);\n par[rx] += par[ry];\n par[ry] = rx;\n return true;\n }\n};\n\nstruct Edge{\n int from;\n int to;\n ll cost;\n Edge(int from, int to, ll cost=1): from(from), to(to), cost(cost){}\n};\nusing Graph = vvc<Edge>;\n\n/* Kruskal :クラスカル法で minimum spanning tree を求める構造体\n Kruskal(g): 無向グラフgからMSTをつくる\n sum: MSTの重みの総和\n 計算量: O(|E|log|V|)\n*/\nstruct Kruskal {\n\tvc<Edge> edges;\n\tll sum=0; // 最小全域木の重みの総和\n\tint n;\n\tKruskal(const Graph &g) : n(sz(g)) {\n\t\trep(i,n) for(auto &e: g[i]) edges.pb(e);\n\t\tbuild();\n\t}\n\tvoid build() {\n\t\tsort(all(edges),[&](Edge a, Edge b){ return a.cost < b.cost; });\n\t\tUF uf(n);\n\t\tfor (auto &e : edges) {\n\t\t\tif (!uf.same(e.from, e.to)) {\n\t\t\t\tuf.merge(e.from, e.to);\n\t\t\t\tsum += e.cost;\n\t\t\t}\n\t\t}\n\t}\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n,m; cin >> n >> m;\n Graph g(n);\n rep(i,m){\n int s,t; ll c; cin >> s >> t >> c;\n g[s].eb(s,t,c);\n g[t].eb(t,s,c);\n }\n Kruskal k(g);\n cout << k.sum << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 14456, "score_of_the_acc": -1.2, "final_rank": 18 }, { "submission_id": "aoj_GRL_2_A_11010812", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\nstruct Edge{\n int from;\n int to;\n ll cost;\n Edge(int from, int to, ll cost=1): from(from), to(to), cost(cost){}\n};\nusing Graph = vvc<Edge>;\n\n/* Prim :プリム法で minimum spanning tree を求める構造体\n Prim(g,r): 無向グラフgからrを根とするMSTをつくる\n sum: 最小全域木の重みの総和\n 計算量: O(|E|log|V|)\n*/\nstruct Prim {\n\tll sum=0; // 最小全域木の重みの総和\n\tPrim(const Graph &g, int r=0){\n vb flag(sz(g));\n using P=pair<ll,int>;\n pqg<P> q;\n q.emplace(0,0);\n while(sz(q)){\n auto [c,u]=q.top(); q.pop();\n if(flag[u]) continue;\n flag[u]=true;\n sum+=c;\n for(auto [from,to,cost]: g[u]){\n if(flag[to]) continue;\n q.emplace(cost,to);\n }\n }\n }\n};\n\n\nint main(){\t\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n,m; cin >> n >> m;\n Graph g(n);\n rep(i,m){\n int s,t; ll c; cin >> s >> t >> c;\n g[s].eb(s,t,c);\n g[t].eb(t,s,c);\n }\n Prim k(g);\n cout << k.sum << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 10628, "score_of_the_acc": -0.8226, "final_rank": 13 }, { "submission_id": "aoj_GRL_2_A_11010804", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* UnionFind\n root(x): xの根。O(α(n))\n size(x): x を含む集合の要素数。\n same(x, y): x と y が同じ集合にいるか。O(α(n))\n merge(x, y): x と y を同じ集合にする。 O(α(n))\n*/\nstruct UF{\n int _n;\n vi par;\n UF(): _n(0){}\n UF(int n): _n(n),par(n,-1){}\n int root(int x){\n if(par[x] < 0) return x;\n return par[x] = root(par[x]); //経路圧縮\n }\n int size(int x){\n return -par[root(x)];\n }\n bool same(int x, int y){\n return root(x) == root(y);\n }\n bool merge(int x, int y){\n int rx = root(x), ry = root(y);\n if(rx == ry) return false;\n if(-par[rx]<-par[ry]) swap(rx,ry);\n par[rx] += par[ry];\n par[ry] = rx;\n return true;\n }\n};\n\nstruct Edge{\n int from;\n int to;\n ll cost;\n Edge(int from, int to, ll cost=1): from(from), to(to), cost(cost){}\n};\nusing Graph = vvc<Edge>;\n\n/* Kruskal :クラスカル法で minimum spanning tree を求める構造体\n Kruskal(g): 無向グラフgからMSTをつくる\n sum: MSTの重みの総和\n 計算量: O(|E|log|V|)\n*/\nstruct Kruskal {\n\tvc<Edge> edges;\n\tll sum=0; // 最小全域木の重みの総和\n\tint n;\n\tKruskal(const Graph &g) : n(sz(g)) {\n\t\trep(i,n) for(auto &e: g[i]) edges.pb(e);\n\t\tbuild();\n\t}\n\tvoid build() {\n\t\tsort(all(edges),[&](Edge a, Edge b){ return a.cost < b.cost; });\n\t\tUF uf(n);\n\t\tfor (auto &e : edges) {\n\t\t\tif (!uf.same(e.from, e.to)) {\n\t\t\t\tuf.merge(e.from, e.to);\n\t\t\t\tsum += e.cost;\n\t\t\t}\n\t\t}\n\t}\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n,m; cin >> n >> m;\n Graph g(n);\n rep(i,m){\n int s,t; ll c; cin >> s >> t >> c;\n g[s].eb(s,t,c);\n }\n Kruskal k(g);\n cout << k.sum << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8028, "score_of_the_acc": -0.3663, "final_rank": 4 }, { "submission_id": "aoj_GRL_2_A_11010797", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* UnionFind\n root(x): xの根。O(α(n))\n size(x): x を含む集合の要素数。\n same(x, y): x と y が同じ集合にいるか。O(α(n))\n merge(x, y): x と y を同じ集合にする。 O(α(n))\n*/\nstruct UF{\n int _n;\n vi par;\n UF(): _n(0){}\n UF(int n): _n(n),par(n,-1){}\n int root(int x){\n if(par[x] < 0) return x;\n return par[x] = root(par[x]); //経路圧縮\n }\n int size(int x){\n return -par[root(x)];\n }\n bool same(int x, int y){\n return root(x) == root(y);\n }\n bool merge(int x, int y){\n int rx = root(x), ry = root(y);\n if(rx == ry) return false;\n if(-par[rx]<-par[ry]) swap(rx,ry);\n par[rx] += par[ry];\n par[ry] = rx;\n return true;\n }\n};\n\nstruct Edge{\n int from;\n int to;\n ll cost;\n Edge(int from, int to, ll cost=1): from(from), to(to), cost(cost){}\n};\nusing Graph = vvc<Edge>;\n\n/* Kruskal :クラスカル法で minimum spanning tree を求める構造体\n 入力: Graph g\n 最小全域木の重みの総和: sum\n 計算量: O(|E|log|V|)\n*/\nstruct Kruskal {\n\tUF uf;\n\tvc<Edge> edges;\n\tll sum; // 最小全域木の重みの総和\n\tint n;\n\tKruskal(const Graph &g) : n(sz(g)) {\n\t\trep(i,n) for(auto &e: g[i]) edges.pb(e);\n\t\tinit();\n\t}\n\tvoid init() {\n\t\tsort(all(edges),[&](Edge a, Edge b)->bool{\n\t\t\treturn a.cost < b.cost;\n\t\t});\n\t\tuf = UF(n);\n\t\tsum = 0;\n\t\tfor (auto &e : edges) {\n\t\t\tif (!uf.same(e.from, e.to)) {\n\t\t\t\tuf.merge(e.from, e.to);\n\t\t\t\tsum += e.cost;\n\t\t\t}\n\t\t}\n\t}\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n,m; cin >> n >> m;\n Graph g(n);\n rep(i,m){\n int s,t; ll c; cin >> s >> t >> c;\n g[s].eb(s,t,c);\n }\n Kruskal k(g);\n cout << k.sum << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8040, "score_of_the_acc": -0.3675, "final_rank": 6 }, { "submission_id": "aoj_GRL_2_A_11010788", "code_snippet": "#define _USE_MATH_DEFINES\n#include<bits/stdc++.h>\n#define OVERLOAD_REP(v1, v2, v3, v4, NAME, ...) NAME\n#define REP1(i, n) for (int i = 0; (i) < (n); ++(i))\n#define REP2(i, l, r) for (int i = (l); (i) < (r); ++(i))\n#define REP3(i, l, r, d) for (int i = (l); (i) < (r); (i)+=(d))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(__VA_ARGS__)\n#define OVERLOAD_PRE(v1, v2, v3, v4, NAME, ...) NAME\n#define PRE1(i, n) for (int i = (n)-1; (i) >= 0; --(i)) // [0,n)\n#define PRE2(i, l, r) for (int i = (r)-1; (i) >= (l); --(i)) //[l,r)\n#define PRE3(i, l, r, d) for (int i = (r)-1; (i) >= (l); (i)-=(d))\n#define pre(...) OVERLOAD_PRE(__VA_ARGS__, PRE3, PRE2, PRE1)(__VA_ARGS__)\n#define bg begin()\n#define en end()\n#define rbg rbegin()\n#define ren rend()\n#define all(x) x.bg,x.en\n#define rall(x) x.rbg,x.ren\n#define pf push_front\n#define pb push_back\n#define eb emplace_back\n#define fir first\n#define sec second\n#define sz(x) ((int)(x).size())\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = long double;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing sti = stack<int>;\nusing sei = set<int>;\nusing qi = queue<int>;\nusing qii = queue<pii>;\nusing dqi = deque<int>;\ntemplate<class t, class s> using umap = unordered_map<t,s>;\ntemplate<class t> using uset = unordered_set<t>;\ntemplate<class t> using mset = multiset<t>;\ntemplate<class t> using pq=priority_queue<t>;\ntemplate<class t> using pqg=priority_queue<t,vector<t>, greater<t>>;\ntemplate<class t> using vc=vector<t>;\ntemplate<class t> using vvc=vc<vc<t>>;\ntemplate<class t> using vvvc=vc<vc<vc<t>>>;\nusing vi=vc<int>;\nusing vvi=vc<vc<int>>;\nusing vll=vc<ll>;\nusing vvll=vc<vc<ll>>;\nusing vd=vc<double>;\nusing vvd=vc<vc<double>>;\nusing vb=vc<bool>;\nusing vvb=vc<vc<bool>>;\nusing vch=vc<char>;\nusing vs=vc<string>;\nconst int inf = 1001001001;\nconst ll infl = 1LL << 60;\nconst ll mod = 998244353;\ntemplate<class t,class u> bool chmax(t&a,u b){if(a<b){a=b; return true;} return false;}\ntemplate<class t,class u> bool chmin(t&a,u b){if(a>b){a=b; return true;} return false;}\nvoid yes(){ cout << \"Yes\" << '\\n'; }\nvoid no(){ cout << \"No\" << '\\n'; }\n\n/* UnionFind\n root(x): xの根。O(α(n))\n size(x): x を含む集合の要素数。\n same(x, y): x と y が同じ集合にいるか。O(α(n))\n merge(x, y): x と y を同じ集合にする。 O(α(n))\n*/\nstruct UF{\n int _n;\n vi par;\n UF(): _n(0){}\n UF(int n): _n(n),par(n,-1){}\n int root(int x){\n if(par[x] < 0) return x;\n return par[x] = root(par[x]); //経路圧縮\n }\n int size(int x){\n return -par[root(x)];\n }\n bool same(int x, int y){\n return root(x) == root(y);\n }\n bool merge(int x, int y){\n int rx = root(x), ry = root(y);\n if(rx == ry) return false;\n if(-par[rx]<-par[ry]) swap(rx,ry);\n par[rx] += par[ry];\n par[ry] = rx;\n return true;\n }\n};\n\nstruct Edge{\n int from;\n int to;\n ll cost;\n Edge(int from, int to, ll cost=1): from(from), to(to), cost(cost){}\n};\nusing Graph = vvc<Edge>;\n\n/* Kruskal :クラスカル法で minimum spanning tree を求める構造体\n 入力: Graph g\n 最小全域木の重みの総和: sum\n 計算量: O(|E|log|V|)\n*/\nstruct Kruskal {\n\tUF uf;\n\tvc<Edge> edges;\n\tll sum; // 最小全域木の重みの総和\n\tint n;\n\tKruskal(const Graph &g) : n(g.size()) {\n\t\trep(i,n) for(auto &e: g[i]) edges.pb(e);\n\t\tinit();\n\t}\n\tvoid init() {\n\t\tsort(all(edges),[&](Edge a, Edge b)->bool{\n\t\t\treturn a.cost < b.cost;\n\t\t});\n\t\tuf = UF(n);\n\t\tsum = 0;\n\t\tfor (auto &e : edges) {\n\t\t\tif (!uf.same(e.from, e.to)) {\n\t\t\t\tuf.merge(e.from, e.to);\n\t\t\t\tsum += e.cost;\n\t\t\t}\n\t\t}\n\t}\n};\n\nint main(){\t\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n,m; cin >> n >> m;\n Graph g(n);\n rep(i,m){\n int s,t; ll c; cin >> s >> t >> c;\n g[s].eb(s,t,c);\n }\n Kruskal k(g);\n cout << k.sum << \"\\n\";\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8032, "score_of_the_acc": -0.3667, "final_rank": 5 }, { "submission_id": "aoj_GRL_2_A_10986101", "code_snippet": "//原理是利用互斥集合(union-find)将边升序排列保证不出现环的情况下放入(n-1)条边\n//用上节课学的讲一个类的class(两个端点加边的权值)放进vecotr啊!!!\n#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nconst int MAX=10000;\nclass disjointset{//创个互斥集合来判断放哪些边\n public:\n vector<int> p,rank;\n disjointset(){}\n disjointset(int size){\n p.resize(size,0);\n rank.resize(size,0);\n for(int i=0;i<size;i++){\n makeset(i);\n }\n }\n void makeset(int i){\n p[i]=i;\n rank[i]=0;\n }\n bool same(int a,int b){\n return findset(a)==findset(b);\n }\n int findset(int a){\n if(a!=p[a]){\n p[a]=findset(p[a]);\n }\n return p[a];\n }\n void unite(int a,int b){\n link(findset(a),findset(b));\n }\n void link(int a,int b){\n if(rank[a]>rank[b]){\n p[b]=a;\n }else {\n p[a]=b;\n if(rank[a]==rank[b]){\n rank[b]++;\n }\n }\n }\n};\nclass Edge{\n public:\n int source;\n int target;\n int weight;\n Edge(int a,int b,int c):source(a),target(b),weight(c){}\n};\n bool edges(const Edge &a,const Edge &b){//注意自定义比较规则,引用前是类型后面你随便加个标识符,也可以在edge改变控制符\n return a.weight<b.weight;\n }\nvector<Edge> A;\nint main(){\n int V,E;\n scanf(\"%d %d\",&V,&E);\n disjointset ds=disjointset(V+1);\n long long sum=0;\n for(int i=0;i<E;i++){\n int s,t,w;\n scanf(\"%d %d %d\",&s,&t,&w);\n A.push_back(Edge(s,t,w));//在类定义完初始化方式,就可以pushback直接放进去\n }\n sort(A.begin(),A.end(),edges);\n int q=0;\n int i=0;\n while(q!=(V-1)){//从小到大放进n-1条边\n if(!ds.same(A[i].source,A[i].target)){\n ds.unite(A[i].source,A[i].target);\n q++;\n sum+=A[i].weight;\n }//可以不用外部指示器而只用并查集,因为放入n-1条边后之后same的判断肯定始终都是false\n i++;\n }\n printf(\"%lld\\n\",sum);\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4312, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_GRL_2_A_10962451", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n\n\n\n\n\n\nclass UnionFind {\n public:\n int par[100009];\n int siz[100009];\n\n void init(int n) {\n for(int i = 0; i < n; i++) par[i] = -1;\n for(int i = 0; i < n; i++) siz[i] = 1;\n }\n\n int root(int x) {\n if(par[x] == -1) return x;\n return root(par[x]);\n }\n\n void unite(int v, int u) {\n int rv = root(v), ru = root(u);\n if(rv == ru) return ;\n\n if(siz[rv] > siz[ru]) {\n par[ru] = rv;\n siz[rv] += siz[ru];\n } else {\n par[rv] = ru;\n siz[ru] += siz[rv];\n }\n }\n\n bool same(int v, int u) {\n return root(v) == root(u);\n }\n};\n\n\n\n\n\n\n\n\nint main() {\n int N, M; cin >> N >> M;\n vector<vector<pair<int, int>>> g(N);\n\n vector<int> A(M), B(M), C(M);\n\n for(int i = 0; i < M; i++) {\n cin >> A[i] >> B[i] >> C[i];\n }\n\n vector<pair<int, int>> len(M);\n for(int i = 0; i < M; i++) len[i] = {C[i], i};\n\n sort(len.begin(), len.end());\n\n\n UnionFind UF;\n UF.init(N);\n\n int ans = 0;\n for(int i = 0; i < M; i++) {\n int pos = len[i].second;\n if(UF.same(A[pos], B[pos])) continue;\n UF.unite(A[pos], B[pos]);\n ans += C[pos];\n }\n\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5452, "score_of_the_acc": -0.5124, "final_rank": 9 }, { "submission_id": "aoj_GRL_2_A_10954615", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nclass UnionFind {\n public:\n int par[100009];\n int siz[100009];\n\n // N 頂点の Union-Findを作成\n void init(int N) {\n for(int i = 0; i < N; i++) par[i] = -1;\n for(int i = 0; i < N; i++) siz[i] = 1;\n }\n\n // 頂点 x の根を返す関数\n int root(int x) {\n while(true) {\n if(par[x] == -1) break;\n x = par[x];\n }\n\n return x;\n }\n\n // 要素 u と v を結合する関数\n void unite(int u, int v) {\n int rootU = root(u);\n int rootV = root(v);\n if(rootU == rootV) return;\n\n if(siz[rootU] < siz[rootV]) {\n par[rootU] = rootV;\n siz[rootV] += siz[rootU];\n } else {\n par[rootV] = rootU;\n siz[rootU] += siz[rootV];\n }\n }\n\n // 要素 u と v が同じグループに属しているかどうか返す関数\n bool same(int u, int v) {\n return root(u) == root(v);\n }\n};\n\n\n\n\n\n\n\n\nint main() {\n int N, M; cin >> N >> M;\n UnionFind UF;\n vector<int> s(M), t(M), w(M);\n for(int i = 0; i < M; i++) cin >> s[i] >> t[i] >> w[i];\n\n vector<pair<int, int>> EdgeList;\n for(int i = 0; i < M; i++) EdgeList.push_back({w[i], i});\n sort(EdgeList.begin(), EdgeList.end());\n\n int ans = 0;\n UF.init(N);\n for(int i = 0; i < EdgeList.size(); i++) {\n int index = EdgeList[i].second;\n if(UF.same(s[index], t[index])) continue;\n UF.unite(s[index], t[index]);\n ans += w[index];\n }\n\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5276, "score_of_the_acc": -0.495, "final_rank": 7 }, { "submission_id": "aoj_GRL_2_A_10947796", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, a, n) for (int i = a; i < n; ++i)\n#define rrep(i, a, n) for (int i = n - 1; i >= a; --i)\nusing ll = long long;\nusing ld = long double;\nusing pl = pair<ll, ll>;\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing vp = vector<pl>;\nusing vvp = vector<vp>;\nusing vb = vector<bool>;\nusing vvb = vector<vb>;\nusing vs = vector<string>;\nusing vc = vector<char>;\nusing vvc = vector<vc>;\nconst int mod = 1000000007;\nconst ll hashh = 2147483647;\n\n#ifndef ATCODER_DSU_HPP\n#define ATCODER_DSU_HPP 1\n\n#include <algorithm>\n#include <cassert>\n#include <vector>\n\nnamespace atcoder\n{\n\n // Implement (union by size) + (path compression)\n // Reference:\n // Zvi Galil and Giuseppe F. Italiano,\n // Data structures and algorithms for disjoint set union problems\n struct dsu\n {\n public:\n dsu() : _n(0) {}\n explicit dsu(int n) : _n(n), parent_or_size(n, -1) {}\n\n int merge(int a, int b)\n {\n assert(0 <= a && a < _n);\n assert(0 <= b && b < _n);\n int x = leader(a), y = leader(b);\n if (x == y)\n return x;\n if (-parent_or_size[x] < -parent_or_size[y])\n std::swap(x, y);\n parent_or_size[x] += parent_or_size[y];\n parent_or_size[y] = x;\n return x;\n }\n\n bool same(int a, int b)\n {\n assert(0 <= a && a < _n);\n assert(0 <= b && b < _n);\n return leader(a) == leader(b);\n }\n\n int leader(int a)\n {\n assert(0 <= a && a < _n);\n return _leader(a);\n }\n\n int size(int a)\n {\n assert(0 <= a && a < _n);\n return -parent_or_size[leader(a)];\n }\n\n std::vector<std::vector<int>> groups()\n {\n std::vector<int> leader_buf(_n), group_size(_n);\n for (int i = 0; i < _n; i++)\n {\n leader_buf[i] = leader(i);\n group_size[leader_buf[i]]++;\n }\n std::vector<std::vector<int>> result(_n);\n for (int i = 0; i < _n; i++)\n {\n result[i].reserve(group_size[i]);\n }\n for (int i = 0; i < _n; i++)\n {\n result[leader_buf[i]].push_back(i);\n }\n result.erase(\n std::remove_if(result.begin(), result.end(),\n [&](const std::vector<int> &v)\n { return v.empty(); }),\n result.end());\n return result;\n }\n\n private:\n int _n;\n // root node: -1 * component size\n // otherwise: parent\n std::vector<int> parent_or_size;\n\n int _leader(int a)\n {\n if (parent_or_size[a] < 0)\n return a;\n return parent_or_size[a] = _leader(parent_or_size[a]);\n }\n };\n\n} // namespace atcoder\n\n#endif // ATCODER_DSU_HPP\n\nusing namespace atcoder;\n\n// main\nint main()\n{\n ll v, e, ans = 0;\n cin >> v >> e;\n dsu d(v);\n vector<tuple<ll, ll, ll>> s(e);\n rep(i, 0, e)\n {\n cin >> get<1>(s[i]) >> get<2>(s[i]) >> get<0>(s[i]);\n }\n sort(s.begin(), s.end());\n rep(i, 0, e)\n {\n if (!d.same(get<1>(s[i]), get<2>(s[i])))\n {\n d.merge(get<1>(s[i]), get<2>(s[i]));\n ans += get<0>(s[i]);\n }\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5420, "score_of_the_acc": -0.5092, "final_rank": 8 }, { "submission_id": "aoj_GRL_2_A_10926388", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n\nconst int MAXN = 10000;\n\nstruct Edge {\n int s;\n int t;\n int w;\n\n Edge(int s, int t, int w): s(s), t(t), w(w) {}\n int either() { return s; }\n int other(int v) { if (v == s) return t; return s; }\n int weight() { return w; }\n};\n\nstruct EdgeCompare {\n bool operator()(const Edge& lhs, const Edge& rhs) const {\n return lhs.w > rhs.w;\n }\n};\n\nstd::vector<Edge> G[MAXN];\nbool visited[MAXN];\nstd::priority_queue<Edge, std::vector<Edge>, EdgeCompare> pq;\nstd::queue<Edge> mst;\n\nvoid visit(int v)\n{\n visited[v] = true;\n for (int i = 0; i < G[v].size(); ++i) {\n if (!visited[G[v][i].other(v)]) {\n pq.push(G[v][i]);\n }\n }\n}\n\nint main()\n{\n int v, e;\n std::cin >> v >> e;\n for (int i = 0; i < e; ++i) {\n int s, t, w;\n std::cin >> s >> t >> w;\n G[s].push_back(Edge(s, t, w));\n G[t].push_back(Edge(t, s, w));\n }\n\n visit(0);\n while (!pq.empty()) {\n Edge e = pq.top();\n pq.pop();\n int v = e.either();\n int w = e.other(v);\n if (visited[v] && visited[w]) continue;\n mst.push(e);\n if (!visited[v]) visit(v);\n if (!visited[w]) visit(w);\n }\n\n int weight = 0;\n while (!mst.empty()) {\n Edge e = mst.front();\n mst.pop();\n weight += e.weight();\n }\n std::cout << weight << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 9024, "score_of_the_acc": -1.0645, "final_rank": 15 }, { "submission_id": "aoj_GRL_2_A_10889515", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/math>\nusing namespace atcoder;\n#endif\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vstr = vector<string>;\nusing vchr = vector<char>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(int i = (int)a; i < (int)b; i++)\n#define REP(i, a, b) for (int i = (int)a; i <= (int)b; i++)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\nconst long long MOD = 998244353;\n//const long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<class T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<class T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\n\n//xのn乗\nll llpow(ll x, ll n) {\n ll ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\nll modpow(ll x, ll n, ll mod) {\n ll ans = 1;\n while(n > 0) {\n if(n & 1) ans = ans * x % mod;\n x = x * x % mod;\n n >>= 1;\n }\n return ans;\n}\n//mod pでのaの逆元\nll inverse(ll a, ll p) {\n return modpow(a, p-2, p);\n}\n//nの階乗\nll fact(ll n) {\n if(n == 0) return 1;\n else return n * fact(n-1);\n}\nll modfact(ll n, ll mod) {\n if(n == 0) return 1;\n else return (n * modfact(n-1, mod)) % mod;\n}\n//nCr=n!/r!(n-r)! mod p\nll comb(ll n, ll r, ll mod) {\n ll a = modfact(n, mod), b = modfact(r, mod), c = modfact(n-r, mod);\n b = inverse(b, mod); c = inverse(c, mod);\n return (((a*b)%mod)*c)%mod;\n}\n\n//1+2+...+n = n(n+1)/2\nll triangle(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n//素数判定\nbool is_prime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\n//左回転\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\ndouble dist(ll a, ll b, ll x, ll y) {\n return sqrt((a-x)*(a-x) + (b-y)*(b-y));\n}\nint man(int a, int b, int x, int y) {\n return abs(a-x) + abs(b-y);\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n rep(i,0,H) rep(j,0,W) dist[i][j] = inf;\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n \n UnionFind(int N) : par(N) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int V, E; cin >> V >> E;\n priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<tuple<int,int,int>>> q;\n rep(i,0,E) {\n int s, t, w; cin >> s >> t >> w;\n q.push(make_tuple(w,s,t));\n }\n\n UnionFind tree(V);\n ll ans = 0;\n while(!q.empty()) {\n int w, s, t;\n tie(w, s, t) = q.top();\n if(!tree.same(s,t)) {\n ans += w;\n tree.unite(s,t);\n }\n q.pop();\n }\n cout << ans << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4820, "score_of_the_acc": -0.6501, "final_rank": 11 }, { "submission_id": "aoj_GRL_2_A_10886906", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\n\nclass DisjointSet {\n public:\n vector<int> rank, p;\n DisjointSet() = default;\n DisjointSet(int size) {\n rank.resize(size,0);\n p.resize(size,0);\n for (int i=0; i<size; i++) makeSet(i);\n }\n\n void makeSet(int x) {\n p[x] = x;\n rank[x] = 0;\n }\n\n bool same(int x, int y) {\n return findSet(x) == findSet(y);\n }\n\n void unite(int x, int y) {\n link(findSet(x), findSet(y));\n }\n\n void link(int x, int y) {\n if (rank[x] > rank[y]) {\n p[y] = x;\n } else {\n p[x] = y;\n if (rank[x] == rank[y]) {\n rank[y]++;\n }\n }\n }\n\n int findSet(int x) {\n if (x != p[x]) {\n p[x] = findSet(p[x]);\n }\n return p[x];\n }\n};\n\n\nstruct Edge {\n int s, t, cost;\n Edge() = default;\n Edge(int s, int t, int cost) : s(s), t(t), cost(cost) {}\n bool operator<(const Edge &other) const {\n return cost < other.cost;\n }\n};\n\nint kruskal(int v, vector<Edge> e) {\n sort(e.begin(), e.end());\n DisjointSet ds(v);\n int res = 0;\n\n for (Edge x : e) {\n if (!ds.same(x.s, x.t)) {\n ds.unite(x.s, x.t);\n res += x.cost;\n }\n }\n return res;\n}\n\nint main()\n{\n int v, e;\n cin >> v >> e;\n vector<Edge> a(e);\n rep(i,e) cin >> a[i].s >> a[i].t >> a[i].cost;\n \n int ans = kruskal(v,a);\n\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 5492, "score_of_the_acc": -0.5163, "final_rank": 10 } ]
aoj_GRL_3_A_cpp
Articulation Points Find articulation points of a given undirected graph G(V, E) . A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Input |V| |E| s 0 t 0 s 1 t 1 : s |E|-1 t |E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V| -1 respectively. s i and t i represent source and target verticess of i -th edge (undirected). Output A list of articulation points of the graph G ordered by name. Constraints 1 ≤ |V| ≤ 100,000 0 ≤ |E| ≤ 100,000 The graph is connected There are no parallel edges There are no self-loops Sample Input 1 4 4 0 1 0 2 1 2 2 3 Sample Output 1 2 Sample Input 2 5 4 0 1 1 2 2 3 3 4 Sample Output 2 1 2 3
[ { "submission_id": "aoj_GRL_3_A_11037910", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nvector<int> br;\nvector<vector<int>> adj;\nint Time=0;\nvector<int> low, disc;\n\nvoid dfsBR(int u, int p) {\n low[u] = disc[u] = ++Time; int c=0;\n for (int& v : adj[u]) {\n if (v == p) continue; // we don't want to go back through the same path.\n // if we go back is because we found another way back\n if (!disc[v]) { // if V has not been discovered before\n dfsBR(v, u); // recursive DFS call\n if (p!=u && disc[u] <= low[v]) // condition to find a bridge\n br[u]=1;\n low[u] = min(low[u], low[v]); // low[v] might be an ancestor of u\n c++;\n\n } else // if v was already discovered means that we found an ancestor\n low[u] = min(low[u], disc[v]); // finds the ancestor with the least discovery time\n }\n if(c>1 && p==u) br[u]=1;\n}\n\nvoid BR() {\n br = low = disc = vector<int>(adj.size());\n Time = 0;\n for (int u = 0; u < adj.size(); u++)\n if (!disc[u])\n dfsBR(u, u);\n}\n\nint main(){\n int n;\n cin >> n;\n int m;\n cin >> m;\n adj.assign(n+1,{});\n for(int i=0;i<m;i++){\n int x,y;\n cin >> x>> y;\n adj[x].push_back(y);\n adj[y].push_back(x);\n }\n low.assign(n+1,0);\n disc.assign(n+1,0);\n BR();\n for(int i=0;i<n;i++){\n if(br[i]) cout << i << '\\n';\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4848, "score_of_the_acc": -0.0667, "final_rank": 5 }, { "submission_id": "aoj_GRL_3_A_11008886", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define MM << ' ' <<\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vv<vec<T>>;\ntemplate <class T> using minpq = priority_queue<T, vector<T>, greater<T>>;\n#define rep(i, r) for(ll i = 0; i < (r); i++)\n#define reps(i, l, r) for(ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for(ll i = (r) - 1; i >= l; i--)\ntemplate <class T> void uniq(T &a) { sort(all(a)); erase(unique(all(a)), a.end()); }\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\nconst ll INF = numeric_limits<ll>::max() / 4;\nconst ld inf = numeric_limits<ld>::max() / 2;\nconst ll mod1 = 1000000007;\nconst ll mod2 = 998244353;\nconst ld pi = 3.141592653589793238;\ntemplate <class T> void rev(T &a) { reverse(all(a)); }\nll popcnt(ll a) { return __builtin_popcountll(a); }\ntemplate<typename T>\nbool chmax(T &a, const T& b) { return a < b ? a = b, true : false; }\ntemplate<typename T>\nbool chmin(T &a, const T& b) { return a > b ? a = b, true : false; }\ntemplate <typename T1, typename T2>\nostream& operator<<(ostream& os, const pair<T1, T2>& p) {\n\tos << p.first << \" \" << p.second;\n\treturn os;\n}\ntemplate <typename T1, typename T2>\nistream& operator>>(istream& is, pair<T1, T2>& p) {\n\tis >> p.first >> p.second;\n\treturn is;\n}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vec<T>& v) {\n\trep(i, sz(v)) {\n\t\tos << v[i] << \" \\n\"[i + 1 == sz(v)];\n\t}\n\treturn os;\n}\ntemplate <typename T>\nistream& operator>>(istream& is, vec<T>& v) {\n\tfor (T& in : v) is >> in;\n\treturn is;\n}\nvoid yesno(bool t) {\n\tcout << (t ? \"Yes\" : \"No\") << endl;\n}\nll modmul(ll a, ll b, ll mod) { return __int128(a) * b % mod; }\nll modpow(ll a, ll b, ll mod) {\n ll ans = 1;\n for (; b; a = modmul(a, a, mod), b /= 2)\n if (b & 1) ans = modmul(ans, a, mod);\n return ans;\n}\n// a^x == b (mod p), if no such x exists than -1\nll modlog(ll a, ll b, ll p) {\n ll n = (ll)sqrtl(p) + 1, e = 1, f = 1, j = 1;\n unordered_map<ll, ll> A;\n while (j = n && (e = f = e * a % p) != b % p)\n A[e * b % p] = j++;\n if (e == b % p) return j;\n if (gcd(p, e) == gcd(p, b))\n reps(i, 2, n + 2) if (A.count(e = e * f % p)) \n return n * i - A[e];\n return -1;\n}\n// x^2 == a (mod p)\nll modsqrt(ll a, ll p) {\n a %= p;\n while (a < 0) a += p;\n if (a == 0) return 0;\n if (modpow(a, (p - 1) / 2, p) != 1) return -1;\n if (p % 4 == 3) return modpow(a, (p + 1) / 4, p);\n ll s = p - 1, n = 2;\n ll r = 0, m;\n while (s % 2 == 0) ++r, s /= 2;\n while (modpow(n, (p - 1) / 2, p) != p - 1) ++n;\n ll x = modpow(a, (s + 1) / 2, p);\n ll b = modpow(a, s, p), g = modpow(n, s, p);\n for (;; r = m) {\n ll t = b;\n for (m = 0; m < r && t != 1; ++m) t = modmul(t, t, p);\n if (m == 0) return x;\n ll gs = modpow(g, 1ll << (r - m - 1), p);\n g = modmul(gs, gs, p);\n x = modmul(x, gs, p);\n b = modmul(b, g, p);\n }\n}\nll modinv(ll x, ll mod) { return modpow(x, mod - 2, mod); }\ntemplate <typename G>\nstruct LowLink {\n ll n;\n const G g;\n vl ord, low, arti;\n vec<pll> bridge;\n\n LowLink(G g) : n(sz(g)), g(g), ord(sz(g), -1), low(sz(g), -1) {\n ll k = 0;\n rep(i, n) {\n if (ord[i] == -1) k = dfs(i, k, -1);\n }\n }\n\n ll dfs(ll x, ll k, ll p) {\n low[x] = (ord[x] = k++);\n ll cnt = 0;\n bool is_arti = false, second = false;\n for (auto &e : g[x]) {\n if (ord[e] == -1) {\n cnt++;\n k = dfs(e, k, x);\n chmin(low[x], low[e]);\n is_arti |= (p != -1) && (low[e] >= ord[x]);\n if (ord[x] < low[e]) bridge.emplace_back(min(x, e), max(x, e));\n } else if (e != p || second) {\n chmin(low[x], ord[e]);\n } else {\n second = true;\n }\n }\n is_arti |= p == -1 && cnt > 1;\n if (is_arti) arti.emplace_back(x);\n return k;\n }\n};\nvoid solve() {\n ll n, m; cin >> n >> m;\n\tvv<ll> g(n);\n\trep(i, m) {\n\t\tll u, v; cin >> u >> v;\n\t\tg[u].emplace_back(v);\n\t\tg[v].emplace_back(u);\n\t}\n\tLowLink<vv<ll>> LL(g);\n\tauto ans = LL.arti;\n\tsort(all(ans));\n\trep(i, sz(ans)) {\n\t\tcout << ans[i] << endl;\n\t}\n}\nint main() {\n ll T = 1;\n // cin >> T;\n while (T--) solve();\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8448, "score_of_the_acc": -0.6727, "final_rank": 15 }, { "submission_id": "aoj_GRL_3_A_11001321", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Vertex\n{\n vector<int> destinations;\n int rank = 0;\n int relativeRank = 0;\n bool isArticlePoint = false;\n};\n\n// 子の relativeRank が current のランクより数値が高い場合は関節点として扱う\nvoid searchArticulationPoints(vector<Vertex> &vertexs, int current, int rank)\n{\n // current から辿れる頂点を見る\n for (int num : vertexs[current].destinations)\n {\n // 探索した頂点が未探索の場合はその頂点が関節点か調べる\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank;\n vertexs[num].relativeRank = rank++;\n searchArticulationPoints(vertexs, num, rank);\n vertexs[current].relativeRank = min(vertexs[current].relativeRank, vertexs[num].relativeRank);\n if (vertexs[current].rank <= vertexs[num].relativeRank)\n vertexs[current].isArticlePoint = true;\n }\n else\n {\n // 隣接する点のランクが自分より低い場合はそのランクを relativeRank とする\n vertexs[current].relativeRank = min(vertexs[current].relativeRank, vertexs[num].rank);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<Vertex> vertexs(vertexN);\n\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n vertexs[s].destinations.push_back(t);\n vertexs[t].destinations.push_back(s);\n }\n\n // 頂点0を根とする\n int rank = 1;\n vertexs[0].rank = rank;\n vertexs[0].relativeRank = rank++;\n\n int rootChild = 0; // 根の子の数\n for (int num : vertexs[0].destinations)\n {\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank;\n vertexs[num].relativeRank = rank++;\n\n searchArticulationPoints(vertexs, num, rank);\n rootChild++;\n }\n }\n\n // 根が二つ以上の子を持つ場合は関節点\n if (rootChild > 1)\n vertexs[0].isArticlePoint = true;\n\n // 関節点を出力\n for (int i = 0; i < vertexN; i++)\n if (vertexs[i].isArticlePoint)\n cout << i << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4460, "score_of_the_acc": -0.0013, "final_rank": 2 }, { "submission_id": "aoj_GRL_3_A_11001291", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Vertex\n{\n vector<int> destinations;\n int rank = 0;\n int relativeRank = 0;\n bool isArticlePoint = false;\n};\n\n// 子の relativeRank が current のランクより数値が高い場合は関節点として扱う\nvoid searchArticulationPoints(vector<Vertex> &vertexs, int current, int rank)\n{\n // current から辿れる頂点を見る\n for (int num : vertexs[current].destinations)\n {\n // 探索した頂点が未探索の場合はその頂点が関節点か調べる\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank;\n vertexs[num].relativeRank = rank++;\n searchArticulationPoints(vertexs, num, rank);\n vertexs[current].relativeRank = min(vertexs[current].relativeRank, vertexs[num].relativeRank);\n if (vertexs[current].rank <= vertexs[num].relativeRank)\n vertexs[current].isArticlePoint = true;\n }\n else\n {\n // 隣接する点のランクが自分より低い場合はそのランクを relativeRank とする\n vertexs[current].relativeRank = min(vertexs[current].relativeRank, vertexs[num].rank);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<Vertex> vertexs(vertexN);\n\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n vertexs[s].destinations.push_back(t);\n vertexs[t].destinations.push_back(s);\n }\n\n // 頂点0を根とする\n int rank = 1;\n vertexs[0].rank = rank;\n vertexs[0].relativeRank = rank++;\n\n int rootChild = 0; // 根の子の数\n for (int num : vertexs[0].destinations)\n {\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank;\n vertexs[num].relativeRank = rank++;\n\n searchArticulationPoints(vertexs, num, rank);\n rootChild++;\n }\n else\n vertexs[0].relativeRank = min(vertexs[0].relativeRank, vertexs[num].rank);\n }\n\n // 根が二つ以上の子を持つ場合は関節点\n if (rootChild > 1)\n vertexs[0].isArticlePoint = true;\n\n // 関節点を出力\n for (int i = 0; i < vertexN; i++)\n if (vertexs[i].isArticlePoint)\n cout << i << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4752, "score_of_the_acc": -0.0505, "final_rank": 3 }, { "submission_id": "aoj_GRL_3_A_10995565", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Vertex\n{\n vector<int> destinations;\n int rank = 0;\n int relativeRank = 0;\n bool isArticlePoint = false;\n};\n\n// current(親) のランクより数値が低いランクを関節点として扱う\nvoid searchArticulationPoints(vector<Vertex> &vertexs, int current, int rank)\n{\n // current から辿れる頂点を見つける\n for (int num : vertexs[current].destinations)\n {\n // 探索した頂点が未探索の場合はその頂点が関節点か調べる\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank;\n vertexs[num].relativeRank = rank++;\n searchArticulationPoints(vertexs, num, rank);\n vertexs[current].relativeRank = min(vertexs[current].relativeRank, vertexs[num].relativeRank);\n if (vertexs[current].rank <= vertexs[num].relativeRank)\n vertexs[current].isArticlePoint = true;\n }\n else\n vertexs[current].relativeRank = min(vertexs[current].relativeRank, vertexs[num].rank);\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<Vertex> vertexs(vertexN);\n\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n vertexs[s].destinations.push_back(t);\n vertexs[t].destinations.push_back(s);\n }\n\n // 頂点0を根とする\n int rank = 1;\n vertexs[0].rank = rank;\n vertexs[0].relativeRank = rank++;\n\n int rootChild = 0; // 根の子の数\n for (int num : vertexs[0].destinations)\n {\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank;\n vertexs[num].relativeRank = rank++;\n\n searchArticulationPoints(vertexs, num, rank);\n rootChild++;\n }\n else\n vertexs[num].relativeRank = min(vertexs[0].relativeRank, vertexs[num].rank);\n }\n\n // 根が二つ以上の子を持つ場合は関節点\n if (rootChild > 1)\n vertexs[0].isArticlePoint = true;\n\n // 関節点を出力\n for (int i = 0; i < vertexN; i++)\n if (vertexs[i].isArticlePoint)\n cout << i << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4452, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_GRL_3_A_10995174", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nstruct Vertex\n{\n vector<int> destinations;\n int rank = 0;\n bool isArticlePoint = false;\n};\n\n// 子から親を経由せずに自分より数値が低いランクを探索する\nbool searchUnderRank(const vector<Vertex> &vertexs, vector<bool> &rankSearchedMap, int current, int startRank)\n{\n for (int num : vertexs[current].destinations)\n {\n if (!rankSearchedMap[num])\n {\n int numRank = vertexs[num].rank;\n if (numRank != 0 && startRank > numRank)\n return true;\n rankSearchedMap[num] = true;\n if (searchUnderRank(vertexs, rankSearchedMap, num, startRank))\n return true;\n }\n }\n return false;\n}\n\n// current(親) のランクより数値が低いランクを関節点として扱う\nvoid searchArticulationPoints(vector<Vertex> &vertexs, int current, int &rank)\n{\n // current から辿れる頂点を見つける\n for (int num : vertexs[current].destinations)\n {\n // 探索した頂点が未探索の場合はその頂点が関節点か調べる\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank++;\n\n // 親を除いて自身のランクより低いランクが見つからない場合、親は関節点\n if (!vertexs[current].isArticlePoint)\n {\n int n = vertexs.size();\n vector<bool> rankSearchedMap(n);\n rankSearchedMap[current] = true; // 親を探索済みにする\n if (!searchUnderRank(vertexs, rankSearchedMap, num, vertexs[num].rank))\n vertexs[current].isArticlePoint = true;\n }\n\n searchArticulationPoints(vertexs, num, rank);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<Vertex> vertexs(vertexN);\n\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n vertexs[s].destinations.push_back(t);\n vertexs[t].destinations.push_back(s);\n }\n\n // 頂点0を根とする\n int rank = 1;\n vertexs[0].rank = rank++;\n\n int rootChild = 0; // 根の子の数\n for (int num : vertexs[0].destinations)\n {\n if (vertexs[num].rank == 0)\n {\n vertexs[num].rank = rank++;\n\n searchArticulationPoints(vertexs, num, rank);\n rootChild++;\n }\n }\n\n // 根が二つ以上の子を持つ場合は関節点\n if (rootChild > 1)\n vertexs[0].isArticlePoint = true;\n\n // 関節点を出力\n for (int i = 0; i < vertexN; i++)\n if (vertexs[i].isArticlePoint)\n cout << i << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5460, "score_of_the_acc": -0.1697, "final_rank": 8 }, { "submission_id": "aoj_GRL_3_A_10995017", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nstruct Vertex\n{\n vector<int> destinations;\n int rank = 0;\n bool isArticlePoint = false;\n bool isSearched = false;\n};\n\n// 子から親を経由せずに自分より数値が低いランクを探索する\nbool searchUnderRank(const vector<Vertex> &vertexs, vector<bool> &rankSearchedMap, int current, int startRank)\n{\n for (int num : vertexs[current].destinations)\n {\n if (!rankSearchedMap[num])\n {\n int numRank = vertexs[num].rank;\n if (numRank != 0 && startRank > numRank)\n return true;\n rankSearchedMap[num] = true;\n if (searchUnderRank(vertexs, rankSearchedMap, num, startRank))\n return true;\n }\n }\n return false;\n}\n\n// current(親) のランクより数値が低いランクを関節点として扱う\nvoid searchArticulationPoints(vector<Vertex> &vertexs, int current, int &rank)\n{\n // current から辿れる頂点を見つける\n for (int num : vertexs[current].destinations)\n {\n // 探索した頂点が未探索の場合はその頂点が関節点か調べる\n if (!vertexs[num].isSearched)\n {\n vertexs[num].isSearched = true;\n vertexs[num].rank = rank++;\n\n // 親を除いて自身のランクより低いランクが見つからない場合、親は関節点\n if (!vertexs[current].isArticlePoint)\n {\n int n = vertexs.size();\n vector<bool> rankSearchedMap(n);\n rankSearchedMap[current] = true; // 親を探索済みにする\n if (!searchUnderRank(vertexs, rankSearchedMap, num, vertexs[num].rank))\n vertexs[current].isArticlePoint = true;\n }\n\n searchArticulationPoints(vertexs, num, rank);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<Vertex> vertexs(vertexN);\n\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n vertexs[s].destinations.push_back(t);\n vertexs[t].destinations.push_back(s);\n }\n\n // 頂点0を根とする\n vertexs[0].isSearched = true;\n int rank = 1;\n vertexs[0].rank = rank++;\n\n int rootChild = 0; // 根の子の数\n for (int num : vertexs[0].destinations)\n {\n if (!vertexs[num].isSearched)\n {\n vertexs[num].isSearched = true;\n vertexs[num].rank = rank++;\n\n searchArticulationPoints(vertexs, num, rank);\n rootChild++;\n }\n }\n\n // 根が二つ以上の子を持つ場合は関節点\n if (rootChild > 1)\n vertexs[0].isArticlePoint = true;\n\n // 関節点を出力\n for (int i = 0; i < vertexN; i++)\n if (vertexs[i].isArticlePoint)\n cout << i << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5412, "score_of_the_acc": -0.1616, "final_rank": 7 }, { "submission_id": "aoj_GRL_3_A_10978138", "code_snippet": "#include <bits/stdc++.h>\n\n//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"avx,avx2,fma\")\n//#pragma GCC optimization(\"unroll-loops\")\n\nusing namespace std;\n\n#define int long long\n#define double long double\n#define uint unsigned int\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define is2pow(n) (n && (!(n & (n-1))))\n#define OPTIMIZE ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n\nconst int MOD = 1e15 + 7;\nconst int MAX_N = 2e5;\nconst int MAX_K = 80;\nconst long long INF = 1e18;\nconst double EPS = 1e-6;\n\nint binPow(int base, int pow, int mod) {\n if (pow == 0)\n return 1 % mod;\n int res = 1;\n while (pow != 0) {\n if (pow & 1)\n res = res * base % mod;\n base = base * base % mod;\n pow = pow >> 1;\n }\n return res;\n}\n\nstruct Edge {\n int from, to, w;\n\n Edge(int u,int v,int w = 1) {\n from = u, to = v, this->w = w;\n }\n};\n\nstruct ArticulationPoints {\n // Time: O(n + m), Space: O(n + m)\n int n;\n vector<vector<Edge>> graph;\n vector<int> visited, tup, tin, isArticulationPoint, articulationPoints;\n\n explicit ArticulationPoints(const vector<vector<Edge>>& g) :\n n(g.size()), graph(g), visited(n, 0), tin(n, 0), tup(n), isArticulationPoint(n, 0) {\n }\n\n void dfs(int current, int parent = -1, int height = 0) {\n visited[current] = 1, tin[current] = tup[current] = height;\n int cntChildren = 0;\n for (const Edge& edge: graph[current]) {\n if (edge.to == parent)\n continue;\n if (!visited[edge.to]) {\n cntChildren++;\n dfs(edge.to, current, height + 1);\n tup[current] = min(tup[current], tup[edge.to]);\n if ((tup[edge.to] >= tin[current] && parent != -1) || (parent == -1 && cntChildren > 1))\n isArticulationPoint[current] = 1;\n continue;\n }\n tup[current] = min(tup[current], tin[edge.to]);\n }\n }\n\n void findPoints() {\n for (int u = 0; u < n; u++)\n if (!visited[u])\n dfs(u);\n for (int i = 0; i < n; i++)\n if (isArticulationPoint[i])\n articulationPoints.push_back(i);\n }\n};\n\n\nvoid solve() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n int n, m;\n cin >> n >> m;\n vector<vector<Edge>> g(n);\n for (int i = 0, u, v; i < m; i++) {\n cin >> u >> v;\n g[u].emplace_back(u, v);\n g[v].emplace_back(v, u);\n }\n ArticulationPoints finder(g);\n finder.findPoints();\n auto res(finder.articulationPoints);\n sort(begin(res), end(res));\n for (auto u: res) {\n cout << u << endl;\n }\n}\n\n#define TES\n#define LOCA\n#define FIL\n\nint32_t main() {\n OPTIMIZE\n#ifdef FILE\n freopen(\"path_easy.in\", \"r\", stdin); freopen(\"path_easy.out\", \"w\", stdout);\n#endif\n#ifdef LOCAL\n freopen(\"/home/rekname/data/C++ Projects/codedforceProject/input.txt\", \"r\", stdin);\n#endif\n int t = 1;\n#ifdef TEST\n cin >> t;\n#endif\n while (t--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10392, "score_of_the_acc": -1, "final_rank": 16 }, { "submission_id": "aoj_GRL_3_A_10975761", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n Node *parent = nullptr;\n vector<Node *> children;\n int number;\n bool isArticlePoint = false;\n};\n\n// 深さ優先探索で木を作る\nvoid makeTree(const vector<vector<int>> &destGraph, vector<bool> &searchedMap, Node *node, int index, vector<int> &rankMap, int &rank)\n{\n for (int num : destGraph[index])\n {\n if (!searchedMap[num])\n {\n searchedMap[num] = true;\n Node *newNode = new Node();\n newNode->number = num;\n newNode->parent = node;\n rankMap[num] = rank++;\n node->children.push_back(newNode);\n makeTree(destGraph, searchedMap, newNode, num, rankMap, rank);\n }\n }\n}\n\n// 子から親を経由せずに自分より数値が低いランクを探索する\nbool search(const vector<vector<int>> &destGraph, vector<bool> &searchedMap, int current, int startNum, const vector<int> &rankMap)\n{\n for (int num : destGraph[current])\n {\n if (!searchedMap[num])\n {\n if (rankMap[startNum] > rankMap[num])\n return true;\n searchedMap[num] = true;\n if (search(destGraph, searchedMap, num, startNum, rankMap))\n return true;\n }\n }\n return false;\n}\n\nvoid searchArticulationPoints(Node *node, vector<int> &articulationPoints, const vector<vector<int>> &destGraph, const vector<int> &rankMap)\n{\n int n = destGraph.size();\n for (Node *child : node->children)\n {\n searchArticulationPoints(child, articulationPoints, destGraph, rankMap);\n if (node->isArticlePoint)\n continue;\n vector<bool> searchedMap(n);\n searchedMap[node->number] = true;\n if (!search(destGraph, searchedMap, child->number, child->number, rankMap))\n {\n node->isArticlePoint = true;\n articulationPoints.push_back(node->number);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<vector<int>> destGraph(vertexN); // 各頂点から伸びる頂点を保存\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n destGraph[s].push_back(t);\n destGraph[t].push_back(s);\n }\n\n // 木を作成\n Node *root = new Node();\n vector<bool> searchedMap(vertexN);\n vector<int> rankMap(vertexN);\n searchedMap[0] = true;\n int rank = 1;\n rankMap[0] = rank++;\n root->number = 0;\n makeTree(destGraph, searchedMap, root, 0, rankMap, rank);\n\n // 関節点を求める\n vector<int> articulationPoints; // 関節点を保存\n\n if (root->children.size() > 1)\n {\n articulationPoints.push_back(root->number);\n root->isArticlePoint = true;\n }\n\n for (Node *child : root->children)\n searchArticulationPoints(child, articulationPoints, destGraph, rankMap);\n\n sort(articulationPoints.begin(), articulationPoints.end());\n\n for (int p : articulationPoints)\n cout << p << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6088, "score_of_the_acc": -0.2754, "final_rank": 10 }, { "submission_id": "aoj_GRL_3_A_10975744", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n Node *parent = nullptr;\n vector<Node *> children;\n int number;\n bool isArticlePoint = false;\n};\n\n// 深さ優先探索で木を作る\nvoid makeTree(const vector<vector<int>> &destGraph, vector<bool> &searchedMap, Node *node, int index, vector<int> &rankMap, int &rank)\n{\n for (int num : destGraph[index])\n {\n if (!searchedMap[num])\n {\n searchedMap[num] = true;\n Node *newNode = new Node();\n newNode->number = num;\n newNode->parent = node;\n rankMap[num] = rank++;\n node->children.push_back(newNode);\n makeTree(destGraph, searchedMap, newNode, num, rankMap, rank);\n }\n }\n}\n\n// 根を探索する\nbool search(const vector<vector<int>> &destGraph, vector<bool> &searchedMap, int current, int startNum, const vector<int> &rankMap)\n{\n for (int num : destGraph[current])\n {\n if (!searchedMap[num])\n {\n if (rankMap[startNum] > rankMap[num])\n return true;\n searchedMap[num] = true;\n if (search(destGraph, searchedMap, num, startNum, rankMap))\n return true;\n }\n }\n return false;\n}\n\nvoid getArticulationPoints(Node *node, vector<int> &articulationPoints, const vector<vector<int>> &destGraph, const vector<int> &rankMap)\n{\n int n = destGraph.size();\n for (Node *child : node->children)\n {\n getArticulationPoints(child, articulationPoints, destGraph, rankMap);\n if (node->isArticlePoint)\n continue;\n vector<bool> searchedMap(n);\n searchedMap[node->number] = true;\n if (!search(destGraph, searchedMap, child->number, child->number, rankMap))\n {\n node->isArticlePoint = true;\n articulationPoints.push_back(node->number);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<vector<int>> destGraph(vertexN); // 各頂点から伸びる頂点を保存\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n destGraph[s].push_back(t);\n destGraph[t].push_back(s);\n }\n\n // 木を作成\n Node *root = new Node();\n vector<bool> searchedMap(vertexN);\n vector<int> rankMap(vertexN);\n searchedMap[0] = true;\n int rank = 1;\n rankMap[0] = rank++;\n root->number = 0;\n makeTree(destGraph, searchedMap, root, 0, rankMap, rank);\n\n // 関節点を求める\n vector<int> articulationPoints; // 関節点を保存\n\n if (root->children.size() > 1)\n {\n articulationPoints.push_back(root->number);\n root->isArticlePoint = true;\n }\n\n for (Node *child : root->children)\n getArticulationPoints(child, articulationPoints, destGraph, rankMap);\n\n sort(articulationPoints.begin(), articulationPoints.end());\n\n for (int p : articulationPoints)\n cout << p << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6204, "score_of_the_acc": -0.2949, "final_rank": 11 }, { "submission_id": "aoj_GRL_3_A_10975351", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n Node *parent = nullptr;\n vector<Node *> children;\n int number;\n bool isArticlePoint = false;\n};\n\n// 深さ優先探索で木を作る\nvoid makeTree(const vector<vector<int>> &distVec, vector<bool> &map, Node *node, int index)\n{\n for (int num : distVec[index])\n {\n if (!map[num])\n {\n map[num] = true;\n Node *newNode = new Node();\n newNode->number = num;\n newNode->parent = node;\n node->children.push_back(newNode);\n makeTree(distVec, map, newNode, num);\n }\n }\n}\n\n// 子から親を経由せずに根を探索する\nbool search(const vector<vector<int>> &distVec, vector<bool> &map, int current)\n{\n for (int num : distVec[current])\n {\n if (num == 0)\n return true;\n if (!map[num])\n {\n map[num] = true;\n if (search(distVec, map, num))\n return true;\n }\n }\n return false;\n}\n\nvoid getArticulationPoints(Node *node, vector<int> &articulationPoints, const vector<vector<int>> &distVec)\n{\n int n = distVec.size();\n for (Node *child : node->children)\n {\n getArticulationPoints(child, articulationPoints, distVec);\n if (node->isArticlePoint)\n continue;\n vector<bool> map(n);\n map[node->number] = true;\n if (!search(distVec, map, child->number))\n {\n node->isArticlePoint = true;\n articulationPoints.push_back(node->number);\n }\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<vector<int>> distVec(vertexN); // 各頂点から伸びる頂点を保存\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n distVec[s].push_back(t);\n distVec[t].push_back(s);\n }\n\n // 木を作成\n Node *root = new Node();\n vector<bool> map(vertexN);\n map[0] = true;\n root->number = 0;\n makeTree(distVec, map, root, 0);\n\n // 関節点を求める\n vector<int> articulationPoints; // 関節点を保存\n\n if (root->children.size() > 1)\n {\n articulationPoints.push_back(root->number);\n root->isArticlePoint = true;\n }\n for (Node *child : root->children)\n getArticulationPoints(child, articulationPoints, distVec);\n\n sort(articulationPoints.begin(), articulationPoints.end());\n\n for (int p : articulationPoints)\n cout << p << endl;\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 6364, "score_of_the_acc": -1.231, "final_rank": 17 }, { "submission_id": "aoj_GRL_3_A_10971529", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define rep(i,n) for(int i=0;i<(n);i++)\n#define pii pair<int,int>\n#define pipii pair<int,pii>\ntemplate<typename T> bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }\ntemplate<typename T> bool chmin(T& a, const T& b) { if (a > b) { a = b; return 1; } return 0; }\n#define all(v) (v).begin(),(v).end()\n#define bit(i) (1LL<<(i))\n#define test(b, i) (((b) >> i) & 1)\n\nstruct LowLink{\nprivate:\n vector<vector<int>> G;\n int cnt = 0;\n vector<bool> _is_art;\n\n void DFS(int v, int p=-1){\n low[v] = ord[v] = ++cnt;\n int n_ch = 0;\n for(int u : G[v])if(u != p){\n if(ord[u] == 0){\n DFS(u, v);\n low[v] = min(low[v], low[u]);\n n_ch++;\n if(p != -1 && ord[v] <= low[u])_is_art[v] = true;\n }\n else low[v] = min(low[v], ord[u]);\n }\n\n if(p == -1 && n_ch >= 2)_is_art[v] = true;\n\n return;\n }\n\npublic:\n vector<int> ord, low;\n\n LowLink(int N){\n G.resize(N + 1);\n _is_art.resize(N + 1);\n ord.resize(N + 1);\n low.resize(N + 1);\n return;\n }\n\n void add_edge(int a, int b){\n if(G.size() < max(a, b) + 1){\n G.resize(max(a, b) + 1);\n _is_art.resize(max(a, b) + 1);\n ord.resize(max(a, b) + 1);\n low.resize(max(a, b) + 1);\n }\n\n G[a].push_back(b);\n G[b].push_back(a);\n\n return;\n }\n\n void build(){\n for(int v = 0; v < G.size(); v++)if(ord[v] == 0){\n DFS(v);\n }\n\n return;\n }\n\n bool is_art(int n){ return _is_art[n]; }\n\n bool is_edge(int a, int b){\n if(ord[a] > ord[b])swap(a, b);\n return ord[a] < low[b];\n }\n\n bool is_edge(pair<int,int> e){\n return is_edge(e.first, e.second);\n }\n};\n\nconst int MAXN = 1e5 + 10;\nconst int MAXM = 1e5 + 10;\n\nint N, M;\n\nsigned main(){\n cin >> N >> M;\n LowLink ll(N);\n rep(i, M){\n int a, b;\n cin >> a >> b;\n ll.add_edge(a, b);\n }\n\n ll.build();\n\n rep(i, N)if(ll.is_art(i))cout << i << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5672, "score_of_the_acc": -0.2054, "final_rank": 9 }, { "submission_id": "aoj_GRL_3_A_10963482", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n Node *parent = nullptr;\n vector<Node *> children;\n int number;\n bool isBackedge = false;\n bool isArticlePoint = false;\n};\n\n// 深さ優先探索で木を作る\nvoid makeTree(const vector<vector<int>> &distVec, vector<bool> &map, Node *node, int index)\n{\n for (int num : distVec[index])\n {\n if (!map[num])\n {\n map[num] = true;\n Node *newNode = new Node();\n newNode->number = num;\n newNode->parent = node;\n node->children.push_back(newNode);\n makeTree(distVec, map, newNode, num);\n }\n }\n}\n\n// 子から親を経由せずに根を探索する\nbool search(const vector<vector<int>> &distVec, vector<bool> &map, int current)\n{\n for (int num : distVec[current])\n {\n if (num == 0)\n return true;\n if (!map[num])\n {\n map[num] = true;\n if (search(distVec, map, num))\n return true;\n }\n }\n return false;\n}\n\nvoid getArticulationPoints(Node *node, vector<int> &articulationPoints, const vector<vector<int>> &distVec)\n{\n int n = distVec.size();\n for (Node *child : node->children)\n {\n getArticulationPoints(child, articulationPoints, distVec);\n if (node->isArticlePoint)\n continue;\n vector<bool> map(n);\n map[node->number] = true;\n // if (distVec[node->number].size() == 1 && child->isBackedge)\n // node->isBackedge = true;\n if (!search(distVec, map, child->number))\n {\n node->isArticlePoint = true;\n articulationPoints.push_back(node->number);\n }\n }\n if (node->children.size() == 0)\n {\n vector<bool> map(n);\n map[node->parent->number] = true;\n node->isBackedge = search(distVec, map, node->number);\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<vector<int>> distVec(vertexN); // 各頂点から伸びる頂点を保存\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n distVec[s].push_back(t);\n distVec[t].push_back(s);\n }\n\n // 木を作成\n Node *root = new Node();\n vector<bool> map(vertexN);\n map[0] = true;\n root->number = 0;\n makeTree(distVec, map, root, 0);\n\n // 関節点を求める\n vector<int> articulationPoints; // 関節点を保存\n\n if (root->children.size() > 1)\n {\n articulationPoints.push_back(root->number);\n root->isArticlePoint = true;\n }\n for (Node *child : root->children)\n getArticulationPoints(child, articulationPoints, distVec);\n\n sort(articulationPoints.begin(), articulationPoints.end());\n\n for (int p : articulationPoints)\n cout << p << endl;\n}", "accuracy": 1, "time_ms": 330, "memory_kb": 6048, "score_of_the_acc": -1.2384, "final_rank": 18 }, { "submission_id": "aoj_GRL_3_A_10963076", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n Node *parent = nullptr;\n vector<Node *> children;\n int number;\n bool isBackedge = false;\n bool isArticlePoint = false;\n};\n\n// 深さ優先探索で木を作る\nvoid makeTree(const vector<vector<int>> &distVec, vector<bool> &map, Node *node, int index)\n{\n for (int num : distVec[index])\n {\n if (!map[num])\n {\n map[num] = true;\n Node *newNode = new Node();\n newNode->number = num;\n newNode->parent = node;\n node->children.push_back(newNode);\n makeTree(distVec, map, newNode, num);\n }\n }\n}\n\n// 葉から親を経由せずに根を探索する\nbool search(const vector<vector<int>> &distVec, vector<bool> &map, int current)\n{\n for (int num : distVec[current])\n {\n if (num == 0)\n return true;\n if (!map[num])\n {\n map[num] = true;\n if (search(distVec, map, num))\n return true;\n }\n }\n return false;\n}\n\nvoid getArticulationPoints(Node *node, vector<int> &articulationPoints, const vector<vector<int>> &distVec)\n{\n int n = distVec.size();\n for (Node *child : node->children)\n {\n getArticulationPoints(child, articulationPoints, distVec);\n if (node->isArticlePoint)\n continue;\n vector<bool> map(n);\n map[node->number] = true;\n if (distVec[node->number].size() == 1 && child->isBackedge)\n node->isBackedge = true;\n else if (!search(distVec, map, child->number))\n {\n node->isArticlePoint = true;\n articulationPoints.push_back(node->number);\n }\n }\n if (node->children.size() == 0)\n {\n vector<bool> map(n);\n map[node->parent->number] = true;\n if (search(distVec, map, node->number))\n node->isBackedge = true;\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<vector<int>> distVec(vertexN); // 各頂点から伸びる頂点を保存\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n distVec[s].push_back(t);\n distVec[t].push_back(s);\n }\n\n // 木を作成\n Node *root = new Node();\n vector<bool> map(vertexN);\n map[0] = true;\n root->number = 0;\n makeTree(distVec, map, root, 0);\n\n // 関節点を求める\n vector<int> articulationPoints; // 関節点を保存\n\n if (root->children.size() > 1)\n {\n articulationPoints.push_back(root->number);\n root->isArticlePoint = true;\n }\n for (Node *child : root->children)\n getArticulationPoints(child, articulationPoints, distVec);\n\n sort(articulationPoints.begin(), articulationPoints.end());\n\n for (int p : articulationPoints)\n cout << p << endl;\n}", "accuracy": 1, "time_ms": 330, "memory_kb": 6276, "score_of_the_acc": -1.2768, "final_rank": 19 }, { "submission_id": "aoj_GRL_3_A_10963031", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n Node *parent = nullptr;\n vector<Node *> children;\n int number;\n bool isBackedge = false;\n};\n\n// 深さ優先探索で木を作る\nvoid makeTree(const vector<vector<int>> &distVec, vector<bool> &map, Node *node, int index)\n{\n for (int num : distVec[index])\n {\n if (!map[num])\n {\n map[num] = true;\n Node *newNode = new Node();\n newNode->number = num;\n newNode->parent = node;\n node->children.push_back(newNode);\n makeTree(distVec, map, newNode, num);\n }\n }\n}\n\n// 葉から親を経由せずに根を探索する\nbool search(const vector<vector<int>> &distVec, vector<bool> &map, int current)\n{\n for (int num : distVec[current])\n {\n if (num == 0)\n return true;\n if (!map[num])\n {\n map[num] = true;\n if (search(distVec, map, num))\n return true;\n }\n }\n return false;\n}\n\nvoid getArticulationPoints(Node *node, vector<int> &articulationPoints, const vector<vector<int>> &distVec)\n{\n int n = distVec.size();\n for (Node *child : node->children)\n {\n getArticulationPoints(child, articulationPoints, distVec);\n vector<bool> map(n);\n map[node->number] = true;\n if (distVec[node->number].size() == 1 && child->isBackedge)\n node->isBackedge = true;\n else if (!search(distVec, map, child->number))\n articulationPoints.push_back(node->number);\n }\n if (node->children.size() == 0)\n {\n vector<bool> map(n);\n map[node->parent->number] = true;\n if (search(distVec, map, node->number))\n node->isBackedge = true;\n }\n}\n\nint main()\n{\n int vertexN, edgeN;\n cin >> vertexN >> edgeN;\n vector<vector<int>> distVec(vertexN); // 各頂点から伸びる頂点を保存\n for (int i = 0; i < edgeN; i++)\n {\n int s, t;\n cin >> s >> t;\n distVec[s].push_back(t);\n distVec[t].push_back(s);\n }\n\n // 木を作成\n Node *root = new Node();\n vector<bool> map(vertexN);\n map[0] = true;\n root->number = 0;\n makeTree(distVec, map, root, 0);\n\n // 関節点を求める\n vector<int> articulationPoints; // 関節点を保存\n\n if (root->children.size() > 1)\n articulationPoints.push_back(root->number);\n for (Node *child : root->children)\n getArticulationPoints(child, articulationPoints, distVec);\n\n sort(articulationPoints.begin(), articulationPoints.end());\n articulationPoints.erase(unique(articulationPoints.begin(), articulationPoints.end()), articulationPoints.end());\n\n for (int p : articulationPoints)\n cout << p << endl;\n}", "accuracy": 1, "time_ms": 340, "memory_kb": 6360, "score_of_the_acc": -1.3212, "final_rank": 20 }, { "submission_id": "aoj_GRL_3_A_10962179", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n// 再帰DFS(Low-Link計算)\nvoid dfs(int u, const vector<vector<int>> &g,\n vector<int> &ord, vector<int> &low, vector<int> &parent,\n int &timer)\n{\n ord[u] = low[u] = timer++; // はじめは ord も low も同じ値\n\n for (int v : g[u])\n {\n if (ord[v] == -1) // v が未訪問のとき\n {\n parent[v] = u;\n dfs(v, g, ord, low, parent, timer);\n\n low[u] = min(low[u], low[v]); // 子から戻ってきたときに low を更新\n }\n else // v がすでに訪問済み\n {\n low[u] = min(low[u], ord[v]); // 後退辺による更新\n }\n }\n}\n\nint main()\n{\n int n, m;\n cin >> n >> m;\n\n // グラフ\n vector<vector<int>> g(n);\n for (int i = 0; i < m; ++i)\n {\n int s, t;\n cin >> s >> t;\n g[s].push_back(t);\n g[t].push_back(s);\n }\n\n // DFS 用の配列\n vector<int> ord(n, -1), low(n, -1), parent(n, -1);\n int timer = 0;\n\n // DFS 実行\n dfs(0, g, ord, low, parent, timer);\n\n // DFS 終了後に関節点を判定\n vector<int> is_arti(n, false);\n\n // 根に対する判定\n int child_cnt = 0;\n for (int v : g[0])\n {\n if (parent[v] == 0)\n child_cnt++;\n }\n if (child_cnt >= 2) // 子が2つ以上なら関節点\n is_arti[0] = true;\n\n // 根以外に対する判定\n for (int u = 1; u < n; ++u)\n {\n // 子 v に対して ord[u] <= low[v] を満たすものがあれば関節点\n for (int v : g[u])\n {\n if (parent[v] == u && ord[u] <= low[v])\n {\n is_arti[u] = true;\n }\n }\n }\n\n // 関節点を昇順に出力\n for (int i = 0; i < n; ++i)\n {\n if (is_arti[i])\n cout << i << '\\n';\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4780, "score_of_the_acc": -0.0552, "final_rank": 4 }, { "submission_id": "aoj_GRL_3_A_10961999", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n// 再帰DFS(Low-Link計算)\nvoid dfs(int u, const vector<vector<int>> &g,\n vector<int> &ord, vector<int> &low, vector<int> &parent,\n int &timer)\n{\n ord[u] = low[u] = timer++; // はじめは ord も low も同じ値\n\n for (int v : g[u])\n {\n if (ord[v] == -1) // v が未訪問のとき\n {\n parent[v] = u;\n dfs(v, g, ord, low, parent, timer);\n\n low[u] = min(low[u], low[v]); // 子から戻ってきたときに low を更新\n }\n else // v がすでに訪問済み\n {\n low[u] = min(low[u], ord[v]); // 後退辺による更新\n }\n }\n}\n\nint main()\n{\n int n, m;\n cin >> n >> m;\n\n // グラフ\n vector<vector<int>> g(n);\n for (int i = 0; i < m; ++i)\n {\n int s, t;\n cin >> s >> t;\n g[s].push_back(t);\n g[t].push_back(s);\n }\n\n // DFS 用の配列\n vector<int> ord(n, -1), low(n, -1), parent(n, -1);\n int timer = 0;\n\n // DFS 実行\n dfs(0, g, ord, low, parent, timer);\n\n // DFS 終了後に関節点を判定\n vector<int> is_arti(n, false);\n\n for (int u = 0; u < n; ++u)\n {\n // 根のときの特別判定:子が2つ以上なら関節点\n if (parent[u] == -1)\n {\n int child_cnt = 0;\n for (int v : g[u])\n {\n if (parent[v] == u)\n child_cnt++;\n }\n if (child_cnt >= 2)\n is_arti[u] = true;\n }\n else\n {\n // 非根のとき:子 v に対して ord[u] <= low[v] を満たすものがあれば関節点\n for (int v : g[u])\n {\n if (parent[v] == u && ord[u] <= low[v])\n {\n is_arti[u] = true;\n }\n }\n }\n }\n\n // 関節点を昇順に出力\n for (int i = 0; i < n; ++i)\n {\n if (is_arti[i])\n cout << i << '\\n';\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5048, "score_of_the_acc": -0.1003, "final_rank": 6 }, { "submission_id": "aoj_GRL_3_A_10947123", "code_snippet": "#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\n\nusing Graph = std::vector<std::list<int>>; // 隣接リスト\nusing Table = std::vector<int>; // 頂点番号をキーにした表\n\n// 深さ優先探索して、子を返す\nvoid dfs(const Graph& graph, int u, Table& prenum, Table& parent, Table& lowest, std::vector<bool>& result, int order) {\n lowest[u] = prenum[u] = ++order; // 見つけた順に番号を割り振る\n int children = 0;\n for (int c : graph[u]) {\n // 訪問済みならBackedge\n if (prenum[c]) {\n lowest[u] = std::min(lowest[u], prenum[c]); // Backedgeの内小さい値を採用\n continue; // これ以上深く探さない\n }\n // 未訪問なら子\n ++children;\n parent[c] = u; // 親を対応付ける\n dfs(graph, c, prenum, parent, lowest, result, order);\n lowest[u] = std::min(lowest[u], lowest[c]); // 子の方が小さければ採用\n result[u] = result[u] || (prenum[u] <= lowest[c]); // 子の方が大きいなら間接点\n }\n // ルートが2つ以上の子を持つなら、関節点\n result[u] = parent[u] == -1 ? children >= 2 : result[u];\n}\nstd::vector<bool> getArticulationTable(const Graph& graph) {\n // 深さ優先で訪問順序と親番号を記録する\n Table prenum(graph.size(), 0); // 未訪問は0\n Table parent(graph.size(), -1); // ルートの親は -1 \n Table lowest(graph.size());\n std::vector<bool> result(graph.size(), false);\n dfs(graph, 0, prenum, parent, lowest, result, 0);\n return result;\n}\n\nint main() {\n int V, E;\n std::cin >> V >> E;\n\n Graph graph(V);\n for (int i = 0; i < E; ++i) {\n int s, t;\n std::cin >> s >> t;\n graph[s].push_back(t);\n graph[t].push_back(s);\n }\n\n auto result = getArticulationTable(graph);\n\n for (int i = 0; i < V; ++i) {\n if (result[i]) {\n std::cout << i << \"\\n\";\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7808, "score_of_the_acc": -0.565, "final_rank": 13 }, { "submission_id": "aoj_GRL_3_A_10947089", "code_snippet": "#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\n\nusing Graph = std::vector<std::list<int>>; // 隣接リスト\nusing Table = std::vector<int>; // 頂点番号をキーにした表\n\n// 深さ優先探索して、子を返す\nvoid dfs(const Graph& graph, int u, Table& prenum, Table& parent, Table& lowest, std::vector<bool>& result, int order) {\n prenum[u] = ++order; // 見つけた順に番号を割り振る\n lowest[u] = prenum[u];\n int children = 0;\n for (int c : graph[u]) {\n // 訪問済みならBackedge\n if (prenum[c]) {\n lowest[u] = std::min(lowest[u], prenum[c]); // Backedgeの内小さい値を採用\n continue; // これ以上深く探さない\n }\n // 未訪問なら子\n ++children;\n parent[c] = u; // 親を対応付ける\n dfs(graph, c, prenum, parent, lowest, result, order);\n lowest[u] = std::min(lowest[u], lowest[c]); // 子の方が小さければ採用\n result[u] = result[u] || (prenum[u] <= lowest[c]); // 子の方が大きいなら間接点\n }\n // ルートが2つ以上の子を持つなら、関節点\n result[u] = parent[u] == -1 ? children >= 2 : result[u];\n}\nstd::vector<bool> getArticulationTable(const Graph& graph) {\n // 深さ優先で訪問順序と親番号を記録する\n Table prenum(graph.size(), 0); // 未訪問は0\n Table parent(graph.size(), -1); // ルートの親は -1 \n Table lowest(graph.size());\n std::vector<bool> result(graph.size(), false);\n dfs(graph, 0, prenum, parent, lowest, result, 0);\n return result;\n}\n\nint main() {\n int V, E;\n std::cin >> V >> E;\n\n Graph graph(V);\n for (int i = 0; i < E; ++i) {\n int s, t;\n std::cin >> s >> t;\n graph[s].push_back(t);\n graph[t].push_back(s);\n }\n\n auto result = getArticulationTable(graph);\n\n for (int i = 0; i < V; ++i) {\n if (result[i]) {\n std::cout << i << \"\\n\";\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7604, "score_of_the_acc": -0.5306, "final_rank": 12 }, { "submission_id": "aoj_GRL_3_A_10946496", "code_snippet": "#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\n#include <ranges>\n\nusing Graph = std::vector<std::list<int>>; // 隣接リスト\nusing Table = std::vector<int>; // 頂点番号をキーにした表\n\n// 深さ優先探索して、子を返す\nvoid dfs(const Graph& graph, int s, Table& prenum, Table& parent, Table& lowest, std::vector<bool>& result, int order) {\n lowest[s] = prenum[s] = ++order; // 見つけた順に番号を割り振る\n int children = 0;\n for (int t : graph[s]) {\n // 訪問済みならBackedge\n if (prenum[t]) {\n lowest[s] = std::min(lowest[s], prenum[t]);\n continue; // それ以上探さない\n }\n ++children;\n parent[t] = s; // 自身と親を対応付ける\n dfs(graph, t, prenum, parent, lowest, result, order);\n lowest[s] = std::min(lowest[s], lowest[t]); // 子の方が小さければ採用\n }\n // root は子の数で判定する\n if (parent[s] == -1) {\n // ルートが2つ以上の子を持つなら、関節点\n result[s] = children >= 2; \n return;\n }\n int p = parent[s];\n // 親がlowestより小さいならbackedgeがないので、親は関節点\n if (prenum[p] <= lowest[s])\n result[p] = true;\n}\nstd::vector<bool> getArticulationTable(const Graph& graph) {\n // 深さ優先で訪問順序と親番号を記録する\n Table prenum(graph.size(), 0);\n Table parent(graph.size(), -1);\n Table lowest(graph.size(), 0);\n std::vector<bool> result(graph.size(), false);\n int order = 0;\n dfs(graph, 0, prenum, parent, lowest, result, order);\n return result;\n}\n\nint main() {\n int V, E;\n std::cin >> V >> E;\n\n Graph graph(V);\n for (int i = 0; i < E; ++i) {\n int s, t;\n std::cin >> s >> t;\n graph[s].push_back(t);\n graph[t].push_back(s);\n }\n\n auto result = getArticulationTable(graph);\n\n for (int i = 0; i < V; ++i) {\n if (result[i]) {\n std::cout << i << \"\\n\";\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8104, "score_of_the_acc": -0.6148, "final_rank": 14 } ]
aoj_GRL_3_B_cpp
Bridges Find bridges of an undirected graph G(V, E) . A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components. Input |V| |E| s 0 t 0 s 1 t 1 : s |E|-1 t |E|-1 , where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V| -1 respectively. s i and t i represent source and target nodes of i -th edge (undirected). Output A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source. Constraints 1 ≤ |V| ≤ 100,000 0 ≤ |E| ≤ 100,000 The graph is connected There are no parallel edges There are no self-loops Sample Input 1 4 4 0 1 0 2 1 2 2 3 Sample Output 1 2 3 Sample Input 2 5 4 0 1 1 2 2 3 3 4 Sample Output 2 0 1 1 2 2 3 3 4
[ { "submission_id": "aoj_GRL_3_B_11030221", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nvector<pair<int, int>> br;\nvector<vector<int>> adj;\nint Time=0;\nvector<int> low, disc;\n\nvoid dfsBR(int u, int p) {\n low[u] = disc[u] = ++Time;\n for (int& v : adj[u]) {\n if (v == p) continue; // we don't want to go back through the same path.\n // if we go back is because we found another way back\n if (!disc[v]) { // if V has not been discovered before\n dfsBR(v, u); // recursive DFS call\n if (disc[u] < low[v]) // condition to find a bridge\n br.push_back({u, v});\n low[u] = min(low[u], low[v]); // low[v] might be an ancestor of u\n } else // if v was already discovered means that we found an ancestor\n low[u] = min(low[u], disc[v]); // finds the ancestor with the least discovery time\n }\n}\n\nvoid BR() {\n low = disc = vector<int>(adj.size());\n Time = 0;\n for (int u = 0; u < adj.size(); u++)\n if (!disc[u])\n dfsBR(u, u);\n}\n\nint main(){\n int n;\n cin >> n;\n int m;\n cin >> m;\n adj.assign(n+1,{});\n for(int i=0;i<m;i++){\n int x,y;\n cin >> x>> y;\n adj[x].push_back(y);\n adj[y].push_back(x);\n }\n low.assign(n+1,0);\n disc.assign(n+1,0);\n BR();\n for(int i=0;i<br.size();i++){\n if(br[i].first>br[i].second) swap(br[i].first, br[i].second);\n }\n sort(br.begin(),br.end());\n for(auto bd:br){\n cout << bd.first << ' ' << bd.second << '\\n';\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4868, "score_of_the_acc": -0.0421, "final_rank": 4 }, { "submission_id": "aoj_GRL_3_B_10978523", "code_snippet": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n#include <queue>\n#include <stack>\nusing namespace std;\nusing ll = long long;\nstruct Edge {\n\tint to;\n\tint id;\n};\nvector<vector<Edge>> G;\nvector<int> ord, low;\nvector<bool> is_bridge;\nint inf = (int)1e9;\nvoid dfs(int v, int par, int k) {\n\tord[v] = k;\n\tfor (auto nv : G[v]) {\n\t\tif (ord[nv.to] == -1) {\n\t\t\t dfs(nv.to, v, k+1);\n\t\t\t low[v] = min(low[v], low[nv.to]);\n\t\t\t if (ord[v] < low[nv.to]) {\n\t\t\t \tis_bridge[nv.id] = true;\n\t\t\t } else {\n\t\t\t \tis_bridge[nv.id] = false;\n\t\t\t }\n\t\t} else if (nv.to != par) {\n\t\t\tis_bridge[nv.id] = false;\n\t\t\tlow[v] = min(low[v], ord[nv.to]);\n\t\t}\n\t}\n}\nint main() {\n\tint N, M;cin >> N >> M;\t\n\tG.assign(N, {});\n\tord.assign(N, -1);\n\tlow.assign(N, inf);\n\tis_bridge.assign(M, false);\n\tvector<int> A(M), B(M);\n\tfor (int i = 0;i < M;i++) {\n\t\tint u, v;cin >> u >> v;\n\t\tA[i] = u;B[i] = v;\n\t\tG[u].push_back({v, i});\n\t\tG[v].push_back({u, i});\n\t}\n\tdfs(0, 0, 0);\n\tvector<pair<int, int>> res;\n\tfor (int i = 0;i < M;i++) if (is_bridge[i]) res.push_back({min(A[i],B[i]), max(A[i],B[i])});\n\tsort(res.begin(),res.end());\n\tfor (auto v : res) cout << v.first << \" \" << v.second << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5716, "score_of_the_acc": -0.191, "final_rank": 11 }, { "submission_id": "aoj_GRL_3_B_10978090", "code_snippet": "#include <bits/stdc++.h>\n\n//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"avx,avx2,fma\")\n//#pragma GCC optimization(\"unroll-loops\")\n\nusing namespace std;\n\n#define int long long\n#define double long double\n#define uint unsigned int\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define is2pow(n) (n && (!(n & (n-1))))\n#define OPTIMIZE ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n\nconst int MOD = 1e15 + 7;\nconst int MAX_N = 2e5;\nconst int MAX_K = 80;\nconst long long INF = 1e18;\nconst double EPS = 1e-6;\n\nint binPow(int base, int pow, int mod) {\n if (pow == 0)\n return 1 % mod;\n int res = 1;\n while (pow != 0) {\n if (pow & 1)\n res = res * base % mod;\n base = base * base % mod;\n pow = pow >> 1;\n }\n return res;\n}\n\nstruct Edge {\n int from, to, w;\n\n Edge(int u,int v,int w = 1) {\n from = u, to = v, this->w = w;\n }\n};\n\nstruct BridgeFinder {\n // Time: O(n + m), Space: O(n + m)\n vector<vector<Edge>> graph;\n vector<int> visited, tup, tin;\n vector<Edge> bridges;\n int n;\n\n explicit BridgeFinder(const vector<vector<Edge>>& g) :\n n(g.size()), graph(g), visited(g.size()), tup(g.size()), tin(g.size()) {\n }\n\n void dfs(int current, int parent = -1, int height = 0) {\n visited[current] = 1, tin[current] = tup[current] = height;\n Edge parentEdge{0, 0};\n int cntSeenPar = 0;\n for (const Edge& edge: graph[current]) {\n if (edge.to == parent) {\n cntSeenPar++;\n parentEdge = edge;\n continue;\n }\n if (!visited[edge.to])\n dfs(edge.to, current, height + 1);\n tup[current] = min(tup[current], tup[edge.to]);\n }\n if (tup[current] == tin[current] && parent != -1 && cntSeenPar == 1) // found bridge, add new component\n bridges.emplace_back(parentEdge);\n }\n\n void findBridges() {\n for (int u = 0; u < n; u++)\n if (!visited[u])\n dfs(u);\n }\n};\n\nvoid solve() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n int n, m;\n cin >> n >> m;\n vector<vector<Edge>> g(n);\n for (int i = 0; i < m; i++) {\n int u, v;\n cin >> u >> v;\n g[u].emplace_back(u, v);\n g[v].emplace_back(v, u);\n }\n BridgeFinder finder(g);\n finder.findBridges();\n vector<pair<int, int>> bridges;\n for (const auto& edge: finder.bridges) {\n int u = edge.from;\n int v = edge.to;\n if (u > v)\n swap(u, v);\n bridges.emplace_back(u, v);\n }\n sort(bridges.begin(), bridges.end());\n for (auto& [u,v]: bridges) {\n cout << u << \" \" << v << \"\\n\";\n }\n}\n\n#define TES\n#define LOCA\n#define FIL\n\nint32_t main() {\n OPTIMIZE\n#ifdef FILE\n freopen(\"path_easy.in\", \"r\", stdin); freopen(\"path_easy.out\", \"w\", stdout);\n#endif\n#ifdef LOCAL\n freopen(\"/home/rekname/data/C++ Projects/codedforceProject/input.txt\", \"r\", stdin);\n#endif\n int t = 1;\n#ifdef TEST\n cin >> t;\n#endif\n while (t--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10324, "score_of_the_acc": -1, "final_rank": 20 }, { "submission_id": "aoj_GRL_3_B_10971543", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define rep(i,n) for(int i=0;i<(n);i++)\n#define pii pair<int,int>\n#define pipii pair<int,pii>\ntemplate<typename T> bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }\ntemplate<typename T> bool chmin(T& a, const T& b) { if (a > b) { a = b; return 1; } return 0; }\n#define all(v) (v).begin(),(v).end()\n#define bit(i) (1LL<<(i))\n#define test(b, i) (((b) >> i) & 1)\n\nstruct LowLink{\nprivate:\n vector<vector<int>> G;\n int cnt = 0;\n vector<bool> _is_art;\n\n void DFS(int v, int p=-1){\n low[v] = ord[v] = ++cnt;\n int n_ch = 0;\n for(int u : G[v])if(u != p){\n if(ord[u] == 0){\n DFS(u, v);\n low[v] = min(low[v], low[u]);\n n_ch++;\n if(p != -1 && ord[v] <= low[u])_is_art[v] = true;\n }\n else low[v] = min(low[v], ord[u]);\n }\n\n if(p == -1 && n_ch >= 2)_is_art[v] = true;\n\n return;\n }\n\npublic:\n vector<int> ord, low;\n\n LowLink(int N){\n G.resize(N + 1);\n _is_art.resize(N + 1);\n ord.resize(N + 1);\n low.resize(N + 1);\n return;\n }\n\n void add_edge(int a, int b){\n if(G.size() < max(a, b) + 1){\n G.resize(max(a, b) + 1);\n _is_art.resize(max(a, b) + 1);\n ord.resize(max(a, b) + 1);\n low.resize(max(a, b) + 1);\n }\n\n G[a].push_back(b);\n G[b].push_back(a);\n\n return;\n }\n\n void build(){\n for(int v = 0; v < G.size(); v++)if(ord[v] == 0){\n DFS(v);\n }\n\n return;\n }\n\n bool is_art(int n){ return _is_art[n]; }\n\n bool is_edge(int a, int b){\n if(ord[a] > ord[b])swap(a, b);\n return ord[a] < low[b];\n }\n\n bool is_edge(pair<int,int> e){\n return is_edge(e.first, e.second);\n }\n};\n\nconst int MAXN = 1e5 + 10;\nconst int MAXM = 1e5 + 10;\n\nint N, M;\nvector<pii> E;\n\nsigned main(){\n cin >> N >> M;\n LowLink ll(N);\n rep(i, M){\n int a, b;\n cin >> a >> b;\n E.push_back({a, b});\n ll.add_edge(a, b);\n }\n\n ll.build();\n\n set<pii> ans;\n rep(i, M){\n auto [a, b] = E[i];\n if(a > b)swap(a, b);\n if(ll.is_edge(a, b))ans.insert({a, b});\n }\n\n for(auto [a, b] : ans)cout << a << \" \" << b << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6396, "score_of_the_acc": -0.3104, "final_rank": 13 }, { "submission_id": "aoj_GRL_3_B_10751726", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\nconst int INF = (1 << 30);\n\n\nvector<int> prenum, parent, lowest;\nvector<vector<int>> g;\nvector<bool> visited;\nint v, e, t;\n\nvoid dfs(int u, int p) {\n prenum[u] = lowest[u] = t;\n t++;\n visited[u] = true;\n\n for(auto &&_v: g[u]) {\n if (!visited[_v]) {\n parent[_v] = u;\n dfs(_v, u);\n lowest[u] = min(lowest[u], lowest[_v]);\n }\n else if (_v != p) lowest[u] = min(lowest[u], prenum[_v]);\n }\n}\n\nvoid art_points() {\n t = 1;\n dfs(0, -1);\n\n set<int> ap;\n int nc = 0;\n for (int u = 1; u < v; u++)\n {\n int p = parent[u];\n if (p == 0) nc++;\n else if (prenum[p] <= lowest[u]) ap.insert(p);\n }\n if (nc > 1) {\n ap.insert(0);\n }\n for(auto &&x: ap) {\n cout << x << endl;\n }\n}\n\nvoid bridges() {\n t = 1;\n dfs(0, -1);\n\n set<pair<int, int>> bs;\n for (int u = 1; u < v; u++)\n {\n if (lowest[u] == prenum[u]) bs.insert({min(u, parent[u]), max(u, parent[u])});\n }\n for(auto &&x: bs) {\n cout << x.first << \" \" << x.second << endl;\n }\n}\n\nsigned main() {\n cin >> v >> e;\n g.assign(v, vector<int> ());\n prenum.assign(v, INF);\n parent.assign(v, -1);\n lowest.assign(v, INF);\n visited.assign(v, false);\n for (int i = 0; i < e; i++)\n {\n int s, t;\n cin >> s >> t;\n g[s].push_back(t);\n g[t].push_back(s);\n }\n bridges();\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5428, "score_of_the_acc": -0.1404, "final_rank": 8 }, { "submission_id": "aoj_GRL_3_B_10725475", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nstd::vector<std::vector<int>> G;\nstd::vector<bool> visited;\nstd::vector<int> prenum;\nstd::vector<int> lowest;\nstd::vector<int> parent;\nint t = 1;\n\nstruct edge{\n int u, w;\n\n bool operator==(const edge& other) const {\n return u == other.u && w == other.w;\n }\n};\n\nvoid dfs(int u, int p){\n prenum[u] = lowest[u] = t;\n t++;\n visited[u] = true;\n\n for(int v : G[u]){\n if(!visited[v]){\n parent[v] = u;\n dfs(v, u);\n lowest[u] = std::min(lowest[u], lowest[v]);\n }else if(v != p){\n lowest[u] = std::min(lowest[u], prenum[v]);\n }\n }\n}\n\nvoid bridges(int v){\n t = 1;\n dfs(0, -1);\n\n std::vector<edge> bridges;\n for(int u=1; u<v; u++){\n if(lowest[u] == prenum[u]){\n edge tmp;\n tmp.u = std::min(u, parent[u]);\n tmp.w = std::max(u, parent[u]);\n bridges.push_back(tmp);\n }\n }\n \n std::sort(bridges.begin(), bridges.end(), [](const edge& a, const edge& b){\n if(a.u != b.u) return a.u < b.u;\n return a.w < b.w;\n });\n bridges.erase(std::unique(bridges.begin(), bridges.end()), bridges.end());\n for(edge x : bridges){\n std::cout << x.u << \" \" << x.w << std::endl;\n }\n}\n\nint main(){\n int v, e;\n std::cin >> v >> e;\n\n G.resize(v);\n visited.resize(v, false);\n prenum.resize(v, 0);\n lowest.resize(v, 0);\n parent.resize(v, 0);\n \n for(int i=0;i<e;i++){\n int u,w;\n std::cin >> u >> w;\n G[u].push_back(w);\n G[w].push_back(u);\n }\n\n bridges(v);\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4728, "score_of_the_acc": -0.0176, "final_rank": 3 }, { "submission_id": "aoj_GRL_3_B_10724066", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<utility>\nusing namespace std;\n#define loop(a,b) for (int a = 0;a < b;a++)\n#define rep(a,b,c) for(int a = b;a < c;a++)\n#define vec(a) vector<a>\n\n\n\nstruct edge{\n int s,t;\n edge(int s,int t){\n this->s = s;\n this->t = t;\n if(s > t) swap(this->s,this->t);\n }\n bool operator<(const edge& e) const{\n return s < e.s || (s == e.s && t < e.t);\n }\n\n};\n\nstruct GRL_3_B{\n int n;\n vec(int) parent, prenum, lowest;\n vec(bool) visited;\n vec(edge) bridges;\n vec(vec(int)) G;\n\n GRL_3_B(int n):n(n),parent(n),prenum(n),lowest(n),G(n),visited(n,false){}\n\n void add_edge(int s,int t){\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n void dfs(int u,int& time,int p){\n prenum[u] = time++;\n lowest[u] = prenum[u];\n visited[u] = true;\n for(int v:G[u]){\n if(!visited[v]){\n parent[v] = u;\n dfs(v,time,u);\n lowest[u] = min(lowest[u], lowest[v]);\n }else if(v != p){\n lowest[u] = min(lowest[u],prenum[v]);\n }\n }\n }\n \n void get_bridges()\n {\n int time = 1;\n dfs(0,time,-1);\n rep(i,1,n){\n int p = parent[i];\n \n if(prenum[p] < lowest[i]){\n bridges.push_back(edge(p,i));\n }\n }\n sort(bridges.begin(),bridges.end());\n for(edge e:bridges) cout << e.s << \" \" << e.t << endl;\n }\n};\n\nint main(){\n int n,m;\n cin >> n >> m;\n GRL_3_B grl(n);\n loop(i,m){\n int s,t;\n cin >> s >> t;\n grl.add_edge(s,t);\n }\n grl.get_bridges();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5120, "score_of_the_acc": -0.0864, "final_rank": 7 }, { "submission_id": "aoj_GRL_3_B_10709125", "code_snippet": "// GRL_3_B\n#include <bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\n\nusing Graph = vector<vector<int>>;\n\nGraph G;\nvector<bool> seen;\nvector<int> prenum, parent, lowest;\nint t;\n\nvoid DFS(int u, int p) {\n prenum[u] = lowest[u] = t;\n t++;\n seen[u] = true;\n\n for(auto& v : G[u]) {\n if(!seen[v]) {\n parent[v] = u;\n DFS(v, u);\n lowest[u] = min(lowest[u], lowest[v]);\n }\n else if(v != p) {\n lowest[u] = min(lowest[u], prenum[v]);\n }\n }\n}\n\nvoid bridges(int v) {\n t = 1;\n DFS(0, -1);\n\n vector<pair<int, int>> bridge;\n for(int u=1; u<v; ++u) {\n if(lowest[u] == prenum[u]) {\n int a = parent[u];\n int b = u;\n if(a > b) swap(a, b);\n bridge.emplace_back(a, b);\n }\n }\n sort(bridge.begin(), bridge.end());\n for(auto& [a, b] : bridge) {\n cout << a << \" \" << b << endl;\n }\n}\n\nint main() {\n int v, e;\n cin >> v >> e;\n\n\n G.resize(v);\n seen.assign(v, false);\n prenum.resize(v);\n parent.resize(v, -1);\n lowest.resize(v);\n\n for(int i=0; i<e; ++i) {\n int s, t;\n cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n bridges(v);\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4628, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_GRL_3_B_10705201", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; (i) < (n); ++(i))\n\nvector<int> adjList[100010];\n\nint prenum[100010];\nint lowest[100010];\nint parent[100010];\nbool visited[100010];\n\nint t, V, E;\nvoid dfs(int, int);\n\nvoid Articulation_Points()\n{\n\n t = 1;\n dfs(0, -1);\n vector<int> art_points;\n int nc = 0;\n\n for (int u = 1; u < V; u++)\n {\n int p = parent[u];\n if (p == 0)\n {\n nc++;\n }\n else if (prenum[p] <= lowest[u])\n {\n art_points.push_back(p);\n }\n }\n if (nc > 1)\n {\n art_points.push_back(0);\n }\n sort(art_points.begin(), art_points.end());\n art_points.erase(unique(art_points.begin(), art_points.end()), art_points.end());\n\n rep(i, art_points.size())\n {\n cout << art_points[i] << endl;\n }\n}\n\nvoid dfs(int u, int p)\n{\n prenum[u] = lowest[u] = t;\n t++;\n visited[u] = true;\n\n for (int v : adjList[u])\n {\n if (!visited[v])\n {\n parent[v] = u;\n dfs(v, u);\n lowest[u] = min(lowest[u], lowest[v]);\n }\n else if (v != p)\n {\n lowest[u] = min(lowest[u], prenum[v]);\n }\n }\n}\n\nvoid find_bridge()\n{\n t = 1;\n dfs(0, -1);\n\n vector<pair<int, int>> bridges_edge;\n for (int u = 1; u < V; u++)\n {\n if (lowest[u] == prenum[u])\n {\n if (parent[u] < u)\n {\n bridges_edge.push_back({parent[u], u});\n }else {\n bridges_edge.push_back({u, parent[u]});\n }\n }\n }\n sort(bridges_edge.begin(), bridges_edge.end());\n \n rep(i, bridges_edge.size())\n {\n cout << bridges_edge[i].first << \" \" << bridges_edge[i].second << endl;\n }\n}\n\nint main()\n{\n\n cin >> V >> E;\n\n rep(i, E)\n {\n int s, t;\n cin >> s >> t;\n adjList[s].push_back(t);\n adjList[t].push_back(s);\n }\n find_bridge();\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7144, "score_of_the_acc": -0.4417, "final_rank": 14 }, { "submission_id": "aoj_GRL_3_B_10703886", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\n//Global Variable\nvector<int> prenum;\nvector<int> visited;\nvector<int> parent;\n//visited value 0=False, 1=True\nint t; \nvector<int> lowest;\nvector<vector<int>> G;\n//G is graph vector\n\nstruct Edge{\n int s;\n int t;\n\n bool operator<(const Edge& other) const {\n if (s != other.s) return s < other.s;\n return t < other.t;\n }\n\n // 重複削除(unique用):s と t が両方等しい場合\n bool operator==(const Edge& other) const {\n return s == other.s && t == other.t;\n }\n};\n\nvoid dfs(int u,int p){\n prenum[u] = t;\n lowest[u] = t;\n t = t + 1;\n visited[u] = 1;\n\n for(int i=0;i<G[u].size();i++){\n int v = G[u][i];\n if(!visited[v]){\n parent[v] = u;\n dfs(v,u);\n lowest[u] = min(lowest[u],lowest[v]);\n }else if(v!=p){\n lowest[u] = min(lowest[u],prenum[v]);\n }\n }\n return;\n}\n\nvoid bridges(int V){\n vector<Edge> bridges;\n Edge e;\n\n t = 1;\n dfs(0,-1);\n for(int u=1;u<V;u++){\n if(lowest[u]==prenum[u]){\n if(u<parent[u]){\n e.s = u;\n e.t = parent[u];\n bridges.push_back(e);\n }else{\n e.s = parent[u];\n e.t = u;\n bridges.push_back(e);\n }\n }\n }\n\n sort(bridges.begin(),bridges.end());\n bridges.erase(unique(bridges.begin(),bridges.end()), bridges.end());\n\n for(int i=0;i<bridges.size();i++){\n cout << bridges[i].s << \" \" << bridges[i].t << endl;\n }\n\n return;\n}\n\nint main(){\n int V,E;\n int s,t;\n\n cin >> V >> E;\n\n G.resize(V);\n\n for(int i=0;i<E;i++){\n cin >> s >> t;\n G[s].push_back(t);\n G[t].push_back(s);\n }\n\n for(int i=0;i<V;i++){\n prenum.push_back(0);\n visited.push_back(0);\n parent.push_back(0);\n lowest.push_back(0);\n }\n\n bridges(V);\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4720, "score_of_the_acc": -0.0162, "final_rank": 2 }, { "submission_id": "aoj_GRL_3_B_10524002", "code_snippet": "#include <bits/stdc++.h>\n#define INF 0x7fffffff\n#define MAXN 200010\ntypedef long long LL;\nusing namespace std;\n\nstruct edge\n{\n\tint u, v;\n};\n\nint n, m, cnt;\nvector <int> g[MAXN];\nint dfn[MAXN], low[MAXN];\nvector <edge> ans;\n\nvoid Tarjan(int u, int parent)\n{\n\tlow[u] = dfn[u] = ++cnt;\n\tfor(int x = 0; x < g[u].size(); x++)\n\t{\n\t\tint v = g[u][x];\n\t\tif(v == parent) continue;\n\t\tif(!dfn[v])\n\t\t{\n\t\t\tTarjan(v, u);\n\t\t\tlow[u] = min(low[u], low[v]);\n\t\t\tif(low[v] > dfn[u]) ans.push_back((edge){min(u,v), max(u,v)});\n\t\t}\n\t\telse low[u] = min(low[u], dfn[v]);\n\t}\n}\n\nbool cmp(edge x, edge y)\n{\n\tif(x.u == y.u) return x.v < y.v;\n\treturn x.u < y.u;\n}\n\nvector <edge> getBridge()\n{\n\tfor(int x = 0; x < n; x++)\n\t\tif(!dfn[x]) Tarjan(x, -1);\n\tsort(ans.begin(), ans.end(), cmp);\n\treturn ans;\n}\n\nint main()\n{\n\tcin >> n >> m;\n\tfor(int x = 1; x <= m; x++)\n\t{\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\tvector <edge> B = getBridge();\n\tfor(int x = 0; x < B.size(); x++) cout << B[x].u << \" \" << B[x].v << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 9712, "score_of_the_acc": -0.8926, "final_rank": 19 }, { "submission_id": "aoj_GRL_3_B_10502040", "code_snippet": "//0 points && ik that but i'll have a try..\n#include <bits/stdc++.h>\n#define ll long long\n#define db double\n#define ld long double\n#define endl '\\n'\n#define eb emplace_back\n#define em emplace\n#define pb push_back\n#define pf push_front\n#define pp pop_back\n#define fr first\n#define sc second\n#define sz size\nusing namespace std;\nconst ll mx = 100005;\nvector<ll> g[mx] ;\nvector<pair<ll, ll>> res;\nll in[mx] , lw[mx] ,t ;\nbool vs[mx] ;\nvoid dfs(ll u , ll p = -1) {\n vs[u] = true;\n in[u] = lw[u] = t++ ;\n for (ll v : g[u]) {\n if (v == p) continue;\n if (vs[v]) lw[u] = min(lw[u] , in[v]);\n else {\n dfs(v, u);\n lw[u] = min(lw[u] , lw[v]);\n if (lw[v] > in[u]) res.eb(min(u ,v) , max(u , v));\n }\n }\n}\nsigned main() {\n ll n , m ;\n cin >> n >> m ;\n while (m--) {\n ll u , v ;\n cin >> u >> v ;\n g[u].pb(v) ;\n g[v].pb(u) ;\n }\n for (ll i = 0 ; i < n ; i++) if (!vs[i]) dfs(i) ;\n sort(res.begin(), res.end());\n for (auto &x : res) cout << x.fr << \" \" << x.sc << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7852, "score_of_the_acc": -0.566, "final_rank": 15 }, { "submission_id": "aoj_GRL_3_B_10383034", "code_snippet": "//#pragma GCC target(\"avx2\")\n//#pragma GCC optimize(\"O3\")\n//#pragma GCC optimize(\"unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing pli = pair<ll,int>;\nvoid inline TEST(void){cerr << \"TEST\" << endl;}\n#define AMARI 998244353\n//#define AMARI 1000000007\n#define el '\\n'\n#define El '\\n'\n#define YESNO(x) ((x) ? \"Yes\" : \"No\")\n#define YES YESNO(true)\n#define NO YESNO(false)\n#define REV_PRIORITY_QUEUE(tp) priority_queue<tp,vector<tp>,greater<tp>>\n#define NO_ANS(x) {cout << (x) << '\\n'; return;}\ntemplate <typename T>\nvoid inline VEC_UNIQ(vector<T> &v){\n sort(v.begin(),v.end());\n v.erase(unique(v.begin(),v.end()),v.end());\n return;\n}\n\n\n//lowlink\n//このライブラリでは無向グラフにしか対応していないが、本来は有向グラフでもできるらしい。\nclass ococo_lowlink{\n private:\n int n;\n int cnt = 0;\n vector<vector<int>> g;\n vector<int> ord,low,par,depth;\n vector<vector<int>> depth_inv;\n vector<bool> kansetuten;\n void dfs(int p,int v){\n par[v] = p;\n low[v] = ord[v] = cnt;\n cnt++;\n for(int i = 0; i < (int)g[v].size(); i++){\n int to = g[v][i];\n if(to == p)continue;\n if(ord[to] == -1){\n depth[to] = depth[v] + 1;\n depth_inv[depth[to]].push_back(to);\n dfs(v,to);\n low[v] = min(low[v],low[to]);\n }\n else low[v] = min(low[v],ord[to]);\n }\n }\n public:\n ococo_lowlink(int N = 0){\n n = N;\n g.resize(n);\n ord.resize(n);\n low.resize(n);\n par.resize(n);\n depth.resize(n);\n depth_inv.resize(n);\n kansetuten.resize(n);\n for(int i = 0; i < n; i++)depth_inv[i].clear();\n }\n void einsert(int u,int v){\n g[u].push_back(v);\n g[v].push_back(u);\n }\n void peinsert(pair<int,int> p){\n einsert(p.first,p.second);\n }\n void build(void){\n //cerr << (int)depth.size() << ' ' << (int)depth_inv.size() << el;\n cnt = 0;\n for(int i = 0; i < n; i++)ord[i] = -1;\n for(int i = 0; i < n; i++){\n if(ord[i] == -1){\n depth[i] = 0;\n depth_inv[i].push_back(0);\n dfs(-1,i);\n }\n }\n for(int i = n - 1; i >= 0; i--){\n for(int j = 0; j < depth_inv[i].size(); j++){\n int fr = depth_inv[i][j];\n for(int l = 0; l < g[fr].size(); l++){\n int to = g[fr][l];\n if(to == par[fr])continue;\n //low[fr] = min(low[to],low[fr]);\n }\n }\n }\n for(int i = 0; i < n; i++){\n int bc = 0;\n for(int j = 0; j < (int)g[i].size(); j++){\n int to = g[i][j];\n if(par[to] != i)continue;\n if(ord[i] <= low[to])bc++;\n }\n if(i == 0 && bc >= 2)kansetuten[i] = true;\n if(i >= 1 && bc >= 1)kansetuten[i] = true;\n }\n }\n bool is_bridge(int u,int v){\n if(par[v] != u)swap(u,v);\n //いま、vの親がu\n if(low[v] > ord[u])return true;\n return false;\n }\n bool is_kansetuten(int v){\n return kansetuten[v];\n }\n \n //DFS 順でその頂点に辿り着いたのが何個目の頂点かを持つ配列 order を返す\n vector<int> get_order(void){\n return ord;\n }\n \n //DFS木上の辺を親→子の方向に好きな回数、後退辺(DFS 木上にない辺)を1回以下通って到達可能な order の最小値を返す。\n //↑この説明は有向グラフだと間違いらしい。\n //order[u] < order[v] としたとき、order[u] < low[v] であることと辺 (u,v) が橋であることが同値であることを利用して、lowlink は動いている。(らしい)\n //(橋でないなら (u,v)間に後退辺がないから、low[v] >= order[u] になる)\n vector<int> get_low(void){\n return low;\n }\n };\n \n#define MULTI_TEST_CASE false\nvoid solve(void){\n //問題を見たらまず「この問題設定から言えること」をいっぱい言う\n //一個回答に繋がりそうな解法が見えても、実装や細かい詰めに時間がかかりそうなら別の方針を考えてみる\n //ある程度考察しても全然取っ掛かりが見えないときは実験をしてみる\n //よりシンプルな問題に言い換えられたら、言い換えた先の問題を自然言語ではっきりと書く\n //複数の解法のアイデアを思いついた時は全部メモしておく\n //g++ -D_GLIBCXX_DEBUG -Wall -O2 XXX.cpp -o o\n\n int n,m;\n cin >> n >> m;\n ococo_lowlink llink(n);\n vector<pii> edge;\n while(m--){\n int u,v;\n cin >> u >> v;\n if(u > v)swap(u,v);\n llink.einsert(u,v);\n edge.push_back(pair(u,v));\n }\n llink.build();\n sort(edge.begin(),edge.end());\n\n for(int i = 0; i < (int)edge.size(); i++){\n if(llink.is_bridge(edge[i].first,edge[i].second)){\n cout << edge[i].first << ' ' << edge[i].second << el;\n }\n }\n\n return;\n}\n\nvoid calc(void){\n return;\n}\n\nsigned main(void){\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n calc();\n int t = 1;\n if(MULTI_TEST_CASE)cin >> t;\n while(t--){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5624, "score_of_the_acc": -0.1749, "final_rank": 9 }, { "submission_id": "aoj_GRL_3_B_10376146", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<vector<int>> G;\nvector<int> disc, low;\nvector<pair<int, int>> bridges;\nint tt;\n\nvoid dfs(int u, int parent) {\n\tdisc[u] = low[u] = ++tt;\n\tfor (int v : G[u]) {\n\t\tif (disc[v] == 0) {\n\t\t\tdfs(v, u);\n\t\t\tlow[u] = min(low[u], low[v]);\n\t\t\tif (low[v] > disc[u]) {\n\t\t\t\tif (u < v) bridges.push_back({u, v});\n\t\t\t\telse bridges.push_back({v, u});\n\t\t\t}\n\t\t} else if (v != parent) \n\t\t\tlow[u] = min(low[u], disc[v]);\n\t}\n}\n\nint main() {\n\tint V, E;\n\tcin >> V >> E;\n\tG.resize(V);\n\twhile (E--) {\n\t\tint s, t;\n\t\tcin >> s >> t;\n\t\tG[s].push_back(t);\n\t\tG[t].push_back(s);\n\t}\n\t\n\tdisc.assign(V, 0);\n\tlow.resize(V);\n\tdfs(0, -1);\n\tsort(bridges.begin(), bridges.end());\n\t\n\tfor (auto& bridge : bridges) {\n\t\tcout << bridge.first << \" \" << bridge.second << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5020, "score_of_the_acc": -0.0688, "final_rank": 6 }, { "submission_id": "aoj_GRL_3_B_10352501", "code_snippet": "#line 1 \"verify/AOJ-GRL-3-B.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/3/GRL_3_B\"\n\n#line 2 \"Library/Template.hpp\"\n\n/**\n * @file Template.hpp\n * @author log K (lX57)\n * @brief Template - テンプレート\n * @version 1.10\n * @date 2025-03-16\n */\n\n#line 2 \"Library/Common.hpp\"\n\n/**\n * @file Common.hpp\n */\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\nusing namespace std;\n\nusing ll = int64_t;\nusing ull = uint64_t;\n\nconstexpr const ll INF = (1LL << 62) - (1LL << 30) - 1;\n#line 12 \"Library/Template.hpp\"\n\ninline bool YnPrint(bool flag){cout << (flag ? \"Yes\" : \"No\") << '\\n'; return flag;}\ninline bool YNPrint(bool flag){cout << (flag ? \"YES\" : \"NO\") << '\\n'; return flag;}\ntemplate<typename Container>\ninline void Sort(Container &container){sort(container.begin(), container.end());}\ntemplate<typename Container>\ninline void ReverseSort(Container &container){sort(container.rbegin(), container.rend());}\ntemplate<typename Container>\ninline void Reverse(Container &container){reverse(container.begin(), container.end());}\ntemplate<typename Value>\ninline int PopCount(const Value &value){return __builtin_popcount(value);}\ntemplate<typename Value>\ninline Value Ceil(const Value &numerator, const Value &denominator){return (numerator + denominator - 1) / denominator;}\ntemplate<typename Value>\ninline int LowerBoundIndex(const vector<Value> &container, const Value &value){return distance(container.begin(), lower_bound(container.begin(), container.end(), value));}\ntemplate<typename Value>\ninline int UpperBoundIndex(const vector<Value> &container, const Value &value){return distance(container.begin(), upper_bound(container.begin(), container.end(), value));}\ntemplate<typename Value>\ninline bool Between(const Value &lower, const Value &x, const Value &higher){return lower <= x && x <= higher;}\ntemplate<typename Value>\ninline bool InGrid(const Value &y, const Value &x, const Value &ymax, const Value &xmax){return Between(0, y, ymax - 1) && Between(0, x, xmax - 1);}\ntemplate<typename Value>\ninline Value Median(const Value &a, const Value &b, const Value &c){return Between(b, a, c) || Between(c, a, b) ? a : (Between(a, b, c) || Between(c, b, a) ? b : c);}\ntemplate<typename Value>\ninline Value Except(Value &src, Value &cond, Value &excp){return (src == cond ? excp : src);}\n\ntemplate<class Value>\nbool chmin(Value &src, const Value &cmp){if(src > cmp){src = cmp; return true;} return false;}\ntemplate<class Value>\nbool chmax(Value &src, const Value &cmp){if(src < cmp){src = cmp; return true;} return false;}\ntemplate<typename Value>\ninline Value min(vector<Value> &v){return *min_element((v).begin(), (v).end());}\ntemplate<typename Value>\ninline Value max(vector<Value> &v){return *max_element((v).begin(), (v).end());}\n\nconst int dx4[4] = {1, 0, -1, 0};\nconst int dy4[4] = {0, -1, 0, 1};\nconst int dx8[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst int dy8[8] = {0, -1, -1, -1, 0, 1, 1, 1};\n\nvector<pair<int, int>> adjacent(int current_y, int current_x, int max_y, int max_x, bool dir_8 = false){\n vector<pair<int, int>> ret;\n for(int d = 0; d < 4 * (1 + dir_8); ++d){\n int next_y = current_y + (dir_8 ? dy8[d] : dy4[d]);\n int next_x = current_x + (dir_8 ? dx8[d] : dx4[d]);\n if(InGrid(next_y, next_x, max_y, max_x)){\n ret.emplace_back(next_y, next_x);\n }\n }\n return ret;\n}\n\ntemplate <typename T1, typename T2>\nostream &operator<<(ostream &os, const pair<T1, T2> &p){\n os << p.first << \" \" << p.second;\n return os;\n}\n\ntemplate <typename T1, typename T2>\nistream &operator>>(istream &is, pair<T1, T2> &p){\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<T> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<vector<T>> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \"\\n\" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v){\n for (int i = 0; i < v.size(); ++i) is >> v[i];\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, set<T> &v){\n for (auto &u : v){\n os << u << \" \";\n }\n return os;\n}\n\ntemplate<typename T1, typename T2>\nvector<pair<T1, T2>> AssembleVectorPair(vector<T1> &v1, vector<T2> &v2){\n assert(v1.size() == v2.size());\n vector<pair<T1, T2>> v;\n for(int i = 0; i < v1.size(); ++i) v.push_back({v1[i], v2[i]});\n return v;\n}\n\ntemplate<typename T1, typename T2>\npair<vector<T1>, vector<T2>> DisassembleVectorPair(vector<pair<T1, T2>> &v){\n vector<T1> v1;\n vector<T2> v2;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return p.first;});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return p.second;});\n return {v1, v2};\n}\n\ntemplate<typename T1, typename T2, typename T3>\ntuple<vector<T1>, vector<T2>, vector<T3>> DisassembleVectorTuple(vector<tuple<T1, T2, T3>> &v){\n vector<T1> v1;\n vector<T2> v2;\n vector<T3> v3;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return get<0>(p);});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return get<1>(p);});\n transform(v.begin(), v.end(), back_inserter(v3), [](auto p){return get<2>(p);});\n return {v1, v2, v3};\n}\n\ntemplate<typename T1 = int, typename T2 = T1>\npair<vector<T1>, vector<T2>> InputVectorPair(int size){\n vector<pair<T1, T2>> v(size);\n for(auto &[p, q] : v) cin >> p >> q;\n return DisassembleVectorPair(v);\n}\n\ntemplate<typename T1 = int, typename T2 = T1, typename T3 = T1>\ntuple<vector<T1>, vector<T2>, vector<T3>> InputVectorTuple(int size){\n vector<tuple<T1, T2, T3>> v(size);\n for(auto &[p, q, r] : v) cin >> p >> q >> r;\n return DisassembleVectorTuple(v);\n}\n#line 2 \"Library/Graph/LowLink.hpp\"\n\n#line 2 \"Library/Graph/Graph.hpp\"\n\n#line 4 \"Library/Graph/Graph.hpp\"\n\nusing Vertex = int;\n\ntemplate<typename CostType = int32_t>\nstruct Edge{\n public:\n Edge() = default;\n\n Edge(Vertex from_, Vertex to_, CostType cost_ = 1, int idx_ = -1) :\n from(from_), to(to_), cost(cost_), idx(idx_){}\n \n bool operator<(const Edge<CostType> &e) const {return cost < e.cost;}\n\n operator int() const {return to;}\n\n Vertex from, to;\n CostType cost;\n int idx;\n};\n\ntemplate<typename CostType = int32_t>\nclass Graph{\n public:\n Graph() = default;\n\n Graph(int n) : vertex_size_(n), edge_size_(0), adjacent_list_(n){}\n \n inline void AddUndirectedEdge(Vertex u, Vertex v, CostType w = 1){\n int idx = edge_size_++;\n adjacent_list_[u].push_back(Edge<CostType>(u, v, w, idx));\n adjacent_list_[v].push_back(Edge<CostType>(v, u, w, idx));\n }\n \n inline void AddDirectedEdge(Vertex u, Vertex v, CostType w = 1){\n int idx = edge_size_++;\n adjacent_list_[u].push_back(Edge<CostType>(u, v, w, idx));\n }\n\n inline size_t VertexSize() const {\n return vertex_size_;\n }\n\n inline size_t EdgeSize() const {\n return edge_size_;\n }\n\n inline vector<Edge<CostType>> &operator[](const int v){\n return adjacent_list_[v];\n }\n\n inline const vector<Edge<CostType>> &operator[](const int v) const {\n return adjacent_list_[v];\n }\n \n private:\n size_t vertex_size_, edge_size_;\n vector<vector<Edge<CostType>>> adjacent_list_;\n};\n\ntemplate<typename CostType = int32_t>\nGraph<CostType> InputGraph(int N, int M, int padding = -1, bool weighted = false, bool directed = false){\n Graph<CostType> G(N);\n for(int i = 0; i < M; ++i){\n Vertex u, v; CostType w = 1;\n cin >> u >> v, u += padding, v += padding;\n if(weighted) cin >> w;\n if(directed) G.AddDirectedEdge(u, v, w);\n else G.AddUndirectedEdge(u, v, w);\n }\n return G;\n}\n#line 4 \"Library/Graph/LowLink.hpp\"\n\ntemplate<typename CostType>\nclass LowLink{\n public:\n LowLink(Graph<CostType> &graph) : G(graph), n(graph.VertexSize()), ord_(n, -1), low_(n, -1), in_(n), out_(n){\n for(int i = 0, k = 0, t = 0; i < n; ++i){\n if(ord_[i] == -1){\n k = dfs(i, -1, k, t);\n }\n }\n }\n\n vector<Vertex> &ArticulationVertex(){\n return articulation_vertex_;\n }\n\n vector<pair<Vertex, Vertex>> &Bridge(){\n return bridge_;\n }\n\n pair<int, int> EulerTour(const Vertex v) const {\n return {in_[v], out_[v]};\n }\n\n private:\n Graph<CostType> &G;\n int n;\n vector<int> ord_, low_, in_, out_;\n vector<Vertex> articulation_vertex_;\n vector<pair<Vertex, Vertex>> bridge_;\n\n int dfs(Vertex v, int p, int k, int &t){\n in_[v] = t++;\n low_[v] = (ord_[v] = k++);\n int cnt = 0;\n bool is_articulation = false, second = false;\n for(int u : G[v]){\n if(ord_[u] == -1){\n ++cnt;\n k = dfs(u, v, k, t);\n low_[v] = min(low_[v], low_[u]);\n is_articulation |= (p != -1) && (low_[u] >= ord_[v]);\n if(ord_[v] < low_[u]){\n bridge_.emplace_back(minmax(u, v));\n }\n }\n else if(u != p || second){\n low_[v] = min(low_[v], ord_[u]);\n }\n else{\n second = true;\n }\n }\n is_articulation |= (p == -1) && (cnt > 1);\n if(is_articulation) articulation_vertex_.emplace_back(v);\n out_[v] = t;\n return k;\n }\n};\n#line 5 \"verify/AOJ-GRL-3-B.test.cpp\"\n\nint main(){\n int V, E; cin >> V >> E;\n auto G = InputGraph<ll>(V, E, 0, false, false);\n \n LowLink llk(G);\n auto ans = llk.Bridge();\n Sort(ans);\n for(const auto [s, t] : ans) cout << s << ' ' << t << '\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8140, "score_of_the_acc": -0.6166, "final_rank": 16 }, { "submission_id": "aoj_GRL_3_B_10264866", "code_snippet": "#line 1 \"verify/AOJ-GRL-3-B.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/1/GRL_3_B\"\n\n#line 2 \"Library/Template.hpp\"\n\n/**\n * @file Template.hpp\n * @author log K (lX57)\n * @brief Template - テンプレート\n * @version 1.9\n * @date 2024-10-27\n */\n\n#line 2 \"Library/Common.hpp\"\n\n/**\n * @file Common.hpp\n */\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\nusing namespace std;\n#line 12 \"Library/Template.hpp\"\n#define ALL(x) (x).begin(), (x).end()\n#define RALL(x) (x).rbegin(), (x).rend()\n#define SORT(x) sort(ALL(x))\n#define RSORT(x) sort(RALL(x))\n#define REVERSE(x) reverse(ALL(x))\n#define SETPRE(digit) fixed << setprecision(digit)\n#define POPCOUNT(x) __builtin_popcount(x)\n#define SUM(x) reduce((x).begin(), (x).end())\n#define CEIL(nume, deno) ((nume) + (deno) - 1) / (deno)\n#define IOTA(x) iota((x).begin(), (x).end(), 0)\n#define LOWERBOUND_IDX(arr, val) distance((arr).begin(), lower_bound((arr).begin(), (arr).end(), val))\n#define UPPERBOUND_IDX(arr, val) distance((arr).begin(), upper_bound((arr).begin(), (arr).end(), val))\n\ninline string Yn(bool flag){return (flag) ? \"Yes\" : \"No\";}\ninline bool YnPrint(bool flag){cout << Yn(flag) << endl;return flag;}\ninline string YN(bool flag){return (flag) ? \"YES\" : \"NO\";}\ninline bool YNPrint(bool flag){cout << YN(flag) << endl;return flag;}\ntemplate<class T>\nbool chmin(T &src, const T &cmp){if(src > cmp){src = cmp; return true;}return false;}\ntemplate<class T>\nbool chmax(T &src, const T &cmp){if(src < cmp){src = cmp; return true;}return false;}\ntemplate<typename T>\ninline bool between(T min, T x, T max){return min <= x && x <= max;}\ntemplate<typename T>\ninline bool ingrid(T y, T x, T ymax, T xmax){return between(0, y, ymax - 1) && between(0, x, xmax - 1);}\ntemplate<typename T>\ninline T median(T a, T b, T c){return between(b, a, c) || between(c, a, b) ? a : (between(a, b, c) || between(c, b, a) ? b : c);}\ntemplate<typename T>\ninline T except(T src, T cond, T excp){return (src == cond ? excp : src);}\ntemplate<typename T>\ninline T min(vector<T> &v){return *min_element((v).begin(), (v).end());}\ntemplate<typename T>\ninline T max(vector<T> &v){return *max_element((v).begin(), (v).end());}\nvector<int> make_sequence(int Size){\n vector<int> ret(Size);\n IOTA(ret);\n return ret;\n}\ntemplate<typename T>\nvoid make_unique(vector<T> &v){\n sort(v.begin(), v.end());\n auto itr = unique(v.begin(), v.end());\n v.erase(itr, v.end());\n}\n\nusing ll = int64_t;\nusing ull = uint64_t;\nusing ld = long double;\n\nconst int INF_INT = numeric_limits<int>::max() >> 2;\nconst ll INF_LL = numeric_limits<ll>::max() >> 2;\n\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\nusing vs = vector<string>;\ntemplate <typename T>\nusing pq = priority_queue<T>;\ntemplate <typename T>\nusing rpq = priority_queue<T, vector<T>, greater<T>>;\n\nconst int dx4[4] = {1, 0, -1, 0};\nconst int dy4[4] = {0, -1, 0, 1};\nconst int dx8[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst int dy8[8] = {0, -1, -1, -1, 0, 1, 1, 1};\n\nvector<pair<int, int>> adjacent(int current_y, int current_x, int max_y, int max_x, bool dir_8 = false){\n vector<pair<int, int>> ret;\n for(int d = 0; d < 4 * (1 + dir_8); ++d){\n int next_y = current_y + (dir_8 ? dy8[d] : dy4[d]);\n int next_x = current_x + (dir_8 ? dx8[d] : dx4[d]);\n if(0 <= next_y and next_y < max_y and 0 <= next_x and next_x < max_x){\n ret.emplace_back(next_y, next_x);\n }\n }\n return ret;\n}\n\ntemplate <typename T1, typename T2>\nostream &operator<<(ostream &os, const pair<T1, T2> &p){\n os << p.first << ' ' << p.second;\n return os;\n}\n\ntemplate <typename T1, typename T2>\nistream &operator>>(istream &is, pair<T1, T2> &p){\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v){\n for (int i = 0; i < v.size(); ++i) is >> v[i];\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v){\n os << v[0];\n for (int i = 1; i < v.size(); ++i){\n os << ' ' << v[i];\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<vector<T>> &v){\n os << v[0];\n for (int i = 0; i < v.size(); ++i){\n os << '\\n' << v[i];\n }\n return os;\n}\n\ntemplate<class T>\nvoid Print(const T &a){\n cout << a << '\\n';\n}\n\ntemplate<class T, class... Ts>\nvoid Print(const T &a, const Ts &...b){\n cout << a;\n (cout << ... << (cout << ' ', b));\n cout << '\\n';\n}\n\ntemplate<typename T1, typename T2>\nvector<pair<T1, T2>> AssembleVectorPair(vector<T1> &v1, vector<T2> &v2){\n assert(v1.size() == v2.size());\n vector<pair<T1, T2>> v;\n for(int i = 0; i < v1.size(); ++i) v.push_back({v1[i], v2[i]});\n return v;\n}\n\ntemplate<typename T1, typename T2>\npair<vector<T1>, vector<T2>> DisassembleVectorPair(vector<pair<T1, T2>> &v){\n vector<T1> v1;\n vector<T2> v2;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return p.first;});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return p.second;});\n return {v1, v2};\n}\n\ntemplate<typename T1, typename T2, typename T3>\ntuple<vector<T1>, vector<T2>, vector<T3>> DisassembleVectorTuple(vector<tuple<T1, T2, T3>> &v){\n vector<T1> v1;\n vector<T2> v2;\n vector<T3> v3;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return get<0>(p);});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return get<1>(p);});\n transform(v.begin(), v.end(), back_inserter(v3), [](auto p){return get<2>(p);});\n return {v1, v2, v3};\n}\n\ntemplate<typename T1 = int, typename T2 = T1>\npair<vector<T1>, vector<T2>> InputVectorPair(int size){\n vector<pair<T1, T2>> v(size);\n for(auto &[p, q] : v) cin >> p >> q;\n return DisassembleVectorPair(v);\n}\n\ntemplate<typename T1 = int, typename T2 = T1, typename T3 = T1>\ntuple<vector<T1>, vector<T2>, vector<T3>> InputVectorTuple(int size){\n vector<tuple<T1, T2, T3>> v(size);\n for(auto &[p, q, r] : v) cin >> p >> q >> r;\n return DisassembleVectorTuple(v);\n}\n\nll modpow(ll a, ll x, ll m){\n ll ret = 1, cur = a % m, rem = x;\n while(rem){\n if(rem & 1) ret = (ret * cur) % m;\n rem >>= 1, cur = (cur * cur) % m;\n }\n return ret;\n}\n\n#ifdef LOGK\n#define VARIABLE(var) cerr << \"# \" << #var << \" = \" << var << endl;\n#else\n#define VARIABLE(...) 42\n#endif\n#line 2 \"Library/Graph/LowLink.hpp\"\n\n#line 4 \"Library/Graph/LowLink.hpp\"\n\nclass LowLink{\n public:\n LowLink(size_t n) : n_(n), edges_(0), G(n), in_(n, -1), out_(n, -1), low_(n, -1){}\n\n void AddEdge(int u, int v, int id = -1){\n if(id == -1) id = edges_;\n G[u].emplace_back(v, id);\n G[v].emplace_back(u, id);\n ++edges_;\n }\n\n void Build(){\n for(int i = 0, t = 0; i < n_; ++i){\n if(in_[i] < 0) dfs(i, -1, t);\n }\n }\n\n bool IsBridge(int id){\n return bridge_.contains(id);\n }\n\n bool IsArticulation(int v){\n return articulation_.contains(v);\n }\n\n vector<int> GetBridge(){\n vector<int> ret;\n for(const auto &[id, _] : bridge_) ret.push_back(id);\n sort(ret.begin(), ret.end());\n return ret;\n }\n\n vector<int> GetArticulation(){\n vector<int> ret;\n for(const auto &[v, _] : articulation_) ret.push_back(v);\n sort(ret.begin(), ret.end());\n return ret;\n }\n\n private:\n void dfs(int u, int e, int &t){\n in_[u] = low_[u] = t++;\n int c = 0;\n for(const auto &[v, id] : G[u]){\n if(in_[v] < 0){\n dfs(v, id, t);\n low_[u] = min(low_[u], low_[v]);\n ++c;\n if(low_[v] > in_[u]) bridge_[id] = v;\n if(e != -1 && low_[v] >= in_[u]) articulation_[u] = v;\n }\n else if(id != e){\n low_[u] = min(low_[u], in_[v]);\n }\n }\n if(e == -1 && c >= 2) articulation_[u] = G[u].front().first;\n out_[u] = t;\n }\n\n size_t n_, edges_;\n vector<vector<pair<int, int>>> G;\n vector<int> in_, out_, low_;\n unordered_map<int, int> bridge_, articulation_;\n};\n#line 5 \"verify/AOJ-GRL-3-B.test.cpp\"\n\nint main(){\n int V, E; cin >> V >> E;\n auto [s, t] = InputVectorPair<int>(E);\n \n LowLink lk(V);\n for(int i = 0; i < E; ++i){\n lk.AddEdge(s[i], t[i], i);\n }\n lk.Build();\n\n vector<pair<int, int>> ans;\n for(const auto &i : lk.GetBridge()){\n ans.emplace_back(min(s[i], t[i]), max(s[i], t[i]));\n }\n sort(ans.begin(), ans.end());\n for(const auto &[S, T] : ans){\n cout << S << ' ' << T << '\\n';\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6224, "score_of_the_acc": -0.2802, "final_rank": 12 }, { "submission_id": "aoj_GRL_3_B_10132742", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass BridgeDetection {\n private:\n map<int, vector<int>> edges;\n int size;\n vector<int> ord;\n vector<int> low;\n vector<int> parent;\n vector<bool> visited;\n vector<pair<int, int>> bridges;\n\n public:\n BridgeDetection(int n) : size(n) {\n ord = vector<int>(n, -1);\n low = vector<int>(n, -1);\n parent = vector<int>(n, -1);\n visited = vector<bool>(n, false);\n }\n void add_edge(int u, int v) {\n edges[u].push_back(v);\n edges[v].push_back(u);\n }\n void dfs(int u, int time) {\n visited[u] = true;\n ord[u] = time;\n low[u] = time;\n\n for (auto v : edges[u]) {\n if (!visited[v]) {\n parent[v] = u;\n dfs(v, time + 1);\n\n low[u] = min(low[u], low[v]);\n if (low[v] > ord[u]) {\n pair<int, int> p;\n if (u < v) {\n p.first = u;\n p.second = v;\n } else {\n p.first = v;\n p.second = u;\n }\n bridges.push_back(p);\n }\n } else if (v != parent[u]) {\n low[u] = min(low[u], ord[v]);\n }\n }\n }\n void exec() {\n for (int i = 0; i < size; ++i) {\n if (!visited[i]) {\n dfs(i, 0);\n }\n }\n }\n void print() {\n sort(bridges.begin(), bridges.end());\n for (auto p : bridges) {\n cout << p.first << \" \" << p.second << endl;\n }\n }\n};\nint main() {\n std::ios::sync_with_stdio(0);\n std::cin.tie(0);\n\n int v, e;\n cin >> v >> e;\n BridgeDetection graph = BridgeDetection(v);\n for (int i = 0; i < e; ++i) {\n int s, t;\n cin >> s >> t;\n graph.add_edge(s, t);\n }\n graph.exec();\n graph.print();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5704, "score_of_the_acc": -0.1889, "final_rank": 10 }, { "submission_id": "aoj_GRL_3_B_9989125", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n//#include <atcoder/all>\n//using namespace atcoder;\nusing ll=long long;\nusing ld=long double;\nusing uint=uint32_t;\nusing ull=uint64_t;\nusing pii=pair<int,int>;\nusing pll=pair<ll,ll>;\n//using mint=modint998244353;\nusing graph=vector<vector<int>>;\nconst ll INF=1ll<<60;\n\nstruct Edge {\n int to;\n};\nusing Graph = vector<vector<Edge>>;\nusing P = pair<long, long>;\n\n/* Lowlink: グラフの関節点・橋を列挙する構造体\n 作成: O(E+V)\n 関節点の集合: vector<int> aps\n 橋の集合: vector<P> bridges\n*/\nstruct LowLink {\n const Graph &G;\n vector<int> used, ord, low;\n vector<int> aps; // articulation points\n vector<P> bridges;\n\n LowLink(const Graph &G_) : G(G_) {\n used.assign(G.size(), 0);\n ord.assign(G.size(), 0);\n low.assign(G.size(), 0);\n int k = 0;\n for (int i = 0; i < (int)G.size(); i++) {\n if (!used[i]) k = dfs(i, k, -1);\n }\n sort(aps.begin(), aps.end()); // 必要ならソートする\n sort(bridges.begin(), bridges.end()); // 必要ならソートする\n }\n\n int dfs(int id, int k, int par) { // id:探索中の頂点, k:dfsで何番目に探索するか, par:idの親\n used[id] = true;\n ord[id] = k++;\n low[id] = ord[id];\n bool is_aps = false;\n int count = 0; // 子の数\n for (auto &e : G[id]) {\n if (!used[e.to]) {\n count++;\n k = dfs(e.to, k, id);\n low[id] = min(low[id], low[e.to]);\n if (par != -1 && ord[id] <= low[e.to]) is_aps = true; \n if (ord[id] < low[e.to]) bridges.emplace_back(min(id, e.to), max(id, e.to)); // 条件を満たすので橋 \n } else if (e.to != par) { // eが後退辺の時\n low[id] = min(low[id], ord[e.to]);\n }\n }\n if (par == -1 && count >= 2) is_aps = true; \n if (is_aps) aps.push_back(id);\n return k;\n }\n};\n\nint main(){\n int V,E; cin>>V>>E;\n Graph G(V);\n for(int i=0;i<E;i++){\n int u,v; cin>>u>>v;\n G[u].emplace_back(Edge{v});\n G[v].emplace_back(Edge{u});\n }\n LowLink L{G};\n for(P i:L.bridges){\n cout<<i.first<<\" \"<<i.second<<endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4904, "score_of_the_acc": -0.0485, "final_rank": 5 }, { "submission_id": "aoj_GRL_3_B_9964979", "code_snippet": "// ### test.cpp ###\n#include <bits/stdc++.h>\n#ifdef __DEBUG_VECTOR\nnamespace for_debugging{\n struct subscript_and_location{\n int sub;\n std::source_location loc;\n subscript_and_location(int sub_,std::source_location loc_=std::source_location::current()){\n sub=sub_;\n loc=loc_;\n }\n void check_out_of_range(size_t sz){\n if(sub<0||(int)sz<=sub){\n std::clog << loc.file_name() << \":(\" << loc.line() << \":\" << loc.column() << \"):\" << loc.function_name() << std::endl;\n std::clog << \"out of range: subscript = \" << sub << \", vector_size = \" << sz << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n };\n}\nnamespace std{\n template<class T,class Allocator=std::allocator<T>> class vector_for_debugging:public std::vector<T,Allocator>{\n using std::vector<T,Allocator>::vector;\n public:\n [[nodiscard]] constexpr std::vector<T,Allocator>::reference operator[](for_debugging::subscript_and_location n) noexcept(!std::is_same<T,bool>::value){\n n.check_out_of_range(this->size());\n return std::vector<T,Allocator>::operator[](n.sub);\n }\n [[nodiscard]] constexpr std::vector<T,Allocator>::const_reference operator[](for_debugging::subscript_and_location n) const noexcept(!std::is_same<T,bool>::value){\n n.check_out_of_range(this->size());\n return std::vector<T,Allocator>::operator[](n.sub);\n }\n };\n namespace pmr{\n template<class T> using vector_for_debugging=std::vector_for_debugging<T,std::pmr::polymorphic_allocator<T>>;\n }\n}\n#define vector vector_for_debugging\n#endif\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing sll = __int128_t;\nusing db = double;\nusing Pr = pair<ll, ll>;\nusing Pd = pair<double, double>;\nusing vi = vector<int>;\nusing vs = vector<string>;\nusing vc = vector<char>;\nusing vl = vector<ll>;\nusing vb = vector<bool>;\nusing vd = vector<double>;\nusing vp = vector<Pr>;\nusing vpd = vector<Pd>;\nusing vvi = vector<vector<int>>;\nusing vvc = vector<vector<char>>;\nusing vvl = vector<vector<ll>>;\nusing vvp = vector<vector<Pr>>;\nusing vvb = vector<vector<bool>>;\nusing vvd = vector<vector<double>>;\nusing vvs = vector<vector<string>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vvvl = vector<vector<vector<ll>>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing vvvd = vector<vector<vector<double>>>;\nusing t3 = tuple<ll,ll,ll>;\nusing t3d = tuple<db,db,db>;\nusing t4 = tuple<ll,ll,ll,ll>;\nusing vt3 = vector<t3>;\nusing vt3d = vector<t3d>;\nusing vt4 = vector<t4>;\nusing vvt3 = vector<vector<t3>>;\nusing vvt3d = vector<vector<t3d>>;\nusing vvt4 = vector<vector<t4>>;\nusing pq = priority_queue<Pr,vector<Pr>,greater<Pr>>;\nusing cl = complex<ll>;\nusing cd = complex<double>;\n#define rep(i, N) for (ll i=0; i<(ll)(N); ++i)\n#define repr(i, N) for (ll i = (ll)(N) - 1; i >= 0; --i)\n#define repk(i, k, N) for (ll i = k; i < (ll)(N); ++i)\n#define rep1(i, N) for (ll i=1; i<(ll)(N+1); ++i)\n#define rep1r(i, N) for (ll i=(ll)(N); i>0; i--)\n#define all(v) (v).begin(), (v).end()\n#define allr(v) (v).rbegin(), (v).rend()\n#define SIZE(v) (ll)((v).size())\n#define PYes {puts(\"Yes\"); exit(0);}\n#define PNo {puts(\"No\"); exit(0);}\n#define PFi {puts(\"First\"); exit(0);}\n#define PSe {puts(\"Second\"); exit(0);}\n#define Pm0 {puts(\"0\"); exit(0);}\n#define Pm1 {puts(\"-1\"); exit(0);}\n#define INT(...) int __VA_ARGS__; in(__VA_ARGS__)\n#define INTM(...) int __VA_ARGS__; inm(__VA_ARGS__)\n#define LONG(...) ll __VA_ARGS__; in(__VA_ARGS__)\n#define LONGM(...) ll __VA_ARGS__; inm(__VA_ARGS__)\n#define DOUBLE(...) double __VA_ARGS__; in(__VA_ARGS__)\n#define CHAR(...) char __VA_ARGS__; in(__VA_ARGS__)\n#define STRING(...) string __VA_ARGS__; in(__VA_ARGS__)\n#define VI(ivec, n) vi ivec(n); input_ivec(ivec, n)\n#define VIM(ivec, n) vi ivec(n); input_ivecm(ivec, n)\n#define VL(lvec, n) vl lvec(n); input_lvec(lvec, n)\n#define VLM(lvec, n) vl lvec(n); input_lvecm(lvec, n)\n#define VL2(lvec1, lvec2, n) vl lvec1(n), lvec2(n); input_lvec12(lvec1, lvec2, n)\n#define VL2M(lvec1, lvec2, n) vl lvec1(n), lvec2(n); input_lvec12m(lvec1, lvec2, n)\n#define VC(cvec, n) vc cvec(n); input_cvec(cvec, n)\n#define VS(svec, n) vs svec(n); input_svec(svec, n)\n#define VD(dvec, n) vd dvec(n); input_dvec(dvec, n)\n#define VP(pvec, n) vp pvec(n); input_pvec(pvec, n)\n#define VPD(pvec, n) vpd pvec(n); input_pvecd(pvec, n)\n#define VPM(pvec, n) vp pvec(n); input_pvecm(pvec, n)\n#define VVI(ivec2, h, w) vvi ivec2(h, vi(w)); input_ivec2(ivec2, h, w)\n#define VVL(lvec2, h, w) vvl lvec2(h, vl(w)); input_lvec2(lvec2, h, w)\n#define VVLM(lvec2, h, w) vvl lvec2(h, vl(w)); input_lvec2m(lvec2, h, w)\n#define VVC(cvec2, h, w) vvc cvec2(h, vc(w)); input_cvec2(cvec2, h, w)\n#define pcnt(x) (ll)__builtin_popcountll(x)\n#define parity(x) (ll)__builtin_parityll(x)\n#define uset unordered_set\n#define umap unordered_map\ninline void Out(double x) {printf(\"%.15f\",x);cout<<'\\n';}\ntemplate<typename T> inline void Out(pair<T,T> x) {cout<<x.first<<' '<<x.second<<'\\n';}\ntemplate<typename T> inline void Out(T x) {cout<<x<<'\\n';}\ninline void Out(vector<string> v) {rep(i,SIZE(v)) cout<<v[i]<<'\\n';}\ntemplate<typename T> inline void Out(queue<T> q){while(!q.empty()) {cout<<q.front()<<\" \"; q.pop();} cout<<endl;}\ntemplate<typename T> inline void Out(deque<T> q){while(!q.empty()) {cout<<q.front()<<\" \"; q.pop_front();} cout<<endl;}\ntemplate<typename T> inline void Out(vector<T> v) {rep(i,SIZE(v)) cout<<v[i]<<(i==SIZE(v)-1?'\\n':' ');}\ntemplate<typename T> inline void Out(vector<vector<T>> &vv){for(auto &v: vv) Out(v);}\ntemplate<typename T> inline void Out(vector<pair<T,T>> v) {for(auto p:v) Out(p);}\ntemplate<typename T> inline void Outend(T x) {Out(x); exit(0);}\ntemplate<typename T> inline void chmin(T &a, T b) { a = min(a, b); }\ntemplate<typename T> inline void chmax(T &a, T b) { a = max(a, b); }\ninline void mi(void) {return;}\ntemplate<typename T1, typename... T2> void mi(T1& f, T2&... r) {--f; mi(r...);}\ntemplate<class... T> void in(T&... x) {(cin >> ... >> x);}\ntemplate<class... T> void inm(T&... x) {(cin >> ... >> x); mi(x...);}\ninline void input_ivec(vi &ivec, int n) {rep(i, n) {cin>>ivec[i];}}\ninline void input_ivecm(vi &ivec, int n) {rep(i, n) {cin>>ivec[i];--ivec[i];}}\ninline void input_lvec(vl &lvec, ll n) {rep(i, n) {cin>>lvec[i];}}\ninline void input_lvecm(vl &lvec, ll n) {rep(i, n) {cin>>lvec[i];--lvec[i];}}\ninline void input_lvec12(vl &lvec1, vl &lvec2, ll n) {rep(i, n) {cin>>lvec1[i]>>lvec2[i];}}\ninline void input_lvec12m(vl &lvec1, vl &lvec2, ll n) {rep(i, n) {cin>>lvec1[i]>>lvec2[i];--lvec1[i];--lvec2[i];}}\ninline void input_cvec(vc &cvec, ll n) {rep (i, n) {cin>>cvec[i];}}\ninline void input_svec(vs &svec, ll n) {rep (i, n) {cin>>svec[i];}}\ninline void input_dvec(vd &dvec, ll n) {rep (i, n) {cin>>dvec[i];}}\ninline void input_pvec(vp &pvec, ll n) {rep (i, n) {cin>>pvec[i].first>>pvec[i].second;}}\ninline void input_pvecm(vp &pvec, ll n) {rep (i, n) {cin>>pvec[i].first>>pvec[i].second;pvec[i].first--,pvec[i].second--;}}\ninline void input_pvecd(vpd &pvec, ll n) {rep (i, n) {cin>>pvec[i].first>>pvec[i].second;}}\ninline void input_ivec2(vvi &ivec2, int h, int w) {rep(i, h) rep(j, w) {cin>>ivec2[i][j];}}\ninline void input_lvec2(vvl &lvec2, ll h, ll w) {rep(i, h) rep(j, w) {cin>>lvec2[i][j];}}\ninline void input_lvec2m(vvl &lvec2, ll h, ll w) {rep(i, h) rep(j, w) {cin>>lvec2[i][j];--lvec2[i][j];}}\ninline void input_cvec2(vvc &cvec2, ll h, ll w) {rep(i, h) rep(j, w) {cin>>cvec2[i][j];}}\ninline bool isin(ll i, ll j, ll h, ll w) {if(i<0||i>=h||j<0||j>=w) return false; else return true;}\ntemplate<typename T> inline T TmpPercent(T a, T b) {if(b<0){a=-a,b=-b;} return (a%b+b)%b;}\ntemplate<typename T> inline T Percent(T a, T b) {if(b<0) return -TmpPercent(a,b); return TmpPercent(a,b);}\ntemplate<typename T> inline T Div(T a, T b) {if(b<0){a=-a,b=-b;} return (a-TmpPercent(a,b))/b; }\ntemplate<typename T> inline T Divceil(T a, T b) {if(TmpPercent(a,b)==0) return Div(a,b); return Div(a,b)+1;}\ntemplate<typename T> void erase(multiset<T> &st, T x) {if(st.contains(x)) st.erase(st.find(x));}\ntemplate<typename T> T pop(vector<T> &x) {T ret=x.back(); x.pop_back(); return ret;}\n#ifdef __DEBUG\n#define de(var) {cerr << #var << \": \"; debug_view(var);}\n#define de2(var1,var2) {cerr<<#var1<<' '<<#var2<<\": \"; debug_view(var1,var2);}\n#define de3(var1,var2,var3) {cerr<<#var1<<' '<<#var2<<' '<<#var3<<\": \"; debug_view(var1,var2,var3);}\n#define de4(var1,var2,var3,var4) {cerr<<#var1<<' '<<#var2<<' '<<#var3<<' '<<#var4<<\": \"; debug_view(var1,var2,var3,var4);}\n#define de5(var1,var2,var3,var4,var5) {cerr<<#var1<<' '<<#var2<<' '<<#var3<<' '<<#var4<<' '<<#var5<<\": \"; debug_view(var1,var2,var3,var4,var5);}\ntemplate<typename T> inline void debug_view(T e){cerr << e << endl;}\ntemplate<typename T1, typename T2> inline void debug_view(T1 e1, T2 e2){cerr<<e1<<' '<<e2<<endl;}\ntemplate<typename T1, typename T2, typename T3> inline void debug_view(T1 e1, T2 e2, T3 e3){cerr<<e1<<' '<<e2<<' '<<e3<<endl;}\ntemplate<typename T1, typename T2, typename T3, typename T4> inline void debug_view(T1 e1, T2 e2, T3 e3, T4 e4){cerr<<e1<<' '<<e2<<' '<<e3<<' '<<e4<<endl;}\ntemplate<typename T1, typename T2, typename T3, typename T4, typename T5> inline void debug_view(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5){cerr<<e1<<' '<<e2<<' '<<e3<<' '<<e4<<' '<<e5<<endl;}\ntemplate<typename T1, typename T2> inline void debug_view(pair<T1,T2> &p){cerr<<\"{\"<<p.first<<\" \"<<p.second<<\"}\\n\";}\ntemplate<typename T1, typename T2> inline void debug_view(vector<pair<T1,T2>> &v){for(auto [a,b]: v){cerr<<\"{\"<<a<<\" \"<<b<<\"} \";} cerr << endl;}\ntemplate<typename T1, typename T2> inline void debug_view(set<pair<T1,T2>> &s){for(auto [a,b]: s){cerr<<\"{\"<<a<<\" \"<<b<<\"} \";} cerr << endl;}\ntemplate<typename T> inline void debug_view(tuple<T,T,T> t){cerr<<get<0>(t)<<' '<<get<1>(t)<<' '<<get<2>(t)<< endl;}\ntemplate<typename T> inline void debug_view(queue<T> q){while(!q.empty()) {cerr << q.front() << \" \"; q.pop();}cerr << endl;}\ntemplate<typename T> inline void debug_view(deque<T> q){while(!q.empty()) {cerr << q.front() << \" \"; q.pop_front();}cerr << endl;}\ntemplate<typename T> inline void debug_view(set<T> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(set<T,greater<T>> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(unordered_set<T> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(multiset<T> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(multiset<T,greater<T>> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(vector<pair<T,T>> &v){for(auto [a,b]: v){cerr<<\"{\"<<a<<\" \"<<b<<\"} \";} cerr << endl;}\ninline void debug_view(vector<string> &v){cerr << \"----\" << endl; for(auto s: v) debug_view(s);}\ntemplate<typename T> inline void debug_view(vector<T> &v){for(auto e: v){cerr << e << \" \";} cerr << endl;}\ntemplate<typename T> inline void debug_view(vector<vector<pair<T,T>>> &vv){cerr << \"----\" << endl;for(auto &v: vv){debug_view(v);} cerr << \"--------\" << endl;}\ntemplate<typename T> inline void debug_view(vector<vector<T>> &vv){cerr << \"----\" << endl;for(auto &v: vv){debug_view(v);} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2> inline void debug_view(map<T1,T2> &mp){cerr << \"----\" << endl;for(auto [k,v]: mp){cerr << k << ' ' << v << endl;} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2> inline void debug_view(unordered_map<T1,T2> &mp){cerr << \"----\" << endl;for(auto [k,v]: mp){cerr << k << ' ' << v << endl;} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2> inline void debug_view(map<T1,vector<T2>> &mp){cerr<<\"----\"<<endl;for(auto [k,v]: mp){cerr<<k<<\": \";debug_view(v);} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2,typename T3> inline void debug_view(map<pair<T1,T2>,T3> &mp){cerr << \"----\" << endl;for(auto [p,v]: mp){cerr<<'{'<<p.first<<' '<<p.second<<'}'<<\": \"<<v<<endl;} cerr<<\"--------\"<<endl;}\n#define deb(var) {cerr << #var << \": \"; debugb_view(var);}\ntemplate<typename T> inline void debugb_view(T e){bitset<20> b(e); cerr<<b<<endl;}\ntemplate<typename T> inline void debugb_view(vector<T> &v){cerr<<\"----\"<<endl;for(auto e: v){debugb_view(e);}}\n#else\n#define de(var) {}\n#define de2(var1,var2) {}\n#define de3(var1,var2,var3) {}\n#define de4(var1,var2,var3,var4) {}\n#define de5(var1,var2,var3,var4,var5) {}\n#define deb(var) {}\n#endif\nint IINF = 1001001001;\nll INF = 3e18;\nconst ll M998 = 998244353;\nconst ll M107 = 1000000007;\ntemplate<typename T> inline void ch1(T &x){if(x==INF)x=-1;}\nconst double PI = acos(-1);\nconst double EPS = 1e-8; //eg) if x=1e6, EPS >= 1e6/1e14(=1e-8)\nconst vi di = {0, 1, 0, -1};\nconst vi dj = {1, 0, -1, 0};\nconst vp dij = {{0,1},{1,0},{0,-1},{-1,0}};\nconst vp hex0 = {{-1,-1},{-1,0},{0,-1},{0,1},{1,-1},{1,0}}; // tobide\nconst vp hex1 = {{-1,0},{-1,1},{0,-1},{0,1},{1,0},{1,1}}; // hekomi\nconst vi di8 = {-1, -1, -1, 0, 0, 1, 1, 1};\nconst vi dj8 = {-1, 0, 1, -1, 1, -1, 0, 1};\nconst vp dij8 = {{0,1},{1,0},{0,-1},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};\nPr operator+ (Pr a, Pr b) {return {a.first+b.first, a.second+b.second};}\nPr operator- (Pr a, Pr b) {return {a.first-b.first, a.second-b.second};}\nPr operator* (Pr a, Pr b) {return {a.first*b.first, a.second*b.second};}\nPr operator/ (Pr a, Pr b) {return {a.first/b.first, a.second/b.second};}\n\nstruct Bridge {\n using PII = pair<int,int>;\n int n, m, idx;\n vector<vector<PII>> from;\n vector<int> ord, low, bridge, artcl;\n Bridge(int n): n(n), m(0), idx(0), from(n), ord(n,-1), low(n) {}\n void add_edge(int a, int b, int ei=-1) {\n if(ei==-1) {\n from[a].emplace_back(b, m); from[b].emplace_back(a, m);\n ++m;\n } else {\n from[a].emplace_back(b, ei); from[b].emplace_back(a, ei);\n }\n }\n void start_calc() { rep(i, n) if(ord[i]==-1) dfs(i); }\n void dfs(int v, int p=-1) {\n ord[v] = idx++; low[v] = ord[v];\n int c = 0;\n bool art = false;\n for(auto [nv,ei]: from[v]) if(nv!=p) {\n if(ord[nv]!=-1) {\n low[v] = min(low[v], ord[nv]); continue;\n }\n ++c;\n dfs(nv, v);\n low[v] = min(low[v], low[nv]);\n if(low[nv]>ord[v]) bridge.push_back(ei);\n if(low[nv]>=ord[v]) art = true;\n }\n if(p!=-1 && art) artcl.push_back(v);\n if(p==-1 && c>1) artcl.push_back(v);\n }\n vector<int> get_bridge() { return bridge;}\n vector<int> get_articulation() { return artcl;}\n};\n\nvoid solve() {\n LONG(N, M);\n vvp from(N);\n Bridge graph(N);\n vp edge;\n rep(i, M) {\n LONG(a, b);\n from[a].emplace_back(b, i);\n from[b].emplace_back(a, i);\n graph.add_edge(a,b);\n if(a>b) swap(a,b);\n edge.emplace_back(a,b);\n }\n graph.start_calc();\n auto eis = graph.get_bridge();\n vp ans;\n for(auto ei: eis) ans.emplace_back(edge[ei]);\n\n sort(all(ans));\n for(auto x: ans) Out(x);\n \n\n\n\n}\n\nint main () {\n // ios::sync_with_stdio(false);\n cin.tie(nullptr);\n solve();\n}\n\n// ### test.cpp ###", "accuracy": 1, "time_ms": 10, "memory_kb": 8948, "score_of_the_acc": -0.7584, "final_rank": 18 }, { "submission_id": "aoj_GRL_3_B_9964862", "code_snippet": "// ### test.cpp ###\n#include <bits/stdc++.h>\n#ifdef __DEBUG_VECTOR\nnamespace for_debugging{\n struct subscript_and_location{\n int sub;\n std::source_location loc;\n subscript_and_location(int sub_,std::source_location loc_=std::source_location::current()){\n sub=sub_;\n loc=loc_;\n }\n void check_out_of_range(size_t sz){\n if(sub<0||(int)sz<=sub){\n std::clog << loc.file_name() << \":(\" << loc.line() << \":\" << loc.column() << \"):\" << loc.function_name() << std::endl;\n std::clog << \"out of range: subscript = \" << sub << \", vector_size = \" << sz << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n };\n}\nnamespace std{\n template<class T,class Allocator=std::allocator<T>> class vector_for_debugging:public std::vector<T,Allocator>{\n using std::vector<T,Allocator>::vector;\n public:\n [[nodiscard]] constexpr std::vector<T,Allocator>::reference operator[](for_debugging::subscript_and_location n) noexcept(!std::is_same<T,bool>::value){\n n.check_out_of_range(this->size());\n return std::vector<T,Allocator>::operator[](n.sub);\n }\n [[nodiscard]] constexpr std::vector<T,Allocator>::const_reference operator[](for_debugging::subscript_and_location n) const noexcept(!std::is_same<T,bool>::value){\n n.check_out_of_range(this->size());\n return std::vector<T,Allocator>::operator[](n.sub);\n }\n };\n namespace pmr{\n template<class T> using vector_for_debugging=std::vector_for_debugging<T,std::pmr::polymorphic_allocator<T>>;\n }\n}\n#define vector vector_for_debugging\n#endif\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing sll = __int128_t;\nusing db = double;\nusing Pr = pair<ll, ll>;\nusing Pd = pair<double, double>;\nusing vi = vector<int>;\nusing vs = vector<string>;\nusing vc = vector<char>;\nusing vl = vector<ll>;\nusing vb = vector<bool>;\nusing vd = vector<double>;\nusing vp = vector<Pr>;\nusing vpd = vector<Pd>;\nusing vvi = vector<vector<int>>;\nusing vvc = vector<vector<char>>;\nusing vvl = vector<vector<ll>>;\nusing vvp = vector<vector<Pr>>;\nusing vvb = vector<vector<bool>>;\nusing vvd = vector<vector<double>>;\nusing vvs = vector<vector<string>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vvvl = vector<vector<vector<ll>>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing vvvd = vector<vector<vector<double>>>;\nusing t3 = tuple<ll,ll,ll>;\nusing t3d = tuple<db,db,db>;\nusing t4 = tuple<ll,ll,ll,ll>;\nusing vt3 = vector<t3>;\nusing vt3d = vector<t3d>;\nusing vt4 = vector<t4>;\nusing vvt3 = vector<vector<t3>>;\nusing vvt3d = vector<vector<t3d>>;\nusing vvt4 = vector<vector<t4>>;\nusing pq = priority_queue<Pr,vector<Pr>,greater<Pr>>;\nusing cl = complex<ll>;\nusing cd = complex<double>;\n#define rep(i, N) for (ll i=0; i<(ll)(N); ++i)\n#define repr(i, N) for (ll i = (ll)(N) - 1; i >= 0; --i)\n#define repk(i, k, N) for (ll i = k; i < (ll)(N); ++i)\n#define rep1(i, N) for (ll i=1; i<(ll)(N+1); ++i)\n#define rep1r(i, N) for (ll i=(ll)(N); i>0; i--)\n#define all(v) (v).begin(), (v).end()\n#define allr(v) (v).rbegin(), (v).rend()\n#define SIZE(v) (ll)((v).size())\n#define PYes {puts(\"Yes\"); exit(0);}\n#define PNo {puts(\"No\"); exit(0);}\n#define PFi {puts(\"First\"); exit(0);}\n#define PSe {puts(\"Second\"); exit(0);}\n#define Pm0 {puts(\"0\"); exit(0);}\n#define Pm1 {puts(\"-1\"); exit(0);}\n#define INT(...) int __VA_ARGS__; in(__VA_ARGS__)\n#define INTM(...) int __VA_ARGS__; inm(__VA_ARGS__)\n#define LONG(...) ll __VA_ARGS__; in(__VA_ARGS__)\n#define LONGM(...) ll __VA_ARGS__; inm(__VA_ARGS__)\n#define DOUBLE(...) double __VA_ARGS__; in(__VA_ARGS__)\n#define CHAR(...) char __VA_ARGS__; in(__VA_ARGS__)\n#define STRING(...) string __VA_ARGS__; in(__VA_ARGS__)\n#define VI(ivec, n) vi ivec(n); input_ivec(ivec, n)\n#define VIM(ivec, n) vi ivec(n); input_ivecm(ivec, n)\n#define VL(lvec, n) vl lvec(n); input_lvec(lvec, n)\n#define VLM(lvec, n) vl lvec(n); input_lvecm(lvec, n)\n#define VL2(lvec1, lvec2, n) vl lvec1(n), lvec2(n); input_lvec12(lvec1, lvec2, n)\n#define VL2M(lvec1, lvec2, n) vl lvec1(n), lvec2(n); input_lvec12m(lvec1, lvec2, n)\n#define VC(cvec, n) vc cvec(n); input_cvec(cvec, n)\n#define VS(svec, n) vs svec(n); input_svec(svec, n)\n#define VD(dvec, n) vd dvec(n); input_dvec(dvec, n)\n#define VP(pvec, n) vp pvec(n); input_pvec(pvec, n)\n#define VPD(pvec, n) vpd pvec(n); input_pvecd(pvec, n)\n#define VPM(pvec, n) vp pvec(n); input_pvecm(pvec, n)\n#define VVI(ivec2, h, w) vvi ivec2(h, vi(w)); input_ivec2(ivec2, h, w)\n#define VVL(lvec2, h, w) vvl lvec2(h, vl(w)); input_lvec2(lvec2, h, w)\n#define VVLM(lvec2, h, w) vvl lvec2(h, vl(w)); input_lvec2m(lvec2, h, w)\n#define VVC(cvec2, h, w) vvc cvec2(h, vc(w)); input_cvec2(cvec2, h, w)\n#define pcnt(x) (ll)__builtin_popcountll(x)\n#define parity(x) (ll)__builtin_parityll(x)\n#define uset unordered_set\n#define umap unordered_map\ninline void Out(double x) {printf(\"%.15f\",x);cout<<'\\n';}\ntemplate<typename T> inline void Out(pair<T,T> x) {cout<<x.first<<' '<<x.second<<'\\n';}\ntemplate<typename T> inline void Out(T x) {cout<<x<<'\\n';}\ninline void Out(vector<string> v) {rep(i,SIZE(v)) cout<<v[i]<<'\\n';}\ntemplate<typename T> inline void Out(queue<T> q){while(!q.empty()) {cout<<q.front()<<\" \"; q.pop();} cout<<endl;}\ntemplate<typename T> inline void Out(deque<T> q){while(!q.empty()) {cout<<q.front()<<\" \"; q.pop_front();} cout<<endl;}\ntemplate<typename T> inline void Out(vector<T> v) {rep(i,SIZE(v)) cout<<v[i]<<(i==SIZE(v)-1?'\\n':' ');}\ntemplate<typename T> inline void Out(vector<vector<T>> &vv){for(auto &v: vv) Out(v);}\ntemplate<typename T> inline void Out(vector<pair<T,T>> v) {for(auto p:v) Out(p);}\ntemplate<typename T> inline void Outend(T x) {Out(x); exit(0);}\ntemplate<typename T> inline void chmin(T &a, T b) { a = min(a, b); }\ntemplate<typename T> inline void chmax(T &a, T b) { a = max(a, b); }\ninline void mi(void) {return;}\ntemplate<typename T1, typename... T2> void mi(T1& f, T2&... r) {--f; mi(r...);}\ntemplate<class... T> void in(T&... x) {(cin >> ... >> x);}\ntemplate<class... T> void inm(T&... x) {(cin >> ... >> x); mi(x...);}\ninline void input_ivec(vi &ivec, int n) {rep(i, n) {cin>>ivec[i];}}\ninline void input_ivecm(vi &ivec, int n) {rep(i, n) {cin>>ivec[i];--ivec[i];}}\ninline void input_lvec(vl &lvec, ll n) {rep(i, n) {cin>>lvec[i];}}\ninline void input_lvecm(vl &lvec, ll n) {rep(i, n) {cin>>lvec[i];--lvec[i];}}\ninline void input_lvec12(vl &lvec1, vl &lvec2, ll n) {rep(i, n) {cin>>lvec1[i]>>lvec2[i];}}\ninline void input_lvec12m(vl &lvec1, vl &lvec2, ll n) {rep(i, n) {cin>>lvec1[i]>>lvec2[i];--lvec1[i];--lvec2[i];}}\ninline void input_cvec(vc &cvec, ll n) {rep (i, n) {cin>>cvec[i];}}\ninline void input_svec(vs &svec, ll n) {rep (i, n) {cin>>svec[i];}}\ninline void input_dvec(vd &dvec, ll n) {rep (i, n) {cin>>dvec[i];}}\ninline void input_pvec(vp &pvec, ll n) {rep (i, n) {cin>>pvec[i].first>>pvec[i].second;}}\ninline void input_pvecm(vp &pvec, ll n) {rep (i, n) {cin>>pvec[i].first>>pvec[i].second;pvec[i].first--,pvec[i].second--;}}\ninline void input_pvecd(vpd &pvec, ll n) {rep (i, n) {cin>>pvec[i].first>>pvec[i].second;}}\ninline void input_ivec2(vvi &ivec2, int h, int w) {rep(i, h) rep(j, w) {cin>>ivec2[i][j];}}\ninline void input_lvec2(vvl &lvec2, ll h, ll w) {rep(i, h) rep(j, w) {cin>>lvec2[i][j];}}\ninline void input_lvec2m(vvl &lvec2, ll h, ll w) {rep(i, h) rep(j, w) {cin>>lvec2[i][j];--lvec2[i][j];}}\ninline void input_cvec2(vvc &cvec2, ll h, ll w) {rep(i, h) rep(j, w) {cin>>cvec2[i][j];}}\ninline bool isin(ll i, ll j, ll h, ll w) {if(i<0||i>=h||j<0||j>=w) return false; else return true;}\ntemplate<typename T> inline T TmpPercent(T a, T b) {if(b<0){a=-a,b=-b;} return (a%b+b)%b;}\ntemplate<typename T> inline T Percent(T a, T b) {if(b<0) return -TmpPercent(a,b); return TmpPercent(a,b);}\ntemplate<typename T> inline T Div(T a, T b) {if(b<0){a=-a,b=-b;} return (a-TmpPercent(a,b))/b; }\ntemplate<typename T> inline T Divceil(T a, T b) {if(TmpPercent(a,b)==0) return Div(a,b); return Div(a,b)+1;}\ntemplate<typename T> void erase(multiset<T> &st, T x) {if(st.contains(x)) st.erase(st.find(x));}\ntemplate<typename T> T pop(vector<T> &x) {T ret=x.back(); x.pop_back(); return ret;}\n#ifdef __DEBUG\n#define de(var) {cerr << #var << \": \"; debug_view(var);}\n#define de2(var1,var2) {cerr<<#var1<<' '<<#var2<<\": \"; debug_view(var1,var2);}\n#define de3(var1,var2,var3) {cerr<<#var1<<' '<<#var2<<' '<<#var3<<\": \"; debug_view(var1,var2,var3);}\n#define de4(var1,var2,var3,var4) {cerr<<#var1<<' '<<#var2<<' '<<#var3<<' '<<#var4<<\": \"; debug_view(var1,var2,var3,var4);}\n#define de5(var1,var2,var3,var4,var5) {cerr<<#var1<<' '<<#var2<<' '<<#var3<<' '<<#var4<<' '<<#var5<<\": \"; debug_view(var1,var2,var3,var4,var5);}\ntemplate<typename T> inline void debug_view(T e){cerr << e << endl;}\ntemplate<typename T1, typename T2> inline void debug_view(T1 e1, T2 e2){cerr<<e1<<' '<<e2<<endl;}\ntemplate<typename T1, typename T2, typename T3> inline void debug_view(T1 e1, T2 e2, T3 e3){cerr<<e1<<' '<<e2<<' '<<e3<<endl;}\ntemplate<typename T1, typename T2, typename T3, typename T4> inline void debug_view(T1 e1, T2 e2, T3 e3, T4 e4){cerr<<e1<<' '<<e2<<' '<<e3<<' '<<e4<<endl;}\ntemplate<typename T1, typename T2, typename T3, typename T4, typename T5> inline void debug_view(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5){cerr<<e1<<' '<<e2<<' '<<e3<<' '<<e4<<' '<<e5<<endl;}\ntemplate<typename T1, typename T2> inline void debug_view(pair<T1,T2> &p){cerr<<\"{\"<<p.first<<\" \"<<p.second<<\"}\\n\";}\ntemplate<typename T1, typename T2> inline void debug_view(vector<pair<T1,T2>> &v){for(auto [a,b]: v){cerr<<\"{\"<<a<<\" \"<<b<<\"} \";} cerr << endl;}\ntemplate<typename T1, typename T2> inline void debug_view(set<pair<T1,T2>> &s){for(auto [a,b]: s){cerr<<\"{\"<<a<<\" \"<<b<<\"} \";} cerr << endl;}\ntemplate<typename T> inline void debug_view(tuple<T,T,T> t){cerr<<get<0>(t)<<' '<<get<1>(t)<<' '<<get<2>(t)<< endl;}\ntemplate<typename T> inline void debug_view(queue<T> q){while(!q.empty()) {cerr << q.front() << \" \"; q.pop();}cerr << endl;}\ntemplate<typename T> inline void debug_view(deque<T> q){while(!q.empty()) {cerr << q.front() << \" \"; q.pop_front();}cerr << endl;}\ntemplate<typename T> inline void debug_view(set<T> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(set<T,greater<T>> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(unordered_set<T> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(multiset<T> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(multiset<T,greater<T>> s){for(auto x:s){cerr << x << ' ';}cerr << endl;}\ntemplate<typename T> inline void debug_view(vector<pair<T,T>> &v){for(auto [a,b]: v){cerr<<\"{\"<<a<<\" \"<<b<<\"} \";} cerr << endl;}\ninline void debug_view(vector<string> &v){cerr << \"----\" << endl; for(auto s: v) debug_view(s);}\ntemplate<typename T> inline void debug_view(vector<T> &v){for(auto e: v){cerr << e << \" \";} cerr << endl;}\ntemplate<typename T> inline void debug_view(vector<vector<pair<T,T>>> &vv){cerr << \"----\" << endl;for(auto &v: vv){debug_view(v);} cerr << \"--------\" << endl;}\ntemplate<typename T> inline void debug_view(vector<vector<T>> &vv){cerr << \"----\" << endl;for(auto &v: vv){debug_view(v);} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2> inline void debug_view(map<T1,T2> &mp){cerr << \"----\" << endl;for(auto [k,v]: mp){cerr << k << ' ' << v << endl;} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2> inline void debug_view(unordered_map<T1,T2> &mp){cerr << \"----\" << endl;for(auto [k,v]: mp){cerr << k << ' ' << v << endl;} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2> inline void debug_view(map<T1,vector<T2>> &mp){cerr<<\"----\"<<endl;for(auto [k,v]: mp){cerr<<k<<\": \";debug_view(v);} cerr << \"--------\" << endl;}\ntemplate<typename T1,typename T2,typename T3> inline void debug_view(map<pair<T1,T2>,T3> &mp){cerr << \"----\" << endl;for(auto [p,v]: mp){cerr<<'{'<<p.first<<' '<<p.second<<'}'<<\": \"<<v<<endl;} cerr<<\"--------\"<<endl;}\n#define deb(var) {cerr << #var << \": \"; debugb_view(var);}\ntemplate<typename T> inline void debugb_view(T e){bitset<20> b(e); cerr<<b<<endl;}\ntemplate<typename T> inline void debugb_view(vector<T> &v){cerr<<\"----\"<<endl;for(auto e: v){debugb_view(e);}}\n#else\n#define de(var) {}\n#define de2(var1,var2) {}\n#define de3(var1,var2,var3) {}\n#define de4(var1,var2,var3,var4) {}\n#define de5(var1,var2,var3,var4,var5) {}\n#define deb(var) {}\n#endif\nint IINF = 1001001001;\nll INF = 3e18;\nconst ll M998 = 998244353;\nconst ll M107 = 1000000007;\ntemplate<typename T> inline void ch1(T &x){if(x==INF)x=-1;}\nconst double PI = acos(-1);\nconst double EPS = 1e-8; //eg) if x=1e6, EPS >= 1e6/1e14(=1e-8)\nconst vi di = {0, 1, 0, -1};\nconst vi dj = {1, 0, -1, 0};\nconst vp dij = {{0,1},{1,0},{0,-1},{-1,0}};\nconst vp hex0 = {{-1,-1},{-1,0},{0,-1},{0,1},{1,-1},{1,0}}; // tobide\nconst vp hex1 = {{-1,0},{-1,1},{0,-1},{0,1},{1,0},{1,1}}; // hekomi\nconst vi di8 = {-1, -1, -1, 0, 0, 1, 1, 1};\nconst vi dj8 = {-1, 0, 1, -1, 1, -1, 0, 1};\nconst vp dij8 = {{0,1},{1,0},{0,-1},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};\nPr operator+ (Pr a, Pr b) {return {a.first+b.first, a.second+b.second};}\nPr operator- (Pr a, Pr b) {return {a.first-b.first, a.second-b.second};}\nPr operator* (Pr a, Pr b) {return {a.first*b.first, a.second*b.second};}\nPr operator/ (Pr a, Pr b) {return {a.first/b.first, a.second/b.second};}\n\nstruct Bridge {\n using PII = pair<int,int>;\n int n, m, idx;\n vector<vector<PII>> from;\n vector<int> ord, low, bridge, artcl;\n Bridge(int n): n(n), m(0), idx(0), from(n), ord(n,-1), low(n) {}\n void add_edge(int a, int b) {\n from[a].emplace_back(b, m); from[b].emplace_back(a, m);\n ++m;\n }\n void start_calc() { rep(i, n) if(ord[i]==-1) dfs(i); }\n void dfs(int v, int p=-1) {\n ord[v] = idx++; low[v] = ord[v];\n int c = 0;\n bool art = false;\n for(auto [nv,ei]: from[v]) if(nv!=p) {\n if(ord[nv]!=-1) {\n low[v] = min(low[v], ord[nv]); continue;\n }\n ++c;\n dfs(nv, v);\n low[v] = min(low[v], low[nv]);\n if(low[nv]>ord[v]) bridge.push_back(ei);\n if(low[nv]>=ord[v]) art = true;\n }\n if(p!=-1 && art) artcl.push_back(v);\n if(p==-1 && c>1) artcl.push_back(v);\n }\n vector<int> get_bridge() { return bridge;}\n vector<int> get_articulation() { return artcl;}\n};\n\nvoid solve() {\n LONG(N, M);\n vvp from(N);\n Bridge graph(N);\n vp edge;\n rep(i, M) {\n LONG(a, b);\n from[a].emplace_back(b, i);\n from[b].emplace_back(a, i);\n graph.add_edge(a,b);\n if(a>b) swap(a,b);\n edge.emplace_back(a,b);\n }\n graph.start_calc();\n auto eis = graph.get_bridge();\n vp ans;\n for(auto ei: eis) ans.emplace_back(edge[ei]);\n\n sort(all(ans));\n for(auto x: ans) Out(x);\n \n\n\n\n}\n\nint main () {\n // ios::sync_with_stdio(false);\n cin.tie(nullptr);\n solve();\n}\n\n// ### test.cpp ###", "accuracy": 1, "time_ms": 10, "memory_kb": 8824, "score_of_the_acc": -0.7367, "final_rank": 17 } ]
aoj_GRL_3_C_cpp
Strongly Connected Components A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable. Input A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v . |V| |E| s 0 t 0 s 1 t 1 : s |E|-1 t |E|-1 Q u 0 v 0 u 1 v 1 : u Q-1 v Q-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V| -1 respectively. s i and t i represent source and target nodes of i -th edge (directed). u i and v i represent a pair of nodes given as the i -th query. Output For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise. Constraints 1 ≤ |V| ≤ 10,000 0 ≤ |E| ≤ 30,000 1 ≤ Q ≤ 100,000 Sample Input 1 5 6 0 1 1 0 1 2 2 4 4 3 3 2 4 0 1 0 3 2 3 3 4 Sample Output 1 1 0 1 1
[ { "submission_id": "aoj_GRL_3_C_11053568", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n// #include \"all.h\"\n\n#define int long long\n#define uint unsigned int\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define is2pow(n) (n && (!(n & (n - 1))))\n#define OPTIMIZE \\\n ios_base::sync_with_stdio(false); \\\n cin.tie(nullptr); \\\n cout.tie(nullptr);\n\nusing ld = long double;\nconstexpr int maxn = 2e5;\nconstexpr int maxk = 305;\nconstexpr long long inf = 1e18;\nconstexpr ld eps = 1e-8L;\nconstexpr long long mod = 998244353;\n\nvector<vector<int>> graph;\nvector<vector<int>> reversed;\nvector<int> comp;\n\nvoid solve() {\n int n,m; cin >> n >> m;\n graph.assign(n, vector<int>());\n reversed.assign(n, vector<int>());\n comp.assign(n,0);\n for (int i = 0; i < m; i++) {\n int u,v; cin >> u >> v;\n graph[u].push_back(v);\n reversed[v].push_back(u);\n }\n\n vector<int> visited(n,0);\n vector<int> order;\n\n auto topsort = [&](auto&& self, int u) -> void {\n visited[u] = 1;\n for (int v : graph[u])\n if (!visited[v])\n self(self,v);\n order.push_back(u);\n };\n for (int i = 0; i < n; i++) {\n if (!visited[i])\n topsort(topsort,i);\n }\n reverse(all(order));\n visited.assign(n,0);\n\n int color = 1;\n\n for (auto v : order) {\n if (visited[v]) continue;\n\n auto dfs = [&](auto&& self, int u) -> void {\n visited[u] = 1;\n comp[u] = color;\n for (auto to : reversed[u])\n if (!visited[to])\n self(self,to);\n };\n\n dfs(dfs,v);\n color++;\n }\n\n\n\n\n\n\n\n int q; cin >> q;\n while (q--) {\n int u,v; cin >> u >> v;\n cout << (comp[u] == comp[v]) << \"\\n\";\n }\n\n}\n\n#define TES\n#define LOCA\n#define FIL\n\nint32_t main() {\n OPTIMIZE;\n\n#ifdef FILE\n freopen(\"coins.in\", \"r\", stdin);\n freopen(\"coins.out\", \"w\", stdout);\n#endif\n#ifdef LOCAL\n freopen(\"/home/sq/CLionProjects/graph/input.txt\", \"r\", stdin);\n#endif\n int tt = 1;\n#ifdef TEST\n cin >> tt;\n#endif\n while (tt--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5464, "score_of_the_acc": -0.1745, "final_rank": 3 }, { "submission_id": "aoj_GRL_3_C_11013956", "code_snippet": "#include<iostream>\n#include<vector>\n\nusing namespace std;\nusing Graph = vector<vector<int>>;\n\nint n;\nGraph g;\n\nvoid Graph_rev(){\n\tGraph tmp(n);\n\tfor(int i = 0; i < n; i++){\n\t\tfor(auto j : g[i]) tmp[j].push_back(i);\n\t}\n\tg = tmp;\n}\n\nvector<int> group, ended;\nvector<bool> view;\n\nvoid dfs1(int f){\n\tview[f] = true;\n\tfor(auto i : g[f]){\n\t\tif(!view[i]) dfs1(i);\n\t}\n\tended.push_back(f);\n}\n\nvoid dfs2(int f, int num){\n\tgroup[f] = num;\n\tfor(auto i : g[f]){\n\t\tif(group[i] == -1) dfs2(i, num);\n\t}\n}\n\nvoid scc(){\n\tview.assign(n, false);\n\tended.clear();\n\tfor(int i = 0; i < n; i++){\n\t\tif(!view[i]) dfs1(i);\n\t}\n\tGraph_rev();\n\tgroup.assign(n, -1);\n\tfor(int i = n - 1, gn = 0; i >= 0; i--){\n\t\tif(group[ended[i]] == -1) dfs2(ended[i], gn++);\n\t}\n}\n\nint main(){\n\tint E;\n\tcin >> n >> E;\n\tg = Graph(n);\n\tint s, t;\n\twhile(E--){\n\t\tcin >> s >> t;\n\t\tg[s].push_back(t);\n\t}\n\tscc();\n\tint Q;\n\tcin >> Q;\n\twhile(Q--){\n\t\tcin >> s >> t;\n\t\tif(group[s] == group[t]) cout << 1 << endl;\n\t\telse cout << 0 << endl;\n\t}\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 5120, "score_of_the_acc": -0.6637, "final_rank": 4 }, { "submission_id": "aoj_GRL_3_C_10996207", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Scc{\n vector<vector<int>> G,H;\n vector<int> T,ord,seq,vis;\n int N,timer,sz;\n Scc(int n):N(n),G(n),H(n),vis(n),T(n,-1),timer(0),ord(n,-1),sz(1),seq(n){\n for(int i=0;i<N;i++) seq[i]=i;\n }\n void add(int u,int v){\n G[u].push_back(v);\n H[v].push_back(u);\n }\n vector<vector<int>> scc(){\n timer = 0;\n for(int i=0;i<N;i++) if(T[i]==-1) dfs1(i,-1);\n\n sort(seq.begin(),seq.end(),[&](auto a,auto b){\n return T[a]>T[b];\n });\n\n\n vector<vector<int>> ret;\n\n for(int i=0;i<N;i++) if(ord[seq[i]]==-1){\n vector<int> tmp;\n dfs2(tmp,seq[i],-1);\n ret.push_back(tmp);\n sz++;\n }\n\n return ret;\n }\nprivate:\n void dfs1(int v,int par){\n vis[v]=1;\n for(auto nv : G[v]) if(nv!=par&&!vis[nv]) {\n dfs1(nv,v);\n }\n T[v] = timer++;\n }\n void dfs2(vector<int> &ret,int v,int par){\n ord[v] = sz;\n for(auto nv : H[v]) if(nv!=par&&ord[nv]==-1){\n dfs2(ret,nv,v);\n }\n ret.push_back(v);\n }\n};\n\n\nint main(){\n ios::sync_with_stdio(false);cin.tie(nullptr);\n int N,M;\n cin>>N>>M;\n Scc scc(N);\n for(int i=0;i<M;i++){\n int a,b;\n cin>>a>>b;\n scc.add(a,b);\n }\n auto vvec = scc.scc();\n int Q;\n cin>>Q;\n while(Q--){\n int u,v;\n cin>>u>>v;\n cout << int(scc.ord[u]==scc.ord[v]) << endl;\n }\n\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5148, "score_of_the_acc": -0.7802, "final_rank": 6 }, { "submission_id": "aoj_GRL_3_C_10947679", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(n);i++)\n#define all(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\nusing ll=long long;\nusing pi=pair<int,int>;\nconst int di[]={+1,-1,+0,+0};\nconst int dj[]={+0,+0,+1,-1};\nconst int INF=1e9;\n//const ll INF=1e18;\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n, m;\n cin >> n >> m;\n vector<vector<int>> G(n), rG(n);\n rep(i, m) {\n int s, t;\n cin >> s >> t;\n G[s].push_back(t);\n rG[t].push_back(s);\n }\n vector<bool> seen(n, false);\n vector<int> order;\n auto dfs=[&](auto dfs, int v) -> void {\n seen[v]=true;\n for(int nv:G[v]) if(!seen[nv]) {\n dfs(dfs, nv);\n }\n order.push_back(v);\n };\n rep(i, n) if(!seen[i]) {\n dfs(dfs, i);\n }\n vector<int> comp(n, -1);\n auto rdfs=[&](auto rdfs, int v, int id) -> void {\n comp[v]=id;\n for(int nv:rG[v]) if(comp[nv]==-1) {\n rdfs(rdfs, nv, id);\n }\n };\n int cnt=0;\n reverse(all(order));\n for(int v:order) if(comp[v]==-1) {\n rdfs(rdfs, v, cnt);\n cnt++;\n }\n int q; cin >> q;\n vector<int> ans;\n while(q--) {\n int u, v; cin >> u >> v;\n ans.push_back(comp[u]==comp[v] ? 1:0);\n }\n for(int x:ans) cout << x << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 5632, "score_of_the_acc": -0.8736, "final_rank": 7 }, { "submission_id": "aoj_GRL_3_C_10907209", "code_snippet": "#include <iostream>\n#include <vector>\n#include <stack>\n\nconst int MAXN = 10000 + 1;\n\nstd::vector<int> G[MAXN];\nstd::vector<int> RG[MAXN];\nstd::stack<int> reverse_post;\nbool visited[MAXN];\nint scc[MAXN];\nint count = 0;\nbool record_scc = false;\n\nvoid dfs(std::vector<int> g[], int v)\n{\n visited[v] = true;\n if (record_scc) scc[v] = count;\n for (int i = 0; i < g[v].size(); ++i) {\n if (!visited[g[v][i]]) {\n dfs(g, g[v][i]);\n }\n }\n reverse_post.push(v);\n}\n\nint main()\n{\n int v, e;\n std::cin >> v >> e;\n for (int i = 0; i < e; ++i) {\n int s, t;\n std::cin >> s >> t;\n G[s].push_back(t);\n RG[t].push_back(s);\n }\n for (int i = 0; i < v; ++i) {\n if (!visited[i]) {\n dfs(RG, i);\n }\n }\n for (int i = 0; i < v; ++i) {\n visited[i] = false;\n }\n record_scc = true;\n while (!reverse_post.empty()) {\n int v = reverse_post.top();\n reverse_post.pop();\n if (!visited[v]) {\n dfs(G, v);\n count++;\n }\n }\n\n int q;\n std::cin >> q;\n while (q--) {\n int u, v;\n std::cin >> u >> v;\n if (scc[u] == scc[v]) std::cout << 1;\n else std::cout << 0;\n std::cout << std::endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5020, "score_of_the_acc": -0.9777, "final_rank": 11 }, { "submission_id": "aoj_GRL_3_C_10853234", "code_snippet": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n#define MAX 10010\nvector<int> edge[MAX], group[MAX];\nbool instk[MAX];\nint stk[MAX], groupID[MAX], nGroup, dfn[MAX], low[MAX], top, nowDfn;\nvoid tarjan(int start)\n{\n dfn[start] = low[start] = ++nowDfn;\n instk[start] = 1;\n stk[top++] = start;\n for(int i = 0; i < edge[start].size(); ++i){\n int next = edge[start][i];\n if(!dfn[next]){\n tarjan(next);\n if(low[start] > low[next])\n low[start] = low[next];\n }\n if(instk[next])\n if(low[start] > dfn[next])\n low[start] = dfn[next];\n }\n if(dfn[start] == low[start]){\n do {\n --top;\n instk[stk[top]] = 0;\n groupID[stk[top]] = nGroup;\n group[nGroup].push_back(stk[top]);\n } while(stk[top] != start);\n ++nGroup;\n }\n}\nvoid init(int n){\n for(int i = 0; i < n; ++i){\n instk[i] = dfn[i] = 0, edge[i].clear(), group[i].clear();\n }\n nowDfn = nGroup = top = 0;\n}\n\nint main()\n{\n int V, E;\n cin >> V >> E;\n init(V);\n int s, t;\n for(int i = 0; i < E; ++i){\n cin >> s >> t;\n edge[s].push_back(t);\n }\n for(int i = 0; i < V; ++i){\n if(dfn[i] == 0) tarjan(i);\n }\n int q;\n cin >> q;\n int u, v;\n for(int i = 0; i < q; ++i){\n cin >> u >> v;\n cout << (groupID[u] == groupID[v]) << '\\n';\n }\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 4924, "score_of_the_acc": -0.9592, "final_rank": 10 }, { "submission_id": "aoj_GRL_3_C_10849877", "code_snippet": "#pragma once\n#include <bits/stdc++.h>\nusing namespace std;\n\n\nstruct Edge {\n int from;\n int to;\n int weight;\n int capacity{};\n int flow{};\n int index{};\n Edge(int from, int to, int weight) : from(from), to(to), weight(weight) {}\n bool operator>(const Edge& other) const {\n return weight > other.weight;\n }\n};\n\nstruct SCC {\n // Finds strongly connected components in a directed graph using Kosaraju's algorithm\n // Time: O(n + m)\n // Space: O(n + m)\n // Strongly Connected Components https://judge.yosupo.jp/submission/311149\n vector<vector<Edge>> graph;\n vector<vector<Edge>> reversedGraph;\n vector<int> comp; // comp[v] - component index for vertex v\n vector<vector<int>> components;\n int vertexCount{};\n\n explicit SCC(int vertexCount) : vertexCount(vertexCount) {\n graph.resize(vertexCount);\n reversedGraph.resize(vertexCount);\n comp.resize(vertexCount);\n components.reserve(vertexCount);\n }\n\n void addEdge(int from, int to, int weight = 1) {\n graph[from].emplace_back(from, to, weight);\n reversedGraph[to].emplace_back(to, from, weight);\n }\n\n vector<vector<int>> buildComponents() {\n vector<int> order(vertexCount);\n vector<int> visited(vertexCount, false);\n auto topologicalSort = [&](auto&& topSort, int start = 0) -> void {\n visited[start] = true;\n for (Edge edge : graph[start])\n if (!visited[edge.to])\n topSort(topSort, edge.to);\n order.push_back(start);\n };\n for (int i = 0; i < vertexCount; i++)\n if (!visited[i])\n topologicalSort(topologicalSort, i);\n\n visited.assign(vertexCount, false);\n comp.assign(vertexCount, -1);\n int compId = 0;\n for (int i = order.size() - 1; i >= 0; i--) {\n if (!visited[order[i]]) {\n // Traverse the vertices in reverse topological order, through edges that point into the current vertex\n // One way to do that is using reversed graph\n auto dfsRev = [&](auto&& dfs, int start) -> void {\n visited[start] = true;\n comp[start] = compId;\n components.back().push_back(start);\n for (Edge edge : reversedGraph[start])\n if (!visited[edge.to])\n dfs(dfs, edge.to);\n };\n components.emplace_back();\n dfsRev(dfsRev, order[i]);\n compId++;\n }\n }\n return components;\n }\n\n vector<vector<Edge>> condense() {\n int componentCount = components.size();\n vector<vector<Edge>> condensedGraph(componentCount);\n vector<unordered_set<int>> usedEdges(componentCount);\n for (int from = 0; from < vertexCount; from++) {\n for (Edge edge : graph[from]) {\n int to = edge.to;\n if (comp[from] != comp[to] && !usedEdges[comp[from]].count(comp[to])) {\n Edge condensedEdge(comp[from], comp[to], edge.weight);\n condensedGraph[comp[from]].push_back(condensedEdge);\n usedEdges[comp[from]].insert(comp[to]);\n }\n }\n }\n return condensedGraph;\n }\n};\n\nint main() {\n // SCC\n int n, m;\n cin >> n >> m;\n\n SCC scc(n);\n for (int i = 0; i < m; ++i) {\n int u, v;\n cin >> u >> v;\n scc.addEdge(u, v);\n }\n\n auto components = scc.buildComponents();\n int q; cin >> q;\n while (q--) {\n int u, v;\n cin >> u >> v;\n cout << (scc.comp[u] == scc.comp[v]) << endl;\n }\n\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5760, "score_of_the_acc": -1.1205, "final_rank": 18 }, { "submission_id": "aoj_GRL_3_C_10801356", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing int128 = __int128;\nusing State = string::const_iterator;\nclass ParseError {};\n#define rep(i, n) for(ll i = 0; i < (n); i++)\n#define reps(i, l, r) for(ll i = (l); i < (r); i++)\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define endl \"\\n\";\nconst ll INF = LLONG_MAX / 4;\nconst ld inf = numeric_limits<long double>::max() / (ld)4;\nconst ll mod1 = 1000000007;\nconst ll mod2 = 998244353;\nconst ld pi = 3.1415926535897;\nll dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nll dy[8] = {0, -1, -1, -1, 0, 1, 1, 1};\ntemplate <typename T>\nbool chmax(T &a, const T& b) {\n\tif (a < b) { a = b; return true; }\n\treturn false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T &b) {\n\tif (a > b) { a = b; return true; }\n\treturn false;\n}\nstruct Edge {\n\tll from, to, cost;\n\tEdge (ll from, ll to, ll cost = 1ll) : from(from), to(to), cost(cost) {}\n};\nstruct Graph {\n\tvector<vector<Edge>> G;\n\tGraph() = default;\n\texplicit Graph(ll N) : G(N) {}\n\tsize_t size() const {\n\t\treturn G.size();\n\t}\n\tvoid add(ll from, ll to, ll cost = 1ll, bool direct = 0) {\n\t\tG[from].emplace_back(from, to, cost);\n\t\tif (!direct) G[to].emplace_back(to, from, cost);\n\t}\n\tvector<Edge> &operator[](const int &k) {\n\t\treturn G[k];\n\t}\n};\nusing Edges = vector<Edge>;\nstruct SCC {\n\tGraph &g;\n\tGraph gg, rg;\n\tvector<ll> cmp, ord, use;\n\n\tSCC(Graph &g): g(g), gg(g.size()), rg(g.size()), cmp(g.size(), -1), use(g.size()) {\n\t\trep(i, g.size()) {\n\t\t\tfor (auto e : g[i]) {\n\t\t\t\tgg.add(i, e.to, 1, 1);\n\t\t\t\trg.add(e.to, i, 1, 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tll operator[](ll k) { return cmp[k]; }\n\n\tvoid dfs(ll p) {\n\t\tif (use[p]) return;\n\t\tuse[p] = 1;\n\t\tfor (auto e : gg[p]) dfs(e.to);\n\t\tord.push_back(p);\n\t}\n\n\tvoid rdfs(ll p, ll cnt) {\n\t\tif (cmp[p] != -1) return;\n\t\tcmp[p] = cnt;\n\t\tfor (auto e : rg[p]) rdfs(e.to, cnt);\n\t}\n\n\tvoid build(Graph &t) {\n\t\trep(i, gg.size()) {\n\t\t\tdfs(i);\n\t\t}\n\t\treverse(all(ord));\n\t\tll ptr = 0;\n\t\tfor (ll i : ord) {\n\t\t\tif (cmp[i] == -1) rdfs(i, ptr), ptr++;\n\t\t}\n\n\t\tt = Graph(ptr);\n\t\trep(i, g.size()) {\n\t\t\tfor (auto &e : g[i]) {\n\t\t\t\tll x = cmp[i], y = cmp[e.to];\n\t\t\t\tif (x == y) continue;\n\t\t\t\tt.add(x, y, 1, 1);\n\t\t\t}\n\t\t}\n\t}\n};\nvoid solve() {\n\tll V, E; cin >> V >> E;\n\tGraph G(V);\n\trep(i, E) {\n\t\tll s, t; cin >> s >> t;\n\t\tG.add(s, t, 1, 1);\n\t}\n\tSCC scc(G);\n\tGraph T;\n\tscc.build(T);\n\tll Q; cin >> Q;\n\twhile (Q--) {\n\t\tll x, y; cin >> x >> y;\n\t\tcout << (scc[x] == scc[y]) << endl;\n\t}\n}\nint main() {\n\tll T = 1;\n\t// cin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 6428, "score_of_the_acc": -1.2495, "final_rank": 19 }, { "submission_id": "aoj_GRL_3_C_10801259", "code_snippet": "// nur_008\n// بِسْمِ اللَّهِ الرَّحْمَـٰنِ الرَّحِيمِ\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long int;\n\nvoid champ()\n{\n int V, E;\n cin >> V >> E;\n vector<vector<int>> g(V), rg(V);\n for (int i = 0; i < E; i++) {\n int s, t;\n cin >> s >> t;\n g[s].push_back(t);\n rg[t].push_back(s);\n }\n\n vector<int> order, comp(V, -1);\n vector<bool> vis(V, false);\n\n function<void(int)> dfs1 = [&](int u) {\n vis[u] = true;\n for (int v : g[u]) if (!vis[v]) dfs1(v);\n order.push_back(u);\n };\n\n function<void(int,int)> dfs2 = [&](int u, int cid) {\n comp[u] = cid;\n for (int v : rg[u]) if (comp[v] == -1) dfs2(v, cid);\n };\n\n for (int i = 0; i < V; i++) if (!vis[i]) dfs1(i);\n reverse(order.begin(), order.end());\n\n int cid = 0;\n for (int u : order) if (comp[u] == -1) dfs2(u, cid++);\n\n int Q;\n cin >> Q;\n while (Q--) {\n int u, v;\n cin >> u >> v;\n cout << (comp[u] == comp[v] ? 1 : 0) << \"\\n\";\n }\n}\n\nint main()\n{\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n int t = 1;\n // cin >> t;\n while (t--) champ();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4880, "score_of_the_acc": -0.0618, "final_rank": 1 }, { "submission_id": "aoj_GRL_3_C_10751738", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\nconst int INF = (1 << 30);\n\nvector<int> group, order;\nvector<vector<int>> g, gt;\nvector<bool> visited;\nint v, e, t;\n\n\nvoid dfs1(int u) {\n assert(u >= 0);\n visited[u] = true;\n for(auto && _v: g[u]) {\n if (!visited[_v]) {\n dfs1(_v);\n }\n }\n order.push_back(u);\n}\n\nvoid dfs2(int u) {\n assert(u >= 0);\n group[u] = t;\n for(auto && _v: gt[u]) {\n if (group[_v] == -1) dfs2(_v);\n }\n}\n\nsigned main() {\n cin >> v >> e;\n g.assign(v, vector<int> ());\n gt.assign(v, vector<int> ());\n group.assign(v, -1);\n visited.assign(v, false);\n\n for (int i = 0; i < e; i++)\n {\n int _s, _t;\n cin >> _s >> _t;\n g[_s].push_back(_t);\n gt[_t].push_back(_s);\n\n }\n for (int i = 0; i < v; i++)\n {\n if (!visited[i]) dfs1(i);\n }\n \n for (int i = v-1; i>=0; i--) {\n int _v = order[i];\n if (group[_v] == -1) {\n dfs2(_v);\n t++;\n }\n }\n int q;\n cin >> q;\n for (int i = 0; i < q; i++)\n {\n int _u, _v;\n cin >> _u >> _v;\n if (group[_u] == group[_v]) cout << 1 << endl;\n else cout << 0 << endl;\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5008, "score_of_the_acc": -1.0865, "final_rank": 17 }, { "submission_id": "aoj_GRL_3_C_10737520", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long int\n#define X first\n#define Y second\n\nstruct SCC\n{\n int n, cnt, dfs_num;\n vector<vector<int>> adj, dagList;\n vector<int> inStack, lowLink, dfn, comp;\n stack<int> st;\n vector<vector<int>> scc;\n vector<int> artipoints;\n\n vector<pair<int, int>> ciriticalEdges;\n\n stack<pair<int, int>> bi_comps;\n\n bool root = false;\n\n SCC(int n)\n : n(n), cnt(0), adj(n), inStack(n), lowLink(n), dfn(n, -1), comp(n, -1), dfs_num(0)\n {\n artipoints.assign(n, 0);\n }\n\n void add_edge(int u, int v)\n {\n adj[u].push_back(v);\n }\n\n void dfs(int node)\n {\n inStack[node] = 1;\n for (auto &child : dagList[node])\n {\n if (!inStack[child])\n {\n dfs(child);\n }\n }\n }\n\n void tarjan(int node, int parent = -1)\n {\n lowLink[node] = dfn[node] = dfs_num++, inStack[node] = 1;\n st.push(node);\n int to_parent = 0;\n for (auto &child : adj[node])\n {\n if (child == parent and to_parent == 0)\n {\n to_parent = 1;\n continue;\n }\n if (dfn[child] == -1)\n {\n tarjan(child);\n lowLink[node] = min(lowLink[node], lowLink[child]);\n if ((lowLink[child] >= dfn[node]) and (dfn[node] or root))\n {\n artipoints[node] = 1;\n }\n if (dfn[node] == 0 and root == false)\n {\n root = true;\n }\n }\n else if (inStack[child])\n {\n lowLink[node] = min(lowLink[node], dfn[child]);\n }\n }\n if (lowLink[node] == dfn[node])\n {\n if (parent != -1)\n {\n ciriticalEdges.push_back({parent, node});\n }\n scc.push_back({});\n while (true)\n {\n int v = st.top();\n st.pop();\n inStack[v] = 0;\n scc.back().push_back(v);\n comp[v] = cnt;\n if (v == node)\n break;\n }\n cnt++;\n }\n }\n\n void get_dag_list()\n {\n dagList.resize(cnt);\n for (int i = 0; i < n; i++)\n {\n for (auto &child : adj[i])\n {\n if (comp[i] != comp[child])\n {\n dagList[comp[i]].push_back(comp[child]);\n }\n }\n }\n }\n\n void run()\n {\n for (int i = 0; i < n; i++)\n {\n if (dfn[i] == -1)\n {\n tarjan(i);\n }\n }\n }\n};\n\n/*\n@Problems:\nhttps://www.spoj.com/problems/EC_P/\nhttps://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/3/GRL_3_B\n*/\n\nvoid solve()\n{\n int n, m;\n cin >> n >> m;\n SCC scc(n);\n for (int i = 0; i < m; i++)\n {\n int u, v;\n cin >> u >> v;\n scc.add_edge(u, v);\n }\n scc.run();\n int q;\n cin >> q;\n while (q--)\n {\n int u, v;\n cin >> u >> v;\n cout << (scc.comp[u] == scc.comp[v]) << '\\n';\n }\n}\n\nint main()\n{\n ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);\n#ifdef LOCAL_IO\n freopen(\"input.txt\", \"r\", stdin), freopen(\"output.txt\", \"w\", stdout);\n#endif\n int tc = 1;\n // cin >> tc;\n for (int i = 1; i <= tc; ++i)\n {\n solve();\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5172, "score_of_the_acc": -0.1181, "final_rank": 2 }, { "submission_id": "aoj_GRL_3_C_10731389", "code_snippet": "#include <bits/stdc++.h>\n#include <vector>\n#define REP(i,n) for(int i=0;i<(n);i++)\n#define FOR(i,r,n) for(int i=(r);i<(n);i++)\n#define ALL(obj) begin(obj),end(obj)\ntemplate<typename T> bool chmin(T &a,T b){\n if (a>b) {\n a=b;\n return true;\n }\n else return false;\n}\nusing namespace std;\ntypedef long long ll;\ntypedef vector<vector<int>> vvi; \nstruct StronglyConnectedComponent{\n int N;\n vvi G,rG;\n vector<int> ord,vis,comp;\n\n void dfs(int v){\n vis[v]=1;\n for(auto u:G[v]) if (!vis[u]) dfs(u);\n ord.push_back(v);\n }\n void rdfs(int v,int k){\n comp[v]=k;\n for(auto u:rG[v]) if (comp[u]==-1) rdfs(u,k);\n }\n StronglyConnectedComponent(vvi &_G){\n G=_G;\n int N=G.size();\n rG.resize(N); \n comp.assign(N,-1);\n vis.assign(N,0);\n REP(i,N) {\n for(auto u:G[i]) rG[u].push_back(i);\n }\n REP(i,N) if (!vis[i]){\n dfs(i);\n }\n int k=0;\n reverse(ALL(ord));\n for(auto v:ord) if (comp[v]==-1) {\n rdfs(v,k);\n k++;\n }\n }\n bool same(int u,int v){\n if (comp[u]==comp[v]) return 1;\n else return 0;\n }\n};\nint main(){\n int N,M,Q;\n cin >> N >> M;\n vvi G(N);\n REP(i,M) {\n int a,b;\n cin >> a >> b;\n G[a].push_back(b);\n }\n StronglyConnectedComponent SCC(G);\n cin >> Q;\n REP(_,Q){\n int a,b;\n cin >> a >> b;\n cout <<SCC.same(a,b)<<endl;\n }\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5512, "score_of_the_acc": -1.0727, "final_rank": 16 }, { "submission_id": "aoj_GRL_3_C_10730422", "code_snippet": "#include <bits/stdc++.h>\n#include <vector>\n#define REP(i,n) for(int i=0;i<(n);i++)\n#define FOR(i,r,n) for(int i=(r);i<(n);i++)\n#define ALL(obj) begin(obj),end(obj)\ntemplate<typename T> bool chmin(T &a,T b){\n if (a>b) {\n a=b;\n return true;\n }\n else return false;\n}\nusing namespace std;\ntypedef long long ll;\ntypedef vector<vector<int>> vvi; \nstruct StronglyConnectedComponents{\n int n;\n vvi G,rG;\n vector<int> ord,vis,comp;\n void dfs(int v){\n vis[v]=1;\n for(auto u:G[v]) if (!vis[u]) dfs(u);\n ord.push_back(v);\n }\n void rdfs(int v,int k){\n comp[v]=k;\n for(auto u:rG[v]) if (comp[u]==-1){\n rdfs(u,k);\n }\n }\n StronglyConnectedComponents(vvi &_G){\n G=_G;\n n=G.size();\n rG.resize(n);\n REP(i,n){\n for(auto u:G[i]) rG[u].push_back(i);\n }\n vis.assign(n,0);\n REP(i,n) if (!vis[i]) dfs(i);\n reverse(ALL(ord));\n comp.assign(n,-1);\n int k=0;\n REP(i,n) if (comp[ord[i]]==-1) {\n rdfs(ord[i],k);\n k++;\n }\n } \n};\nint main(){\n int N,M,Q;\n cin >> N >> M;\n vvi G(N);\n REP(i,M){\n int a,b;\n cin >> a >> b;\n G[a].push_back(b);\n }\n StronglyConnectedComponents SCC(G);\n cin >> Q;\n REP(i,Q){\n int u,v;\n cin >> u >> v;\n if (SCC.comp[u]==SCC.comp[v]) cout << 1 << endl;\n else cout << 0 << endl;\n }\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5492, "score_of_the_acc": -1.0688, "final_rank": 15 }, { "submission_id": "aoj_GRL_3_C_10725581", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nstd::vector<std::vector<int>> G, rG;\nstd::vector<bool> visited;\nstd::vector<int> order;\nstd::vector<int> component;\n\nvoid dfs(int u){\n visited[u] = true;\n\n for(int v : G[u]){\n if(!visited[v]){\n dfs(v);\n }\n }\n order.push_back(u);\n}\n\nvoid rdfs(int u, int k){\n visited[u] = true;\n component[u] = k;\n for(int v : rG[u]){\n if(!visited[v]){\n rdfs(v, k);\n }\n }\n}\n\nint main(){\n int v, e;\n std::cin >> v >> e;\n\n G.resize(v);\n rG.resize(v);\n \n for(int i=0;i<e;i++){\n int u,w;\n std::cin >> u >> w;\n G[u].push_back(w);\n rG[w].push_back(u);\n }\n\n visited.assign(v, false);\n for(int i=0;i<v;i++) {\n if(!visited[i]){\n dfs(i);\n }\n }\n\n visited.assign(v, false);\n component.resize(v);\n int scc_id = 0;\n for(int i=v-1;i>=0;i--) {\n int u = order[i];\n if(!visited[u]){\n rdfs(u, scc_id);\n scc_id++;\n }\n }\n\n int q;\n std::cin >> q;\n for(int i=0;i<q;i++){\n int u,w;\n std::cin >> u >> w;\n\n if(component[u] == component[w]){\n std::cout << 1 << std::endl;\n }else{\n std::cout << 0 << std::endl;\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 4900, "score_of_the_acc": -0.9545, "final_rank": 9 }, { "submission_id": "aoj_GRL_3_C_10716240", "code_snippet": "// GRL_3_C\n#include <bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\n\nusing Graph = vector<vector<int>>;\nGraph G, rG;\n\nvector<bool> seen;\nvector<int> st;\nvector<int> comp;\nint cid = 0;\n\nvoid DFS1(int u) {\n seen[u] = true;\n for(auto& next : G[u]) {\n if(!seen[next]) DFS1(next);\n }\n st.push_back(u);\n}\n\nvoid DFS2(int u) {\n comp[u] = cid;\n for(auto& next : rG[u]) {\n if(comp[next] < 0) DFS2(next);\n }\n}\n\nint main() {\n int V, E;\n cin >> V >> E;\n G.resize(V);\n rG.resize(V);\n for(int i=0; i<E; ++i) {\n int s, t;\n cin >> s >> t;\n G[s].push_back(t);\n rG[t].push_back(s);\n }\n\n seen.assign(V, false);\n st.reserve(V);\n comp.assign(V, -1);\n\n for(int u=0; u<V; ++u) {\n if(!seen[u]) DFS1(u);\n }\n\n for(int i=V-1; i >= 0; --i) {\n int u = st[i];\n if(comp[u] < 0) {\n DFS2(u);\n cid++;\n }\n }\n\n int q;\n cin >> q;\n for(int i=0; i<q; ++i) {\n int u, v;\n cin >> u >> v;\n if(comp[u] == comp[v]) {\n cout << 1 << endl;\n }\n else cout << 0 << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 4560, "score_of_the_acc": -1, "final_rank": 13 }, { "submission_id": "aoj_GRL_3_C_10704157", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\nvector<vector<int>> G; //グラフ\nvector<vector<int>> GT; //転置グラフ\nvector<int> visited;\nvector<int> order; // 終了順に格納する\nvector<vector<int>> scc; \n// sccごとの集合で表示する\n\nvector<int> node_to_comp;\n// nodeの所属するのはどこか?\n\nvoid dfs(int u){\n visited[u] = 1;\n for(int i=0;i<G[u].size();i++){\n int v = G[u][i];\n if(!visited[v]){\n dfs(v);\n }\n }\n order.push_back(u);\n}\n\nvoid dfs_T(int u, vector<int>& component){\n visited[u] = 1;\n component.push_back(u);\n for(int i=0;i<GT[u].size();i++){\n int v = GT[u][i];\n if(!visited[v]){\n dfs_T(v, component);\n }\n }\n}\n\nbool sameComp(int a,int b){\n return node_to_comp[a] == node_to_comp[b];\n}\n\nint main(){\n int V,E;\n int s,t;\n int Q,x,y;\n\n cin >> V >> E;\n G.resize(V);\n GT.resize(V);\n node_to_comp.resize(V,-1);\n visited.resize(V,0);\n\n for(int i=0;i<E;i++){\n cin >> s >> t;\n G[s].push_back(t);\n GT[t].push_back(s);\n }\n\n for(int i=0;i<V;i++){\n if(!visited[i]){\n //訪問していないすべてを見るから\n dfs(i);\n }\n }\n\n //visitedをリセットする\n for(int i=0;i<V;i++){\n visited[i] = 0;\n }\n\n reverse(order.begin(),order.end());\n //これで反転させる\n\n for(int i=0;i<order.size();i++){\n if(!visited[order[i]]){\n vector<int> comp; //sccの集合体を求める\n dfs_T(order[i], comp);\n\n // わかりやすくするためにソートする\n sort(comp.begin(), comp.end());\n scc.push_back(comp);\n }\n }\n\n // node_to_compの前処理\n for(int i=0;i<scc.size();i++){\n for(int j=0;j<scc[i].size();j++){\n int v = scc[i][j];\n node_to_comp[v] = i;\n }\n }\n\n // クエリの処理をする\n cin >> Q;\n\n for(int i=0;i<Q;i++){\n cin >> x >> y;\n if(sameComp(x,y)){\n cout << 1 << endl;\n }else{\n cout << 0 << endl;\n }\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 4876, "score_of_the_acc": -0.9499, "final_rank": 8 }, { "submission_id": "aoj_GRL_3_C_10576126", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing lli=long long int;\nusing ld=long double;\nusing vi=vector<int>;\nusing vvi=vector<vi>;\nusing vvvi=vector<vvi>;\nusing vvvvi=vector<vvvi>;\nusing vl=vector<lli>;\nusing vvl=vector<vl>;\nusing vb=vector<bool>;\nusing vvb=vector<vb>;\n#define rep(i,s,e) for(int i=s;i<e;i++)\n#define leap(i,s,e,j) for(int i=s;i<e;i+=j)\n#define repl(i,s,e) for(lli i=s;i<e;i++)\n#define rrep(i,s,e) for(int i=s-1;i>=e;i--)\n#define rleap(i,s,e,j) for(int i=s-1;i>=e;i-=j)\n#define in(v,seq) for(auto v:seq)\n#define veci(v,s) vi v(s); rep(i,0,s) cin >> v.at(i);\n#define vecl(v,s) vl v(s); rep(i,0,s) cin >> v.at(i);\n#define all(s) s.begin(),s.end()\n#define rall(s) s.rbegin(),s.rend()\nusing pii=pair<int,int>;\nusing pll=pair<lli,lli>;\n#define mp(f,s) make_pair(f,s)\n#define fi first\n#define se second\nusing vpii=vector<pii>;\nusing vpll=vector<pll>;\n#define vecpii(v,s) vpii v(s); rep(i,0,s) cin >> v.at(i).fi >> v.at(i).se;\n#define vecpll(v,s) vpll v(s); rep(i,0,s) cin >> v.at(i).fi >> v.at(i).se;\n#define pub(x) push_back(x)\n#define puf(x) push_front(x)\n#define pob(x) pop_back(x)\n#define pof(x) pop_front(x)\n#define emb(x) emplace_back(x)\n#define print(s) cout << s << endl;\n#define ptp(p) cout << p.fi << \" \" << p.se << endl;\nconst int I_INF=1<<30;\nconst lli LL_INF=1ll<<60;\nconst string alp=\"abcdefghijklmnopqrstuvwxyz\";\nconst int let=alp.size(); // 26\n\nusing SGraph=vector<vector<int>>;\n\nvector<vector<int>> SCC(SGraph &G,SGraph &RG){\n int vertex=G.size();\n vector<int> rpost;\n vector<bool> seen(vertex,false);\n\n auto dfs=[&](auto &dfs,int v)->void{\n seen.at(v)=true;\n for(int nv:RG.at(v)){\n if(seen.at(nv)) continue;\n dfs(dfs,nv);\n }\n rpost.emplace_back(v);\n return;\n };\n\n for(int i=0;i<vertex;i++){\n if(seen.at(i)) continue;\n dfs(dfs,i);\n }\n\n seen.assign(vertex,false);\n vector<vector<int>> ret;\n int index=0;\n\n auto dfs_again=[&](auto &dfs_again,int v)->void{\n seen.at(v)=true;\n ret.at(index).emplace_back(v);\n for(int nv:G.at(v)){\n if(seen.at(nv)) continue;\n dfs_again(dfs_again,nv);\n }\n return;\n };\n\n for(int i=vertex-1;i>=0;i--){\n if(seen.at(rpost.at(i))) continue;\n ret.push_back({});\n dfs_again(dfs_again,rpost.at(i));\n index++;\n }\n\n return ret;\n}\n\nint main(){\n int vertex,edge; cin >> vertex >> edge;\n SGraph G(vertex),RG(vertex);\n rep(i,0,edge){\n int u,v; cin >> u >> v;\n G[u].pub(v);\n RG[v].pub(u);\n }\n\n auto c=SCC(G,RG);\n vi t(vertex,-1);\n rep(i,0,c.size()){\n in(v,c[i]) t[v]=i;\n }\n\n int q; cin >> q;\n rep(i,0,q){\n int u,v; cin >> u >> v;\n print((t[u]==t[v]));\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 5248, "score_of_the_acc": -0.6884, "final_rank": 5 }, { "submission_id": "aoj_GRL_3_C_10524150", "code_snippet": "#include <bits/stdc++.h>\n#define INF 0x7fffffff\n#define MAXN 200010\ntypedef long long LL;\nusing namespace std;\n\nint n, m, cnt, colcnt;\nvector <int> g[MAXN];\nint dfn[MAXN], low[MAXN], color[MAXN];\nbool vis[MAXN];\nstack <int> st;\n\nvoid Tarjan(int u)\n{\n\tdfn[u] = low[u] = ++cnt;\n\tst.push(u);\n\tvis[u] = true;\n\tfor(int x = 0; x < g[u].size(); x++)\n\t{\n\t\tint v = g[u][x];\n\t\tif(!dfn[v])\n\t\t{\n\t\t\tTarjan(v);\n\t\t\tlow[u] = min(low[u], low[v]);\n\t\t}\n\t\telse if(vis[v]) low[u] = min(low[u], dfn[v]);\n\t}\n\tif(dfn[u] == low[u])\n\t{\n\t\tcolcnt++;\n\t\tint v;\n\t\tdo\n\t\t{\n\t\t\tv = st.top(); st.pop();\n\t\t\tvis[v] = false;\n\t\t\tcolor[v] = colcnt;\n\t\t} while(v != u);\n\t}\n}\n\nint main()\n{\n\tcin >> n >> m;\n\tfor(int x = 1; x <= m; x++)\n\t{\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tg[u].push_back(v);\n\t}\n\tfor(int x = 0; x < n; x++)\n\t\tif(!dfn[x]) Tarjan(x);\n\t// for(int x = 0; x < n; x++) cout << color[x] << \" \";\n\t// cout << endl;\n\tint q;\n\tcin >> q;\n\twhile(q--)\n\t{\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tcout << (color[u] == color[v]) << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 9740, "score_of_the_acc": -1.8889, "final_rank": 20 }, { "submission_id": "aoj_GRL_3_C_10444608", "code_snippet": "//\n// 強連結成分分解\n//\n// verified:\n// Yosupo Judge - Strongly Connected Components\n// https://judge.yosupo.jp/problem/scc\n//\n// AOJ Course GRL_3_C - 強連結成分分解\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_3_C&lang=ja\n//\n\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n\n// Edge Class\ntemplate<class T> struct Edge {\n int from, to;\n T val;\n Edge() : from(-1), to(-1), val(-1) { }\n Edge(int f, int t, T v = -1) : from(f), to(t), val(v) {}\n friend ostream& operator << (ostream& s, const Edge& E) {\n return s << E.from << \"->\" << E.to;\n }\n};\n\n// graph class\ntemplate<class T> struct Graph {\n vector<vector<Edge<T>>> list;\n vector<vector<Edge<T>>> reversed_list;\n \n Graph(int n = 0) : list(n), reversed_list(n) { }\n void init(int n = 0) {\n list.assign(n, vector<Edge<T>>());\n reversed_list.assign(n, vector<Edge<T>>());\n }\n const vector<Edge<T>> &operator [] (int i) const { return list[i]; }\n const vector<Edge<T>> &get_rev_edges(int i) const { return reversed_list[i]; }\n const size_t size() const { return list.size(); }\n \n void add_edge(int from, int to, T val = -1) {\n list[from].push_back(Edge(from, to, val));\n reversed_list[to].push_back(Edge(to, from, val));\n }\n \n void add_bidirected_edge(int from, int to, T val = -1) {\n list[from].push_back(Edge(from, to, val));\n list[to].push_back(Edge(to, from, val));\n reversed_list[from].push_back(Edge(from, to, val));\n reversed_list[to].push_back(Edge(to, from, val));\n }\n\n friend ostream &operator << (ostream &s, const Graph &G) {\n s << endl;\n for (int i = 0; i < G.size(); ++i) {\n s << i << \" -> \";\n for (const auto &e : G[i]) s << e.to << \" \";\n s << endl;\n }\n return s;\n }\n};\n\n// strongly connected components decomposition\ntemplate<class T> struct SCC {\n // results\n vector<int> cmp;\n vector<vector<int>> groups;\n Graph<T> dag;\n \n // intermediate results\n vector<bool> seen;\n vector<int> vs, rvs;\n \n // constructor\n SCC() { }\n SCC(const Graph<T> &G) { \n solve(G);\n }\n void init(const Graph<T> &G) { \n solve(G);\n }\n\n // getter, compressed dag(v: node-id of compressed dag)\n int get_size(int v) const {\n return groups[v].size();\n }\n vector<int> get_group(int v) const {\n return groups[v];\n }\n\n // solver\n void dfs(const Graph<T> &G, int v) {\n seen[v] = true;\n for (const auto &e : G[v]) if (!seen[e.to]) dfs(G, e.to);\n vs.push_back(v);\n }\n void rdfs(const Graph<T> &G, int v, int k) {\n seen[v] = true;\n cmp[v] = k;\n for (const auto &e : G.get_rev_edges(v)) if (!seen[e.to]) rdfs(G, e.to, k);\n rvs.push_back(v);\n }\n void reconstruct(const Graph<T> &G) {\n dag.init((int)groups.size());\n set<pair<int,int>> new_edges;\n for (int i = 0; i < (int)G.size(); ++i) {\n int u = cmp[i];\n for (const auto &e : G[i]) {\n int v = cmp[e.to];\n if (u == v) continue;\n if (!new_edges.count({u, v})) {\n dag.add_edge(u, v);\n new_edges.insert({u, v});\n }\n }\n }\n }\n void solve(const Graph<T> &G) {\n // first dfs\n seen.assign((int)G.size(), false);\n vs.clear();\n for (int v = 0; v < (int)G.size(); ++v) if (!seen[v]) dfs(G, v);\n\n // back dfs\n int k = 0;\n groups.clear();\n seen.assign((int)G.size(), false);\n cmp.assign((int)G.size(), -1);\n for (int i = (int)G.size()-1; i >= 0; --i) {\n if (!seen[vs[i]]) {\n rvs.clear();\n rdfs(G, vs[i], k++);\n groups.push_back(rvs);\n }\n }\n reconstruct(G);\n }\n};\n\n\n\n//------------------------------//\n// Examples\n//------------------------------//\n\nvoid Yosupo_Strongly_Connected_Components() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n \n // 入力\n int N, M;\n cin >> N >> M;\n Graph<int> G(N);\n for (int i = 0; i < M; ++i) {\n int u, v;\n cin >> u >> v;\n G.add_edge(u, v);\n }\n //cout << G << endl;\n \n // SCC (not build dag)\n SCC<int> scc(G);\n const auto &groups = scc.groups;\n \n // 出力\n cout << groups.size() << endl;\n for (const auto &list : groups) {\n cout << list.size();\n for (auto v : list) cout << \" \" << v;\n cout << endl;\n }\n}\n\nvoid AOJ_GRL_3_C() {\n // 入力\n int N, M;\n cin >> N >> M;\n Graph<int> G(N);\n for (int i = 0; i < M; ++i) {\n int u, v;\n cin >> u >> v;\n G.add_edge(u, v);\n }\n \n // SCC\n SCC<int> scc(G);\n \n // クエリ\n int Q;\n cin >> Q;\n while (Q--) {\n int u, v;\n cin >> u >> v;\n if (scc.cmp[u] == scc.cmp[v]) cout << 1 << endl;\n else cout << 0 << endl;\n }\n}\n\n\nint main() {\n //Yosupo_Strongly_Connected_Components();\n AOJ_GRL_3_C();\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5200, "score_of_the_acc": -1.0124, "final_rank": 14 }, { "submission_id": "aoj_GRL_3_C_10376280", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 10005;\n\nvector<int> G[MAXN];\nvector<int> rG[MAXN];\nvector<bool> vis(MAXN, false);\nstack<int> st;\nint id[MAXN];\nint cnt = 0;\n\nvoid dfs1(int u) {\n\tvis[u] = true;\n\tfor (int v : G[u]) {\n\t\tif (!vis[v]) dfs1(v);\n\t}\n\tst.push(u);\n}\n\nvoid dfs2(int u) {\n\tvis[u] = true;\n\tid[u] = cnt;\n\tfor (int v : rG[u]) {\n\t\tif (!vis[v]) dfs2(v);\n\t}\n}\n\nvoid kosaraju(int n) {\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (!vis[i]) dfs1(i);\n\t}\n\tvis.assign(n, false);\n\twhile (!st.empty()) {\n\t\tint u = st.top(); st.pop();\n\t\tif (!vis[u]) {\n\t\t\tcnt++;\n\t\t\tdfs2(u);\n\t\t}\n\t}\n}\n\nint main() {\n\tint V, E;\n\tcin >> V >> E;\n\twhile (E--) {\n\t\tint s, t;\n\t\tcin >> s >> t;\n\t\tG[s].push_back(t);\n\t\trG[t].push_back(s);\n\t}\n\tkosaraju(V);\n\t\n\tint Q; cin >> Q;\n\twhile (Q--) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tcout << (id[u] == id[v]) << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 5088, "score_of_the_acc": -0.9908, "final_rank": 12 } ]
aoj_GRL_5_A_cpp
Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Input n s 1 t 1 w 1 s 2 t 2 w 2 : s n-1 t n-1 w n-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n -1 respectively. In the following n -1 lines, edges of the tree are given. s i and t i represent end-points of the i -th edge (undirected) and w i represents the weight (distance) of the i -th edge. Output Print the diameter of the tree in a line. Constraints 1 ≤ n ≤ 100,000 0 ≤ w i ≤ 1,000 Sample Input 1 4 0 1 2 1 2 1 1 3 3 Sample Output 1 5 Sample Input 2 4 0 1 1 1 2 2 2 3 4 Sample Output 2 7
[ { "submission_id": "aoj_GRL_5_A_11059886", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\npair<int, int> theFurthest(const vector<Node> &nodes, int current, vector<bool> &searched)\n{\n int furthestDestination = current;\n int furthestLength = 0;\n for (auto [dest, length] : nodes[current].children)\n {\n if (searched[dest])\n continue;\n searched[dest] = true;\n auto [tmpDest, tmpLength] = theFurthest(nodes, dest, searched);\n if (furthestLength < tmpLength + length)\n {\n furthestDestination = tmpDest;\n furthestLength = tmpLength + length;\n }\n }\n return pair<int, int>(furthestDestination, furthestLength);\n}\n\nint getInitialFurthestDestination(const vector<Node> &nodes)\n{\n vector<bool> searched(nodes.size());\n searched[0] = true;\n auto [dest, length] = theFurthest(nodes, 0, searched);\n return dest;\n}\n\nint getFurthestLength(const vector<Node> &nodes, int startingNode)\n{\n vector<bool> searched(nodes.size());\n searched[startingNode] = true;\n auto [dest, length] = theFurthest(nodes, startingNode, searched);\n return length;\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.emplace_back(t, w);\n nodes[t].children.emplace_back(s, w);\n }\n\n int initialFurthestDestination = getInitialFurthestDestination(nodes);\n cout << getFurthestLength(nodes, initialFurthestDestination) << endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 16908, "score_of_the_acc": -0.6289, "final_rank": 10 }, { "submission_id": "aoj_GRL_5_A_11059868", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\npair<int, int> theFurthest(const vector<Node> &nodes, int current, vector<bool> &searched)\n{\n int furthestDestination = current;\n int furthestLength = 0;\n for (auto [dest, length] : nodes[current].children)\n {\n if (searched[dest])\n continue;\n searched[dest] = true;\n auto [tmpDest, tmpLength] = theFurthest(nodes, dest, searched);\n if (furthestLength < tmpLength + length)\n {\n furthestDestination = tmpDest;\n furthestLength = tmpLength + length;\n }\n }\n return pair<int, int>(furthestDestination, furthestLength);\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.emplace_back(t, w);\n nodes[t].children.emplace_back(s, w);\n }\n\n int initialFurthestDestination = 0;\n {\n vector<bool> searched(n);\n searched[0] = true;\n auto [dest, length] = theFurthest(nodes, 0, searched);\n initialFurthestDestination = dest;\n }\n\n int diameter = 0;\n {\n vector<bool> searched(n);\n searched[initialFurthestDestination] = true;\n auto [dest, length] = theFurthest(nodes, initialFurthestDestination, searched);\n diameter = length;\n }\n\n cout << diameter << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 17300, "score_of_the_acc": -0.4697, "final_rank": 6 }, { "submission_id": "aoj_GRL_5_A_11059857", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\npair<int, int> theFurthest(const vector<Node> &nodes, int current, vector<bool> &searched)\n{\n int furthestDestination = current;\n int furthestLength = 0;\n for (auto [dest, length] : nodes[current].children)\n {\n if (searched[dest])\n continue;\n searched[dest] = true;\n auto [tmpDest, tmpLength] = theFurthest(nodes, dest, searched);\n if (furthestLength < tmpLength + length)\n {\n furthestDestination = tmpDest;\n furthestLength = tmpLength + length;\n }\n }\n return pair<int, int>(furthestDestination, furthestLength);\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.push_back(pair<int, int>(t, w));\n nodes[t].children.push_back(pair<int, int>(s, w));\n }\n\n int initialFurthestDestination = 0;\n int initialFurthestLength = 0;\n {\n vector<bool> searched(n);\n searched[0] = true;\n auto [dest, length] = theFurthest(nodes, 0, searched);\n initialFurthestDestination = dest;\n initialFurthestLength = length;\n }\n\n int diameter = 0;\n {\n vector<bool> searched(n);\n searched[initialFurthestDestination] = true;\n auto [dest, length] = theFurthest(nodes, initialFurthestDestination, searched);\n diameter = length;\n }\n\n cout << diameter << endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 17080, "score_of_the_acc": -0.6322, "final_rank": 12 }, { "submission_id": "aoj_GRL_5_A_11059838", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\npair<int, int> theFurthest(const vector<Node> &nodes, int current, vector<bool> &searched)\n{\n int maxLengthDestination = current;\n int maxLength = 0;\n for (auto [dest, length] : nodes[current].children)\n {\n if (searched[dest])\n continue;\n searched[dest] = true;\n auto [tmpDest, tmpLength] = theFurthest(nodes, dest, searched);\n if (maxLength < tmpLength + length)\n {\n maxLengthDestination = tmpDest;\n maxLength = tmpLength + length;\n }\n }\n return pair<int, int>(maxLengthDestination, maxLength);\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.push_back(pair<int, int>(t, w));\n nodes[t].children.push_back(pair<int, int>(s, w));\n }\n\n int initialMaxDestination = 0;\n int initialMaxLength = 0;\n {\n vector<bool> searched(n);\n searched[0] = true;\n auto [dest, length] = theFurthest(nodes, 0, searched);\n initialMaxDestination = dest;\n initialMaxLength = length;\n }\n\n int diameter = 0;\n {\n vector<bool> searched(n);\n searched[initialMaxDestination] = true;\n auto [dest, length] = theFurthest(nodes, initialMaxDestination, searched);\n diameter = length;\n }\n\n cout << diameter << endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 16992, "score_of_the_acc": -0.6305, "final_rank": 11 }, { "submission_id": "aoj_GRL_5_A_11048812", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\npair<int, int> theFurthest(const vector<Node> &nodes, int current, vector<bool> &searched)\n{\n int biggest = 0;\n int biggestDestination = current;\n for (auto [dest, length] : nodes[current].children)\n {\n if (searched[dest])\n continue;\n searched[dest] = true;\n auto [tmpDest, tmpLength] = theFurthest(nodes, dest, searched);\n if (biggest < tmpLength + length)\n {\n biggestDestination = tmpDest;\n biggest = tmpLength + length;\n }\n }\n return pair<int, int>(biggestDestination, biggest);\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.push_back(pair<int, int>(t, w));\n nodes[t].children.push_back(pair<int, int>(s, w));\n }\n\n int firstBiggestDestination = 0;\n int firstBiggest = 0;\n {\n vector<bool> searched(n);\n searched[0] = true;\n auto [dest, length] = theFurthest(nodes, 0, searched);\n firstBiggestDestination = dest;\n firstBiggest = length;\n }\n\n int secondBiggestDestination = 0;\n int secondBiggest = 0;\n {\n vector<bool> searched(n);\n searched[firstBiggestDestination] = true;\n auto [dest, length] = theFurthest(nodes, firstBiggestDestination, searched);\n secondBiggestDestination = dest;\n secondBiggest = length;\n }\n\n cout << secondBiggest << endl;\n}\n\n// 0 から一番遠い点を見つけて、その点から一番遠い点が直径", "accuracy": 1, "time_ms": 50, "memory_kb": 17304, "score_of_the_acc": -0.6364, "final_rank": 13 }, { "submission_id": "aoj_GRL_5_A_11043133", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n bool searched = false;\n};\n\nint maxDiameter(vector<Node> &nodes, int current, int &diameter)\n{\n // 節点から伸びる辺で重みが大きい上位2つを記録する\n int firstBiggest = 0;\n int secondBiggest = 0;\n\n nodes[current].searched = true;\n // 節点から伸びる辺ごとの重みを調べる\n for (auto [dest, length] : nodes[current].children)\n {\n if (nodes[dest].searched)\n continue;\n // 節点から伸びた辺の重みとその先の点の重みの和\n int num = length + maxDiameter(nodes, dest, diameter);\n if (firstBiggest < num)\n {\n secondBiggest = firstBiggest;\n firstBiggest = num;\n }\n else if (secondBiggest < num)\n secondBiggest = num;\n }\n diameter = max(diameter, firstBiggest + secondBiggest);\n return firstBiggest;\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.push_back(pair<int, int>(t, w));\n nodes[t].children.push_back(pair<int, int>(s, w));\n }\n\n int diameter = 0;\n maxDiameter(nodes, 0, diameter);\n cout << diameter << endl;\n}\n\n// 各節点で二番目までの大きさの和が最大か確認する", "accuracy": 1, "time_ms": 40, "memory_kb": 17164, "score_of_the_acc": -0.4671, "final_rank": 5 }, { "submission_id": "aoj_GRL_5_A_11015466", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\nint maxDiameter(const vector<Node> &nodes, int current, int &diameter)\n{\n // 節点から伸びる辺で重みが大きい上位2つを記録する\n int firstBiggest = 0;\n int secondBiggest = 0;\n\n // 節点から伸びる辺ごとの重みを調べる\n for (auto [dest, length] : nodes[current].children)\n {\n // 節点から伸びた辺の重みとその先の点の重みの和\n int num = length + maxDiameter(nodes, dest, diameter);\n if (firstBiggest < num)\n {\n secondBiggest = firstBiggest;\n firstBiggest = num;\n }\n else if (secondBiggest < num)\n secondBiggest = num;\n }\n diameter = max(diameter, firstBiggest + secondBiggest);\n return firstBiggest;\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.push_back(pair<int, int>(t, w));\n }\n\n int diameter = 0;\n maxDiameter(nodes, 0, diameter);\n cout << diameter << endl;\n}\n\n// 各節点で二番目までの大きさの和が最大か確認する", "accuracy": 1, "time_ms": 40, "memory_kb": 17304, "score_of_the_acc": -0.4697, "final_rank": 7 }, { "submission_id": "aoj_GRL_5_A_11015435", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\nint maxDiameter(vector<Node> &nodes, int current, int &diameter)\n{\n // 節点から伸びる辺で重みが大きい上位2つを記録する\n int firstBiggest = 0;\n int secondBiggest = 0;\n\n // 節点から伸びる辺ごとの重みを調べる\n for (pair<int, int> &child : nodes[current].children)\n {\n // 節点から伸びた辺の重みとその先の点の重みの和\n int num = child.second + maxDiameter(nodes, child.first, diameter);\n if (firstBiggest < num)\n {\n secondBiggest = firstBiggest;\n firstBiggest = num;\n }\n else if (secondBiggest < num)\n secondBiggest = num;\n }\n diameter = max(diameter, firstBiggest + secondBiggest);\n return firstBiggest;\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.push_back(pair<int, int>(t, w));\n }\n\n int diameter = 0;\n maxDiameter(nodes, 0, diameter);\n cout << diameter << endl;\n}\n\n// 中心の点をどこにするかによって直径は変わってくる\n// 中心は s, 各中心から長い距離を二つ探す(親も可)\n// 中間の点は決まっている\n// 各親で二番目までの大きさの和が最大か確認する", "accuracy": 1, "time_ms": 40, "memory_kb": 16988, "score_of_the_acc": -0.4638, "final_rank": 4 }, { "submission_id": "aoj_GRL_5_A_11015413", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n// 中心の点をどこにするかによって直径は変わってくる\n// 中心は s, 各中心から長い距離を二つ探す(親も可)\n// 中間の点は決まっている\n// 各親で二番目までの大きさの和が最大か確認する\n\nstruct Node\n{\n vector<pair<int, int>> children; // destination node, length\n int length;\n};\n\nint maxDiameter(vector<Node> &nodes, int current, int &diameter)\n{\n int firstBiggest = 0;\n int secondBiggest = 0;\n for (pair<int, int> &child : nodes[current].children)\n {\n int num = maxDiameter(nodes, child.first, diameter) + child.second;\n if (firstBiggest < num)\n {\n secondBiggest = firstBiggest;\n firstBiggest = num;\n }\n else if (secondBiggest < num)\n secondBiggest = num;\n }\n diameter = max(diameter, firstBiggest + secondBiggest);\n return firstBiggest;\n}\n\nint main()\n{\n int n;\n cin >> n;\n\n vector<Node> nodes(n);\n for (int i = 0; i < n - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n nodes[s].children.push_back(pair<int, int>(t, w));\n }\n\n int diameter = 0;\n maxDiameter(nodes, 0, diameter);\n cout << diameter << endl;\n}\n\n/*\n 0 1\n 0 2\n の場合は\n 1 0 2 の距離\n*/", "accuracy": 1, "time_ms": 40, "memory_kb": 15312, "score_of_the_acc": -0.4321, "final_rank": 3 }, { "submission_id": "aoj_GRL_5_A_11001399", "code_snippet": "#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\nusing namespace std;\n\nstruct Edge\n{\n size_t t; // 端点\n size_t w; // 重み\n Edge(size_t t, size_t w) : t(t), w(w) {}\n};\n\n// 幅優先探索(再帰)\nvoid breadth_first_search(int u, int distance, const vector<list<Edge>> &A, vector<int> &d)\n{\n if (d[u] != -1 && distance >= d[u])\n {\n return;\n }\n\n d[u] = distance;\n\n for (auto e : A[u])\n {\n breadth_first_search(e.t, distance + e.w, A, d);\n }\n}\n\nint main()\n{\n size_t n; // 頂点数\n cin >> n;\n vector<list<Edge>> A(n); // 隣接行列\n\n for (size_t i = 0; i < n - 1; ++i)\n {\n int s, t, w;\n cin >> s >> t >> w;\n\n A[s].push_back(Edge(t, w));\n A[t].push_back(Edge(s, w));\n }\n\n vector<int> d0(n, -1); // ノード0からの最短距離\n breadth_first_search(0, 0, A, d0);\n auto iter = max_element(d0.begin(), d0.end()); // ノード0から最遠点\n size_t index = distance(d0.begin(), iter); // ノード0から最遠点index\n\n vector<int> di(n, -1); // ノードindexからの最短距離\n breadth_first_search(index, 0, A, di);\n auto iter_max = max_element(di.begin(), di.end()); // ノードindexから最遠点\n\n // 結果を出力\n cout << *iter_max << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 20188, "score_of_the_acc": -0.6909, "final_rank": 15 }, { "submission_id": "aoj_GRL_5_A_10986169", "code_snippet": "//任求一个点到达的最远点,那个最远点的最长路径就是最远距离也就是树的直径\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#define INF 0x3f3f3f3f\nusing namespace std;\nconst int MAX=100000+2;\nint n;\nint dis=0;\nint far;\nvector<pair<int,int>> A[MAX];\n//答案做法,class类居然也可以放在vector里!!!\n//求最远距离和最远点,我们只需要求一个点到所有点的所有距离然后比较就行了,一个dps或者bps就可以了;\nclass Edge{\n public:\n int s,w;\n Edge(){}\n Edge(int s,int w):s(s),w(w){}\n};\nvector<Edge> B[MAX];\nint d[MAX];//既充当记录距离又负责判断有没有访问过\nvoid bps(int l){\n for(int i=0;i<n;i++){\n d[i]=INF;\n }\n queue<int> O;\n O.push(l);\n d[l]=0;\n while(!O.empty()){\n int u=O.front();\n O.pop();\n for(int i=0;i<(int)B[u].size();i++){\n Edge m=B[u][i];\n if(d[m.s]==INF){//防止走回头路回到父结点,类似于dps关于父节点的判断\n d[m.s]=m.w+d[u];\n O.push(m.s);\n }\n }\n }\n}\nvoid solve(){\n bps(0);\n int maxv=0;\n int tgt=0;\n for(int i=0;i<n;i++){\n /*if(d[i]!=INF){\n\n }可以用下面的continue换掉*/\n if(d[i]==INF)continue;\n if(d[i]>maxv){\n maxv=d[i];\n tgt=i;//找到最远点\n }\n }\n bps(tgt);\n maxv=0;\n for(int i=0;i<n;i++){\n if(d[i]!=INF){\n maxv=max(maxv,d[i]);\n }\n }\n printf(\"%d\",maxv);\n}//答案的做法至此\nvoid searchmax(int a,int m,int c){\n if(c>dis){\n dis=c;\n far=a;\n }\n for(int i=0;i<(int)A[a].size();i++){\n int v=A[a][i].first;\n int g=A[a][i].second;\n if(v!=m){\n searchmax(v,a,c+g);\n }\n }\n}\nint main(){\n scanf(\"%d\",&n);\n for(int i=0;i<(n-1);i++){\n int s,t,w;\n scanf(\"%d %d %d\",&s,&t,&w);\n A[s].push_back(make_pair(t,w));\n A[t].push_back(make_pair(s,w));\n }\n searchmax(0,-1,0);\n dis=0;\n searchmax(far,-1,0);\n printf(\"%d\\n\",dis);\n return 0;\n}\n//答案做法,class类居然也可以放在vector里!!!", "accuracy": 1, "time_ms": 20, "memory_kb": 15312, "score_of_the_acc": -0.0988, "final_rank": 1 }, { "submission_id": "aoj_GRL_5_A_10962763", "code_snippet": "#define _GLGBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge\n{\n int to;\n int weight;\n};\n\nstruct DP\n{\n int max_dist;\n int max_dist_vertex;\n\n bool operator<(const DP &other) const\n {\n if (max_dist != other.max_dist)\n return max_dist < other.max_dist;\n\n return max_dist_vertex < other.max_dist_vertex;\n }\n};\n\nint N, ID = 0, invalid_vertex = -1;\nvector<vector<Edge>> G;\nvector<vector<DP>> dp;\nvector<DP> ans;\nvector<int> to_parent_edge_weights;\n\nDP dfs(int root, int parent)\n{\n int out_degree_of_root = static_cast<int>(G.at(root).size());\n DP max_dp_of_subtree{ID, root};\n\n dp.at(root) = vector<DP>(out_degree_of_root, DP{ID, invalid_vertex});\n\n for (int i = 0; i < out_degree_of_root; i++)\n {\n int adjacent = G.at(root).at(i).to;\n\n if (adjacent == parent) {\n to_parent_edge_weights.at(root) = G.at(root).at(i).weight;\n continue;\n }\n\n dp.at(root).at(i) = dfs(adjacent, root);\n\n if (max_dp_of_subtree < dp.at(root).at(i))\n max_dp_of_subtree = dp.at(root).at(i);\n }\n\n return DP{\n max_dp_of_subtree.max_dist + to_parent_edge_weights.at(root),\n max_dp_of_subtree.max_dist_vertex,\n };\n}\n\nvoid dfs_reroot(int root, DP parent_subtree_dp_info, int parent)\n{\n int out_degree_of_root = static_cast<int>(G.at(root).size());\n\n for (int i = 0; i < out_degree_of_root; i++)\n if (G.at(root).at(i).to == parent) {\n dp.at(root).at(i) = parent_subtree_dp_info;\n break;\n }\n\n vector<DP> dp_prefix(out_degree_of_root + 1, DP{ID, invalid_vertex}), dp_suffix(out_degree_of_root + 1, DP{ID, invalid_vertex});\n\n for (int i = 0; i < out_degree_of_root; i++)\n {\n if (dp_prefix.at(i) < dp.at(root).at(i))\n dp_prefix.at(i + 1) = dp.at(root).at(i);\n else\n dp_prefix.at(i + 1) = dp_prefix.at(i);\n }\n\n for (int i = out_degree_of_root - 1; i >= 0; i--)\n {\n if (dp_suffix.at(i + 1) < dp.at(root).at(i))\n dp_suffix.at(i) = dp.at(root).at(i);\n else\n dp_suffix.at(i) = dp_suffix.at(i + 1);\n }\n\n ans.at(root) = DP{\n dp_prefix.at(out_degree_of_root).max_dist,\n dp_prefix.at(out_degree_of_root).max_dist_vertex,\n };\n\n for (int i = 0; i < out_degree_of_root; i++)\n {\n int adjacent = G.at(root).at(i).to;\n\n if (adjacent == parent)\n continue;\n\n DP max_dp_info;\n\n if (dp_prefix.at(i) < dp_suffix.at(i + 1))\n max_dp_info = dp_suffix.at(i + 1);\n else\n max_dp_info = dp_prefix.at(i);\n\n max_dp_info.max_dist += to_parent_edge_weights.at(adjacent);\n\n if (out_degree_of_root == 1)\n max_dp_info.max_dist_vertex = root;\n\n dfs_reroot(adjacent, max_dp_info, root);\n }\n}\n\nint main()\n{\n cin >> N;\n\n G.resize(N);\n dp.resize(N);\n ans.resize(N, DP{ID, invalid_vertex});\n to_parent_edge_weights.resize(N);\n\n for (int i = 1; i <= N - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n\n G.at(s).push_back(Edge{t, w});\n G.at(t).push_back(Edge{s, w});\n }\n\n dfs(0, -1);\n dfs_reroot(0, DP{ID, -1}, -1);\n\n int tree_diameter = 0;\n\n for (int i = 0; i < N; i++)\n tree_diameter = max(tree_diameter, ans.at(i).max_dist);\n\n cout << tree_diameter << '\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 32392, "score_of_the_acc": -1.0883, "final_rank": 19 }, { "submission_id": "aoj_GRL_5_A_10962759", "code_snippet": "#define _GLGBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge\n{\n int to;\n int weight;\n};\n\nstruct DP\n{\n int max_dist;\n int max_dist_vertex;\n\n bool operator<(const DP &other) const\n {\n if (max_dist != other.max_dist)\n return max_dist < other.max_dist;\n\n return max_dist_vertex < other.max_dist_vertex;\n }\n};\n\nint N, ID = 0, invalid_vertex = -1;\nvector<vector<Edge>> G;\nvector<vector<DP>> dp;\nvector<DP> ans;\nvector<int> to_parent_edge_weights;\n\nDP dfs(int root, int parent)\n{\n int out_degree_of_root = static_cast<int>(G.at(root).size()), to_parent_edge_weight;\n DP max_dp_of_subtree{ID, root};\n\n dp.at(root) = vector<DP>(out_degree_of_root, DP{ID, invalid_vertex});\n\n for (int i = 0; i < out_degree_of_root; i++)\n {\n int adjacent = G.at(root).at(i).to;\n\n if (adjacent == parent) {\n to_parent_edge_weights.at(root) = G.at(root).at(i).weight;\n continue;\n }\n\n dp.at(root).at(i) = dfs(adjacent, root);\n\n if (max_dp_of_subtree < dp.at(root).at(i))\n max_dp_of_subtree = dp.at(root).at(i);\n }\n\n return DP{\n max_dp_of_subtree.max_dist + to_parent_edge_weights.at(root),\n max_dp_of_subtree.max_dist_vertex,\n };\n}\n\nvoid dfs_reroot(int root, DP parent_subtree_dp_info, int parent)\n{\n int out_degree_of_root = static_cast<int>(G.at(root).size()), to_parent_edge_weight;\n\n for (int i = 0; i < out_degree_of_root; i++)\n if (G.at(root).at(i).to == parent) {\n dp.at(root).at(i) = parent_subtree_dp_info;\n break;\n }\n\n vector<DP> dp_prefix(out_degree_of_root + 1, DP{ID, invalid_vertex}), dp_suffix(out_degree_of_root + 1, DP{ID, invalid_vertex});\n\n for (int i = 0; i < out_degree_of_root; i++)\n {\n if (dp_prefix.at(i) < dp.at(root).at(i))\n dp_prefix.at(i + 1) = dp.at(root).at(i);\n else\n dp_prefix.at(i + 1) = dp_prefix.at(i);\n }\n\n for (int i = out_degree_of_root - 1; i >= 0; i--)\n {\n if (dp_suffix.at(i + 1) < dp.at(root).at(i))\n dp_suffix.at(i) = dp.at(root).at(i);\n else\n dp_suffix.at(i) = dp_suffix.at(i + 1);\n }\n\n ans.at(root) = DP{\n dp_prefix.at(out_degree_of_root).max_dist,\n dp_prefix.at(out_degree_of_root).max_dist_vertex,\n };\n\n for (int i = 0; i < out_degree_of_root; i++)\n {\n int adjacent = G.at(root).at(i).to;\n\n if (adjacent == parent)\n continue;\n\n DP max_dp_info;\n\n if (dp_prefix.at(i) < dp_suffix.at(i + 1))\n max_dp_info = dp_suffix.at(i + 1);\n else\n max_dp_info = dp_prefix.at(i);\n\n max_dp_info.max_dist += to_parent_edge_weights.at(adjacent);\n\n if (out_degree_of_root == 1)\n max_dp_info.max_dist_vertex = root;\n\n dfs_reroot(adjacent, max_dp_info, root);\n }\n}\n\nint main()\n{\n cin >> N;\n\n G.resize(N);\n dp.resize(N);\n ans.resize(N, DP{ID, invalid_vertex});\n to_parent_edge_weights.resize(N);\n\n for (int i = 1; i <= N - 1; i++)\n {\n int s, t, w;\n cin >> s >> t >> w;\n\n G.at(s).push_back(Edge{t, w});\n G.at(t).push_back(Edge{s, w});\n }\n\n dfs(0, -1);\n dfs_reroot(0, DP{ID, -1}, -1);\n\n int tree_diameter = 0;\n\n for (int i = 0; i < N; i++)\n tree_diameter = max(tree_diameter, ans.at(i).max_dist);\n\n cout << tree_diameter << '\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 32196, "score_of_the_acc": -0.9179, "final_rank": 17 }, { "submission_id": "aoj_GRL_5_A_10962544", "code_snippet": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <list>\n#include <queue>\n\nusing Path = std::pair<int, int>; // 経路。頂点0から頂点番号secondまでの距離はfirst\nusing Edge = std::pair<int, int>; // 辺。ある点から頂点番号firstまでの距離はsecond\nusing Graph = std::vector<std::list<Edge>>;\nstd::vector<int> sssp(const Graph& G, int index) {\n int n = G.size();\n std::vector<int> D(n, -1); // 始点から各頂点までの距離、負数は距離未確定\n\n // 始点からの距離が近い順に、距離・頂点番号ペアを保持する\n std::priority_queue<Path, std::deque<Path>, std::greater<Path>> paths;\n paths.emplace(0, index); // 始点から始点までの距離は0\n\n int count = 0;\n while(paths.empty() == false) {\n // 始点からの最も近い点を得る\n const auto [d, u] = paths.top(); paths.pop();\n // その点へ接続する、接続済みなら飛ばす\n if (D[u] >= 0) continue;\n D[u] = d;\n if (++count == n) break;\n\n // 新たな頂点に隣接する頂点の経路を追加する\n for (const auto& [v, c] : G[u]) {\n if (D[v] >= 0) continue;\n paths.emplace(D[u] + c, v);\n }\n }\n return D;\n}\n\nint main() {\n int n;\n std::cin >> n;\n Graph g(n);\n for (int i = 0; i < n - 1; ++i) {\n int s, t, w;\n std::cin >> s >> t >> w;\n g[s].push_back({t, w});\n g[t].push_back({s, w});\n }\n\n auto d = sssp(g, 0);\n auto m = std::distance(d.begin(), std::max_element(d.begin(), d.end()));\n d = sssp(g, m);\n std::cout << *std::max_element(d.begin(), d.end()) << std::endl;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 12584, "score_of_the_acc": -1.0472, "final_rank": 18 }, { "submission_id": "aoj_GRL_5_A_10960136", "code_snippet": "#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <limits.h>\n#include <map>\n#include <math.h>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n#include <stack>\n#include <complex>\n#include <array>\n#include <cassert>\n#include <random>\n\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < n; i++)\n#define all(A) A.begin(), A.end()\n#define debug(var) cout << #var << \" = \" << var << endl;\ntypedef long long ll;\n\ntemplate <typename T1, typename T2>\nostream &operator<<(ostream &os, const pair<T1, T2> &p)\n{\n os << \"(\" << p.first << \",\" << p.second << \")\";\n return os;\n}\n\ntemplate <typename T1, typename T2>\nistream &operator>>(istream &is, pair<T1, T2> &p)\n{\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v)\n{\n for (int i = 0; i < (int)v.size(); i++)\n {\n os << v[i] << (i + 1 != (int)v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<vector<T>> &v)\n{\n for (int i = 0; i < (int)v.size(); i++)\n {\n os << v[i] << endl;\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<vector<vector<T>>> &v)\n{\n int n = v.size();\n int m = v[0].size();\n int p = v[0][0].size();\n rep(k, p)\n {\n os << \"k = \" << k << endl;\n rep(i, n)\n {\n rep(j, m)\n {\n os << v[i][j][k];\n if (j < m - 1)\n {\n os << \" \";\n }\n else\n {\n os << endl;\n }\n }\n }\n }\n return os;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v)\n{\n for (T &in : v)\n is >> in;\n return is;\n}\n\ntemplate <typename T, typename S>\nostream &operator<<(ostream &os, map<T, S> &mp)\n{\n for (auto &[key, val] : mp)\n {\n os << key << \":\" << val << \" \";\n }\n cout << endl;\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, set<T> st)\n{\n auto itr = st.begin();\n for (int i = 0; i < (int)st.size(); i++)\n {\n os << *itr << (i + 1 != (int)st.size() ? \" \" : \"\");\n itr++;\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, multiset<T> st)\n{\n auto itr = st.begin();\n for (int i = 0; i < (int)st.size(); i++)\n {\n os << *itr << (i + 1 != (int)st.size() ? \" \" : \"\");\n itr++;\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, queue<T> q)\n{\n while (q.size())\n {\n os << q.front() << \" \";\n q.pop();\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, deque<T> q)\n{\n while (q.size())\n {\n os << q.front() << \" \";\n q.pop_front();\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, stack<T> st)\n{\n while (st.size())\n {\n os << st.top() << \" \";\n st.pop();\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, priority_queue<T> pq)\n{\n while (pq.size())\n {\n os << pq.top() << \" \";\n pq.pop();\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, priority_queue<T, vector<T>, greater<T>> mpq)\n{\n while (mpq.size())\n {\n os << mpq.top() << \" \";\n mpq.pop();\n }\n return os;\n}\ntemplate <class E, class V, E (*merge)(E, E), E (*e)(), E (*put_edge)(V, int), V (*put_vertex)(E, int)>\nstruct RerootingDP {\n struct edge {\n int to, idx, xdi;\n };\n RerootingDP(int n_ = 0) : n(n_), inner_edge_id(0) {\n es.resize(2*n-2);\n start.resize(2*n-2);\n if (n == 1) es_build();\n }\n void add_edge(int u, int v, int idx, int xdi){\n start[inner_edge_id] = u;\n es[inner_edge_id] = {v,idx,xdi};\n inner_edge_id++;\n start[inner_edge_id] = v;\n es[inner_edge_id] = {u,xdi,idx};\n inner_edge_id++;\n if (inner_edge_id == 2*n-2){\n es_build();\n }\n }\n vector<V> build(int root_ = 0){\n root = root_;\n vector<V> subdp(n); subdp[0] = put_vertex(e(),0);\n outs.resize(n);\n vector<int> geta(n+1,0);\n for (int i = 0; i < n; i++) geta[i+1] = start[i+1] - start[i] - 1;\n geta[root+1]++;\n for (int i = 0; i < n; i++) geta[i+1] += geta[i];\n auto dfs = [&](auto sfs, int v, int f) -> void {\n E val = e();\n for (int i = start[v]; i < start[v+1]; i++){\n if (es[i].to == f){\n swap(es[start[v+1]-1],es[i]);\n }\n if (es[i].to == f) continue;\n sfs(sfs,es[i].to,v);\n E nval = put_edge(subdp[es[i].to],es[i].idx);\n outs[geta[v]++] = nval;\n val = merge(val,nval);\n }\n subdp[v] = put_vertex(val, v);\n };\n dfs(dfs,root,-1);\n return subdp;\n }\n vector<V> reroot(){\n vector<E> reverse_edge(n);\n reverse_edge[root] = e();\n vector<V> answers(n);\n auto dfs = [&](auto sfs, int v) -> void {\n int le = outs_start(v);\n int ri = outs_start(v+1);\n int siz = ri - le;\n vector<E> rui(siz+1);\n rui[siz] = e();\n for (int i = siz-1; i >= 0; i--){\n rui[i] = merge(outs[le+i],rui[i+1]);\n }\n answers[v] = put_vertex(merge(rui[0],reverse_edge[v]),v);\n E lui = e();\n for (int i = 0; i < siz; i++){\n V rdp = put_vertex(merge(merge(lui,rui[i+1]),reverse_edge[v]),v);\n reverse_edge[es[start[v]+i].to] = put_edge(rdp,es[start[v]+i].xdi);\n lui = merge(lui,outs[le+i]);\n sfs(sfs,es[start[v]+i].to);\n }\n };\n dfs(dfs,root);\n return answers;\n }\n private:\n int n, root, inner_edge_id;\n vector<E> outs;\n vector<edge> es;\n vector<int> start;\n int outs_start(int v){\n int res = start[v] - v;\n if (root < v) res++;\n return res;\n }\n void es_build(){\n vector<edge> nes(2*n-2);\n vector<int> nstart(n+2,0);\n for (int i = 0; i < 2*n-2; i++) nstart[start[i]+2]++;\n for (int i = 0; i < n; i++) nstart[i+1] += nstart[i];\n for (int i = 0; i < 2*n-2; i++) nes[nstart[start[i]+1]++] = es[i];\n swap(es,nes);\n swap(start,nstart);\n }\n};\n\n// mint merge(mint a, mint b){\n// return a * b;\n// }\n// mint e(){\n// return mint(1);\n// }\n// mint put_edge(mint v, int i){\n// return v + 1;\n// }\n// mint put_vertex(mint e, int v){\n// return e;\n// }\n\nint merge(int a,int b){\n return max(a,b);\n}\nint e(){\n return 0;\n}\nint put_edge(int v,int i){\n return v+i;\n}\nint put_vertex(int e,int v){\n return e;\n}\nint main(){\n int n;\n cin >> n;\n RerootingDP<int,int,merge,e,put_edge,put_vertex> dp(n);\n rep(i,n-1){\n int u,v,w;\n cin >> u >> v >> w;\n dp.add_edge(u,v,w,w);\n }\n dp.build();\n int ans = INT_MIN;\n auto chmax = [](auto &a, const auto &b) {\n if(a<b){\n a=b;\n return true;\n }\n return false;\n };\n for(auto p:dp.reroot()){\n // debug(p);\n chmax(ans,p);\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 22412, "score_of_the_acc": -0.5663, "final_rank": 9 }, { "submission_id": "aoj_GRL_5_A_10954870", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(n);i++)\n#define all(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\nusing ll=long long;\nusing pi=pair<ll,int>;\nconst int di[]={+1,-1,+0,+0};\nconst int dj[]={+0,+0,+1,-1};\nconst int INF=1e9;\n//const ll INF=1e18;\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n;\n cin >> n;\n vector<vector<pi>> G(n);\n rep(i, n-1) {\n int s, t;\n ll w;\n cin >> s >> t >> w;\n G[s].push_back({w, t});\n G[t].push_back({w, s});\n }\n vector<ll> dist(n, -1);\n auto dfs=[&](auto dfs, ll w, int v, int p=-1) -> void {\n dist[v]=w;\n for(auto [nw, nv]:G[v]) if(nv!=p) {\n nw+=w;\n dfs(dfs, nw, nv, v);\n }\n };\n dfs(dfs, 0LL, 0);\n ll mx=-1;\n int start=0;\n rep(i, n) {\n if(mx<dist[i]) {\n mx=dist[i];\n start=i;\n }\n }\n dfs(dfs, 0LL, start);\n ll diameter=-1;\n rep(i, n) diameter=max(diameter, dist[i]);\n cout << diameter << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 18384, "score_of_the_acc": -0.1568, "final_rank": 2 }, { "submission_id": "aoj_GRL_5_A_10925301", "code_snippet": "#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\n\nusing Edge = std::pair<int, int>; // 辺:向かう先, 重み\nusing Graph = std::vector<std::list<Edge>>; // 隣接リスト\n\n// x を根とする部分木で葉までの最大と直径を返す\n// x が葉なら [0, 0] を返す\nstd::pair<int, int> dfs(const Graph& g, int x, int parent) {\n int diameter = 0;\n int max = 0; // 葉までの重みの最大\n int sec = 0; // 葉までの重みの2番目\n // xから伸びる辺のうち、子を探す\n for (auto [to, weight] : g[x]) {\n if (to == parent) continue; // 子を探す。親なら無視する\n auto [m, d] = dfs(g, to, x);\n // toを根とする部分木で大きい直径が見つかれば更新する\n diameter = std::max(diameter, d);\n // xからtoまでの重みにtoから葉までの重みを足す\n m += weight;\n // xからtoを辿って葉までの重みが大きいなら更新する\n if (m >= max) {\n sec = max;\n max = m;\n } else if (m > sec) {\n sec = m;\n }\n\n }\n // 子が1つなら、その子を辿って葉までの重みが直径候補\n // 子が2つ以上なら、1番目と2番目の重みの和が直径候補\n diameter = std::max(diameter, max + sec);\n\n return {max, diameter};\n}\nint main() {\n int n;\n std::cin >> n;\n Graph g(n);\n for (int i = 0; i < n - 1; ++i) {\n int s, t, w;\n std::cin >> s >> t >> w;\n g[s].push_back({t, w});\n g[t].push_back({s, w});\n }\n auto [_, d] = dfs(g, 0, 0);\n std::cout << d << std::endl;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 19376, "score_of_the_acc": -0.6756, "final_rank": 14 }, { "submission_id": "aoj_GRL_5_A_10924922", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define pii pair<int, int>\n#define pll pair<ll, ll>\n#define vi vector<int>\n#define vl vector<ll>\n#define ov4(a, b, c, d, name, ...) name\n#define rep3(i, a, b, c) for(ll i = (a); i < (b); i += (c))\n#define rep2(i, a, b) rep3(i, a, b, 1)\n#define rep1(i, n) rep2(i, 0, n)\n#define rep0(n) rep1(aaaaa, n)\n#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)\n#define per(i, a, b) for(ll i = (a)-1; i >= (b); i--)\n#define fore(e, v) for(auto&& e : v)\n#define all(a) begin(a), end(a)\n#define si(a) (int)(size(a))\n#define lb(v, x) (lower_bound(all(v), x) - begin(v))\n#define eb emplace_back\n\ntemplate<typename T, typename S> bool chmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; }\ntemplate<typename T, typename S> bool chmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; }\n\nconst int INF = 1e9 + 100;\nconst ll INFL = 3e18 + 100;\n\n#define i128 __int128_t\n\nstruct _ {\n _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }\n} __;\n\nvi par, dep, dist, q;\nvector<bool> vis;\n\nvoid dfs(vector<vector<pii>> &edges, int i, int b) {\n par[i] = b;\n vis[i] = true;\n q.push_back(i);\n for (auto [j, w] : edges[i]) {\n if (j == b) continue;\n dep[j] = dep[i] + 1;\n dist[j] = dist[i] + w;\n dfs(edges, j, i);\n }\n}\n\nint main() {\n int n;\n cin >> n;\n int m = n - 1;\n vector edges(n, vector<pii>{});\n rep(_, m) {\n int a, b, w;\n cin >> a >> b >> w;\n edges[a].push_back({b, w});\n edges[b].push_back({a, w});\n }\n\n par.resize(n); dep.resize(n); dist.resize(n); vis.resize(n);\n fill(all(dist), 0);\n fill(all(dep), 0);\n fill(all(vis), false);\n\n int B = 21;\n vector<vi> dub(n, vi(B, -1));\n\n auto up = [&](int i, int d) {\n rep(j, B) {\n if (d & 1) i = dub[i][j];\n d >>= 1;\n }\n return i;\n };\n auto lca = [&](int i, int j) {\n if (dep[i] < dep[j]) swap(i, j);\n i = up(i, dep[i] - dep[j]);\n if (i == j) return i;\n per(k, B, 0) if (dub[i][k] != dub[j][k]) {\n i = dub[i][k]; j = dub[j][k];\n }\n return par[i];\n };\n auto dis = [&](int i, int j) {\n int l = lca(i, j);\n return dist[i] + dist[j] - 2 * dist[l];\n };\n\n vl v{};\n\n rep(i, n) {\n if (vis[i]) continue;\n q.resize(0);\n dfs(edges, i, -1);\n\n fore(j, q) {\n dub[j][0] = par[j];\n }\n rep(j, B - 1) fore(k, q) if (dub[k][j] != -1) {\n dub[k][j + 1] = dub[dub[k][j]][j];\n }\n \n int l = i, mi = i;\n fore(j, q) if (dis(l, mi) < dis(l, j)) mi = j;\n l = mi;\n int r = i;\n fore(j, q) if (dis(l, r) < dis(l, j)) r = j;\n int c = i, mx = INF;\n fore(j, q) if (mx > dis(l, j) + dis(r, j)) c = j, mx = dis(l, j) + dis(r, j);\n v.push_back(mx);\n }\n\n cout << v[0] << endl; \n}", "accuracy": 1, "time_ms": 40, "memory_kb": 30124, "score_of_the_acc": -0.7121, "final_rank": 16 }, { "submission_id": "aoj_GRL_5_A_10886874", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\n\nstruct Edge {\n int to, cost;\n Edge() = default;\n Edge(int to, int cost) : to(to), cost(cost) {}\n};\n\nint n;\nvector<vector<Edge>> to;\n\nvector<int> bfs(int s) {\n queue<int> q;\n vector<bool> visited(n);\n vector<int> length(n);\n int res = -1;\n\n q.push(s);\n visited[s] = true;\n length[s] = 0;\n while (!q.empty()) {\n int x = q.front(); q.pop();\n visited[x] = true;\n for (Edge e : to[x]) {\n if (visited[e.to]) continue;\n length[e.to] = length[x] + e.cost;\n q.push(e.to);\n }\n }\n\n return length;\n}\n\nint main()\n{\n cin >> n;\n to.resize(n);\n rep(i,n-1) {\n int s, t, w;\n cin >> s >> t >> w;\n to[s].emplace_back(t,w);\n to[t].emplace_back(s,w);\n }\n\n vector<int> length = bfs(0);\n int x = -1, y = -1, max = -1;\n rep(i,n) {\n if (length[i] > max) {\n x = i;\n max = length[i];\n }\n }\n\n max = -1;\n length = bfs(x);\n rep(i,n) {\n if (length[i] > max) {\n y = i;\n max = length[i];\n }\n }\n\n cout << length[y] << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 10088, "score_of_the_acc": -0.5, "final_rank": 8 }, { "submission_id": "aoj_GRL_5_A_10867035", "code_snippet": "// # pragma GCC target(\"avx2\")\n// # pragma GCC optimize(\"O3\")\n// # pragma GCC optimize(\"unroll-loops\")\n\n#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\n// #include <boost/multiprecision/cpp_int.hpp>\n// using namespace boost::multiprecision;\n\n#define ll long long\n#define rep(i,n) for(ll i=0;i<(ll)(n);i++)\n#define vi vector<int>\n#define vl vector<ll>\n#define vd vector<double>\n#define vb vector<bool>\n#define vs vector<string>\n#define vc vector<char>\n#define ull unsigned long long\n#define chmax(a,b) a=max(a,b)\n#define chmin(a,b) a=min(a,b)\n\n\n\nll inf=(1ll<<60);\n// const double PI=3.1415926535897932384626433832795028841971;\n\n\n// ll rui(ll a,ll b){\n// if(b==0)return 1;\n// if(b%2==1) return a*rui(a*a,b/2);\n// return rui(a*a,b/2);\n// }\n\n// ll kai(ll n){\n// if(n==0)return 1;\n// return n*kai(n-1);\n// }\n\n// using mint = modint998244353;//static_modint<998244353>\n// using mint = modint1000000007;//static_modint<1000000007>\n// using mint = modint;//mint::set_mod(mod);\n\n\n// ll const mod=1000000007ll;\n// ll const mod=998244353ll;\n// ll modrui(ll a,ll b,ll mod){\n// a%=mod;\n// if(b==0)return 1;\n// if(b%2==1) return a*modrui(a*a%mod,b/2,mod)%mod;\n// return modrui(a*a%mod,b/2,mod)%mod;\n// }\n\n// ll inv(ll x){\n// x%=mod;\n// return modrui(x,mod-2);\n// }\n\n// ll modkai(ll n){\n// ll ret=1;\n// rep(i,n){\n// ret*=(i+1)%mod;\n// ret%=mod;\n// }\n// return ret;\n// }\n\n\n// void incr(vl &v,ll n){// n進法\n// ll k=v.size();\n// v[k-1]++;\n// ll now=k-1;\n// while (v[now]>=n)\n// {\n// v[now]=0;\n// if(now==0)break;\n// v[now-1]++;\n// now--;\n// }\n// return;\n// }\n\n\n\nvl dist(1<<17);\nll ans=0;\n\nvoid dfs(vector<vector<vl>> const&g,ll x,ll p){\n for(auto &to:g[x]){\n if(to[0]==p)continue;\n dfs(g,to[0],x);\n chmax(dist[x],dist[to[0]]+to[1]);\n }\n}\n\nvoid dfs2(vector<vector<vl>> const&g,ll x,ll p,ll dp){\n vector<vl> d={{0,-1},{0,-2}};\n for(auto &to:g[x]){\n if(to[0]==p){\n d.push_back({dp+to[1],p});\n }\n else{\n d.push_back({dist[to[0]]+to[1],to[0]});\n }\n }\n sort(d.begin(),d.end());\n reverse(d.begin(),d.end());\n chmax(ans,d[0][0]+d[1][0]);\n for(auto &to:g[x]){\n if(to[0]==p)continue;\n if(d[0][1]!=to[0])dfs2(g,to[0],x,d[0][0]);\n else dfs2(g,to[0],x,d[1][0]);\n }\n}\n\n\n\nvoid solve(){\n ll n;\n cin >> n;\n vector<vector<vl>> g(n);\n rep(i,n-1){\n ll u,v,w;\n cin >> u >> v >> w;\n g[u].push_back({v,w});\n g[v].push_back({u,w});\n }\n dfs(g,0,-1);\n dfs2(g,0,-1,-1);\n\n \n cout << ans << endl;\n}\n\nint main(){\n ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n ll t=1;\n // cin >> t;\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 62988, "score_of_the_acc": -1.3333, "final_rank": 20 } ]
aoj_GRL_5_B_cpp
Height of a Tree Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Input n s 1 t 1 w 1 s 2 t 2 w 2 : s n-1 t n-1 w n-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n -1 respectively. In the following n -1 lines, edges of the tree are given. s i and t i represent end-points of the i -th edge (undirected) and w i represents the weight (distance) of the i -th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Constraints 1 ≤ n ≤ 10,000 0 ≤ w i ≤ 1,000 Sample Input 1 4 0 1 2 1 2 1 1 3 3 Sample Output 1 5 3 4 5
[ { "submission_id": "aoj_GRL_5_B_10853207", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cstring>\n\n#define MAXN 10000\n\nusing namespace std;\n\nstruct edge{\n\tint nn;\n\tint w;\n\tedge(int a, int b){nn = a; w = b;}\n};\n\nvector<edge> node[MAXN];\n\nint maxdist[MAXN];\nint visited[MAXN];\n\nvoid DFS(int idx, int w){\n\tvisited[idx] = 1;\n\tif(w > maxdist[idx]) maxdist[idx] = w;\n\t\n\tfor(int i = 0; i < node[idx].size(); i++){\n\t\tif(visited[node[idx][i].nn]) continue;\n\t\t\n\t\tDFS(node[idx][i].nn, w + node[idx][i].w);\n\t}\n}\n\nint main(){\n\t\n\tint n;\n\tint x, y, z;\n\t\n\tcin >> n;\n\t\n\tfor(int i = 0; i < n - 1; i++){\n\t\tcin >> x >> y >> z;\n\t\t\n\t\tnode[x].push_back(edge(y,z));\n\t\tnode[y].push_back(edge(x,z));\n\t}\n\t\n\tfor(int i = 0; i < n; i++){\n\t\tif(node[i].size() != 1) continue;\n\t\tmemset(visited, 0, sizeof(visited));\n\t\tDFS(i, 0);\n\t}\n\t\n\tfor(int i = 0; i < n; i++) cout << maxdist[i] << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 780, "memory_kb": 4288, "score_of_the_acc": -1.0351, "final_rank": 20 }, { "submission_id": "aoj_GRL_5_B_10547242", "code_snippet": "#include <bits/stdc++.h>\n#define INF 0x7fffffff\n#define MAXN 200010\ntypedef long long LL;\nusing namespace std;\n\nstruct node\n{\n\tint v, w;\t\n};\n\nint n, m;\nvector <node> g[MAXN];\nint dp[MAXN], ans[MAXN];\n\nvoid treeDepth(int u, int parent)\n{\n\tdp[u] = 0;\n\tfor(int x = 0; x < g[u].size(); x++)\n\t{\n\t\tint v = g[u][x].v, w = g[u][x].w;\n\t\tif(v == parent) continue;\n\t\ttreeDepth(v, u);\n\t\tdp[u] = max(dp[u], dp[v] + w);\n\t}\n}\n\nvoid changeRoot(int u, int parent, int up)\n{\n\tvector <int> pre, suf;\n\tfor(int x = 0; x < g[u].size(); x++)\n\t{\n\t\tint v = g[u][x].v, w = g[u][x].w;\n\t\tif(v == parent) pre.push_back(up);\n\t\telse pre.push_back(dp[v] + w);\n\t}\n\tsuf = pre;\n\tfor(int x = 1; x < g[u].size(); x++) pre[x] = max(pre[x], pre[x-1]);\n\tfor(int x = g[u].size() - 2; x >= 0; x--) suf[x] = max(suf[x], suf[x+1]);\n\tans[u] = max(dp[u], up);\n\tfor(int x = 0; x < g[u].size(); x++)\n\t{\n\t\tint v = g[u][x].v, w = g[u][x].w;\n\t\tif(v == parent) continue;\n\t\tint left = (x == 0 ? -INF : pre[x-1]);\n\t\tint right = (x == g[u].size()-1 ? -INF : suf[x+1]);\n\t\tint newUp = max(up, max(left, right)) + w;\n\t\tchangeRoot(v, u, newUp);\n\t}\n}\n\nvoid treeHeight()\n{\n\ttreeDepth(0, -1);\n\tchangeRoot(0, -1, 0);\n}\n\nint main()\n{\n\tcin >> n;\n\tm = n - 1;\n\tfor(int x = 1; x <= m; x++)\n\t{\n\t\tint u, v, w;\n\t\tcin >> u >> v >> w;\n\t\tg[u].push_back((node){v, w});\n\t\tg[v].push_back((node){u, w});\n\t}\n\ttreeHeight();\n\tfor(int x = 0; x < n; x++) cout << ans[x] << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10568, "score_of_the_acc": -0.7153, "final_rank": 18 }, { "submission_id": "aoj_GRL_5_B_10447844", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\ntypedef pair<ll, ll> P;\n\nstruct Edge {\n ll to, cost;\n};\n\nconst ll INF = 8e18;\nvector<ll> dijkstra(ll n, vector<vector<Edge>>& graph, ll start) {\n vector<ll> dist(n,INF);\n priority_queue<P, vector<P>, greater<P>> que;\n dist[start] = 0;\n que.push({0,start});\n\n while (!que.empty()) {\n ll current_dist = que.top().first;\n ll pos = que.top().second;\n que.pop();\n\n if (current_dist > dist[pos]) continue;\n\n for (auto edge : graph[pos]) {\n ll nex = edge.to;\n ll cost = edge.cost;\n\n if (dist[nex] > dist[pos]+cost) {\n dist[nex] = dist[pos] + cost;\n que.push({dist[nex], nex});\n }\n }\n }\n return dist;\n}\n\nint main() {\n ll n; cin >> n;\n vector<vector<Edge>> graph(n);\n for (ll i = 0; i < n-1; i++) {\n ll a, b, w;\n cin >> a >> b >> w;\n graph[a].push_back({b,w});\n graph[b].push_back({a,w});\n }\n\n vector<ll> a = dijkstra(n, graph, 0);\n ll num1 = 0;\n ll A_index = 0;\n for (int i = 0; i < n; i++) {\n if (num1 < a[i]) {\n num1 = a[i];\n A_index = i;\n }\n }\n\n vector<ll> b = dijkstra(n, graph, A_index);\n ll num2 = 0;\n ll B_index = 0;\n for (int i = 0; i < n; i++) {\n if (num2 < b[i]) {\n num2 = b[i];\n B_index = i;\n }\n }\n\n vector<ll> distA = b;\n vector<ll> distB = dijkstra(n, graph, B_index);\n\n for (int i = 0; i < n; i++) {\n ll ans = max(distA[i], distB[i]);\n cout << ans << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4504, "score_of_the_acc": -0.0585, "final_rank": 9 }, { "submission_id": "aoj_GRL_5_B_9912685", "code_snippet": "// aizu_GRL_5_B_HeightTree_a.cc\n// \n\n#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\nusing namespace std;\n#define rep(i,n) for (int i=0;i<(n);i++)\n\nvoid bfs(int s, vector<vector<pair<int,int>>> &graph,vector<int> &height){\n queue<pair<int,int>> que;\n que.push(make_pair(s,-1));\n while ( que.size()!= 0){\n auto q = que.front();\n que.pop();\n int now =q.first;\n int par = q.second;\n for ( auto t : graph[now]){\n if (t.first == par )continue;\n height[t.first] =height[now] +t.second;\n que.push(make_pair(t.first,now));\n }\n }\n}\n\nint main(){\n int n;\n cin >> n;\n vector<vector<pair<int,int>>> graph(n);\n\n rep(i,n-1) {\n int s,t,w;\n cin >> s >> t >> w;\n graph[s].emplace_back(t,w);\n graph[t].emplace_back(s,w);\n }\n vector<int>height0(n),height1(n);\n bfs(0,graph,height0);\n auto iterator = max_element(height0.begin(), height0.end());\n int index0 = distance(height0.begin(), iterator);\n\n rep(i,n) height0[i] = 0;\n bfs(index0,graph,height0); \n auto iterator1 = max_element(height0.begin(), height0.end());\n int index1 = distance(height0.begin(), iterator1);\n\n bfs(index1,graph,height1); \n rep(i,n){\n cout << max(height0[i], height1[i]) << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3964, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_GRL_5_B_9756110", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <queue>\nusing namespace std;\ntypedef long long ll;\n// const ll INF64 = 1LL << 60;\nconst ll INF64 = ((1LL<<62)-(1LL<<31)); // 10^18より大きく、かつ2倍しても負にならない数\nconst int INF32 = 0x3FFFFFFF; // =(2^30)-1 10^9より大きく、かつ2倍しても負にならない数\ntemplate<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; }\n#define YesNo(T) cout << ((T) ? \"Yes\" : \"No\") << endl; // T:bool\n\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_B\n\n/*\n * 木の直径をs-tとすると、\n * 各頂点iについて i-s もしくは i-t が最も遠い点となる。\n */\n\n// 頂点を結ぶ辺\nstruct Edge\n{\n\tint to; // 隣接頂点番号\n\tll weight; // 辺の重み\n\tEdge(int to_, ll weight_) : to(to_), weight(weight_) {}\n};\nusing Graph = vector<vector<Edge>>;\n\n// 頂点sから最も遠い頂点を返す BFS使用\nint mostfar(Graph &G, int s, vector<int> &dist)\n{\n\tqueue<int> que;\n\tdist[s] = 0;\n\tque.push(s);\n\n\twhile(!que.empty())\n\t{\n\t\tint v = que.front();\n\t\tque.pop();\n\t\tfor(auto &e : G[v])\n\t\t{\n\t\t\tif(dist[e.to] != INF32) continue;\n\t\t\tdist[e.to] = dist[v] + e.weight;\n\t\t\tque.push(e.to);\n\t\t}\n\t}\n\tint idx = max_element(dist.begin(), dist.end()) - dist.begin();\n\treturn idx;\n}\n\nint main(void)\n{\n\tint i;\n\tint N; cin >> N;\n\tGraph g(N);\n\tfor(i = 0; i < N-1; i++)\n\t{\n\t\tint s, t, w; cin >> s >> t >> w;\n\t\tg[s].push_back({t, w});\n\t\tg[t].push_back({s, w});\n\t}\n\tvector<int> dist_0(N, INF32), dist_s(N, INF32), dist_t(N, INF32);\n\tint s = mostfar(g, 0, dist_0);\n\tint t = mostfar(g, s, dist_s);\n\tmostfar(g, t, dist_t);\n\tfor(i = 0; i < N; i++)\n\t{\n\t\tcout << max(dist_s[i], dist_t[i]) << endl;\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4188, "score_of_the_acc": -0.0243, "final_rank": 4 }, { "submission_id": "aoj_GRL_5_B_9756098", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <queue>\nusing namespace std;\ntypedef long long ll;\n// const ll INF64 = 1LL << 60;\nconst ll INF64 = ((1LL<<62)-(1LL<<31)); // 10^18より大きく、かつ2倍しても負にならない数\nconst int INF32 = 0x3FFFFFFF; // =(2^30)-1 10^9より大きく、かつ2倍しても負にならない数\ntemplate<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; }\n#define YesNo(T) cout << ((T) ? \"Yes\" : \"No\") << endl; // T:bool\n\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_B\n\n/*\n * \n * \n * \n */\n\n// 頂点を結ぶ辺\nstruct Edge\n{\n\tint to; // 隣接頂点番号\n\tll weight; // 辺の重み\n\tEdge(int to_, ll weight_) : to(to_), weight(weight_) {}\n};\nusing Graph = vector<vector<Edge>>;\n\n// 頂点sから最も遠い頂点を返す BFS使用\nint mostfar(Graph &G, int s, vector<int> &dist)\n{\n\tqueue<int> que;\n\tdist[s] = 0;\n\tque.push(s);\n\n\twhile(!que.empty())\n\t{\n\t\tint v = que.front();\n\t\tque.pop();\n\t\tfor(auto &e : G[v])\n\t\t{\n\t\t\tif(dist[e.to] != INF32) continue;\n\t\t\tdist[e.to] = dist[v] + e.weight;\n\t\t\tque.push(e.to);\n\t\t}\n\t}\n\tint idx = max_element(dist.begin(), dist.end()) - dist.begin();\n\t/*\n\tint idx = -1, mx = -1;\n\tfor(int i = 0; i < (int)dist.size(); i++)\n\t{\n\t\tif(chmax(mx, dist[i])) idx = i;\n\t}\n\t*/\n\treturn idx;\n}\n\nint main(void)\n{\n\tint i;\n\tint N; cin >> N;\n\tGraph g(N);\n\tfor(i = 0; i < N-1; i++)\n\t{\n\t\tint s, t, w; cin >> s >> t >> w;\n\t\tg[s].push_back({t, w});\n\t\tg[t].push_back({s, w});\n\t}\n\tvector<int> dist_0(N, INF32), dist_s(N, INF32), dist_t(N, INF32);\n\tint s = mostfar(g, 0, dist_0);\n\tint t = mostfar(g, s, dist_s);\n\tmostfar(g, t, dist_t);\n\tfor(i = 0; i < N; i++)\n\t{\n\t\tcout << max(dist_s[i], dist_t[i]) << endl;\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4132, "score_of_the_acc": -0.0182, "final_rank": 3 }, { "submission_id": "aoj_GRL_5_B_9657609", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int N;cin>>N;\n vector<vector<pair<int,int>>>E(N);\n for(int i=0;i<N-1;i++){\n int s,t,w;cin>>s>>t>>w;\n E[s].emplace_back(make_pair(t,w));\n E[t].emplace_back(make_pair(s,w));\n }\n vector<int>D(N,1000000000);\n D[0]=0;\n function<void(int)>dfs=[&](int v){\n for(auto[u,w]:E[v])if(D[u]>D[v]+w){\n D[u]=D[v]+w;\n dfs(u);\n }\n };\n dfs(0);\n int a=max_element(D.begin(),D.end())-D.begin();\n fill(D.begin(),D.end(),1000000000);\n D[a]=0;\n dfs(a);\n auto D0=D;\n int b=max_element(D.begin(),D.end())-D.begin();\n fill(D.begin(),D.end(),1000000000);\n D[b]=0;\n dfs(b);\n for(int i=0;i<N;i++)cout<<max(D[i],D0[i])<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4444, "score_of_the_acc": -0.052, "final_rank": 8 }, { "submission_id": "aoj_GRL_5_B_9605674", "code_snippet": "#line 1 \"verify/AOJ-GRL-5-B.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/5/GRL_5_B\"\n\n#line 2 \"Library/Template.hpp\"\n\n/**\n * @file Template.hpp\n * @author log K (lX57)\n * @brief Template - テンプレート\n * @version 1.8\n * @date 2024-06-16\n */\n\n#line 2 \"Library/Common.hpp\"\n\n/**\n * @file Common.hpp\n */\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\nusing namespace std;\n#line 12 \"Library/Template.hpp\"\n#define ALL(x) (x).begin(), (x).end()\n#define RALL(x) (x).rbegin(), (x).rend()\n#define SORT(x) sort(ALL(x))\n#define RSORT(x) sort(RALL(x))\n#define REVERSE(x) reverse(ALL(x))\n#define SETPRE(digit) fixed << setprecision(digit)\n#define POPCOUNT(x) __builtin_popcount(x)\n#define SUM(x) reduce((x).begin(), (x).end())\n#define CEIL(nume, deno) ((nume) + (deno) - 1) / (deno)\n#define IOTA(x) iota((x).begin(), (x).end(), 0)\n#define LOWERBOUND_IDX(arr, val) distance((arr).begin(), lower_bound((arr).begin(), (arr).end(), val))\n#define UPPERBOUND_IDX(arr, val) distance((arr).begin(), upper_bound((arr).begin(), (arr).end(), val))\n\ninline string Yn(bool flag){return (flag) ? \"Yes\" : \"No\";}\ninline bool YnPrint(bool flag){cout << Yn(flag) << endl;return flag;}\ninline string YN(bool flag){return (flag) ? \"YES\" : \"NO\";}\ninline bool YNPrint(bool flag){cout << YN(flag) << endl;return flag;}\ntemplate<class T>\nbool chmin(T &src, const T &cmp){if(src > cmp){src = cmp; return true;}return false;}\ntemplate<class T>\nbool chmax(T &src, const T &cmp){if(src < cmp){src = cmp; return true;}return false;}\ntemplate<typename T>\ninline bool between(T min, T x, T max){return min <= x && x <= max;}\ntemplate<typename T>\ninline bool ingrid(T y, T x, T ymax, T xmax){return between(0, y, ymax - 1) && between(0, x, xmax - 1);}\ntemplate<typename T>\ninline T median(T a, T b, T c){return between(b, a, c) || between(c, a, b) ? a : (between(a, b, c) || between(c, b, a) ? b : c);}\ntemplate<typename T>\ninline T except(T src, T cond, T excp){return (src == cond ? excp : src);}\ntemplate<typename T>\ninline T min(vector<T> &v){return *min_element((v).begin(), (v).end());}\ntemplate<typename T>\ninline T max(vector<T> &v){return *max_element((v).begin(), (v).end());}\nvector<int> make_sequence(int Size){\n vector<int> ret(Size);\n IOTA(ret);\n return ret;\n}\ntemplate<typename T>\nvoid make_unique(vector<T> &v){\n sort(v.begin(), v.end());\n auto itr = unique(v.begin(), v.end());\n v.erase(itr, v.end());\n}\n\nusing ll = int64_t;\nusing ull = uint64_t;\nusing ld = long double;\n\nconst int INF_INT = numeric_limits<int>::max() >> 2;\nconst ll INF_LL = numeric_limits<ll>::max() >> 2;\n\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\nusing vs = vector<string>;\ntemplate <typename T>\nusing pq = priority_queue<T>;\ntemplate <typename T>\nusing rpq = priority_queue<T, vector<T>, greater<T>>;\n\nconst int dx4[4] = {1, 0, -1, 0};\nconst int dy4[4] = {0, -1, 0, 1};\nconst int dx8[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst int dy8[8] = {0, -1, -1, -1, 0, 1, 1, 1};\n\nvector<pair<int, int>> adjacent(int current_y, int current_x, int max_y, int max_x, bool dir_8 = false){\n vector<pair<int, int>> ret;\n for(int d = 0; d < 4 * (1 + dir_8); ++d){\n int next_y = current_y + (dir_8 ? dy8[d] : dy4[d]);\n int next_x = current_x + (dir_8 ? dx8[d] : dx4[d]);\n if(0 <= next_y and next_y < max_y and 0 <= next_x and next_x < max_x){\n ret.emplace_back(next_y, next_x);\n }\n }\n return ret;\n}\n\ntemplate <typename T1, typename T2>\nostream &operator<<(ostream &os, const pair<T1, T2> &p){\n os << p.first << \" \" << p.second;\n return os;\n}\n\ntemplate <typename T1, typename T2>\nistream &operator>>(istream &is, pair<T1, T2> &p){\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<T> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<vector<T>> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \"\\n\" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v){\n for (int i = 0; i < v.size(); ++i) is >> v[i];\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, set<T> &v){\n for (auto &u : v){\n os << u << \" \";\n }\n return os;\n}\n\ntemplate<typename T1, typename T2>\nvector<pair<T1, T2>> AssembleVectorPair(vector<T1> &v1, vector<T2> &v2){\n assert(v1.size() == v2.size());\n vector<pair<T1, T2>> v;\n for(int i = 0; i < v1.size(); ++i) v.push_back({v1[i], v2[i]});\n return v;\n}\n\ntemplate<typename T1, typename T2>\npair<vector<T1>, vector<T2>> DisassembleVectorPair(vector<pair<T1, T2>> &v){\n vector<T1> v1;\n vector<T2> v2;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return p.first;});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return p.second;});\n return {v1, v2};\n}\n\ntemplate<typename T1, typename T2, typename T3>\ntuple<vector<T1>, vector<T2>, vector<T3>> DisassembleVectorTuple(vector<tuple<T1, T2, T3>> &v){\n vector<T1> v1;\n vector<T2> v2;\n vector<T3> v3;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return get<0>(p);});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return get<1>(p);});\n transform(v.begin(), v.end(), back_inserter(v3), [](auto p){return get<2>(p);});\n return {v1, v2, v3};\n}\n\ntemplate<typename T1 = int, typename T2 = T1>\npair<vector<T1>, vector<T2>> InputVectorPair(int size){\n vector<pair<T1, T2>> v(size);\n for(auto &[p, q] : v) cin >> p >> q;\n return DisassembleVectorPair(v);\n}\n\ntemplate<typename T1 = int, typename T2 = T1, typename T3 = T1>\ntuple<vector<T1>, vector<T2>, vector<T3>> InputVectorTuple(int size){\n vector<tuple<T1, T2, T3>> v(size);\n for(auto &[p, q, r] : v) cin >> p >> q >> r;\n return DisassembleVectorTuple(v);\n}\n\n#ifdef LOGK\n#define DEBUG(fmt, ...) fprintf(stderr, fmt __VA_OPT__(,) __VA_ARGS__)\n#define VARIABLE(var) cerr << \"# \" << #var << \" = \" << var << endl;\n#else\n#define DEBUG(...) 42\n#define VARIABLE(...) 42\n#endif\n\n// ==============================================================\n// \n// Main Program Start\n// \n// ==============================================================\n#line 1 \"Library/Tree/RerootingDP.hpp\"\n/**\n * @file RerootingDP.hpp\n * @author your name ([email protected])\n * @brief \n * @version 0.1\n * @date 2024-09-03\n * \n * @copyright Copyright (c) 2024\n * \n */\n\n#line 2 \"Library/Tree/Tree.hpp\"\n\n/**\n * @file Tree.hpp\n * @brief Tree - 木テンプレート\n * @version 0.1\n * @date 2024-07-29\n */\n\n#line 11 \"Library/Tree/Tree.hpp\"\n\nusing Vertex = int;\n\ntemplate<typename CostType = int32_t>\nclass RootedTree{\n public:\n struct Node{\n Node(Vertex parent = -1) : parent(parent){}\n\n Vertex parent{-1};\n CostType cost{};\n vector<Vertex> children{};\n };\n\n /**\n * @brief 頂点 `root_vertex` を根とする頂点数 `vertex_size` の根付き木を構築する。\n * @note 根が入力で与えられなれないが後で分かる、みたいな状況の時は `root_vertex = -1` とするとよい\n * @param vertex_size 頂点数\n * @param root_vertex 根とする頂点 (default = 0)\n */\n RootedTree(int vertex_size, Vertex root_vertex = 0) :\n vertex_size_(vertex_size), root_vertex_(root_vertex),\n node_(vertex_size){}\n\n /**\n * @brief 木の頂点数を返す。\n * @return int 木の頂点数\n */\n int get_vertex_size() const {\n return vertex_size_;\n }\n\n /**\n * @brief 木の根の頂点を返す。\n * @return Vertex 木の根の頂点番号 (0-index)\n */\n Vertex get_root() const {\n return root_vertex_;\n }\n\n /**\n * @brief 頂点 `v` の親の頂点番号を返す。\n * @note `v` が根の場合、`-1` が返される。\n * @param v 子の頂点番号 (0-index)\n * @return Vertex 親の頂点番号 (0-index)\n */\n Vertex get_parent(Vertex v) const {\n Validate(v);\n return node_[v].parent;\n }\n\n /**\n * @brief 頂点 `v` の子の頂点番号列を返す。\n * @note 頂点番号列は入力順に返される。\n * @param v 親の頂点番号 (0-index)\n * @return vector<Vertex> 子の頂点番号列 (0-index)\n */\n vector<Vertex> &get_child(Vertex v){\n Validate(v);\n return node_[v].children;\n }\n\n /**\n * @brief 頂点 `v` とその親を結ぶ辺の重みを返す。\n * @attention `v` が根の場合の返り値は未定義である。\n * @param v 頂点番号 (0-index)\n * @return CostType 辺の重み\n */\n CostType get_cost(Vertex v){\n Validate(v);\n return node_[v].cost;\n }\n\n /**\n * @brief 頂点 `parent` から頂点 `child` への重さ `cost` の辺を張る。\n * @note `cost` を省略することで重みなし辺を張ることができる。\n * @param parent 親の頂点番号 (0-index)\n * @param child 子の頂点番号 (0-index)\n * @param cost 辺の重み (default = 1)\n */\n void AddEdge(Vertex parent, Vertex child, CostType cost = 1){\n Validate(parent);\n Validate(child);\n node_[parent].children.push_back(child);\n node_[child].parent = parent;\n node_[child].cost = cost;\n }\n\n /**\n * @brief `u v w` のような入力形式を受け取る。\n * @param weighted 重み付きの木であるか (default = true)\n * @param one_index 入力される頂点番号が 1-index かどうか (default = true)\n */\n void InputGraphFormat(bool weighted = true, bool one_index = true){\n vector<vector<pair<Vertex, CostType>>> graph(vertex_size_);\n for(int i = 0; i < vertex_size_ - 1; ++i){\n int u, v; cin >> u >> v;\n if(one_index) --u, --v;\n CostType w = 1;\n if(weighted) cin >> w;\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n auto rec = [&](auto self, Vertex v, Vertex p) -> void {\n for(auto [u, w] : graph[v]){\n if(u == p) continue;\n AddEdge(v, u, w);\n self(self, u, v);\n }\n };\n rec(rec, root_vertex_, -1);\n }\n\n /**\n * @brief `p_1 p_2 ... p_N` のような入力形式を受け取る。\n * @attention weighted の処理を書いていないので、`weighted` のパラメータに意味はない\n * @param weighted 重み付きの木であるか (default = true)\n * @param one_index 入力される頂点番号が 1-index かどうか (default = true)\n */\n void InputRootedTreeFormat(bool weighted = true, bool one_index = true){\n assert(root_vertex_ == 0);\n for(int i = 1; i < vertex_size_; ++i){\n int p; cin >> p;\n if(one_index) --p;\n AddEdge(p, i);\n }\n }\n\n /**\n * @brief 頂点 `v` が根の頂点か判定する。\n * @param v 判定する頂点番号 (0-index)\n */\n bool RootVertex(Vertex v){\n Validate(v);\n return node_[v].parent == -1;\n }\n \n /**\n * @brief 頂点 `v` が葉の頂点か判定する。\n * @param v 判定する頂点番号 (0-index)\n */\n bool LeafVertex(Vertex v){\n Validate(v);\n return node_[v].children.empty();\n }\n\n /**\n * @brief 木の根の頂点を求める。\n * @attention 基本的には不要で、根の頂点番号が与えられていない場合に用いる。\n * @note Verify : https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/7/ALDS1_7_A\n * @return Vertex 根の頂点番号\n */\n Vertex FindRoot(){\n for(int i = 0; i < vertex_size_; ++i){\n if(RootVertex(i)){\n root_vertex_ = i;\n return i;\n }\n }\n assert(false);\n }\n\n /**\n * @brief 木の根を変更して再構築する。\n * @param root 新しい根の頂点番号 (0-index)\n */\n void Rerooting(Vertex root){\n if(root == root_vertex_) return;\n vector<Node> new_node_(vertex_size_);\n auto rec = [&](auto self, Vertex v, Vertex p, CostType c) -> void {\n new_node_[v].parent = p;\n new_node_[v].cost = c;\n if(node_[v].parent != p && node_[v].parent != -1){\n new_node_[v].children.push_back(node_[v].parent);\n self(self, node_[v].parent, v, node_[v].cost);\n }\n for(Vertex u : node_[v].children){\n if(u != p){\n new_node_[v].children.push_back(u);\n self(self, u, v, node_[u].cost);\n }\n }\n };\n rec(rec, root, -1, 0);\n swap(new_node_, node_);\n root_vertex_ = root;\n }\n\n void Print(bool one_index = true) const {\n for(int i = 0; i < vertex_size_; ++i){\n // fprintf(stderr, \"# Vertex %d : parent = %d (cost = %d), children = [\", i + int(one_index), get_parent(i) + int(one_index), node_[i].cost);\n fprintf(stderr, \"# Vertex %d : parent = %d (cost = \", i + int(one_index), get_parent(i) + int(one_index));\n cerr << node_[i].cost;\n fprintf(stderr, \"), children = [\");\n for(int j = 0; j < node_[i].children.size(); ++j){\n fprintf(stderr, \"%d\", node_[i].children[j]);\n if(j + 1 < node_[i].children.size()){\n fprintf(stderr, \", \");\n }\n }\n fprintf(stderr, \"]\\n\");\n }\n }\n\n private:\n inline void Validate(Vertex v) const {\n assert(0 <= v && v < vertex_size_);\n }\n\n int vertex_size_, root_vertex_{-1};\n vector<Node> node_;\n};\n\n/**\n * @brief 木 `tree` の各頂点の深さを求める。\n * @note 根の頂点は深さ 0 である。\n * @note Verify : https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/7/ALDS1_7_A\n * @param tree 木\n * @param root 根の頂点番号 (default = 0)\n * @return vector<int> 各頂点の深さ\n */\ntemplate<typename CostType>\nvector<int> CalculateTreeDepth(RootedTree<CostType> &tree){\n int V = tree.get_vertex_size();\n vector<int> ret(V, 0);\n auto rec = [&](auto self, Vertex v, int d) -> void {\n ret[v] = d;\n for(Vertex u : tree.get_child(v)){\n self(self, u, d + 1);\n }\n };\n Vertex root = tree.get_root();\n if(root < 0) root = tree.FindRoot();\n rec(rec, root, 0);\n return ret;\n}\n\n/**\n * @brief 木の根から各頂点への辺の重みの累積和を計算する。\n * @param tree 木\n * @return vector<CostType> 根から各頂点への重みの累積和\n */\ntemplate<typename CostType>\nvector<CostType> CalculateTreeCumlativeSum(RootedTree<CostType> &tree){\n Vertex root = tree.get_root();\n int V = tree.get_vertex_size();\n vector<CostType> ret(V, 0);\n auto rec = [&](auto self, Vertex v, CostType s) -> void {\n ret[v] = s + tree.get_cost(v);\n for(Vertex u : tree.get_child(v)){\n self(self, u, ret[v]);\n }\n };\n rec(rec, root, 0);\n return ret;\n}\n#line 13 \"Library/Tree/RerootingDP.hpp\"\n\ntemplate<typename CostType, typename Monoid>\nclass RerootingDP{\n public:\n using F = function<Monoid(Monoid, Monoid, Vertex)>;\n using G = function<Monoid(Monoid, CostType, Vertex)>;\n using H = function<Monoid(Monoid, Vertex)>;\n using Fsub = function<Monoid(Monoid, Monoid)>;\n using Gsub = function<Monoid(Monoid, CostType)>;\n\n /**\n * @brief 木 `tree` に対して全方位木DPを行う。(辺属性のみ)\n * @param tree 根付き木\n * @param merge `(Monoid, Monoid) -> Monoid` : `Monoid` 同士に関する二項演算。\n * @param add `(Monoid, CostType) -> Monoid` : `Monoid` と `CostType` に関する二項演算。\n * @param monoid_identity `Monoid` の単位元。\n */\n RerootingDP(RootedTree<CostType> &tree, Fsub merge, Gsub add, const Monoid monoid_identity) :\n tree_(tree), V(tree.get_vertex_size()), merge_sub_(merge), add_sub_(add), id_(monoid_identity){\n merge_ = [&](Monoid x, Monoid y, Vertex i){return merge_sub_(x, y);};\n add_ = [&](Monoid x, CostType y, Vertex i){return add_sub_(x, y);};\n finalize_ = [](Monoid x, Vertex i){return x;};\n solve();\n }\n\n /**\n * @brief 木 `tree` に対して全方位木DPを行う。(頂点属性を含む)\n * @param tree 根付き木\n * @param merge `(Monoid, Monoid, Vertex) -> Monoid` : `Monoid` 同士に関する二項演算。\n * @param add `(Monoid, CostType, Vertex) -> Monoid` : `Monoid` と `CostType` に関する二項演算。\n * @param finalize `(Monoid, Vertex) -> Monoid` : `Monoid` に頂点 `Vertex` が根のときの処理。\n * @param monoid_identity `Monoid` の単位元。\n */\n RerootingDP(RootedTree<CostType> &tree, F merge, G add, H finalize, const Monoid monoid_identity) :\n tree_(tree), V(tree.get_vertex_size()), merge_(merge), add_(add), finalize_(finalize), id_(monoid_identity){\n solve();\n }\n\n /**\n * @brief 全頂点に関するDPの配列を取得する。\n */\n vector<Monoid> &get_all_answer(){\n return dp_;\n }\n\n Monoid operator[](Vertex v){\n return dp_[v];\n }\n\n const Monoid operator[](Vertex v) const {\n return dp_[v];\n }\n\n void Print() const {\n cerr << \"# dp table :\";\n for(int i = 0; i < V; ++i){\n cerr << \" \" << dp_[i];\n }\n cerr << endl;\n cerr << \"# subtree_dp table\" << endl;\n for(int i = 0; i < V; ++i){\n cerr << \"# vertex \" << i << endl;\n cerr << \"# subtree_dp :\";\n for(int j = 0; j < subtree_dp_[i].size(); ++j){\n cerr << \" \" << subtree_dp_[i][j];\n }\n cerr << endl;\n cerr << \"# left_cum :\";\n for(int j = 0; j < left_cum_[i].size(); ++j){\n cerr << \" \" << left_cum_[i][j];\n }\n cerr << endl;\n cerr << \"# right_cum :\";\n for(int j = 0; j < right_cum_[i].size(); ++j){\n cerr << \" \" << right_cum_[i][j];\n }\n cerr << endl;\n }\n }\n\n private:\n RootedTree<CostType> &tree_;\n\n Monoid dfs(Vertex v, bool root = false){\n Monoid ret = id_;\n for(auto u : tree_.get_child(v)){\n Monoid res = dfs(u);\n subtree_dp_[v].push_back(res);\n ret = merge_(ret, res, v);\n }\n if(root) ret = finalize_(ret, v);\n else ret = add_(ret, tree_.get_cost(v), v);\n return ret;\n }\n\n void solve(){\n dp_.resize(V, id_);\n subtree_dp_.resize(V, vector<Monoid>{id_});\n left_cum_.resize(V);\n right_cum_.resize(V);\n Vertex root = tree_.get_root();\n\n dp_[root] = dfs(root, true);\n int root_size = subtree_dp_[root].size();\n left_cum_[root].resize(root_size + 1);\n left_cum_[root].front() = id_;\n for(int i = 1; i < root_size; ++i){\n left_cum_[root][i] = merge_(left_cum_[root][i - 1], subtree_dp_[root][i], root);\n }\n right_cum_[root].resize(root_size + 1);\n right_cum_[root].back() = id_;\n for(int i = root_size - 1; i - 1 >= 0; --i){\n right_cum_[root][i] = merge_(right_cum_[root][i + 1], subtree_dp_[root][i], root);\n }\n\n queue<tuple<int, int, int>> que;\n for(int i = 0; i < tree_.get_child(root).size(); ++i){\n que.push({tree_.get_child(root)[i], root, i + 1});\n }\n while(que.size()){\n auto [v, p, idx] = que.front(); que.pop();\n Monoid ret = id_;\n ret = merge_(ret, left_cum_[p][idx - 1], v);\n ret = merge_(ret, right_cum_[p][idx + 1], v);\n ret = add_(ret, tree_.get_cost(v), p);\n subtree_dp_[v].push_back(ret);\n for(int i = 1; i + 1 < subtree_dp_[v].size(); ++i){\n ret = merge_(ret, subtree_dp_[v][i], v);\n }\n dp_[v] = finalize_(ret, v);\n int c = subtree_dp_[v].size();\n left_cum_[v].resize(c + 1);\n left_cum_[v][0] = id_;\n for(int i = 1; i < c; ++i){\n left_cum_[v][i] = merge_(left_cum_[v][i - 1], subtree_dp_[v][i], v);\n }\n right_cum_[v].resize(c + 1);\n right_cum_[v].back() = id_;\n for(int i = c - 1; i - 1 >= 0; --i){\n right_cum_[v][i] = merge_(right_cum_[v][i + 1], subtree_dp_[v][i], v);\n }\n for(int i = 0; i < tree_.get_child(v).size(); ++i){\n que.push({tree_.get_child(v)[i], v, i + 1});\n }\n }\n }\n \n int V;\n vector<Monoid> dp_;\n vector<vector<Monoid>> subtree_dp_, left_cum_, right_cum_;\n\n const Monoid id_;\n\n F merge_;\n G add_;\n H finalize_;\n const Fsub merge_sub_;\n const Gsub add_sub_;\n};\n#line 5 \"verify/AOJ-GRL-5-B.test.cpp\"\n\nint main(){\n int n; cin >> n;\n RootedTree T(n);\n T.InputGraphFormat(true, false);\n\n RerootingDP<int, int> dp(\n T,\n [](int l, int r){return max(l, r);},\n [](int l, int r){return l + r;},\n 0);\n for(int i = 0; i < n; ++i){\n cout << dp[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6704, "score_of_the_acc": -0.2968, "final_rank": 13 }, { "submission_id": "aoj_GRL_5_B_9605341", "code_snippet": "#line 1 \"verify/AOJ-GRL-5-B.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/5/GRL_5_B\"\n\n#line 2 \"Library/Template.hpp\"\n\n/**\n * @file Template.hpp\n * @author log K (lX57)\n * @brief Template - テンプレート\n * @version 1.8\n * @date 2024-06-16\n */\n\n#line 2 \"Library/Common.hpp\"\n\n/**\n * @file Common.hpp\n */\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\nusing namespace std;\n#line 12 \"Library/Template.hpp\"\n#define ALL(x) (x).begin(), (x).end()\n#define RALL(x) (x).rbegin(), (x).rend()\n#define SORT(x) sort(ALL(x))\n#define RSORT(x) sort(RALL(x))\n#define REVERSE(x) reverse(ALL(x))\n#define SETPRE(digit) fixed << setprecision(digit)\n#define POPCOUNT(x) __builtin_popcount(x)\n#define SUM(x) reduce((x).begin(), (x).end())\n#define CEIL(nume, deno) ((nume) + (deno) - 1) / (deno)\n#define IOTA(x) iota((x).begin(), (x).end(), 0)\n#define LOWERBOUND_IDX(arr, val) distance((arr).begin(), lower_bound((arr).begin(), (arr).end(), val))\n#define UPPERBOUND_IDX(arr, val) distance((arr).begin(), upper_bound((arr).begin(), (arr).end(), val))\n\ninline string Yn(bool flag){return (flag) ? \"Yes\" : \"No\";}\ninline bool YnPrint(bool flag){cout << Yn(flag) << endl;return flag;}\ninline string YN(bool flag){return (flag) ? \"YES\" : \"NO\";}\ninline bool YNPrint(bool flag){cout << YN(flag) << endl;return flag;}\ntemplate<class T>\nbool chmin(T &src, const T &cmp){if(src > cmp){src = cmp; return true;}return false;}\ntemplate<class T>\nbool chmax(T &src, const T &cmp){if(src < cmp){src = cmp; return true;}return false;}\ntemplate<typename T>\ninline bool between(T min, T x, T max){return min <= x && x <= max;}\ntemplate<typename T>\ninline bool ingrid(T y, T x, T ymax, T xmax){return between(0, y, ymax - 1) && between(0, x, xmax - 1);}\ntemplate<typename T>\ninline T median(T a, T b, T c){return between(b, a, c) || between(c, a, b) ? a : (between(a, b, c) || between(c, b, a) ? b : c);}\ntemplate<typename T>\ninline T except(T src, T cond, T excp){return (src == cond ? excp : src);}\ntemplate<typename T>\ninline T min(vector<T> &v){return *min_element((v).begin(), (v).end());}\ntemplate<typename T>\ninline T max(vector<T> &v){return *max_element((v).begin(), (v).end());}\nvector<int> make_sequence(int Size){\n vector<int> ret(Size);\n IOTA(ret);\n return ret;\n}\ntemplate<typename T>\nvoid make_unique(vector<T> &v){\n sort(v.begin(), v.end());\n auto itr = unique(v.begin(), v.end());\n v.erase(itr, v.end());\n}\n\nusing ll = int64_t;\nusing ull = uint64_t;\nusing ld = long double;\n\nconst int INF_INT = numeric_limits<int>::max() >> 2;\nconst ll INF_LL = numeric_limits<ll>::max() >> 2;\n\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\nusing vs = vector<string>;\ntemplate <typename T>\nusing pq = priority_queue<T>;\ntemplate <typename T>\nusing rpq = priority_queue<T, vector<T>, greater<T>>;\n\nconst int dx4[4] = {1, 0, -1, 0};\nconst int dy4[4] = {0, -1, 0, 1};\nconst int dx8[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst int dy8[8] = {0, -1, -1, -1, 0, 1, 1, 1};\n\nvector<pair<int, int>> adjacent(int current_y, int current_x, int max_y, int max_x, bool dir_8 = false){\n vector<pair<int, int>> ret;\n for(int d = 0; d < 4 * (1 + dir_8); ++d){\n int next_y = current_y + (dir_8 ? dy8[d] : dy4[d]);\n int next_x = current_x + (dir_8 ? dx8[d] : dx4[d]);\n if(0 <= next_y and next_y < max_y and 0 <= next_x and next_x < max_x){\n ret.emplace_back(next_y, next_x);\n }\n }\n return ret;\n}\n\ntemplate <typename T1, typename T2>\nostream &operator<<(ostream &os, const pair<T1, T2> &p){\n os << p.first << \" \" << p.second;\n return os;\n}\n\ntemplate <typename T1, typename T2>\nistream &operator>>(istream &is, pair<T1, T2> &p){\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<T> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<vector<T>> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \"\\n\" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v){\n for (int i = 0; i < v.size(); ++i) is >> v[i];\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, set<T> &v){\n for (auto &u : v){\n os << u << \" \";\n }\n return os;\n}\n\ntemplate<typename T1, typename T2>\nvector<pair<T1, T2>> AssembleVectorPair(vector<T1> &v1, vector<T2> &v2){\n assert(v1.size() == v2.size());\n vector<pair<T1, T2>> v;\n for(int i = 0; i < v1.size(); ++i) v.push_back({v1[i], v2[i]});\n return v;\n}\n\ntemplate<typename T1, typename T2>\npair<vector<T1>, vector<T2>> DisassembleVectorPair(vector<pair<T1, T2>> &v){\n vector<T1> v1;\n vector<T2> v2;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return p.first;});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return p.second;});\n return {v1, v2};\n}\n\ntemplate<typename T1, typename T2, typename T3>\ntuple<vector<T1>, vector<T2>, vector<T3>> DisassembleVectorTuple(vector<tuple<T1, T2, T3>> &v){\n vector<T1> v1;\n vector<T2> v2;\n vector<T3> v3;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return get<0>(p);});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return get<1>(p);});\n transform(v.begin(), v.end(), back_inserter(v3), [](auto p){return get<2>(p);});\n return {v1, v2, v3};\n}\n\ntemplate<typename T1 = int, typename T2 = T1>\npair<vector<T1>, vector<T2>> InputVectorPair(int size){\n vector<pair<T1, T2>> v(size);\n for(auto &[p, q] : v) cin >> p >> q;\n return DisassembleVectorPair(v);\n}\n\ntemplate<typename T1 = int, typename T2 = T1, typename T3 = T1>\ntuple<vector<T1>, vector<T2>, vector<T3>> InputVectorTuple(int size){\n vector<tuple<T1, T2, T3>> v(size);\n for(auto &[p, q, r] : v) cin >> p >> q >> r;\n return DisassembleVectorTuple(v);\n}\n\n#ifdef LOGK\n#define DEBUG(fmt, ...) fprintf(stderr, fmt __VA_OPT__(,) __VA_ARGS__)\n#define VARIABLE(var) cerr << \"# \" << #var << \" = \" << var << endl;\n#else\n#define DEBUG(...) 42\n#define VARIABLE(...) 42\n#endif\n\n// ==============================================================\n// \n// Main Program Start\n// \n// ==============================================================\n#line 1 \"Library/Tree/RerootingDP.hpp\"\n/**\n * @file RerootingDP.hpp\n * @author your name ([email protected])\n * @brief \n * @version 0.1\n * @date 2024-09-03\n * \n * @copyright Copyright (c) 2024\n * \n */\n\n#line 2 \"Library/Tree/Tree.hpp\"\n\n/**\n * @file Tree.hpp\n * @brief Tree - 木テンプレート\n * @version 0.1\n * @date 2024-07-29\n */\n\n#line 11 \"Library/Tree/Tree.hpp\"\n\nusing Vertex = int;\n\ntemplate<typename CostType = int32_t>\nclass RootedTree{\n public:\n struct Node{\n Node(Vertex parent = -1) : parent(parent){}\n\n Vertex parent{-1};\n CostType cost{0};\n vector<Vertex> children{};\n };\n\n /**\n * @brief 頂点 `root_vertex` を根とする頂点数 `vertex_size` の根付き木を構築する。\n * @note 根が入力で与えられなれないが後で分かる みたいなよく分からん状況の時は `root_vertex = -1` とするとよい\n * @param vertex_size 頂点数\n * @param root_vertex 根とする頂点 (default = 0)\n */\n RootedTree(int vertex_size, Vertex root_vertex = 0) :\n vertex_size_(vertex_size), root_vertex_(root_vertex),\n node_(vertex_size){}\n\n /**\n * @brief 木の頂点数を返す。\n * @return int 木の頂点数\n */\n int get_vertex_size() const {\n return vertex_size_;\n }\n\n /**\n * @brief 木の根の頂点を返す。\n * @return Vertex 木の根の頂点番号 (0-index)\n */\n Vertex get_root() const {\n return root_vertex_;\n }\n\n /**\n * @brief 頂点 `v` の親の頂点番号を返す。\n * @note `v` が根の場合、`-1` が返される。\n * @param v 子の頂点番号 (0-index)\n * @return Vertex 親の頂点番号 (0-index)\n */\n Vertex get_parent(Vertex v) const {\n Validate(v);\n return node_[v].parent;\n }\n\n /**\n * @brief 頂点 `v` の子の頂点番号列を返す。\n * @note 頂点番号列は入力順に返される。\n * @param v 親の頂点番号 (0-index)\n * @return vector<Vertex> 子の頂点番号列 (0-index)\n */\n vector<Vertex> &get_child(Vertex v){\n Validate(v);\n return node_[v].children;\n }\n\n /**\n * @brief 頂点 `v` とその親を結ぶ辺の重みを返す。\n * @attention `v` が根の場合の返り値は未定義である。\n * @param v 頂点番号 (0-index)\n * @return CostType 辺の重み\n */\n CostType get_cost(Vertex v){\n Validate(v);\n return node_[v].cost;\n }\n\n /**\n * @brief 頂点 `parent` から頂点 `child` への重さ `cost` の辺を張る。\n * @note `cost` を省略することで重みなし辺を張ることができる。\n * @param parent 親の頂点番号 (0-index)\n * @param child 子の頂点番号 (0-index)\n * @param cost 辺の重み (default = 1)\n */\n void AddEdge(Vertex parent, Vertex child, CostType cost = 1){\n Validate(parent);\n Validate(child);\n node_[parent].children.push_back(child);\n node_[child].parent = parent;\n node_[child].cost = cost;\n }\n\n /**\n * @brief `u v w` のような入力形式を受け取る。\n * @param weighted 重み付きの木であるか (default = true)\n * @param one_index 入力される頂点番号が 1-index かどうか (default = true)\n */\n void InputGraphFormat(bool weighted = true, bool one_index = true){\n vector<vector<pair<Vertex, CostType>>> graph(vertex_size_);\n for(int i = 0; i < vertex_size_ - 1; ++i){\n int u, v; cin >> u >> v;\n if(one_index) --u, --v;\n CostType w = 1;\n if(weighted) cin >> w;\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n auto rec = [&](auto self, Vertex v, Vertex p) -> void {\n for(auto [u, w] : graph[v]){\n if(u == p) continue;\n AddEdge(v, u, w);\n self(self, u, v);\n }\n };\n rec(rec, root_vertex_, -1);\n }\n\n /**\n * @brief `p_1 p_2 ... p_N` のような入力形式を受け取る。\n * @attention weighted の処理を書いていないので、`weighted` のパラメータに意味はない\n * @param weighted 重み付きの木であるか (default = true)\n * @param one_index 入力される頂点番号が 1-index かどうか (default = true)\n */\n void InputRootedTreeFormat(bool weighted = true, bool one_index = true){\n assert(root_vertex_ == 0);\n for(int i = 1; i < vertex_size_; ++i){\n int p; cin >> p;\n if(one_index) --p;\n AddEdge(p, i);\n }\n }\n\n /**\n * @brief 頂点 `v` が根の頂点か判定する。\n * @param v 判定する頂点番号 (0-index)\n */\n bool RootVertex(Vertex v){\n Validate(v);\n return node_[v].parent == -1;\n }\n \n /**\n * @brief 頂点 `v` が葉の頂点か判定する。\n * @param v 判定する頂点番号 (0-index)\n */\n bool LeafVertex(Vertex v){\n Validate(v);\n return node_[v].children.empty();\n }\n\n /**\n * @brief 木の根の頂点を求める。\n * @attention 基本的には不要で、根の頂点番号が与えられていない場合に用いる。\n * @note Verify : https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/7/ALDS1_7_A\n * @return Vertex 根の頂点番号\n */\n Vertex FindRoot(){\n for(int i = 0; i < vertex_size_; ++i){\n if(RootVertex(i)){\n root_vertex_ = i;\n return i;\n }\n }\n assert(false);\n }\n\n /**\n * @brief 木の根を変更して再構築する。\n * @param root 新しい根の頂点番号 (0-index)\n */\n void Rerooting(Vertex root){\n if(root == root_vertex_) return;\n vector<Node> new_node_(vertex_size_);\n auto rec = [&](auto self, Vertex v, Vertex p, CostType c) -> void {\n new_node_[v].parent = p;\n new_node_[v].cost = c;\n if(node_[v].parent != p && node_[v].parent != -1){\n new_node_[v].children.push_back(node_[v].parent);\n self(self, node_[v].parent, v, node_[v].cost);\n }\n for(Vertex u : node_[v].children){\n if(u != p){\n new_node_[v].children.push_back(u);\n self(self, u, v, node_[u].cost);\n }\n }\n };\n rec(rec, root, -1, 0);\n swap(new_node_, node_);\n root_vertex_ = root;\n }\n\n void Print(bool one_index = true) const {\n for(int i = 0; i < vertex_size_; ++i){\n fprintf(stderr, \"# Vertex %d : parent = %d (cost = %d), children = [\", i + int(one_index), get_parent(i) + int(one_index), node_[i].cost);\n for(int j = 0; j < node_[i].children.size(); ++j){\n fprintf(stderr, \"%d\", node_[i].children[j]);\n if(j + 1 < node_[i].children.size()){\n fprintf(stderr, \", \");\n }\n }\n fprintf(stderr, \"]\\n\");\n }\n }\n\n private:\n inline void Validate(Vertex v) const {\n assert(0 <= v && v < vertex_size_);\n }\n\n int vertex_size_, root_vertex_{-1};\n vector<Node> node_;\n};\n\n/**\n * @brief 木 `tree` の各頂点の深さを求める。\n * @note 根の頂点は深さ 0 である。\n * @note Verify : https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/7/ALDS1_7_A\n * @param tree 木\n * @param root 根の頂点番号 (default = 0)\n * @return vector<int> 各頂点の深さ\n */\ntemplate<typename CostType>\nvector<int> CalculateTreeDepth(RootedTree<CostType> &tree){\n int V = tree.get_vertex_size();\n vector<int> ret(V, 0);\n auto rec = [&](auto self, Vertex v, int d) -> void {\n ret[v] = d;\n for(Vertex u : tree.get_child(v)){\n self(self, u, d + 1);\n }\n };\n Vertex root = tree.get_root();\n if(root < 0) root = tree.FindRoot();\n rec(rec, root, 0);\n return ret;\n}\n\n/**\n * @brief 木の根から各頂点への辺の重みの累積和を計算する。\n * @param tree 木\n * @return vector<CostType> 根から各頂点への重みの累積和\n */\ntemplate<typename CostType>\nvector<CostType> CalculateTreeCumlativeSum(RootedTree<CostType> &tree){\n Vertex root = tree.get_root();\n int V = tree.get_vertex_size();\n vector<CostType> ret(V, 0);\n auto rec = [&](auto self, Vertex v, CostType s) -> void {\n ret[v] = s + tree.get_cost(v);\n for(Vertex u : tree.get_child(v)){\n self(self, u, ret[v]);\n }\n };\n rec(rec, root, 0);\n return ret;\n}\n#line 13 \"Library/Tree/RerootingDP.hpp\"\n\ntemplate<typename CostType, typename Monoid>\nclass RerootingDP{\n public:\n using F = function<Monoid(Monoid, Monoid)>;\n using G = function<Monoid(Monoid, CostType)>;\n\n RerootingDP(RootedTree<CostType> &tree, F merge, G add, const Monoid monoid_identity) :\n tree_(tree), V(tree.get_vertex_size()), merge_(merge), add_(add), id_(monoid_identity){\n dp_.resize(V, id_);\n subtree_dp_.resize(V, vector<Monoid>{id_});\n left_cum_.resize(V);\n right_cum_.resize(V);\n Vertex root = tree_.get_root();\n\n dp_[root] = dfs(root);\n int root_size = subtree_dp_[root].size();\n left_cum_[root].resize(root_size + 1);\n left_cum_[root].front() = id_;\n for(int i = 1; i < root_size; ++i){\n left_cum_[root][i] = merge_(left_cum_[root][i - 1], subtree_dp_[root][i]);\n }\n right_cum_[root].resize(root_size + 1);\n right_cum_[root].back() = id_;\n for(int i = root_size - 1; i - 1 >= 0; --i){\n right_cum_[root][i] = merge_(right_cum_[root][i + 1], subtree_dp_[root][i]);\n }\n\n queue<tuple<int, int, int>> que;\n for(int i = 0; i < tree_.get_child(root).size(); ++i){\n que.push({tree_.get_child(root)[i], root, i + 1});\n }\n while(que.size()){\n auto [v, p, idx] = que.front(); que.pop();\n int ret = 0;\n ret = merge_(ret, left_cum_[p][idx - 1]);\n ret = merge_(ret, right_cum_[p][idx + 1]);\n ret = add_(ret, tree_.get_cost(v));\n subtree_dp_[v].push_back(ret);\n for(Monoid cval : subtree_dp_[v]){\n ret = merge_(ret, cval);\n }\n dp_[v] = ret;\n int c = subtree_dp_[v].size();\n left_cum_[v].resize(c + 1);\n left_cum_[v][0] = 0;\n for(int i = 1; i < c; ++i){\n left_cum_[v][i] = merge_(left_cum_[v][i - 1], subtree_dp_[v][i]);\n }\n right_cum_[v].resize(c + 1);\n right_cum_[v].back() = 0;\n for(int i = c - 1; i - 1 >= 0; --i){\n right_cum_[v][i] = merge_(right_cum_[v][i + 1], subtree_dp_[v][i]);\n }\n for(int i = 0; i < tree_.get_child(v).size(); ++i){\n que.push({tree_.get_child(v)[i], v, i + 1});\n }\n }\n }\n\n vector<Monoid> &get_all_answer(){\n return dp_;\n }\n\n Monoid operator[](Vertex v){\n return dp_[v];\n }\n\n const Monoid operator[](Vertex v) const {\n return dp_[v];\n }\n\n private:\n RootedTree<CostType> &tree_;\n\n Monoid dfs(Vertex v){\n Monoid ret = id_;\n for(auto u : tree_.get_child(v)){\n Monoid res = dfs(u);\n subtree_dp_[v].push_back(res);\n ret = merge_(ret, res);\n }\n ret = add_(ret, tree_.get_cost(v));\n return ret;\n }\n \n int V;\n vector<Monoid> dp_;\n vector<vector<Monoid>> subtree_dp_, left_cum_, right_cum_;\n\n const Monoid id_;\n\n const F merge_;\n const G add_;\n};\n#line 5 \"verify/AOJ-GRL-5-B.test.cpp\"\n\nint main(){\n int n; cin >> n;\n RootedTree T(n);\n T.InputGraphFormat(true, false);\n\n RerootingDP<int, int> dp(\n T,\n [](int l, int r){return max(l, r);},\n [](int l, int r){return l + r;},\n 0);\n for(int i = 0; i < n; ++i){\n cout << dp[i] << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6576, "score_of_the_acc": -0.2829, "final_rank": 11 }, { "submission_id": "aoj_GRL_5_B_9605204", "code_snippet": "#line 2 \"Library/Template.hpp\"\n\n/**\n * @file Template.hpp\n * @author log K (lX57)\n * @brief Template - テンプレート\n * @version 1.8\n * @date 2024-06-16\n */\n\n#line 2 \"Library/Common.hpp\"\n\n/**\n * @file Common.hpp\n */\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\nusing namespace std;\n#line 12 \"Library/Template.hpp\"\n#define ALL(x) (x).begin(), (x).end()\n#define RALL(x) (x).rbegin(), (x).rend()\n#define SORT(x) sort(ALL(x))\n#define RSORT(x) sort(RALL(x))\n#define REVERSE(x) reverse(ALL(x))\n#define SETPRE(digit) fixed << setprecision(digit)\n#define POPCOUNT(x) __builtin_popcount(x)\n#define SUM(x) reduce((x).begin(), (x).end())\n#define CEIL(nume, deno) ((nume) + (deno) - 1) / (deno)\n#define IOTA(x) iota((x).begin(), (x).end(), 0)\n#define LOWERBOUND_IDX(arr, val) distance((arr).begin(), lower_bound((arr).begin(), (arr).end(), val))\n#define UPPERBOUND_IDX(arr, val) distance((arr).begin(), upper_bound((arr).begin(), (arr).end(), val))\n\ninline string Yn(bool flag){return (flag) ? \"Yes\" : \"No\";}\ninline bool YnPrint(bool flag){cout << Yn(flag) << endl;return flag;}\ninline string YN(bool flag){return (flag) ? \"YES\" : \"NO\";}\ninline bool YNPrint(bool flag){cout << YN(flag) << endl;return flag;}\ntemplate<class T>\nbool chmin(T &src, const T &cmp){if(src > cmp){src = cmp; return true;}return false;}\ntemplate<class T>\nbool chmax(T &src, const T &cmp){if(src < cmp){src = cmp; return true;}return false;}\ntemplate<typename T>\ninline bool between(T min, T x, T max){return min <= x && x <= max;}\ntemplate<typename T>\ninline bool ingrid(T y, T x, T ymax, T xmax){return between(0, y, ymax - 1) && between(0, x, xmax - 1);}\ntemplate<typename T>\ninline T median(T a, T b, T c){return between(b, a, c) || between(c, a, b) ? a : (between(a, b, c) || between(c, b, a) ? b : c);}\ntemplate<typename T>\ninline T except(T src, T cond, T excp){return (src == cond ? excp : src);}\ntemplate<typename T>\ninline T min(vector<T> &v){return *min_element((v).begin(), (v).end());}\ntemplate<typename T>\ninline T max(vector<T> &v){return *max_element((v).begin(), (v).end());}\nvector<int> make_sequence(int Size){\n vector<int> ret(Size);\n IOTA(ret);\n return ret;\n}\ntemplate<typename T>\nvoid make_unique(vector<T> &v){\n sort(v.begin(), v.end());\n auto itr = unique(v.begin(), v.end());\n v.erase(itr, v.end());\n}\n\nusing ll = int64_t;\nusing ull = uint64_t;\nusing ld = long double;\n\nconst int INF_INT = numeric_limits<int>::max() >> 2;\nconst ll INF_LL = numeric_limits<ll>::max() >> 2;\n\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\nusing vs = vector<string>;\ntemplate <typename T>\nusing pq = priority_queue<T>;\ntemplate <typename T>\nusing rpq = priority_queue<T, vector<T>, greater<T>>;\n\nconst int dx4[4] = {1, 0, -1, 0};\nconst int dy4[4] = {0, -1, 0, 1};\nconst int dx8[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst int dy8[8] = {0, -1, -1, -1, 0, 1, 1, 1};\n\nvector<pair<int, int>> adjacent(int current_y, int current_x, int max_y, int max_x, bool dir_8 = false){\n vector<pair<int, int>> ret;\n for(int d = 0; d < 4 * (1 + dir_8); ++d){\n int next_y = current_y + (dir_8 ? dy8[d] : dy4[d]);\n int next_x = current_x + (dir_8 ? dx8[d] : dx4[d]);\n if(0 <= next_y and next_y < max_y and 0 <= next_x and next_x < max_x){\n ret.emplace_back(next_y, next_x);\n }\n }\n return ret;\n}\n\ntemplate <typename T1, typename T2>\nostream &operator<<(ostream &os, const pair<T1, T2> &p){\n os << p.first << \" \" << p.second;\n return os;\n}\n\ntemplate <typename T1, typename T2>\nistream &operator>>(istream &is, pair<T1, T2> &p){\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<T> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<vector<T>> &v){\n for (int i = 0; i < v.size(); ++i){\n os << v[i] << (i + 1 != v.size() ? \"\\n\" : \"\");\n }\n return os;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v){\n for (int i = 0; i < v.size(); ++i) is >> v[i];\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, set<T> &v){\n for (auto &u : v){\n os << u << \" \";\n }\n return os;\n}\n\ntemplate<typename T1, typename T2>\nvector<pair<T1, T2>> AssembleVectorPair(vector<T1> &v1, vector<T2> &v2){\n assert(v1.size() == v2.size());\n vector<pair<T1, T2>> v;\n for(int i = 0; i < v1.size(); ++i) v.push_back({v1[i], v2[i]});\n return v;\n}\n\ntemplate<typename T1, typename T2>\npair<vector<T1>, vector<T2>> DisassembleVectorPair(vector<pair<T1, T2>> &v){\n vector<T1> v1;\n vector<T2> v2;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return p.first;});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return p.second;});\n return {v1, v2};\n}\n\ntemplate<typename T1, typename T2, typename T3>\ntuple<vector<T1>, vector<T2>, vector<T3>> DisassembleVectorTuple(vector<tuple<T1, T2, T3>> &v){\n vector<T1> v1;\n vector<T2> v2;\n vector<T3> v3;\n transform(v.begin(), v.end(), back_inserter(v1), [](auto p){return get<0>(p);});\n transform(v.begin(), v.end(), back_inserter(v2), [](auto p){return get<1>(p);});\n transform(v.begin(), v.end(), back_inserter(v3), [](auto p){return get<2>(p);});\n return {v1, v2, v3};\n}\n\ntemplate<typename T1 = int, typename T2 = T1>\npair<vector<T1>, vector<T2>> InputVectorPair(int size){\n vector<pair<T1, T2>> v(size);\n for(auto &[p, q] : v) cin >> p >> q;\n return DisassembleVectorPair(v);\n}\n\ntemplate<typename T1 = int, typename T2 = T1, typename T3 = T1>\ntuple<vector<T1>, vector<T2>, vector<T3>> InputVectorTuple(int size){\n vector<tuple<T1, T2, T3>> v(size);\n for(auto &[p, q, r] : v) cin >> p >> q >> r;\n return DisassembleVectorTuple(v);\n}\n\n#ifdef LOGK\n#define DEBUG(fmt, ...) fprintf(stderr, fmt __VA_OPT__(,) __VA_ARGS__)\n#define VARIABLE(var) cerr << \"# \" << #var << \" = \" << var << endl;\n#else\n#define DEBUG(...) 42\n#define VARIABLE(...) 42\n#endif\n\n// ==============================================================\n// \n// Main Program Start\n// \n// ==============================================================\n#line 2 \"Library/Tree/Tree.hpp\"\n\n/**\n * @file Tree.hpp\n * @brief Tree - 木テンプレート\n * @version 0.1\n * @date 2024-07-29\n */\n\n#line 11 \"Library/Tree/Tree.hpp\"\n\nusing Vertex = int;\n\ntemplate<typename CostType = int32_t>\nclass RootedTree{\n public:\n struct Node{\n Node(Vertex parent = -1) : parent(parent){}\n\n Vertex parent{-1};\n CostType cost{0};\n vector<Vertex> children{};\n };\n\n /**\n * @brief 頂点 `root_vertex` を根とする頂点数 `vertex_size` の根付き木を構築する。\n * @note 根が入力で与えられなれないが後で分かる みたいなよく分からん状況の時は `root_vertex = -1` とするとよい\n * @param vertex_size 頂点数\n * @param root_vertex 根とする頂点 (default = 0)\n */\n RootedTree(int vertex_size, Vertex root_vertex = 0) :\n vertex_size_(vertex_size), root_vertex_(root_vertex),\n node_(vertex_size){}\n\n /**\n * @brief 木の頂点数を返す。\n * @return int 木の頂点数\n */\n int get_vertex_size() const {\n return vertex_size_;\n }\n\n /**\n * @brief 木の根の頂点を返す。\n * @return Vertex 木の根の頂点番号 (0-index)\n */\n Vertex get_root() const {\n return root_vertex_;\n }\n\n /**\n * @brief 頂点 `v` の親の頂点番号を返す。\n * @note `v` が根の場合、`-1` が返される。\n * @param v 子の頂点番号 (0-index)\n * @return Vertex 親の頂点番号 (0-index)\n */\n Vertex get_parent(Vertex v) const {\n Validate(v);\n return node_[v].parent;\n }\n\n /**\n * @brief 頂点 `v` の子の頂点番号列を返す。\n * @note 頂点番号列は入力順に返される。\n * @param v 親の頂点番号 (0-index)\n * @return vector<Vertex> 子の頂点番号列 (0-index)\n */\n vector<Vertex> &get_child(Vertex v){\n Validate(v);\n return node_[v].children;\n }\n\n /**\n * @brief 頂点 `v` とその親を結ぶ辺の重みを返す。\n * @attention `v` が根の場合の返り値は未定義である。\n * @param v 頂点番号 (0-index)\n * @return CostType 辺の重み\n */\n CostType get_cost(Vertex v){\n Validate(v);\n return node_[v].cost;\n }\n\n /**\n * @brief 頂点 `parent` から頂点 `child` への重さ `cost` の辺を張る。\n * @note `cost` を省略することで重みなし辺を張ることができる。\n * @param parent 親の頂点番号 (0-index)\n * @param child 子の頂点番号 (0-index)\n * @param cost 辺の重み (default = 1)\n */\n void AddEdge(Vertex parent, Vertex child, CostType cost = 1){\n Validate(parent);\n Validate(child);\n node_[parent].children.push_back(child);\n node_[child].parent = parent;\n node_[child].cost = cost;\n }\n\n /**\n * @brief `u v w` のような入力形式を受け取る。\n * @param weighted 重み付きの木であるか (default = true)\n * @param one_index 入力される頂点番号が 1-index かどうか (default = true)\n */\n void InputGraphFormat(bool weighted = true, bool one_index = true){\n vector<vector<pair<Vertex, CostType>>> graph(vertex_size_);\n for(int i = 0; i < vertex_size_ - 1; ++i){\n int u, v; cin >> u >> v;\n if(one_index) --u, --v;\n CostType w = 1;\n if(weighted) cin >> w;\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n auto rec = [&](auto self, Vertex v, Vertex p) -> void {\n for(auto [u, w] : graph[v]){\n if(u == p) continue;\n AddEdge(v, u, w);\n self(self, u, v);\n }\n };\n rec(rec, root_vertex_, -1);\n }\n\n /**\n * @brief `p_1 p_2 ... p_N` のような入力形式を受け取る。\n * @attention weighted の処理を書いていないので、`weighted` のパラメータに意味はない\n * @param weighted 重み付きの木であるか (default = true)\n * @param one_index 入力される頂点番号が 1-index かどうか (default = true)\n */\n void InputRootedTreeFormat(bool weighted = true, bool one_index = true){\n assert(root_vertex_ == 0);\n for(int i = 1; i < vertex_size_; ++i){\n int p; cin >> p;\n if(one_index) --p;\n AddEdge(p, i);\n }\n }\n\n /**\n * @brief 頂点 `v` が根の頂点か判定する。\n * @param v 判定する頂点番号 (0-index)\n */\n bool RootVertex(Vertex v){\n Validate(v);\n return node_[v].parent == -1;\n }\n \n /**\n * @brief 頂点 `v` が葉の頂点か判定する。\n * @param v 判定する頂点番号 (0-index)\n */\n bool LeafVertex(Vertex v){\n Validate(v);\n return node_[v].children.empty();\n }\n\n /**\n * @brief 木の根の頂点を求める。\n * @attention 基本的には不要で、根の頂点番号が与えられていない場合に用いる。\n * @note Verify : https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/7/ALDS1_7_A\n * @return Vertex 根の頂点番号\n */\n Vertex FindRoot(){\n for(int i = 0; i < vertex_size_; ++i){\n if(RootVertex(i)){\n root_vertex_ = i;\n return i;\n }\n }\n assert(false);\n }\n\n /**\n * @brief 木の根を変更して再構築する。\n * @param root 新しい根の頂点番号 (0-index)\n */\n void Rerooting(Vertex root){\n if(root == root_vertex_) return;\n vector<Node> new_node_(vertex_size_);\n auto rec = [&](auto self, Vertex v, Vertex p, CostType c) -> void {\n new_node_[v].parent = p;\n new_node_[v].cost = c;\n if(node_[v].parent != p && node_[v].parent != -1){\n new_node_[v].children.push_back(node_[v].parent);\n self(self, node_[v].parent, v, node_[v].cost);\n }\n for(Vertex u : node_[v].children){\n if(u != p){\n new_node_[v].children.push_back(u);\n self(self, u, v, node_[u].cost);\n }\n }\n };\n rec(rec, root, -1, 0);\n swap(new_node_, node_);\n root_vertex_ = root;\n }\n\n void Print(bool one_index = true) const {\n for(int i = 0; i < vertex_size_; ++i){\n fprintf(stderr, \"# Vertex %d : parent = %d (cost = %d), children = [\", i + int(one_index), get_parent(i) + int(one_index), node_[i].cost);\n for(int j = 0; j < node_[i].children.size(); ++j){\n fprintf(stderr, \"%d\", node_[i].children[j]);\n if(j + 1 < node_[i].children.size()){\n fprintf(stderr, \", \");\n }\n }\n fprintf(stderr, \"]\\n\");\n }\n }\n\n private:\n inline void Validate(Vertex v) const {\n assert(0 <= v && v < vertex_size_);\n }\n\n int vertex_size_, root_vertex_{-1};\n vector<Node> node_;\n};\n\n/**\n * @brief 木 `tree` の各頂点の深さを求める。\n * @note 根の頂点は深さ 0 である。\n * @note Verify : https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/7/ALDS1_7_A\n * @param tree 木\n * @param root 根の頂点番号 (default = 0)\n * @return vector<int> 各頂点の深さ\n */\ntemplate<typename CostType>\nvector<int> CalculateTreeDepth(RootedTree<CostType> &tree){\n int V = tree.get_vertex_size();\n vector<int> ret(V, 0);\n auto rec = [&](auto self, Vertex v, int d) -> void {\n ret[v] = d;\n for(Vertex u : tree.get_child(v)){\n self(self, u, d + 1);\n }\n };\n Vertex root = tree.get_root();\n if(root < 0) root = tree.FindRoot();\n rec(rec, root, 0);\n return ret;\n}\n\n/**\n * @brief 木の根から各頂点への辺の重みの累積和を計算する。\n * @param tree 木\n * @return vector<CostType> 根から各頂点への重みの累積和\n */\ntemplate<typename CostType>\nvector<CostType> CalculateTreeCumlativeSum(RootedTree<CostType> &tree){\n Vertex root = tree.get_root();\n int V = tree.get_vertex_size();\n vector<CostType> ret(V, 0);\n auto rec = [&](auto self, Vertex v, CostType s) -> void {\n ret[v] = s + tree.get_cost(v);\n for(Vertex u : tree.get_child(v)){\n self(self, u, ret[v]);\n }\n };\n rec(rec, root, 0);\n return ret;\n}\n#line 3 \"Library/test.cpp\"\n\nint main(){\n int n; cin >> n;\n RootedTree T(n);\n T.InputGraphFormat(true, false);\n\n // T.Print(false);\n\n // 頂点 `i` を根とする DP の解\n vector<int> dp(n, 0);\n // 頂点 `i` の各部分木の DP の解(非根については末尾に親の部分木)\n vector<vector<int>> subtree_dp(n, vector<int>{0});\n // `subtree_dp[i]` の左右からの累積\n vector<vector<int>> left_subtree_cum(n), right_subtree_cum(n);\n\n // DFS\n auto dfs = [&](auto self, int v) -> int {\n int ret = 0;\n for(auto u : T.get_child(v)){\n int res = self(self, u);\n subtree_dp[v].push_back(res);\n ret = max(ret, res);\n }\n ret = ret + T.get_cost(v);\n return ret;\n };\n dp[0] = dfs(dfs, 0);\n int c = subtree_dp[0].size();\n left_subtree_cum[0].resize(c + 1);\n left_subtree_cum[0][0] = 0;\n for(int i = 1; i < c; ++i){\n left_subtree_cum[0][i] = max(left_subtree_cum[0][i - 1], subtree_dp[0][i]);\n }\n right_subtree_cum[0].resize(c + 1);\n right_subtree_cum[0].back() = 0;\n for(int i = c - 1; i - 1 >= 0; --i){\n right_subtree_cum[0][i] = max(right_subtree_cum[0][i + 1], subtree_dp[0][i]);\n }\n\n // BFS しながら全方位木 DP をする\n\n // {頂点番号, 親の頂点番号, 親の頂点の何番目の子か (1-index)}\n queue<tuple<int, int, int>> que;\n for(int i = 0; i < T.get_child(0).size(); ++i){\n que.push({T.get_child(0)[i], 0, i + 1});\n }\n while(que.size()){\n auto [v, p, idx] = que.front(); que.pop();\n int ret = 0;\n ret = max(ret, left_subtree_cum[p][idx - 1]);\n ret = max(ret, right_subtree_cum[p][idx + 1]);\n ret = ret + T.get_cost(v);\n subtree_dp[v].push_back(ret);\n for(auto cval : subtree_dp[v]){\n ret = max(ret, cval);\n }\n dp[v] = ret;\n int c = subtree_dp[v].size();\n left_subtree_cum[v].resize(c + 1);\n left_subtree_cum[v][0] = 0;\n for(int i = 1; i < c; ++i){\n left_subtree_cum[v][i] = max(left_subtree_cum[v][i - 1], subtree_dp[v][i]);\n }\n right_subtree_cum[v].resize(c + 1);\n right_subtree_cum[v].back() = 0;\n for(int i = c - 1; i - 1 >= 0; --i){\n right_subtree_cum[v][i] = max(right_subtree_cum[v][i + 1], subtree_dp[v][i]);\n }\n for(int i = 0; i < T.get_child(v).size(); ++i){\n que.push({T.get_child(v)[i], v, i + 1});\n }\n }\n for(auto v : dp){\n cout << v << endl;\n }\n \n // cerr << \"# dp table :\";\n // for(int i = 0; i < n; ++i){\n // cerr << \" \" << dp[i];\n // }\n // cerr << endl;\n // cerr << \"# subtree_dp table\" << endl;\n // for(int i = 0; i < n; ++i){\n // cerr << \"# vertex \" << i << endl;\n // cerr << \"# subtree_dp :\";\n // for(int j = 0; j < subtree_dp[i].size(); ++j){\n // cerr << \" \" << subtree_dp[i][j];\n // }\n // cerr << endl;\n // cerr << \"# left_cum :\";\n // for(int j = 0; j < left_subtree_cum[i].size(); ++j){\n // cerr << \" \" << left_subtree_cum[i][j];\n // }\n // cerr << endl;\n // cerr << \"# right_cum :\";\n // for(int j = 0; j < right_subtree_cum[i].size(); ++j){\n // cerr << \" \" << right_subtree_cum[i][j];\n // }\n // cerr << endl;\n // }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6576, "score_of_the_acc": -0.2829, "final_rank": 11 }, { "submission_id": "aoj_GRL_5_B_9504013", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n// long longの省略\ntypedef long long ll;\n\n// rep(先頭にRで逆からループ、末尾にSで「1~n」となる)\n#define rep(i, a, n) for(int i = a; i < n; i++)\n#define reps(i, a, n) for(int i = a; i <= n; i++)\n#define rrep(i, a, n) for(int i = n - 1; i >= a; i--)\n#define rreps(i, a, n) for(int i = n; i >= a; i--)\n\n// ソートなどに対象を入れる場合\n#define all(x) (x).begin(),(x).end()\n\n// ソートされた配列から重複を削除して詰めなおす\n#define UNIQUE(x) x.erase( unique(x.begin(), x.end()), x.end() );\n\nint d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nint __gcd(int a, int b){\n\tint c;\n\n\twhile((c = a % b) != 0){\n\t\ta = b;\n\t\tb = c;\n\t}\n\n\treturn b;\n}\n\n// 「number」の「n」ビット目が「1」であるか「0」か\n// ビット目の数え方は配列の添え字と同じ\nbool __bit(int number, int n){\n\tif(number & (1 << n))\n\t\treturn true;\n\n\treturn false;\n}\n\n// aよりもbが大きいならばaをbで更新する\n// (更新されたならばtrueを返す)\ntemplate <typename T>\nbool chmax(T &a, const T& b) {\n\tif (a < b) {\n\t\ta = b; // aをbで更新\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n// aよりもbが小さいならばaをbで更新する\n// (更新されたならばtrueを返す)\ntemplate <typename T>\nbool chmin(T &a, const T& b) {\n\tif (a > b) {\n\t\ta = b; // aをbで更新\n\treturn true;\n\t}\n\n\treturn false;\n}\n\nll mod_pow(ll a, ll n, ll mod) {\n\tll res = 1;\n\t// n を 2進数に変換して考える\n\twhile (n > 0) {\n\t\tif (n & 1) res = res * a % mod;\n\t\ta = a * a % mod;\n\t\tn >>= 1;\n\t}\n\treturn res;\n}\n\nusing P = pair<int, int>;\n\nint main()\n{\n\tint N; cin >> N;\n\n\tvector<vector<P>> G(20000);\n\trep(i, 0, N - 1){\n\t\tint a, b, c; cin >> a >> b >> c;\n\t\tG[a].push_back({b, c});\n\t\tG[b].push_back({a, c});\n\t}\n\n\t// 木だからダイクストラ法でなくて良い\n\tauto dist = [&](int start, vector<int> &array){\n\t\tqueue<int> que;\n\t\tque.push(start);\n\t\tarray[start] = 0;\n\n\t\twhile(!que.empty()){\n\t\t\tint curr = que.front(); que.pop();\n\n\t\t\tfor(auto [to, cost] : G[curr]){\n\t\t\t\tif(array[to] > array[curr] + cost){\n\t\t\t\t\tarray[to] = array[curr] + cost;\n\t\t\t\t\tque.push(to);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\tvector<int> v1(N, INT_MAX), v2(N, INT_MAX), v3(N, INT_MAX);\n\tdist(0, v1);\n\tdist(max_element(all(v1)) - v1.begin(), v2);\n\tdist(max_element(all(v2)) - v2.begin(), v3);\n\n\trep(i, 0, N)\n\t\tcout << max(v2[i], v3[i]) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4196, "score_of_the_acc": -0.0251, "final_rank": 5 }, { "submission_id": "aoj_GRL_5_B_9491044", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define INF 1e9\ntypedef vector<int> Vec;\ntypedef pair<int,int> pii;\n\n// エッジを表す構造体\nstruct Edge {\n int to, cost;\n Edge(int to, int cost) : to(to), cost(cost) {}\n};\n\ntypedef vector<Edge> Edges;\ntypedef vector<Edges> Graph;\n\nint N; // ノード数\nGraph G; // グラフの隣接リスト表現\n\n// ダイクストラ法による単一始点最短経路アルゴリズム\nVec dijkstra(int s) {\n Vec dist(N, INF);\n dist[s] = 0;\n priority_queue<pii, vector<pii>, greater<pii>> Q;\n Q.push(pii(0, s));\n while (!Q.empty()) {\n pii p = Q.top(); Q.pop();\n int v = p.second;\n if (dist[v] < p.first) {\n continue;\n }\n for (int i = 0; i < (int)G[v].size(); i++) {\n Edge &e = G[v][i];\n if (dist[v] + e.cost < dist[e.to]) {\n dist[e.to] = dist[v] + e.cost;\n Q.push(pii(dist[e.to], e.to));\n }\n }\n }\n return dist;\n}\n\n// 指定されたノードから最も遠いノードを取得\nint getFarthestPoint(int v) {\n Vec vec = dijkstra(v);\n int resv = -1, max = -1;\n for (int i = 0; i < N; i++) {\n if (max < vec[i]) {\n max = vec[i];\n resv = i;\n }\n }\n return resv;\n}\n\n// 木の各ノードの高さを計算\nVec getTreeHeight() {\n int v1 = getFarthestPoint(0); // 任意の点から最も遠い点を取得\n int v2 = getFarthestPoint(v1); // その点からさらに最も遠い点を取得\n Vec d1 = dijkstra(v1), d2 = dijkstra(v2);\n Vec res(N);\n for (int i = 0; i < N; i++) {\n res[i] = max(d1[i], d2[i]); // 2つの最遠点からの距離のうち、大きい方を取る\n }\n return res;\n}\n\nint main() {\n int a, b, c;\n cin >> N;\n G.resize(N);\n for (int i = 0; i < N - 1; i++) {\n cin >> a >> b >> c;\n G[a].push_back(Edge(b, c));\n G[b].push_back(Edge(a, c));\n }\n Vec height = getTreeHeight();\n for (int i = 0; i < N; i++) {\n cout << height[i] << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3972, "score_of_the_acc": -0.0009, "final_rank": 2 }, { "submission_id": "aoj_GRL_5_B_9466860", "code_snippet": "#include <iostream>\n#include <cassert>\n#include <string>\n#include <stack>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\nusing ll = long long;\nusing Pi = pair<int, int>;\n\n// const ll INF = 1LL << 60;\nconst int INF = 1001001001;\nconst int NIL = -1;\n\nvoid dfs(const vector< vector<Pi> >& edges, int node, int cost, vector<int> &dist) {\n for (const Pi& p : edges[node]) {\n if(dist[p.first] == NIL) {\n int c = cost + p.second;\n dist[p.first] = c;\n dfs(edges, p.first, c, dist);\n }\n }\n}\n\nint main()\n{\n int N, s, t, w;\n cin >> N;\n vector< vector<Pi> > edges(N);\n vector<int> dist1(N, NIL), dist2(N, NIL);\n for (int i=0;i<N-1;++i) {\n cin >> s >> t >> w;\n edges[s].push_back(make_pair(t, w));\n edges[t].push_back(make_pair(s, w));\n }\n\n // 任意のノードから最大遠のノードを求める\n dist1[0] = 0;\n dfs(edges, 0, 0, dist1);\n int node1, d = -1;\n for (int i=0;i<N;++i) {\n if (d < dist1[i]) {\n d = dist1[i];\n node1 = i;\n }\n }\n\n // 求めたノードから最大遠を求める\n dist1.assign(N, NIL);\n dist1[node1] = 0;\n dfs(edges, node1, 0, dist1);\n d = -1;\n int node2 = -1;\n for (int i=0;i<N;++i) {\n if (d < dist1[i]) {\n d = dist1[i];\n node2 = i;\n }\n }\n\n // さらに求めたノードからの距離を求める\n dist2[node2] = 0;\n dfs(edges, node2, 0, dist2);\n\n for (int i=0;i<N;++i) {\n cout << max(dist1[i], dist2[i]) << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4228, "score_of_the_acc": -0.0286, "final_rank": 6 }, { "submission_id": "aoj_GRL_5_B_9379556", "code_snippet": "// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3\")\n// #pragma GCC optimize(\"unroll-loops\")\n\n#define CONSTANTS\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr long long INF = 1e18;\n// constexpr long long INF = LONG_LONG_MAX;\n// constexpr int MOD = 1000000007;\nconstexpr int MOD = 998244353;\nconstexpr long double EPS = 1e-10;\nconstexpr long double PI = M_PI;\n\nusing ll = long long; using ull = unsigned long long; using ld = long double; using pll = pair<ll, ll>; using pii = pair<int, int>; using pli = pair<ll, int>; using pil = pair<int, ll>; template<typename T> using vv = vector<vector<T>>; using vvl = vv<ll>; using vvi = vv<int>; using vvpll = vv<pll>; using vvpli = vv<pli>; using vvpil = vv<pil>;\n#define name4(i, a, b, c, d, e, ...) e\n#define rep(...) name4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)\n#define rep1(i, a) for (ll i = 0, _aa = a; i < _aa; i++)\n#define rep2(i, a, b) for (ll i = a, _bb = b; i < _bb; i++)\n#define rep3(i, a, b, c) for (ll i = a, _bb = b; (c > 0 && a <= i && i < _bb) or (c < 0 && a >= i && i > _bb); i += c)\n#define rrep(i, a, b) for (ll i=(a); i>(b); i--)\n#define pb push_back\n#define eb emplace_back\n#define mkp make_pair\n#define ALL(A) begin(A), end(A)\n#define UNIQUE(A) sort(ALL(A)), A.erase(unique(ALL(A)), A.end())\n#define elif else if\n#define tostr to_string\n#ifndef CONSTANTS\nconstexpr ll INF = 1e18; constexpr int MOD = 1000000007; constexpr ld EPS = 1e-10; constexpr ld PI = M_PI;\n#endif\ntemplate<typename T1, typename T2> istream &operator>>(istream &is, pair<T1, T2> &p) { is >> p.first >> p.second; return is; } template<typename T> istream &operator>>(istream &is, vector<T> &v) { for (T &in : v) is >> in; return is; } template<typename T = ll> vector<T> LIST(int N) { vector<T> A(N); rep(i, N) { cin >> A[i]; } return A; }\ntemplate<typename T> bool chmax(T &x, T y) { return (y > x) ? x = y, true : false; }\ntemplate<typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { return os << p.first << ' ' << p.second; } template<class T, size_t... Is> void print_tuple(ostream &os, const T &arg, index_sequence<Is...>) { static_cast<void>(((os << (Is == 0 ? \"\" : \" \"), os << get<Is>(arg)), ...)); } template<class... Ts> ostream &operator<<(ostream &os, const tuple<Ts...> &arg) { print_tuple(os, arg, make_index_sequence<sizeof...(Ts)>()); return os; } template<typename T, size_t N> ostream &operator<<(ostream &os, const array<T, N> &arr) { rep(i, N) { os << arr[i]; if (i != (int)N - 1) { os << ' '; } } return os; } template<typename T, size_t N> void print(const array<T, N> &arr, string sep = \" \") { rep(i, N) { cout << arr[i]; if (i != (int)N - 1) cout << sep; } cout << '\\n'; } template<typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { rep(i, vec.size()) { os << vec[i]; if (i != (int)vec.size() - 1) { os << ' '; } } return os; } template<typename T> void print(const vector<T> &vec, string sep = \" \") { rep(i, vec.size()) { cout << vec[i]; if (i != (int)vec.size() - 1) cout << sep; } cout << '\\n'; } template<typename T> void print(const deque<T> &que, string sep = \" \") { vector<T> vec(ALL(que)); print(vec, sep); } template<typename T> void print(const set<T> &se, string sep = \" \") { vector<T> vec(ALL(se)); print(vec, sep); } template<typename T> void print(const initializer_list<T> &li, string sep = \" \") { vector<T> V(ALL(li)); print(V, sep); } void print() { cout << '\\n'; } template<typename T> void print(T out) { cout << out << '\\n'; }\n#define debug(...) multi_debug(#__VA_ARGS__, __VA_ARGS__)\ntemplate<typename T> void multi_debug(string name, const vv<T> &grid) { cerr << name << \":\" << endl; int H = grid.size(); int W = grid[0].size(); vector<int> mxlen(W); rep(h, H) { rep(w, W) { chmax(mxlen[w], (int)tostr(grid[h][w]).size()); } } rep(h, H) { rep(w, W) { int pad = mxlen[w] - (int)tostr(grid[h][w]).size(); cerr << string(pad, ' ') << grid[h][w]; if (w == W - 1) { cerr << endl; } else { cerr << ' '; } } } } template<class Tp, class... Ts> void multi_debug(string names, Tp arg, Ts... args) { if constexpr (sizeof...(Ts) == 0) { while (names.back() == ' ') { names.pop_back(); } cerr << names << \": \" << arg << endl; } else { int n = names.size(), comma_pos = -1, paren_depth = 0, inside_quote = false; rep(i, n) { if (not inside_quote and paren_depth == 0 and names[i] == ',') { comma_pos = i; break; } if (names[i] == '\\\"' or names[i] == '\\'') { if (i > 0 and names[i - 1] == '\\\\') continue; inside_quote ^= true; } if (not inside_quote and names[i] == '(') { paren_depth++; } if (not inside_quote and names[i] == ')') { paren_depth--; } } assert(comma_pos != -1); string name = names.substr(0, comma_pos); while (name.back() == ' ') { name.pop_back(); } cerr << name << \": \" << arg << endl; int next_begin_at = comma_pos + 1; while (names[next_begin_at] == ' ') { next_begin_at++; } names = names.substr(next_begin_at); multi_debug(names, args...); } } template<typename T> void print(const vector<T> &V, char sep) { print(V, string{sep}); } template<typename T, size_t N> void print(const array<T, N> &arr, char sep) { print(arr, string{sep}); }\n\nnamespace DynamicRerootingImpl { template<typename Point, Point (*rake)(const Point &, const Point &)> struct SplayTreeforDashedEdge { struct Node { Node *l, *r, *p; Point key, sum; explicit Node(const Point &_key) : l(nullptr), r(nullptr), p(nullptr), key(_key), sum(_key) { } }; SplayTreeforDashedEdge() { } using NP = Node *; void rotr(NP t) { NP x = t->p, y = x->p; if ((x->l = t->r)) t->r->p = x; t->r = x, x->p = t; update(x), update(t); if ((t->p = y)) { if (y->l == x) y->l = t; if (y->r == x) y->r = t; } } void rotl(NP t) { NP x = t->p, y = x->p; if ((x->r = t->l)) t->l->p = x; t->l = x, x->p = t; update(x), update(t); if ((t->p = y)) { if (y->l == x) y->l = t; if (y->r == x) y->r = t; } } void update(NP t) { t->sum = t->key; if (t->l) t->sum = rake(t->sum, t->l->sum); if (t->r) t->sum = rake(t->sum, t->r->sum); } NP get_right(NP t) { while (t->r) t = t->r; return t; } NP alloc(const Point &v) { auto t = new Node(v); update(t); return t; } void splay(NP t) { while (t->p) { NP q = t->p; if (!q->p) { if (q->l == t) rotr(t); else rotl(t); } else { NP r = q->p; if (r->l == q) { if (q->l == t) rotr(q), rotr(t); else rotl(t), rotr(t); } else { if (q->r == t) rotl(q), rotl(t); else rotr(t), rotl(t); } } } } NP insert(NP t, const Point &v) { if (not t) { t = alloc(v); return t; } else { NP cur = get_right(t), z = alloc(v); splay(cur); z->p = cur; cur->r = z; update(cur); splay(z); return z; } } NP erase(NP t) { splay(t); NP x = t->l, y = t->r; delete t; if (not x) { t = y; if (t) t->p = nullptr; } else if (not y) { t = x; t->p = nullptr; } else { x->p = nullptr; t = get_right(x); splay(t); t->r = y; y->p = t; update(t); } return t; } }; template< typename Path, typename Point, typename Info, Path (*vertex)(const Info &), Path (*compress)(const Path &, const Path &), Point (*rake)(const Point &, const Point &), Point (*add_edge)(const Path &), Path (*add_vertex)(const Point &, const Info &)> struct TopTree { private: struct Node { Node *l, *r, *p; Info info; Path key, sum, mus; typename SplayTreeforDashedEdge<Point, rake>::Node *light, *belong; bool rev; bool is_root() const { return not p or (p->l != this and p->r != this); } explicit Node(const Info _info) : l(nullptr), r(nullptr), p(nullptr), info(_info), light(nullptr), belong(nullptr), rev(false) { } }; public: using NP = Node *; SplayTreeforDashedEdge<Point, rake> splay_tree; private: void toggle(NP t) { swap(t->l, t->r); swap(t->sum, t->mus); t->rev ^= true; } void rotr(NP t) { NP x = t->p, y = x->p; push(x), push(t); if ((x->l = t->r)) t->r->p = x; t->r = x, x->p = t; update(x), update(t); if ((t->p = y)) { if (y->l == x) y->l = t; if (y->r == x) y->r = t; } } void rotl(NP t) { NP x = t->p, y = x->p; push(x), push(t); if ((x->r = t->l)) t->l->p = x; t->l = x, x->p = t; update(x), update(t); if ((t->p = y)) { if (y->l == x) y->l = t; if (y->r == x) y->r = t; } } public: TopTree() : splay_tree{} { } void push(NP t) { if (t->rev) { if (t->l) toggle(t->l); if (t->r) toggle(t->r); t->rev = false; } } void push_rev(NP t) { if (t->rev) { if (t->l) toggle(t->l); if (t->r) toggle(t->r); t->rev = false; } } void update(NP t) { Path key = t->light ? add_vertex(t->light->sum, t->info) : vertex(t->info); Path sum = key, mus = key; if (t->l) sum = compress(t->l->sum, sum), mus = compress(mus, t->l->mus); if (t->r) sum = compress(sum, t->r->sum), mus = compress(t->r->mus, mus); t->key = key, t->sum = sum, t->mus = mus; } void splay(NP t) { push(t); { NP rot = t; while (not rot->is_root()) rot = rot->p; t->belong = rot->belong; if (t != rot) rot->belong = nullptr; } while (not t->is_root()) { NP q = t->p; if (q->is_root()) { push_rev(q), push_rev(t); if (q->l == t) rotr(t); else rotl(t); } else { NP r = q->p; push_rev(r), push_rev(q), push_rev(t); if (r->l == q) { if (q->l == t) rotr(q), rotr(t); else rotl(t), rotr(t); } else { if (q->r == t) rotl(q), rotl(t); else rotr(t), rotl(t); } } } } NP expose(NP t) { NP rp = nullptr; for (NP cur = t; cur; cur = cur->p) { splay(cur); if (cur->r) { cur->light = splay_tree.insert(cur->light, add_edge(cur->r->sum)); cur->r->belong = cur->light; } cur->r = rp; if (cur->r) { splay_tree.splay(cur->r->belong); push(cur->r); cur->light = splay_tree.erase(cur->r->belong); } update(cur); rp = cur; } splay(t); return rp; } void link(NP child, NP parent) { expose(parent); expose(child); child->p = parent; parent->r = child; update(parent); } void cut(NP child) { expose(child); NP parent = child->l; child->l = nullptr; parent->p = nullptr; update(child); } void evert(NP t) { expose(t); toggle(t); push(t); } NP alloc(const Info &info) { NP t = new Node(info); update(t); return t; } bool is_connected(NP u, NP v) { expose(u), expose(v); return u == v or u->p; } NP lca(NP u, NP v) { if (not is_connected(u, v)) return nullptr; expose(u); return expose(v); } void set_key(NP t, const Info &v) { expose(t); t->info = v; update(t); } Path query(NP u) { evert(u); return u->sum; } Path query_subtree(NP root, NP u) { evert(root); expose(u); NP l = u->l; u->l = nullptr; update(u); auto ret = u->sum; u->l = l; update(u); return ret; } }; template< typename Path, typename Point, typename Info, Path (*vertex)(const Info &), Path (*compress)(const Path &, const Path &), Point (*rake)(const Point &, const Point &), Point (*Add_edge)(const Path &), Path (*_add_vertex)(const Point &, const Info &)> struct DynamicRerooting { int n; TopTree<Path, Point, Info, vertex, compress, rake, Add_edge, _add_vertex> tt; using NP = typename decltype(tt)::NP; vector<NP> vs; DynamicRerooting(int _n, const vector<Info> &info) : n(_n), vs(n) { for (int i = 0; i < n; i++) vs[i] = tt.alloc(info[i]); } DynamicRerooting() : n(0) {} void add_vertex(Info info) { vs.pb(tt.alloc(info)); n++; } void add_edge(int u, int v) { tt.evert(vs[u]); tt.link(vs[u], vs[v]); } void remove_edge(int u, int v) { tt.evert(vs[u]); tt.cut(vs[v]); } Info get_info(int u) { return vs[u]->info; } void set_info(int u, const Info &info) { tt.set_key(vs[u], info); } Path query(int u) { return tt.query(vs[u]); } Path query_subtree(int root, int u) { return tt.query_subtree(vs[root], vs[u]); } }; } using DynamicRerootingImpl::DynamicRerooting;\n\n// mx := 最遠点への距離\n// ptoc := 上下接点間の距離\nstruct Path {\n ll mx;\n ll ptoc;\n};\nusing Point = ll;\nusing Info = ll;\nPath vertex(const Info &val) {\n Path res;\n res.mx = val;\n res.ptoc = val;\n return res;\n}\nPath compress(const Path &p, const Path &c) {\n Path res;\n //「pの最遠点」と「pの接点間+cの最遠点」を比較\n res.mx = max(p.mx, p.ptoc + c.mx);\n res.ptoc = p.ptoc + c.ptoc;\n return res;\n}\nPoint rake(const Point &a, const Point &b) {\n return max(a, b);\n}\nPoint add_edge(const Path &a) {\n return a.mx;\n}\nPath add_vertex(const Point &a, const Info &val) {\n Path res;\n res.mx = a + val;\n res.ptoc = val;\n return res;\n}\nusing DRR = DynamicRerooting<Path, Point, Info, vertex, compress, rake, add_edge, add_vertex>;\n\nvoid solve() {\n ll N;\n cin >> N;\n vector<Info> info(N * 2 - 1);\n vector<pii> edges;\n rep(i, N - 1) {\n ll u, v, w;\n cin >> u >> v >> w;\n edges.eb(u, N + i);\n edges.eb(v, N + i);\n info[N + i] = w;\n }\n DRR drr(N * 2 - 1, info);\n for (auto [u, v] : edges) {\n drr.add_edge(u, v);\n }\n\n rep(u, N) {\n ll res = drr.query(u).mx;\n print(res);\n }\n}\n\nint main() {\n cin.tie(0);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n\n // single test case\n solve();\n\n // multi test cases\n // int T;\n // cin >> T;\n // while (T--) solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6848, "score_of_the_acc": -0.3124, "final_rank": 14 }, { "submission_id": "aoj_GRL_5_B_9378601", "code_snippet": "// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3\")\n// #pragma GCC optimize(\"unroll-loops\")\n\n#define CONSTANTS\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr long long INF = 1e18;\n// constexpr long long INF = LONG_LONG_MAX;\n// constexpr int MOD = 1000000007;\nconstexpr int MOD = 998244353;\nconstexpr long double EPS = 1e-10;\nconstexpr long double PI = M_PI;\n\nusing ll = long long; using ull = unsigned long long; using ld = long double; using pll = pair<ll, ll>; using pii = pair<int, int>; using pli = pair<ll, int>; using pil = pair<int, ll>; template<typename T> using vv = vector<vector<T>>; using vvl = vv<ll>; using vvi = vv<int>; using vvpll = vv<pll>; using vvpli = vv<pli>; using vvpil = vv<pil>;\n#define name4(i, a, b, c, d, e, ...) e\n#define rep(...) name4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)\n#define rep1(i, a) for (ll i = 0, _aa = a; i < _aa; i++)\n#define rep2(i, a, b) for (ll i = a, _bb = b; i < _bb; i++)\n#define rep3(i, a, b, c) for (ll i = a, _bb = b; (c > 0 && a <= i && i < _bb) or (c < 0 && a >= i && i > _bb); i += c)\n#define rrep(i, a, b) for (ll i=(a); i>(b); i--)\n#define pb push_back\n#define eb emplace_back\n#define mkp make_pair\n#define ALL(A) begin(A), end(A)\n#define UNIQUE(A) sort(ALL(A)), A.erase(unique(ALL(A)), A.end())\n#define elif else if\n#define tostr to_string\n#ifndef CONSTANTS\nconstexpr ll INF = 1e18; constexpr int MOD = 1000000007; constexpr ld EPS = 1e-10; constexpr ld PI = M_PI;\n#endif\ntemplate<typename T1, typename T2> istream &operator>>(istream &is, pair<T1, T2> &p) { is >> p.first >> p.second; return is; } template<typename T> istream &operator>>(istream &is, vector<T> &v) { for (T &in : v) is >> in; return is; } template<typename T = ll> vector<T> LIST(int N) { vector<T> A(N); rep(i, N) { cin >> A[i]; } return A; }\ntemplate<typename T> bool chmax(T &x, T y) { return (y > x) ? x = y, true : false; }\ntemplate<typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { return os << p.first << ' ' << p.second; } template<class T, size_t... Is> void print_tuple(ostream &os, const T &arg, index_sequence<Is...>) { static_cast<void>(((os << (Is == 0 ? \"\" : \" \"), os << get<Is>(arg)), ...)); } template<class... Ts> ostream &operator<<(ostream &os, const tuple<Ts...> &arg) { print_tuple(os, arg, make_index_sequence<sizeof...(Ts)>()); return os; } template<typename T, size_t N> ostream &operator<<(ostream &os, const array<T, N> &arr) { rep(i, N) { os << arr[i]; if (i != (int)N - 1) { os << ' '; } } return os; } template<typename T, size_t N> void print(const array<T, N> &arr, string sep = \" \") { rep(i, N) { cout << arr[i]; if (i != (int)N - 1) cout << sep; } cout << '\\n'; } template<typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { rep(i, vec.size()) { os << vec[i]; if (i != (int)vec.size() - 1) { os << ' '; } } return os; } template<typename T> void print(const vector<T> &vec, string sep = \" \") { rep(i, vec.size()) { cout << vec[i]; if (i != (int)vec.size() - 1) cout << sep; } cout << '\\n'; } template<typename T> void print(const deque<T> &que, string sep = \" \") { vector<T> vec(ALL(que)); print(vec, sep); } template<typename T> void print(const set<T> &se, string sep = \" \") { vector<T> vec(ALL(se)); print(vec, sep); } template<typename T> void print(const initializer_list<T> &li, string sep = \" \") { vector<T> V(ALL(li)); print(V, sep); } void print() { cout << '\\n'; } template<typename T> void print(T out) { cout << out << '\\n'; }\n#define debug(...) multi_debug(#__VA_ARGS__, __VA_ARGS__)\ntemplate<typename T> void multi_debug(string name, const vv<T> &grid) { cerr << name << \":\" << endl; int H = grid.size(); int W = grid[0].size(); vector<int> mxlen(W); rep(h, H) { rep(w, W) { chmax(mxlen[w], (int)tostr(grid[h][w]).size()); } } rep(h, H) { rep(w, W) { int pad = mxlen[w] - (int)tostr(grid[h][w]).size(); cerr << string(pad, ' ') << grid[h][w]; if (w == W - 1) { cerr << endl; } else { cerr << ' '; } } } } template<class Tp, class... Ts> void multi_debug(string names, Tp arg, Ts... args) { if constexpr (sizeof...(Ts) == 0) { while (names.back() == ' ') { names.pop_back(); } cerr << names << \": \" << arg << endl; } else { int n = names.size(), comma_pos = -1, paren_depth = 0, inside_quote = false; rep(i, n) { if (not inside_quote and paren_depth == 0 and names[i] == ',') { comma_pos = i; break; } if (names[i] == '\\\"' or names[i] == '\\'') { if (i > 0 and names[i - 1] == '\\\\') continue; inside_quote ^= true; } if (not inside_quote and names[i] == '(') { paren_depth++; } if (not inside_quote and names[i] == ')') { paren_depth--; } } assert(comma_pos != -1); string name = names.substr(0, comma_pos); while (name.back() == ' ') { name.pop_back(); } cerr << name << \": \" << arg << endl; int next_begin_at = comma_pos + 1; while (names[next_begin_at] == ' ') { next_begin_at++; } names = names.substr(next_begin_at); multi_debug(names, args...); } } template<typename T> void print(const vector<T> &V, char sep) { print(V, string{sep}); } template<typename T, size_t N> void print(const array<T, N> &arr, char sep) { print(arr, string{sep}); }\n\nnamespace DynamicRerootingImpl {\ntemplate<typename Point, Point (*rake)(const Point &, const Point &)>\nstruct SplayTreeforDashedEdge {\n struct Node {\n Node *l, *r, *p;\n Point key, sum;\n\n explicit Node(const Point &_key)\n : l(nullptr),\n r(nullptr),\n p(nullptr),\n key(_key),\n sum(_key) {\n }\n };\n\n SplayTreeforDashedEdge() {\n }\n\n using NP = Node *;\n\n void rotr(NP t) {\n NP x = t->p, y = x->p;\n if ((x->l = t->r)) t->r->p = x;\n t->r = x, x->p = t;\n update(x), update(t);\n if ((t->p = y)) {\n if (y->l == x) y->l = t;\n if (y->r == x) y->r = t;\n }\n }\n\n void rotl(NP t) {\n NP x = t->p, y = x->p;\n if ((x->r = t->l)) t->l->p = x;\n t->l = x, x->p = t;\n update(x), update(t);\n if ((t->p = y)) {\n if (y->l == x) y->l = t;\n if (y->r == x) y->r = t;\n }\n }\n\n void update(NP t) {\n t->sum = t->key;\n if (t->l) t->sum = rake(t->sum, t->l->sum);\n if (t->r) t->sum = rake(t->sum, t->r->sum);\n }\n\n NP get_right(NP t) {\n while (t->r) t = t->r;\n return t;\n }\n\n NP alloc(const Point &v) {\n auto t = new Node(v);\n update(t);\n return t;\n }\n\n void splay(NP t) {\n while (t->p) {\n NP q = t->p;\n if (!q->p) {\n if (q->l == t) rotr(t);\n else rotl(t);\n } else {\n NP r = q->p;\n if (r->l == q) {\n if (q->l == t) rotr(q), rotr(t);\n else rotl(t), rotr(t);\n } else {\n if (q->r == t) rotl(q), rotl(t);\n else rotr(t), rotl(t);\n }\n }\n }\n }\n\n NP insert(NP t, const Point &v) {\n if (not t) {\n t = alloc(v);\n return t;\n } else {\n NP cur = get_right(t), z = alloc(v);\n splay(cur);\n z->p = cur;\n cur->r = z;\n update(cur);\n splay(z);\n return z;\n }\n }\n\n NP erase(NP t) {\n splay(t);\n NP x = t->l, y = t->r;\n delete t;\n if (not x) {\n t = y;\n if (t) t->p = nullptr;\n } else if (not y) {\n t = x;\n t->p = nullptr;\n } else {\n x->p = nullptr;\n t = get_right(x);\n splay(t);\n t->r = y;\n y->p = t;\n update(t);\n }\n return t;\n }\n};\n\ntemplate<\n typename Path, typename Point, typename Info, Path (*vertex)(const Info &),\n Path (*compress)(const Path &, const Path &),\n Point (*rake)(const Point &, const Point &),\n Point (*add_edge)(const Path &),\n Path (*add_vertex)(const Point &, const Info &)>\nstruct TopTree {\nprivate:\n struct Node {\n Node *l, *r, *p;\n Info info;\n Path key, sum, mus;\n typename SplayTreeforDashedEdge<Point, rake>::Node *light, *belong;\n bool rev;\n\n bool is_root() const {\n return not p or (p->l != this and p->r != this);\n }\n\n explicit Node(const Info _info)\n : l(nullptr),\n r(nullptr),\n p(nullptr),\n info(_info),\n light(nullptr),\n belong(nullptr),\n rev(false) {\n }\n };\n\npublic:\n using NP = Node *;\n SplayTreeforDashedEdge<Point, rake> splay_tree;\n\nprivate:\n void toggle(NP t) {\n swap(t->l, t->r);\n swap(t->sum, t->mus);\n t->rev ^= true;\n }\n\n void rotr(NP t) {\n NP x = t->p, y = x->p;\n push(x), push(t);\n if ((x->l = t->r)) t->r->p = x;\n t->r = x, x->p = t;\n update(x), update(t);\n if ((t->p = y)) {\n if (y->l == x) y->l = t;\n if (y->r == x) y->r = t;\n }\n }\n\n void rotl(NP t) {\n NP x = t->p, y = x->p;\n push(x), push(t);\n if ((x->r = t->l)) t->l->p = x;\n t->l = x, x->p = t;\n update(x), update(t);\n if ((t->p = y)) {\n if (y->l == x) y->l = t;\n if (y->r == x) y->r = t;\n }\n }\n\npublic:\n TopTree() : splay_tree{} {\n }\n\n void push(NP t) {\n if (t->rev) {\n if (t->l) toggle(t->l);\n if (t->r) toggle(t->r);\n t->rev = false;\n }\n }\n\n void push_rev(NP t) {\n if (t->rev) {\n if (t->l) toggle(t->l);\n if (t->r) toggle(t->r);\n t->rev = false;\n }\n }\n\n void update(NP t) {\n Path key =\n t->light ? add_vertex(t->light->sum, t->info) : vertex(t->info);\n Path sum = key, mus = key;\n if (t->l)\n sum = compress(t->l->sum, sum), mus = compress(mus, t->l->mus);\n if (t->r)\n sum = compress(sum, t->r->sum), mus = compress(t->r->mus, mus);\n t->key = key, t->sum = sum, t->mus = mus;\n }\n\n void splay(NP t) {\n push(t);\n {\n NP rot = t;\n while (not rot->is_root()) rot = rot->p;\n t->belong = rot->belong;\n if (t != rot) rot->belong = nullptr;\n }\n while (not t->is_root()) {\n NP q = t->p;\n if (q->is_root()) {\n push_rev(q), push_rev(t);\n if (q->l == t) rotr(t);\n else rotl(t);\n } else {\n NP r = q->p;\n push_rev(r), push_rev(q), push_rev(t);\n if (r->l == q) {\n if (q->l == t) rotr(q), rotr(t);\n else rotl(t), rotr(t);\n } else {\n if (q->r == t) rotl(q), rotl(t);\n else rotr(t), rotl(t);\n }\n }\n }\n }\n\n NP expose(NP t) {\n NP rp = nullptr;\n for (NP cur = t; cur; cur = cur->p) {\n splay(cur);\n if (cur->r) {\n cur->light =\n splay_tree.insert(cur->light, add_edge(cur->r->sum));\n cur->r->belong = cur->light;\n }\n cur->r = rp;\n if (cur->r) {\n splay_tree.splay(cur->r->belong);\n push(cur->r);\n cur->light = splay_tree.erase(cur->r->belong);\n }\n update(cur);\n rp = cur;\n }\n splay(t);\n return rp;\n }\n\n void link(NP child, NP parent) {\n expose(parent);\n expose(child);\n child->p = parent;\n parent->r = child;\n update(parent);\n }\n\n void cut(NP child) {\n expose(child);\n NP parent = child->l;\n child->l = nullptr;\n parent->p = nullptr;\n update(child);\n }\n\n void evert(NP t) {\n expose(t);\n toggle(t);\n push(t);\n }\n\n NP alloc(const Info &info) {\n NP t = new Node(info);\n update(t);\n return t;\n }\n\n bool is_connected(NP u, NP v) {\n expose(u), expose(v);\n return u == v or u->p;\n }\n\n NP lca(NP u, NP v) {\n if (not is_connected(u, v)) return nullptr;\n expose(u);\n return expose(v);\n }\n\n void set_key(NP t, const Info &v) {\n expose(t);\n t->info = v;\n update(t);\n }\n\n // u を根とする sum\n Path query(NP u) {\n evert(u);\n return u->sum;\n }\n\n // root を根, u を部分木の根とする sum\n Path query_subtree(NP root, NP u) {\n evert(root);\n expose(u);\n NP l = u->l;\n u->l = nullptr;\n update(u);\n auto ret = u->sum;\n u->l = l;\n update(u);\n return ret;\n }\n};\n\ntemplate<\n typename Path, typename Point, typename Info, Path (*vertex)(const Info &),\n Path (*compress)(const Path &, const Path &),\n Point (*rake)(const Point &, const Point &),\n Point (*Add_edge)(const Path &),\n Path (*add_vertex)(const Point &, const Info &)>\nstruct DynamicRerooting {\n int n;\n TopTree<Path, Point, Info, vertex, compress, rake, Add_edge, add_vertex> tt;\n using NP = typename decltype(tt)::NP;\n vector<NP> vs;\n\n DynamicRerooting(int _n, const vector<Info> &info) : n(_n), vs(n) {\n for (int i = 0; i < n; i++) vs[i] = tt.alloc(info[i]);\n }\n // u-v 間に辺を追加\n void add_edge(int u, int v) {\n tt.evert(vs[u]);\n tt.link(vs[u], vs[v]);\n }\n // u-v 間の辺を削除\n void del_edge(int u, int v) {\n tt.evert(vs[u]);\n tt.cut(vs[v]);\n }\n // 頂点 u の情報を取得\n Info get_info(int u) {\n return vs[u]->info;\n }\n // 頂点 u の情報を設定\n void set_info(int u, const Info &info) {\n tt.set_key(vs[u], info);\n }\n // 頂点 u を根とするクエリ\n Path query(int u) {\n return tt.query(vs[u]);\n }\n // 頂点 root を根, 頂点 u を部分木の根とするクエリ\n Path query_subtree(int root, int u) {\n return tt.query_subtree(vs[root], vs[u]);\n }\n};\n\n} // namespace DynamicRerootingImpl\n\nusing DynamicRerootingImpl::DynamicRerooting;\n\n// mx := 最遠点への距離\n// p := その部分木の上の接点の頂点番号\n// c := その部分木の下の接点の頂点番号\n// mxi := その部分木の最遠点の頂点番号\n// ptoc := 上下接点間の距離\nstruct Path {\n ll mx;\n int p, c, mxi;\n ll ptoc;\n};\nstruct Point {\n ll mx;\n int mxi;\n};\n// struct Info {\n// };\nusing Info = pair<ll, int>;\nPath vertex(const Info &info) {\n auto [val, i] = info;\n Path res;\n res.mx = val;\n res.mxi = i;\n res.p = res.c = i;\n res.ptoc = val;\n return res;\n}\nPath compress(const Path &p, const Path &c) {\n Path res;\n // pの最遠点がcの上接点ならそのまま繋ぐ\n if (p.mxi == c.p) {\n res.mx = p.mx + c.mx;\n res.mxi = c.mxi;\n } else {\n // そうでなければ「pの最遠点」と「pの接点間+cの最遠点」を比較\n if (p.mx >= p.ptoc + c.mx) {\n res.mx = p.mx;\n res.mxi = p.mxi;\n } else {\n res.mx = p.ptoc + c.mx;\n res.mxi = c.mxi;\n }\n }\n res.p = p.p;\n res.c = c.c;\n res.ptoc = p.ptoc + c.ptoc;\n return res;\n}\nPoint rake(const Point &a, const Point &b) {\n Point res;\n if (a.mx >= b.mx) {\n res.mx = a.mx;\n res.mxi = a.mxi;\n } else {\n res.mx = b.mx;\n res.mxi = b.mxi;\n }\n return res;\n}\nPoint add_edge(const Path &a) {\n Point res;\n res.mx = a.mx;\n res.mxi = a.mxi;\n return res;\n}\nPath add_vertex(const Point &a, const Info &info) {\n auto [val, i] = info;\n Path res;\n res.mx = {a.mx + val};\n res.mxi = i;\n res.p = res.c = i;\n res.ptoc = val;\n return res;\n}\nusing DRR = DynamicRerooting<Path, Point, Info, vertex, compress, rake, add_edge, add_vertex>;\n\nvoid solve() {\n ll N;\n cin >> N;\n vector<Info> info(N * 2 - 1);\n vector<pii> edges;\n rep(u, N) {\n info[u] = {0, u};\n }\n rep(i, N - 1) {\n ll u, v, w;\n cin >> u >> v >> w;\n edges.eb(u, N + i);\n edges.eb(v, N + i);\n info[N + i] = {w, N + i};\n }\n DRR drr(N * 2 - 1, info);\n for (auto [u, v] : edges) {\n drr.add_edge(u, v);\n }\n\n rep(u, N) {\n ll res = drr.query(u).mx;\n print(res);\n }\n}\n\nint main() {\n cin.tie(0);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n\n // single test case\n solve();\n\n // multi test cases\n // int T;\n // cin >> T;\n // while (T--) solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8580, "score_of_the_acc": -0.5, "final_rank": 17 }, { "submission_id": "aoj_GRL_5_B_9168244", "code_snippet": "#include <cassert>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <map>\n#include <set>\n#include <list>\n#include <deque>\n#include <tuple>\n#include <functional>\n#include <optional>\n\nusing namespace std;\n\nconstexpr int INF = 1e9;\n\nvector<int> dist(int r, const vector<vector<pair<int, int>>> &edges)\n{\n vector<int> res(edges.size(), INF);\n res[r] = 0;\n\n set<pair<int, int>> breads{{0, r}};\n while (breads.size())\n {\n auto it = breads.begin();\n const auto [d, s] = *it;\n breads.erase(it);\n\n if (res[s] < d)\n continue;\n\n for (const auto &[w, t] : edges[s])\n {\n if (d + w < res[t])\n {\n res[t] = d + w;\n breads.emplace(d + w, t);\n }\n }\n }\n\n return res;\n}\n\nint main()\n{\n int N;\n cin >> N;\n\n vector<vector<pair<int, int>>> edges(N);\n for (int i = 1; i < N; ++i)\n {\n int s, t, w;\n cin >> s >> t >> w;\n edges[s].push_back({w, t});\n edges[t].push_back({w, s});\n }\n\n const auto d0 = dist(0, edges);\n int max_i = -1;\n {\n int max_d = -1;\n for (int i = 0; i < N; ++i)\n {\n if (max_d < d0[i])\n {\n max_d = d0[i];\n max_i = i;\n }\n }\n }\n\n const auto d1 = dist(max_i, edges);\n max_i = -1;\n {\n int max_d = -1;\n for (int i = 0; i < N; ++i)\n {\n if (max_d < d1[i])\n {\n max_d = d1[i];\n max_i = i;\n }\n }\n }\n\n const auto d2 = dist(max_i, edges);\n\n for (int i = 0; i < N; ++i)\n {\n cout << max(d1[i], d2[i]) << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4440, "score_of_the_acc": -0.0516, "final_rank": 7 }, { "submission_id": "aoj_GRL_5_B_9101437", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)\n#define rrep(i,start,end) for (long long i = start;i >= (long long)(end);i--)\n#define repn(i,end) for(long long i = 0; i <= (long long)(end); i++)\n#define reps(i,start,end) for(long long i = start; i < (long long)(end); i++)\n#define repsn(i,start,end) for(long long i = start; i <= (long long)(end); i++)\n#define each(p,a) for(auto &p:a)\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef vector<long long> vll;\ntypedef vector<pair<long long ,long long>> vpll;\ntypedef vector<vector<long long>> vvll;\ntypedef set<ll> sll;\ntypedef map<long long , long long> mpll;\ntypedef pair<long long ,long long> pll;\ntypedef tuple<long long , long long , long long> tpl3;\n#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)\n#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)\n#define Str(...) string __VA_ARGS__; input(__VA_ARGS__)\n#define Ch(...) char __VA_ARGS__; input(__VA_ARGS__)\n#define all(a) (a).begin(),(a).end()\n#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );\n#define sz(x) (int)x.size()\n// << std::fixed << std::setprecision(10)\nconst ll INF = 1LL << 60;\nconst ld EPS = 1e-9;\n \ninline ll lfloor(ll x,ll m){return (x - ((x % m+ m)%m))/m;}\ninline ll positive_mod(ll a,ll m){return (a % m + m)%m;}\ninline ll popcnt(ull a){ return __builtin_popcountll(a);}\ntemplate<class T> bool chmin(T& a, T b){if(a > b){a = b;return true;}return false;}\ntemplate<class T> bool chmax(T& a, T b){if(a < b){a = b;return true;}return false;}\ntemplate<typename T> std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}\ntemplate<typename T> std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?\" \":\"\");}return os;}\ntemplate<typename T1, typename T2>std::ostream &operator<< (std::ostream &os, std::pair<T1,T2> p){os << \"{\" << p.first << \",\" << p.second << \"}\";return os;}\ntemplate<class... T>void input(T&... a){(cin >> ... >> a);}\nvoid print(){cout << endl;}\ntemplate<class T, class... Ts>void print(const T& a, const Ts&... b){cout << a;((cout << ' ' << b), ...);cout << endl;}\ntemplate<class T> void pspace(const T& a){ cout << a << ' ';}\nvoid perr(){cerr << endl;}\ntemplate<class T, class... Ts>void perr(const T& a, const Ts&... b){cerr << a;((cerr << ' ' << b), ...);cerr << endl;}\nvoid yes(bool i = true){ return print(i?\"yes\":\"no\"); }\nvoid Yes(bool i = true){ return print(i?\"Yes\":\"No\"); }\nvoid YES(bool i = true){ return print(i?\"YES\":\"NO\"); }\ntemplate <class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v) e++;return v;}\ntemplate <class T> vector<T> operator++(vector<T> &v, signed) {auto res = v;for(auto &e : v) e++;return res;}\ntemplate <class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v) e--;return v;}\ntemplate <class T> vector<T> operator--(vector<T> &v, signed) {auto res = v;for(auto &e : v) e--;return res;}\n//grid探索用\nvector<ll> _ta = {0,0,1,-1,1,1,-1,-1};\nvector<ll> _yo = {1,-1,0,0,1,-1,1,-1};\nbool isin(ll now_i,ll now_j,ll h,ll w){return (0<=now_i && now_i < h && 0 <= now_j && now_j < w);}\n \nll lpow(ll x,ll n){ll ans = 1;while(n >0){if(n & 1)ans *= x;x *= x;n >>= 1;}return ans;}\nll Modlpow(ll x,ll n,ll m){ll ans = 1;ll a = x%m;while(n >0){if(n & 1){ans *= a;ans%= m;}a *= a;a %= m;n >>= 1;}return ans;} \nconst ll MOD9 = 998244353LL;\nconst ll MOD10 = 1000000007LL;\n\n//ref https://github.com/drken1215/algorithm/blob/master/Tree/rerooting_with_edge.cpp\n//verify https://atcoder.jp/contests/abc348/submissions/52401893\ntemplate<class M,class E>\nstruct ReRooting{\n using Graph = vector<vector<E>>;\n using GetIdFunc = function<ll(E)>;//Eから辺の行き先を取り出す\n using AddEdgeFunc = function<M(E, M)>;//情報を持ち上げるときにやりたい操作\n using MergeFunc = function<M(M, M)>;//情報のマージ\n using AddNodeFunc = function<M(ll, M)>;//頂点の情報で反映させたいもの\n\n Graph g;\n M e;\n GetIdFunc getid;\n AddEdgeFunc addedge;\n MergeFunc merge;\n AddNodeFunc addnode;\n\n vector<vector<M>> dp;\n\n ReRooting(){}\n ReRooting(const Graph &_g,const M &_e,const GetIdFunc &_getid,const AddEdgeFunc &_addedge,const MergeFunc &_merge,const AddNodeFunc &_addnode){\n g = _g;\n e = _e;\n getid = _getid;\n addedge = _addedge;\n merge = _merge;\n addnode = _addnode;\n build();\n }\n\n //木DPする\n M rooting(ll v,ll par){\n M ret = e;\n dp[v].assign((ll)g[v].size(),e);\n rep(i,g[v].size()){\n ll nv = getid(g[v][i]);\n if(nv == par)continue;\n dp[v][i] = rooting(nv,v);\n ret = merge(ret,addedge(g[v][i],dp[v][i]));\n }\n return addnode(v,ret);\n }\n\n void rerooting(ll v,ll par,M pval){\n rep(i,g[v].size()){\n ll nv = getid(g[v][i]);\n if(nv == par){\n dp[v][i] = pval;//親から来たやつ\n continue;\n }\n }\n //左右累積計算\n vector<M> left(g[v].size() + 1,e);\n vector<M> right(g[v].size() + 1,e);\n rep(i,g[v].size()){\n ll ri = (ll)g[v].size() -1- i;\n left[i+1] = merge(left[i],addedge(g[v][i],dp[v][i]));\n right[i+1] = merge(right[i],addedge(g[v][ri],dp[v][ri]));\n }\n rep(i,g[v].size()){\n ll nv = getid(g[v][i]);\n ll ri = (ll) g[v].size()- 1 - i;\n if(nv == par)continue;\n M npval = merge(left[i],right[ri]);\n rerooting(nv,v,addnode(v,npval));\n }\n }\n\n void build(){\n dp.assign((ll)g.size(),vector<M>());\n ll root = 0;\n rooting(root,-1); \n \n rerooting(root,-1,e);\n }\n\n M get(ll x){\n M ret = e;\n rep(i,g[x].size()){\n ret = merge(ret,addedge(g[x][i],dp[x][i]));\n }\n return addnode(x,ret);\n }\n};\n\n \nint main(){\n ios::sync_with_stdio(false);cin.tie(nullptr);\n LL(n);\n vector<vpll> g(n);\n rep(i,n-1){\n LL(a,b,w);\n g[a].push_back({b,w});\n g[b].push_back({a,w}); \n }\n\n using M = ll;\n using E = pll;\n auto getid = [&](E x){\n return x.first;\n };\n auto addedge = [&](E a,M b)-> M{\n return a.second + b;\n };\n auto merge = [&](M a,M b)-> M{\n return max(a,b);\n };\n auto addnode = [&](ll a,M b)->M{\n return b;\n };\n M e = 0;\n ReRooting<M,E> rr(g,e,getid,addedge,merge,addnode);\n rr.build();\n\n rep(i,n){\n cout << rr.get(i) << endl;\n }\n\n\n\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7980, "score_of_the_acc": -0.435, "final_rank": 15 }, { "submission_id": "aoj_GRL_5_B_8859767", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=int64_t;\n \nvector<vector<tuple<int,int,int>>> g(10000);\n\nint dfs(int x,int p){\n if((g[x].size()==1)&&(p!=-1)){\n return get<1>(g[x][0]);\n }\n int mx=0,mp=0;\n for(int i=0;i<(int)g[x].size();i++){\n if(get<0>(g[x][i])==p){ \n mp=get<1>(g[x][i]);\n continue;\n }\n if(get<2>(g[x][i])!=-1){\n mx=max(mx,get<2>(g[x][i]));\n }else{\n get<2>(g[x][i])=dfs(get<0>(g[x][i]),x);\n mx=max(mx,get<2>(g[x][i]));\n // cout << x << \"-\" << get<0>(g[x][i]) << \" \" << mx << endl;\n }\n }\n return mx+mp;\n}\n\nint main(){\n int n;\n cin >> n;\n if(n==1){\n cout << 0 << endl;\n return 0;\n }\n \n int s,t,w;\n for(int i=0;i<n-1;i++){\n cin >> s >> t >> w;\n g[s].emplace_back(t,w,-1);\n g[t].emplace_back(s,w,-1);\n }\n for(int i=0;i<n;i++){\n int ans=dfs(i,-1);\n cout << ans << endl;\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 4532, "score_of_the_acc": -0.1784, "final_rank": 10 }, { "submission_id": "aoj_GRL_5_B_8731668", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing P = pair<ll, ll>;\n#define rep(i, a, b) for(ll i = a; i < b; ++i)\n#define rrep(i, a, b) for(ll i = a; i >= b; --i)\nconstexpr ll inf = 4e18;\nstruct SetupIO {\n SetupIO() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout << fixed << setprecision(30);\n }\n} setup_io;\ntemplate <typename T = int>\nstruct Edge {\n int from, to;\n T cost;\n int idx;\n Edge()\n : from(-1), to(-1), cost(-1), idx(-1) {}\n Edge(int from, int to, T cost = 1, int idx = -1)\n : from(from), to(to), cost(cost), idx(idx) {}\n operator int() const {\n return to;\n }\n};\ntemplate <typename T = int>\nstruct Graph {\n vector<vector<Edge<T>>> g;\n int es;\n Graph(int n)\n : g(n), es(0) {}\n size_t size() const {\n return g.size();\n }\n void add_edge(int from, int to, T cost = 1) {\n g[from].emplace_back(from, to, cost, es);\n g[to].emplace_back(to, from, cost, es++);\n }\n void add_directed_edge(int from, int to, T cost = 1) {\n g[from].emplace_back(from, to, cost, es++);\n }\n inline vector<Edge<T>>& operator[](const int& k) {\n return g[k];\n }\n inline const vector<Edge<T>>& operator[](const int& k) const {\n return g[k];\n }\n};\ntemplate <typename T = int>\nusing Edges = vector<Edge<T>>;\ntemplate <typename DP, typename T, typename F1, typename F2>\nvector<DP> rerooting(const Graph<T>& g, const F1& f1, const F2& f2, const DP& id) {\n const int n = (int)g.size();\n vector<DP> memo(n, id), dp(n, id);\n auto dfs = [&](auto& dfs, int cur, int par) -> void {\n for(const auto& e : g[cur]) {\n if(e.to == par) continue;\n dfs(dfs, e, cur);\n memo[cur] = f1(memo[cur], f2(memo[e.to], e.to, cur));\n }\n };\n auto efs = [&](auto& efs, int cur, int par, const DP& pval) -> void {\n vector<DP> buf;\n for(const auto& e : g[cur]) {\n if(e.to == par) continue;\n buf.push_back(f2(memo[e.to], e.to, cur));\n }\n vector<T> head(buf.size() + 1), tail(buf.size() + 1);\n head[0] = tail[buf.size()] = id;\n for(int i = 0; i < (int)buf.size(); ++i) head[i + 1] = f1(head[i], buf[i]);\n for(int i = (int)buf.size() - 1; i >= 0; --i) {\n tail[i] = f1(tail[i + 1], buf[i]);\n }\n dp[cur] = par == -1 ? head.back() : f1(pval, head.back());\n int idx = 0;\n for(const auto& e : g[cur]) {\n if(e.to == par) continue;\n efs(efs, e.to, cur, f2(f1(pval, f1(head[idx], tail[idx + 1])), cur, e));\n ++idx;\n }\n };\n dfs(dfs, 0, -1);\n efs(efs, 0, -1, id);\n return dp;\n}\nint main(void) {\n int n;\n cin >> n;\n Graph<int> g(n);\n map<pair<int, int>, int> mp;\n rep(i, 0, n - 1) {\n int a, b, c;\n cin >> a >> b >> c;\n g.add_edge(a, b, c);\n mp[{a, b}] = c;\n mp[{b, a}] = c;\n }\n using DP = int;\n auto f1 = [&](DP x, DP y) -> DP {\n return max(x, y);\n };\n auto f2 = [&](DP x, int child, int parent) -> DP {\n return x + mp[{child, parent}];\n };\n DP id = 0;\n vector<DP> dp = rerooting(g, f1, f2, id);\n rep(i, 0, n) {\n cout << dp[i] << '\\n';\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8076, "score_of_the_acc": -0.4454, "final_rank": 16 }, { "submission_id": "aoj_GRL_5_B_8660955", "code_snippet": "#include <bits/stdc++.h>\n// #include <atcoder/all>\n#if __has_include(<boost/algorithm/string.hpp>)\n#include <boost/algorithm/string.hpp>\n#endif\n#if __has_include(<boost/algorithm/cxx11/all_of.hpp>)\n#include <boost/algorithm/cxx11/all_of.hpp>\n#include <boost/algorithm/cxx11/any_of.hpp>\n#include <boost/algorithm/cxx11/none_of.hpp>\n#include <boost/algorithm/cxx11/one_of.hpp>\n#endif\n#if __has_include(<boost/lambda/lambda.hpp>)\n#include <boost/lambda/lambda.hpp>\n#endif\n#if __has_include(<boost/range/irange.hpp>)\n#include <boost/range/irange.hpp>\n#include <boost/range/adaptors.hpp>\n#endif\n#if __has_include(<boost/multiprecision/cpp_int.hpp>)\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n#if __has_include(<gmpxx.h>)\n#include <gmpxx.h>\n#endif\n\nusing namespace std;\n\n// constant values\nconst int INF32 = numeric_limits<int>::max(); //2.147483647×10^{9}:32bit整数のinf\nconst int inf32 = INF32 / 2;\nconst long long INF64 = numeric_limits<long long>::max(); //9.223372036854775807×10^{18}:64bit整数のinf\nconst long long inf64 = INF64 / 2;\nconst double EPS = numeric_limits<double>::epsilon(); //問題による\n// const int MOD = 998244353; //問題による\n\nbool DEBUG = true;\n\n// REP macro\n#define OVERLOAD_REP(_1, _2, _3, name, ...) name\n#define REP1(i, n) REP2(i, 0, n)\n#define REP2(i, l, r) for (long long (i) = (l); (i) < (long long)(r); ++(i))\n#define REP3(i, l, r, s) for (long long (i) = (l); (i) < (long long)(r); (i) += (s))\n#define rep(i, ...) OVERLOAD_REP(__VA_ARGS__, REP3, REP2, REP1)(i, __VA_ARGS__)\n\n#define REPD1(i, n) REPD2(i, 0, n)\n#define REPD2(i, l, r) for (long long (i) = (long long)(r) - 1; (i) >= (long long)(l); --(i))\n#define REPD3(i, l, r, s) for (long long (i) = (long long)(r) - 1; (i) >= (long long)(l); (i) -= (s))\n#define repd(i, ...) OVERLOAD_REP(__VA_ARGS__, REPD3, REPD2, REPD1)(i, __VA_ARGS__)\n\n#define fore(i, I) for (auto& (i): (I))\n#define fored(i, I) for (auto& (i): (I) | views::reverse)\n#define all(A) A.begin(), A.end()\n\n// for debug\n#define debug(x) if (DEBUG) cerr << #x << \": \" << x << endl;\n#define debug_v(A) if (DEBUG) {cerr << #A << \": \" << endl; fore(a, A) cerr << a << \" \"; cerr << endl;}\n#define debug_vv(A) if (DEBUG) {cerr << #A << \": \" << endl; fore(v, A) {fore(a, v) cerr << a << \" \"; cerr << endl;} cerr << endl;}\n\n// 省略\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define fi first\n#define se second\n\nusing ll = long long;\nusing ull = unsigned long long;\nusing vll = vector<ll>;\nusing setll = set<ll>;\nusing mapll = map<ll, ll>;\nusing pll = pair<ll, ll>;\n\ntemplate<typename T>\nusing vec = vector<T>;\n\ntemplate<typename T>\nusing vv = vector<vector<T>>;\n\ntemplate<typename T>\nusing vvv = vector<vector<vector<T>>>;\n\nusing str = string;\nusing vstr = vector<str>;\nusing sstr = set<str>;\n\nusing vchar = vector<char>;\nusing schar = set<char>;\n\nusing vd = vector<double>;\n\n// boost関連\n#if __has_include(<boost/algorithm/cxx11/all_of.hpp>)\nusing boost::algorithm::all_of_equal;\nusing boost::algorithm::any_of_equal;\nusing boost::algorithm::none_of_equal;\nusing boost::algorithm::one_of_equal;\nusing boost::algorithm::all_of;\nusing boost::algorithm::any_of;\nusing boost::algorithm::none_of;\nusing boost::algorithm::one_of;\n#endif\n#if __has_include(<boost/lambda/lambda.hpp>)\nusing boost::lambda::_1;\nusing boost::lambda::_2;\nusing boost::lambda::_3;\n#endif\n#if __has_include(<boost/multiprecision/cpp_int.hpp>)\nusing namespace boost::multiprecision;\nusing lll = int128_t;\n#endif\n#if __has_include(<gmpxx.h>)\n#include <gmpxx.h>\nusing mpz = mpz_class;\n#endif\n\ntemplate<typename T>\ninline void input(T& a) {\n cin >> a;\n}\n\ntemplate<typename T>\ninline void input(T& a, T& b) {\n input(a); input(b);\n}\n\ntemplate<typename T>\ninline void input(T& a, T& b, T& c) {\n input(a); input(b, c);\n}\n\ntemplate<typename T>\ninline void input(T& a, T& b, T& c, T& d) {\n input(a); input(b, c, d);\n}\n\ntemplate<typename T>\ninline void input(T& a, T& b, T& c, T& d, T& e) {\n input(a); input(b, c, d, e);\n}\n\ntemplate<typename T>\ninline void input(T& a, T& b, T& c, T& d, T&e, T& f) {\n input(a); input(b, c, d, e, f);\n}\n\ntemplate<typename T>\ninline void input(vector<T>& A) {\n rep(i, A.size()) cin >> A.at(i);\n}\n\ntemplate<typename T>\ninline void input(vector<T>& A, vector<T>& B) {\n if (A.size() != B.size()) throw runtime_error(\"Vector sizes are different.\");\n \n rep(i, A.size) {\n cin >> A.at(i) >> B.at(i);\n }\n}\n\ntemplate<typename T>\ninline void input(vector<T>& A, vector<T>& B, vector<T>& C) {\n if (A.size() != B.size() or A.size() != C.size()) throw runtime_error(\"Vector sizes are different.\");\n \n rep(i, A.size) {\n cin >> A.at(i) >> B.at(i) >> C.at(i);\n }\n}\n\ntemplate<typename T>\ninline void input(const long long N, vector<T>& A) {\n rep(i, N) {\n T a;\n cin >> a;\n A.push_back(a);\n }\n}\n\ntemplate<typename T>\ninline void input(const long long N, vector<T>& A, vector<T>& B) {\n rep(i, N) {\n T a, b;\n cin >> a >> b;\n A.push_back(a);\n B.push_back(b);\n }\n}\n\ntemplate<typename T>\ninline void input(const long long N, vector<T>& A, vector<T>& B, vector<T>& C) {\n rep(i, N) {\n T a, b, c;\n cin >> a >> b >> c;\n A.push_back(a);\n B.push_back(b);\n C.push_back(c);\n }\n}\n\ntemplate<typename T>\ninline void input(const long long N, set<T>& A) {\n rep(i, N) {\n T a;\n cin >> a;\n A.insert(a);\n }\n}\n\ntemplate<typename T>\ninline void input(const long long N, set<T>& A, set<T>& B) {\n rep(i, N) {\n T a, b;\n cin >> a >> b;\n A.insert(a);\n B.insert(b);\n }\n}\n\ntemplate<typename T>\ninline void input(const long long N, set<T>& A, set<T>& B, set<T>& C) {\n rep(i, N) {\n T a, b, c;\n cin >> a >> b >> c;\n A.insert(a);\n B.insert(b);\n C.insert(c);\n }\n}\n\ntemplate<typename T>\ninline void input(const long long H, const long long W, vector<vector<T>>& A) {\n rep(i, H) {\n vector<T> v;\n rep(j, W) {\n T a;\n cin >> a;\n v.push_back(a);\n }\n \n A.push_back(v);\n }\n}\n\n// 第一引数と第二引数を比較し、第一引数(a)をより大きい/小さい値に上書き\ntemplate<typename T>\ninline bool chmin(T &a, const T &b) {\n bool compare = a > b;\n if (compare) a = b;\n return compare;\n}\n\ntemplate<typename T>\ninline bool chmax(T &a, const T &b) {\n bool compare = a < b;\n if (compare) a = b;\n return compare;\n}\n\ntemplate<class Weight = long long, class Cap = long long>\nstruct Edge {\n long long from;\n long long to;\n Weight weight;\n Cap cap;\n long long id;\n long long rev;\n Cap flow;\n \n explicit Edge(long long u = -1, long long v = -1, Weight w = 1, long long i = -1, Cap cap = 0, long long rev = -1) : from(u), to(v), weight(w), cap(cap), id(i), rev(rev), flow(0) {};\n\n bool operator < (const Edge& other) const {\n if (from == other.from) {\n if (to == other.to) return weight < other.weight;\n else return to < other.to;\n }\n else return from < other.from;\n }\n};\n\nstruct Stamp {\n long long index;\n long long time;\n explicit Stamp(long long i = 0, long long t = -1) : index(i), time(t) {};\n\n bool operator<(const Stamp& right) const {\n return time < right.time;\n }\n};\n\ntemplate<class Weight = long long, class Cap = long long, class DP = long long>\nstruct Graph {\n // DFS, BFS共通\n long long V;\n bool directed;\n vector<vector<Edge<Weight, Cap>>> G;\n vector<bool> seen, done;\n vector<Edge<Weight, Cap>> prev;\n long long edge_index = 0;\n vector<Edge<Weight, Cap>> edges;\n\n // DFS用\n vector<Stamp> pre_order, post_order;\n long long first, last;\n bool has_cycle;\n vector<long long> descendants;\n long long inf = inf64;\n\n // BFS用\n vector<long long> depth;\n\n // ダイクストラ用\n vector<Weight> cost;\n\n // LCA用\n vector<vector<long long>> doubling;\n long long log;\n bool _lca_init_done;\n\n // 二部グラフ用\n bool _is_bipartite = true;\n vector<long long> colors;\n\n // CC用\n vector<long long> groups;\n vector<set<long long>> cc; \n vector<set<long long>> cc_edge;\n\n // SCC用\n vector<vector<Edge<Weight, Cap>>> rG;\n vector<long long> roots;\n vector<set<long long>> scc;\n\n // トポロジカルソート用\n vector<long long> topo_dp;\n\n // 全方位木dp用\n vector<vector<DP>> dp;\n vector<DP> prod_all;\n long long root;\n\n // maxflow用\n vector<long long> level;\n vector<long long> iter;\n\n // mincostflow用\n vector<Weight> dual, dist;\n vector<long long> prevv, preve;\n Cap cur_flow;\n Cap cur_cost, pre_cost;\n vector<pair<Cap, Weight>> min_cost_slope;\n\n explicit Graph(long long V, bool directed) : V(V), directed(directed), G(V), rG(V) {\n init();\n };\n \n void init() {\n first = 0;\n last = 0;\n has_cycle = false;\n _lca_init_done = false;\n cur_flow = 0;\n cur_cost = 0;\n pre_cost = -1;\n\n log = 1;\n while ((1ll << log) <= V) log++;\n\n seen.assign(V, false);\n done.assign(V, false);\n prev.assign(V, Edge<Weight, Cap>());\n colors.assign(V, -1);\n descendants.assign(V, 0);\n roots.assign(V, -1);\n groups.assign(V, -1);\n depth.assign(V, inf);\n cost.assign(V, inf);\n doubling.assign(log, vector<long long>(V, -1));\n level.assign(V, -1);\n iter.assign(V, 0);\n dual.assign(V, 0);\n dist.assign(V, 0);\n prevv.assign(V, -1);\n preve.assign(V, -1);\n topo_dp.assign(V, 0);\n dp.resize(V);\n prod_all.assign(V, id());\n }\n \n void connect(long long from, long long to, Weight weight = 1) {\n assert(0 <= from and from < V);\n assert(0 <= to and to < V);\n\n if (directed) {\n edges.emplace_back(from, to, weight, edge_index);\n\n G.at(from).emplace_back(from, to, weight, edge_index);\n rG.at(to).emplace_back(to, from, weight, edge_index);\n }\n else {\n long long from_id = G.at(from).size();\n long long to_id = G.at(to).size();\n\n edges.emplace_back(from, to, weight, edge_index, weight, from_id);\n\n G.at(from).emplace_back(from, to, weight, edge_index, weight, to_id);\n G.at(to).emplace_back(to, from, weight, edge_index, 0, from_id);\n\n dp.at(from).push_back(id());\n dp.at(to).push_back(id());\n }\n\n edge_index++;\n }\n\n void connect(long long from, long long to, Cap cap, Weight cost) {\n assert(0 <= from and from < V);\n assert(0 <= to and to < V);\n\n if (!directed) {\n long long from_id = G.at(from).size();\n long long to_id = G.at(to).size();\n\n edges.emplace_back(from, to, cost, edge_index, cap, from_id);\n\n G.at(from).emplace_back(from, to, cost, edge_index, cap, to_id);\n G.at(to).emplace_back(to, from, -cost, edge_index, 0, from_id);\n }\n\n edge_index++;\n }\n\n DP id() {\n return 0;\n }\n\n DP merge(DP x, DP y) {\n return max(x, y);\n }\n\n DP put_edge(DP x, Edge<Weight, Cap>& edge) {\n return x + (DP)edge.weight;\n }\n\n DP put_vertex(DP x, long long v) {\n return x;\n }\n\n DP build(long long root_) {\n root = root_;\n return dfs(root);\n }\n\n vector<DP> reroot() {\n dfs_dp(root, id());\n\n return prod_all;\n }\n\n void dfs_all() {\n long long group = 0;\n\n rep(i, V) {\n if (seen.at(i)) continue;\n dfs(i, group);\n group++;\n }\n }\n\n DP dfs(long long now, long long group = 0, Edge<Weight, Cap> e = Edge<Weight, Cap>()) {\n assert(0 <= now and now < V);\n\n DP ret = id();\n\n seen.at(now) = true;\n pre_order.emplace_back(now, first);\n first++;\n\n groups.at(now) = group;\n while (cc.size() <= group) cc.push_back(set<long long>());\n cc.at(group).insert(now);\n while (cc_edge.size() <= group) cc_edge.push_back(set<long long>());\n\n if (colors.at(now) == -1) colors.at(now) = 0;\n long long next_color = !colors.at(now);\n\n rep(i, G.at(now).size()) {\n Edge<Weight, Cap> edge = G.at(now).at(i);\n long long next = edge.to;\n\n if (edge.id == e.id) continue;\n\n cc_edge.at(group).insert(edge.id);\n\n if (colors.at(next) == -1) colors.at(next) = next_color;\n else if (colors.at(next) != next_color) _is_bipartite = false;\n\n if (seen.at(next)) {\n if (!done.at(next)) has_cycle = true;\n continue;\n }\n\n prev.at(next) = edge;\n\n dp.at(now).at(i) = dfs(next, group, edge);\n ret = merge(ret, put_edge(dp.at(now).at(i), edge));\n\n descendants.at(now) += descendants.at(next) + 1;\n }\n\n done.at(now) = true;\n post_order.emplace_back(now, last);\n last++;\n\n return put_vertex(ret, now);\n }\n\n void dfs_dp(long long now, const DP& dp_p, Edge<Weight, Cap> e = Edge<Weight, Cap>()) {\n long long deg = G.at(now).size();\n\n if (e.rev != -1) dp.at(now).at(e.rev) = dp_p;\n\n vector<DP> prod_l(deg + 1, id()), prod_r(deg + 1, id());\n\n rep(i, deg) {\n Edge<Weight, Cap> edge = G.at(now).at(i);\n prod_l.at(i + 1) = merge(prod_l.at(i), put_edge(dp.at(now).at(i), edge));\n }\n\n repd(i, deg) {\n Edge<Weight, Cap> edge = G.at(now).at(i);\n prod_r.at(i) = merge(prod_r.at(i + 1), put_edge(dp.at(now).at(i), edge));\n }\n\n prod_all.at(now) = put_vertex(prod_l.back(), now);\n\n rep(i, deg) {\n if (i == e.rev) continue;\n\n Edge<Weight, Cap> edge = G.at(now).at(i);\n long long child = edge.to;\n dfs_dp(child, put_vertex(merge(prod_l.at(i), prod_r.at(i + 1)), now), edge);\n }\n }\n \n void dfs_scc(long long now, long long group) { // SCC用\n roots.at(now) = group;\n fore(edge, rG.at(now)) {\n long long next = edge.to;\n if (roots.at(next) != -1) continue;\n dfs(next, group);\n }\n }\n\n Cap dfs_flow(long long v, long long s, long long t, Cap flow) { // maxflow用\n if (v == s) return flow;\n\n Cap res = 0;\n long long level_v = level.at(v);\n\n for (long long& i = iter.at(v); i < (long long)(G.at(v).size()); i++) {\n Edge<Weight, Cap>& e = G.at(v).at(i);\n long long next = e.to;\n\n if (level_v <= level.at(next) || G.at(next).at(e.rev).cap == 0) continue;\n\n Cap d = dfs_flow(next, s, t, min(flow - res, G.at(next).at(e.rev).cap));\n\n if (d <= 0) continue;\n\n G.at(v).at(i).cap += d;\n G.at(next).at(e.rev).cap -= d;\n res += d;\n\n if (res == flow) return res;\n }\n\n level.at(v) = V;\n return res;\n }\n\n void bfs_all() {\n long long group = 0;\n\n rep(i, V) {\n if (seen.at(i)) continue;\n bfs(i, group);\n group++;\n }\n }\n\n void bfs(long long start, long long group = -1) {\n assert(0 <= start and start < V);\n\n queue<long long> que;\n\n // 初期条件 (頂点 start を初期ノードとする)\n seen.at(start) = true;\n depth.at(start) = 0;\n groups.at(start) = group;\n que.push(start); // noq を橙色頂点にする\n\n // BFS 開始 (キューが空になるまで探索を行う)\n while (!que.empty()) {\n long long now = que.front(); // キューから先頭頂点を取り出す\n que.pop();\n\n // v から辿れる頂点をすべて調べる\n fore(edge, G.at(now)) {\n long long next = edge.to;\n if (seen.at(next)) continue; // すでに発見済みの頂点は探索しない\n seen.at(next) = true;\n\n // 新たな白色頂点 nv について距離情報を更新してキューに追加する\n depth.at(next) = depth.at(now) + 1;\n prev.at(next) = edge;\n groups.at(next) = group;\n que.push(next);\n doubling.front().at(next) = now;\n }\n }\n }\n\n void bfs_flow(long long s, long long t) {\n assert(0 <= s and s < V);\n assert(0 <= t and t < V);\n\n fill(level.begin(), level.end(), -1);\n queue<long long> que;\n\n // 初期条件 (頂点 start を初期ノードとする)\n level.at(s) = 0;\n que.push(s); // noq を橙色頂点にする\n\n // BFS 開始 (キューが空になるまで探索を行う)\n while (!que.empty()) {\n long long now = que.front(); // キューから先頭頂点を取り出す\n que.pop();\n\n // v から辿れる頂点をすべて調べる\n fore(edge, G.at(now)) {\n long long next = edge.to;\n if (edge.cap == 0 or level.at(next) >= 0) continue; // すでに発見済みの頂点は探索しない\n\n // 新たな白色頂点 nv について距離情報を更新してキューに追加する\n level.at(next) = level.at(now) + 1;\n \n if (next == t) return;\n que.push(next);\n }\n }\n }\n\n void lca_init(long long root) {\n assert(0 <= root and root < V);\n\n bfs(root);\n\n rep(k, log - 1) {\n rep(v, V) {\n if (doubling.at(k).at(v) >= 0) {\n doubling.at(k + 1).at(v) = doubling.at(k).at(doubling.at(k).at(v));\n }\n }\n }\n\n _lca_init_done = true;\n }\n\n // lca_init後にuとvの最小共通祖先を返す\n long long lca(long long u, long long v) {\n assert(_lca_init_done);\n assert(0 <= u and u < V);\n assert(0 <= v and v < V);\n\n if (depth.at(u) < depth.at(v)) swap(u, v);\n\n rep(k, log) {\n if ((depth.at(u) - depth.at(v)) >> k & 1) {\n u = doubling.at(k).at(u);\n }\n }\n\n if (u == v) return u;\n \n repd(k, log - 1) {\n if (doubling.at(k).at(u) != doubling.at(k).at(v)) {\n u = doubling.at(k).at(u);\n v = doubling.at(k).at(v);\n }\n }\n\n return doubling.at(0).at(u);\n }\n\n // lca_init後にuとvの距離を返す\n long long get_dist(long long u, long long v) {\n assert(_lca_init_done);\n assert(0 <= u and u < V);\n assert(0 <= v and v < V);\n\n return depth.at(u) + depth.at(v) - 2 * depth.at(lca(u, v));\n }\n\n // lca_init後にuとvを結ぶパス上にaがあるか返す\n bool is_on_path(long long u, long long v, long long a) {\n assert(0 <= u and u < V);\n assert(0 <= v and v < V);\n assert(0 <= a and a < V);\n assert(_lca_init_done);\n\n return get_dist(u, a) + get_dist(a, v) == get_dist(u, v);\n }\n\n void dijkstra_all() {\n long long group = 0;\n\n rep(i, V) {\n if (done.at(i)) continue;\n dijkstra(i, group);\n group++;\n }\n }\n\n void dijkstra(long long start, long long group = -1) {\n assert(0 <= start and start < V);\n\n using pll = pair<long long, long long>;\n priority_queue<pll, vector<pll>, greater<>> que;\n\n cost.at(start) = 0;\n que.emplace(cost.at(start), start);\n while (!que.empty()) {\n long long now = que.top().second;\n que.pop();\n\n if (done.at(now)) continue; // nowが確定済だったら飛ばす\n done.at(now) = true; // nowを初めてキューから取り出したら最小として確定\n\n fore(edge, G.at(now)) {\n long long next = edge.to;\n if (chmin(cost.at(next), cost.at(now) + edge.weight)) {\n prev.at(next) = edge;\n que.emplace(cost.at(next), next);\n }\n }\n }\n }\n\n long long find_diameter() {\n long long ret = 0;\n\n rep(i, V) {\n if (seen.at(i)) continue;\n bfs(i);\n long long u = distance(depth.begin(), max_element(depth.begin(), depth.end()));\n\n init();\n bfs(u);\n long long v = distance(depth.begin(), max_element(depth.begin(), depth.end()));\n \n chmax(ret, depth.at(v));\n init();\n }\n\n return ret;\n }\n\n bool reach_at(long long to) {\n assert(0 <= to and to < V);\n\n return seen.at(to);\n }\n\n bool is_connected() {\n bool ret = true;\n rep(i, V) {\n if (seen.at(i)) continue;\n ret = false;\n break;\n }\n\n return ret;\n }\n\n vector<long long> path_to(long long to) {\n assert(0 <= to and to < V);\n\n vector<long long> p;\n p.push_back(to);\n\n while (prev.at(p.back()).from != -1) {\n p.push_back(prev.at(p.back()).from);\n }\n\n reverse(p.begin(), p.end());\n\n return p;\n }\n\n long long find_scc() { // 強連結成分分解, 有効グラフで互いに行き来可能な頂点同士を調べる\n vector<long long> v = topological_sort();\n fore(index, v) {\n if (roots.at(index) != -1) continue;\n dfs_scc(index, index);\n }\n\n map<long long, set<long long>> m;\n\n rep(i, roots.size()) {\n m[roots.at(i)].insert(i);\n }\n\n fore(p, m) {\n set<long long> s_i = p.second;\n scc.push_back(s_i);\n }\n\n return (long long)scc.size();\n }\n\n vector<long long> topological_sort() {\n rep(i, V) sort(G.at(i).begin(), G.at(i).end());\n\n dfs_all();\n\n vector<long long> v;\n rep(i, V) v.push_back(post_order.at(i).index);\n reverse(v.begin(), v.end());\n\n return v;\n }\n\n bool is_same(long long u, long long v) { // SCC用, 同じ強連結成分のグループかどうか返す\n assert(0 <= u and u < V);\n assert(0 <= v and v < V);\n \n return roots.at(u) == roots.at(v);\n }\n\n long long longest_path() {\n vector<long long> topo = topological_sort();\n\n init();\n\n rep(i, V) {\n ll now = topo.at(i);\n\n fore(edge, G.at(now)) {\n long long next = edge.to;\n\n if (chmax(topo_dp.at(next), topo_dp.at(now) + 1)) {\n prev.at(next) = edge;\n }\n }\n }\n\n return *max_element(topo_dp.begin(), topo_dp.end());\n }\n\n vector<long long> get_longest_path() {\n vector<long long> ret;\n\n ll goal = dist(topo_dp.begin(), max_element(topo_dp.begin(), topo_dp.end()));\n\n return path_to(goal);\n }\n\n Cap max_flow(long long s, long long t) {\n return max_flow(s, t, numeric_limits<Cap>::max());\n }\n\n Cap max_flow(long long s, long long t, Cap flow_limit) {\n assert(0 <= s && s < V);\n assert(0 <= t && t < V);\n assert(s != t);\n\n Cap flow = 0;\n while (flow < flow_limit) {\n bfs_flow(s, t);\n\n if (level.at(s) == -1) break;\n\n fill(iter.begin(), iter.end(), 0);\n\n Cap f = dfs_flow(t, s, t, flow_limit - flow);\n\n if (!f) break;\n flow += f;\n }\n return flow;\n }\n\n void change_edge(long long i, Cap new_cap, Cap new_flow) {\n long long m = edges.size();\n\n assert(0 <= i && i < m);\n assert(0 <= new_flow && new_flow <= new_cap);\n\n Edge<Weight, Cap> edge = edges.at(i);\n\n auto& _e = G.at(edge.from).at(edge.rev);\n auto& _re = G.at(_e.to).at(_e.rev);\n _e.cap = new_cap - new_flow;\n _re.cap = new_flow;\n }\n\n // max_flow(s, t)後に使用することでs,t間の最小カットを返す\n vector<bool> min_cut(long long s) {\n vector<bool> visited(V);\n\n queue<long long> que;\n que.push(s);\n \n while (!que.empty()) {\n long long p = que.front();\n que.pop();\n visited.at(p) = true;\n\n fore(e, G.at(p)) {\n if (e.cap && !visited.at(e.to)) {\n visited.at(e.to) = true;\n que.push(e.to);\n }\n }\n }\n return visited;\n }\n\n pair<Cap, Weight> min_cost_flow(long long s, long long t) {\n return min_cost_flow(s, t, numeric_limits<Cap>::max());\n }\n \n pair<Cap, Weight> min_cost_flow(long long s, long long t, Cap flow_limit) {\n return slope(s, t, flow_limit).back();\n }\n\n vector<pair<Cap, Weight>> slope(long long s, long long t) {\n return slope(s, t, numeric_limits<Cap>::max());\n }\n\n vector<pair<Cap, Weight>> slope(long long s, long long t, Cap flow_limit) {\n assert(0 <= s && s < V);\n assert(0 <= t && t < V);\n assert(s != t);\n\n min_cost_slope.emplace_back(cur_flow, cur_cost);\n \n // primal-dual\n while (cur_flow < flow_limit) {\n if (!dual_step(s, t)) break;\n primal_step(s, t, flow_limit);\n }\n return min_cost_slope;\n }\n\n bool dual_step(long long s, long long t) {\n priority_queue<pair<Weight, long long>, vector<pair<Weight, long long>>, greater<pair<Weight, long long>>> que;\n que.emplace(0, s);\n\n dist.assign(G.size(), numeric_limits<Weight>::max());\n dist.at(s) = 0;\n\n while (!que.empty()) {\n auto p = que.top();\n auto cur_cost = p.first;\n auto v = p.second;\n que.pop();\n\n if (dist.at(v) < cur_cost) continue;\n rep(i, G.at(v).size()) {\n const auto &e = G.at(v).at(i);\n Weight new_cost = e.weight + dual.at(v) - dual.at(e.to);\n\n if (e.cap > 0 && dist.at(e.to) > dist.at(v) + new_cost) {\n dist.at(e.to) = dist.at(v) + new_cost;\n prevv.at(e.to) = v;\n preve.at(e.to) = i;\n que.emplace(dist.at(e.to), e.to);\n }\n }\n }\n \n if (dist.at(t) == numeric_limits<Weight>::max()) return false;\n \n rep(v, G.size()) {\n if (dist.at(t) == numeric_limits<Weight>::max()) continue;\n dual.at(v) -= dist.at(t) - dist.at(v);\n }\n return true;\n }\n\n void primal_step(long long s, long long t, Cap flow_limit) {\n Cap flow = flow_limit - cur_flow;\n Weight cost = -dual.at(s);\n for (long long v = t; v != s; v = prevv.at(v)) {\n flow = min(flow, G.at(prevv.at(v)).at(preve.at(v)).cap);\n }\n\n for (long long v = t; v != s; v = prevv.at(v)) {\n auto &e = G.at(prevv.at(v)).at(preve.at(v));\n auto &re = G.at(e.to).at(e.rev);\n e.cap -= flow, e.flow += flow;\n re.cap += flow, re.flow -= flow;\n }\n\n cur_flow += flow;\n cur_cost += flow * cost;\n\n if (pre_cost == cost) min_cost_slope.pop_back();\n min_cost_slope.emplace_back(cur_flow, cur_cost);\n pre_cost = cur_cost;\n }\n};\n\nint main() {\n long long N;\n input(N);\n\n Graph graph(N, false);\n\n rep(i, N - 1) {\n long long s, t, w;\n input(s, t, w);\n\n graph.connect(s, t, w);\n }\n\n graph.build(0);\n // debug_vv(graph.dp);\n vector<long long> dp = graph.reroot();\n // debug_vv(graph.dp);\n // debug_v(dp);\n fore(ans, dp) cout << ans << endl;\n\n // cout << fixed << setprecision(10); // 小数点以下を10桁表示,許容誤差が1e-N以下の時はN+1に変更すること(16桁以上はlong double)\n // cout << ans << endl;\n // cout << YesNo(ans) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 13196, "score_of_the_acc": -1, "final_rank": 19 } ]
aoj_GRL_4_B_cpp
Topological Sort A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obtain the proper sequence of all the tasks by a topological sort. Given a DAG $G$, print the order of vertices after the topological sort. Input A directed graph $G$ is given in the following format: $|V|\;|E|$ $s_0 \; t_0$ $s_1 \; t_1$ : $s_{|E|-1} \; t_{|E|-1}$ $|V|$ is the number of vertices and $|E|$ is the number of edges in the graph. The graph vertices are named with the numbers $0, 1,..., |V|-1$ respectively. $s_i$ and $t_i$ represent source and target nodes of $i$-th edge (directed). Output Print the vertices numbers in order. Print a number in a line. If there are multiple possible solutions, print any one of them (the solution is judged by a special validator). Constraints $1 \leq |V| \leq 10,000$ $0 \leq |E| \leq 100,000$ There are no parallel edges in $G$ There are no self loops in $G$ Sample Input 6 6 0 1 1 2 3 1 3 4 4 5 5 2 Sample Output 0 3 1 4 5 2
[ { "submission_id": "aoj_GRL_4_B_11066613", "code_snippet": "#include <iostream>\n#include <vector>\n#include <climits>\n#include <queue>\n#include <algorithm>\nusing namespace std;\nconst int MAXVEX = 10000;\n\n// 需要有向无环图\n\nclass Graph {\npublic:\n int n; // 顶点数\n int m; // 边数\n vector<vector<int>> adjList; // 邻接表\n\n int visited[MAXVEX];\n int inDegree[MAXVEX]; // 各个顶点的入度\n\n Graph() {};\n Graph(int n, int m) : n(n), m(m) {\n adjList.resize(n);\n fill(inDegree, inDegree + n, 0);\n };\n\n void CreateList(); // 根据输入创建邻接表\n\n vector<int> TopologicalSort(); // 返回拓扑排序后的顶点\n};\n\nvoid Graph::CreateList() {\n for (int i = 0; i < m; i++) {\n int s, t;\n cin >> s >> t;\n adjList[s].push_back(t);\n\t\tinDegree[t]++;\n }\n}\n\nvector<int> Graph::TopologicalSort() {\n // 基于 BFS\n queue<int> q;\n\n // 将所有入度为 0 的节点入队\n for (int i = 0; i < n; i++) {\n if (inDegree[i] == 0) {\n q.push(i);\n }\n }\n\n vector<int> topoResult;\n\n while (!q.empty()) {\n int v = q.front();\n q.pop();\n topoResult.push_back(v);\n\n // 遍历 v 指向的所有节点\n for (int u: adjList[v]) {\n inDegree[u]--;\n if (inDegree[u] == 0) {\n q.push(u); // 将入度为 0 的节点入队\n }\n }\n }\n\n // 如果拓扑序节点数 != n,说明有环\n return topoResult;\n}\n\nint main() {\n int n, m;\n cin >> n >> m;\n Graph G(n, m);\n\n G.CreateList();\n vector<int> result = G.TopologicalSort();\n for (int x : result) {\n cout << x << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3916, "score_of_the_acc": -0.0576, "final_rank": 5 }, { "submission_id": "aoj_GRL_4_B_11051809", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int N, M;\n cin >> N >> M;\n\n vector<int> in_deg(N, 0);\n vector<vector<int>> graph(N);\n for (int i = 0; i < M; i++) {\n int s, t; cin >> s >> t;\n graph[s].push_back(t);\n in_deg[t]++;\n }\n\n queue<int> que;\n for (int i = 0; i < N; i++) {\n if (in_deg[i] == 0) que.push(i);\n }\n\n vector<int> result;\n while (!que.empty()) {\n int now = que.front(); que.pop();\n result.push_back(now);\n for (auto nex : graph[now]) {\n in_deg[nex]--;\n if (in_deg[nex] == 0) que.push(nex);\n }\n }\n\n for (int i = 0; i < N; i++) {\n cout << result[i] << \" \";\n }\n\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4036, "score_of_the_acc": -0.1009, "final_rank": 9 }, { "submission_id": "aoj_GRL_4_B_10959445", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, a, n) for (int i = a; i < n; ++i)\n#define rrep(i, a, n) for (int i = n - 1; i >= a; --i)\nusing ll = long long;\nusing ld = long double;\nusing pl = pair<ll, ll>;\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing vp = vector<pl>;\nusing vvp = vector<vp>;\nusing vb = vector<bool>;\nusing vvb = vector<vb>;\nusing vs = vector<string>;\nusing vc = vector<char>;\nusing vvc = vector<vc>;\nconst int mod = 1000000007;\nconst ll hashh = 2147483647;\n\nint main()\n{\n ll v, e;\n cin >> v >> e;\n vl s(e), t(e), a(v);\n vvl g(v);\n rep(i, 0, e)\n {\n cin >> s[i] >> t[i];\n g[s[i]].push_back(t[i]);\n a[t[i]]++;\n }\n queue<ll> q;\n rep(i, 0, v)\n {\n if (a[i] == 0)\n {\n q.push(i);\n }\n }\n vl ans;\n while (!q.empty())\n {\n ll p = q.front();\n q.pop();\n for (auto &z : g[p])\n {\n a[z]--;\n if (a[z] == 0)\n q.push(z);\n }\n ans.push_back(p);\n }\n for (auto &z : ans)\n {\n cout << z << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4884, "score_of_the_acc": -0.4063, "final_rank": 16 }, { "submission_id": "aoj_GRL_4_B_10951783", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(n);i++)\n#define all(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\nusing ll=long long;\nusing pi=pair<int,int>;\nconst int di[]={+1,-1,+0,+0};\nconst int dj[]={+0,+0,+1,-1};\nconst int INF=1e9;\n//const ll INF=1e18;\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n, m;\n cin >> n >> m;\n vector<vector<int>> G(n);\n vector<int> deg(n, 0);\n rep(i, m) {\n int s, t;\n cin >> s >> t;\n G[s].push_back(t);\n deg[t]++;\n }\n vector<bool> seen(n, false);\n vector<int> topo;\n auto dfs=[&](auto dfs, int v) -> void {\n seen[v]=true;\n for(int nv:G[v]) if(!seen[nv]) {\n dfs(dfs, nv);\n }\n topo.push_back(v);\n };\n rep(i, n) if(!seen[i]) dfs(dfs, i);\n reverse(all(topo));\n for(int x:topo) cout << x << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4012, "score_of_the_acc": -0.0922, "final_rank": 7 }, { "submission_id": "aoj_GRL_4_B_10905741", "code_snippet": "#include <iostream>\n#include <vector>\n#include <stack>\n\nconst int MAXN = 10000 + 1;\n\nstd::vector<int> G[MAXN];\nbool visited[MAXN];\nstd::stack<int> si;\n\nvoid dfs(int v)\n{\n visited[v] = true; \n for (int i = 0; i < G[v].size(); ++i) {\n if (!visited[G[v][i]]) {\n dfs(G[v][i]);\n }\n }\n si.push(v);\n}\n\nint main()\n{\n int v, e;\n std::cin >> v >> e;\n for (int i = 0; i < e; ++i) {\n int s, t;\n std::cin >> s >> t;\n G[s].push_back(t);\n }\n\n for (int i = 0; i < v; ++i) {\n if (!visited[i]) {\n dfs(i);\n }\n }\n\n while (!si.empty()) {\n std::cout << si.top() << std::endl;\n si.pop();\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4012, "score_of_the_acc": -0.0922, "final_rank": 7 }, { "submission_id": "aoj_GRL_4_B_10903876", "code_snippet": "using namespace std;\n#include <bits/stdc++.h>\n#define ll long long\n#define vi vector<int>\n#define vll vector<long long>\n#define vb vector<bool>\n#define vc vector<char>\n#define vs vector<string>\n#define si set<int>\n#define sll set<long long>\n#define sc set<char>\n#define ss set<string>\n#define usi unordered_set<int>\n#define qi queue<int>\n#define pqi priority_queue<int>\n#define pqll priority_queue<ll>\n#define mii map<int, int>\n#define umii unordered_map<int, int>\n#define pii pair<int, int>\n#define pllll pair<long long, long long>\n#define f(i,s,e) for(int i = s; i < e; i++)\n#define cf(i,s,e) for(int i = s; i <= e; i++)\n#define rf(i,e,s) for(int i = e-1; i >= s; i--)\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\n#define pb push_back\n#define eb embrace_back\n#define mp make_pair\n#define fi first\n#define se second\n#define ub upper_bound\n#define lb lower_bound\n#define sz(x) (int)(x).size()\n#define fastioa ios::sync_with_stdio(0); cin.tie(0); freopen(\"a.in\", \"r\", stdin); freopen(\"a.out\", \"w\", stdout);\n#define fastio ios::sync_with_stdio(0); cin.tie(0);\n#define mod 1000000007 //1e9 + 7\n#define inf 1e9 // Use for int (e.g., distance)\n#define inf_ll 1e18 // Use for long long\n#define eps 1e-9 // Precision for floating-point comparisons\n\nint main() {\n\tfastio\n\tint v, e; cin >> v >> e;\n\tvector<si> e_out(v);\n\tvi deg_in(v);\n\n\tf(i, 0, e) {\n\t\tint s, t; cin >> s >> t;\n\t\te_out[s].insert(t);\n\t\tdeg_in[t]++;\n\t}\n\n\tqi ans;\n\tf(i, 0, v) if (deg_in[i] == 0) ans.push(i);\n\twhile (!ans.empty()) {\n\t\tauto x = ans.front(); ans.pop();\n\t\tcout << x << endl;\n\t\tfor (auto y: e_out[x]) {\n\t\t\tdeg_in[y]-- ;\n\t\t\tif (deg_in[y] == 0) ans.push(y);\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5576, "score_of_the_acc": -0.6556, "final_rank": 18 }, { "submission_id": "aoj_GRL_4_B_10901456", "code_snippet": "// Lab1-2 Topological Sort.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n\n#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\nvector<vector<int>> g;\nvector<int> indeg;\nvector<bool> visited;\n\nvector<int> Kahn()\n{\n visited.clear(); visited.resize(indeg.size());\n vector<int> ans;\n queue<int> q;\n for (int i = 0; i < indeg.size(); i++)\n {\n if (indeg[i] == 0) q.push(i);\n }\n while (q.size())\n {\n auto f = q.front(); q.pop();\n ans.push_back(f);\n for (auto n : g[f])\n {\n if (!visited[n])\n {\n indeg[n]--;\n if (indeg[n] == 0)\n {\n visited[n] = true;\n q.push(n);\n }\n }\n }\n }\n return ans;\n}\n\nint main()\n{\n int v, e;\n cin >> v >> e;\n g.resize(v);\n indeg.resize(v);\n for (int i = 0; i < e; i++)\n {\n int f, t;\n cin >> f >> t;\n g[f].push_back(t);\n indeg[t]++;\n }\n\n auto ans = Kahn();\n for (auto i : ans)\n {\n cout << i << \"\\n\";\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3896, "score_of_the_acc": -0.0504, "final_rank": 4 }, { "submission_id": "aoj_GRL_4_B_10901381", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nint main()\n{\n int V, E; cin >> V >> E;\n\n vector<vector<int>> adj(V);\n vector<int> in_degree = vector(V, 0);\n\n for (int i = 0; i < E; i++)\n {\n int a, b; cin >> a >> b;\n adj[a].push_back(b);\n }\n\n for (auto list : adj)\n {\n for (auto node : list)\n {\n in_degree[node]++;\n }\n }\n\n queue<int> to_search;\n vector<int> topological;\n\n for (int i = 0; i < V; i++)\n {\n if (in_degree[i] == 0)\n {\n to_search.push(i);\n }\n }\n\n while (!to_search.empty())\n {\n int current = to_search.front(); to_search.pop();\n topological.push_back(current);\n\n for (auto node : adj[current])\n {\n in_degree[node]--;\n if (in_degree[node] == 0)\n {\n to_search.push(node);\n }\n }\n }\n\n for (auto i : topological)\n {\n cout << i << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3892, "score_of_the_acc": -0.049, "final_rank": 3 }, { "submission_id": "aoj_GRL_4_B_10901336", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n\nconst ll MAXN=1e4+5;\n\nll n, m, indeg[MAXN];\nvector<ll> adj[MAXN];\nqueue<ll> indeg0;\n\nint main()\n{\n cin >> n >> m;\n for (int i=0; i<m; i++)\n {\n ll a, b;\n cin >> a >> b;\n adj[a].push_back(b);\n indeg[b]++;\n }\n for (int i=0; i<n; i++)\n {\n if (indeg[i]==0)\n {\n indeg0.push(i);\n }\n }\n while (!indeg0.empty())\n {\n ll pos=indeg0.front();\n indeg0.pop();\n cout << pos << \"\\n\";\n for (auto i:adj[pos])\n {\n indeg[i]--;\n if (indeg[i]==0)\n {\n indeg0.push(i);\n }\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4060, "score_of_the_acc": -0.1095, "final_rank": 10 }, { "submission_id": "aoj_GRL_4_B_10897742", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nvector<ll> topologicalsort(vector<vector<ll>> e){\n int n = e.size();\n vector<ll> ent(n),res;\n for(ll i = 0;i<n;i++) for(ll to : e[i])ent[to]++;\n queue<ll> q;\n vector<bool> seen(n);\n for(ll i = 0;i<n;i++) if(ent[i] == 0) {\n q.emplace(i);\n seen[i] = true;\n res.emplace_back(i);\n }\n while(q.size()){\n ll cur = q.front(); q.pop();\n for(ll to : e[cur]){\n ent[to]--;\n if(ent[to] == 0){\n q.emplace(to);\n seen[to] = true;\n res.emplace_back(to);\n }\n }\n }\n return res;\n};\nint main(){\n ll n,m; cin >> n >> m;\n vector e(n,vector<ll>());\n while(m--){\n ll a,b; cin >> a >> b;\n e[a].emplace_back(b);\n }\n auto res = topologicalsort(e);\n for(ll i : res)cout << i << '\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4716, "score_of_the_acc": -0.3458, "final_rank": 15 }, { "submission_id": "aoj_GRL_4_B_10893463", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int WHITE = 0;\nconst int GRAY = 1;\nconst int BLACK = 2;\n\nconst int MAX = 10000;\n\nint color[MAX];\nvector<int> g[MAX];\n\nlist<int> out;\n\nint V, E;\n\nvoid dfs(int u)\n{\n color[u] = GRAY;\n\n for (auto v : g[u])\n {\n if (color[v] == WHITE)\n dfs(v);\n }\n\n color[u] = BLACK;\n out.push_front(u);\n}\n\nvoid topologucalSort()\n{\n for (int i = 0; i < V; i++)\n {\n color[i] = WHITE;\n }\n\n for (int i = 0; i < V; i++)\n {\n if (color[i] == WHITE) dfs(i);\n }\n}\n\nint main()\n{\n cin >> V >> E;\n for (int i = 0; i < E; i++)\n {\n int s, t;\n cin >> s >> t;\n\n g[s].push_back(t);\n }\n\n topologucalSort();\n\n for (auto v : out)\n {\n cout << v << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4108, "score_of_the_acc": -0.1268, "final_rank": 11 }, { "submission_id": "aoj_GRL_4_B_10892450", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define rep2(i, s, n) for (ll i = (s); i < (n); i++)\n\n\n// vectorを出力する\nvoid vecprint(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << endl;\n }\n}\nvoid newvecprint(vector<ll> vec) {\n rep(i, vec.size()) {\n cout << vec[i] << \" \";\n }\n cout << endl;\n}\n\n// 最大か最小を求める\nll minval(vector<ll> vec) {\n return *min_element(begin(vec), end(vec));\n}\nll maxval(vector<ll> vec) {\n return *max_element(begin(vec), end(vec));\n}\n\nvector<string> color;\nlist<ll> ans;\n\n\nvoid dfs(ll &u, vector<vector<ll>> &G) {\n color[u] = \"gray\";\n for (auto v : G[u]) {\n if (color[v] == \"white\") {\n dfs(v, G);\n }\n }\n ans.push_front(u);\n}\n\nvoid topologicalSort(vector<vector<ll>> G, ll v) {\n color.resize(v);\n rep(i,v) {\n color[i] = \"white\";\n }\n rep(i,v) {\n if (color[i] == \"white\") {\n dfs(i, G);\n }\n }\n}\n\n\n\nvoid solve() {\n ll v, e;\n cin >> v >> e;\n vector<vector<ll>> G(v);\n rep(i, e) {\n ll s, t;\n cin >> s >> t;\n G[s].push_back(t);\n }\n topologicalSort(G, v);\n for (list<ll>::iterator it = ans.begin(); it != ans.end(); it++) {\n cout << *it << endl;\n }\n\n return;\n}\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5504, "score_of_the_acc": -0.6297, "final_rank": 17 }, { "submission_id": "aoj_GRL_4_B_10878926", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing Graph = vector<vector<int>>;\n#define all(v) v.begin(), v.end()\n\n#define debug(x) cout << #x << \" : \" << x << endl;\n#define debug2(x, y) cout << #x << \" : \" << x << \" , \" << #y << \" : \" << y << endl;\n#define debugv(v) cout << #v << \" : \"; for(auto x: v) cout << x << \", \"; cout << endl;\n#define debugvv(vv) cout << #vv << \" :\" << endl; for(auto v: vv){for(auto x: v){cout << x << \", \";} cout << endl;}\n#define debugvvp(vvp) cout << #vvp << \" :\" << endl; for(auto vp: vvp){ \\\n for(auto p: vp){cout << \"(\" << p.first << \", \" << p.second << \"), \";} cout << endl;}\n#define debugcv(v, n) cout << #v << \" : \"; for(int i=0;i<n;i++) cout << v[i] << \", \"; cout << endl;\n#define debugcvv(vv, m, n) cout << #vv << \" :\" << endl; for(int i=0;i<m;i++){ \\\n for(int j=0;j<n;j++){cout << vv[i][j] << \", \";} cout << endl;}\n\n\nvoid dfs(const Graph &G, int u, vector<bool> &seen, vector<int> &order){\n seen[u] = true;\n for(auto v : G[u]) if(!seen[v]) dfs(G, v, seen, order);\n order.push_back(u);\n}\n\nint main(){\n int n, m, i; cin >> n >> m;\n vector<bool> seen(n);\n vector<int> order;\n Graph G(n);\n\n for(i = 0; i < m; i++){\n int s, t; cin >> s >> t;\n G[s].push_back(t);\n }\n\n for(i = 0; i < n; i++) if(!seen[i]) dfs(G, i, seen, order);\n\n reverse(all(order));\n for(i = 0; i < n; i++) cout << order[i] << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3756, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_GRL_4_B_10878904", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\n#define all(v) v.begin(), v.end()\n\n#define debug(x) cout << #x << \" : \" << x << endl;\n#define debug2(x, y) cout << #x << \" : \" << x << \" , \" << #y << \" : \" << y << endl;\n#define debugv(v) cout << #v << \" : \"; for(auto x: v) cout << x << \", \"; cout << endl;\n#define debugvv(vv) cout << #vv << \" :\" << endl; for(auto v: vv){for(auto x: v){cout << x << \", \";} cout << endl;}\n#define debugvvp(vvp) cout << #vvp << \" :\" << endl; for(auto vp: vvp){ \\\n for(auto p: vp){cout << \"(\" << p.first << \", \" << p.second << \"), \";} cout << endl;}\n#define debugcv(v, n) cout << #v << \" : \"; for(int i=0;i<n;i++) cout << v[i] << \", \"; cout << endl;\n#define debugcvv(vv, m, n) cout << #vv << \" :\" << endl; for(int i=0;i<m;i++){ \\\n for(int j=0;j<n;j++){cout << vv[i][j] << \", \";} cout << endl;}\n\n\nint main(){\n int n, m, i; cin >> n >> m;\n vector<int> ind(n);\n vector<vector<int>> G(n);\n queue<int> que;\n\n for(i = 0; i < m; i++){\n int s, t; cin >> s >> t;\n G[s].push_back(t);\n ind[t]++;\n }\n\n for(i = 0; i < n; i++) if(ind[i] == 0) que.push(i);\n\n while(!que.empty()){\n int u = que.front();\n que.pop();\n cout << u << endl;\n for(auto v : G[u]) if(--ind[v] == 0) que.push(v);\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3864, "score_of_the_acc": -0.0389, "final_rank": 2 }, { "submission_id": "aoj_GRL_4_B_10875125", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i=0; i<n; i++)\n\nstatic const int MAX = 100000;\n\nvector<int> G[MAX];\nlist<int> out;\nbool V[MAX];\nint N;\nint indeg[MAX];\n\nvoid bfs(int s) {\n queue<int> q;\n q.push(s);\n V[s] = true;\n\n while (!q.empty()) {\n int u = q.front(); q.pop();\n out.push_back(u);\n for (int i = 0; i < G[u].size(); i++) {\n int v = G[u][i];\n indeg[v]--;\n if (indeg[v] == 0 && !V[v]) {\n V[v] = true;\n q.push(v);\n }\n }\n }\n}\n\nvoid tsort() {\n for (int i=0; i<N; i++) {\n indeg[i] = 0;\n }\n\n for (int u=0; u<N; u++) {\n for (int i=0; i<G[u].size(); i++) {\n int v = G[u][i];\n indeg[v]++;\n }\n }\n\n for (int u=0; u<N; u++) {\n if (indeg[u] == 0 && !V[u]) bfs(u);\n }\n\n for (list<int>::iterator it = out.begin(); it != out.end(); it++) {\n cout << *it << endl;\n }\n}\n\nint main()\n{\n int s, t, M;\n cin >> N >> M;\n\n for (int i=0; i<N; i++) V[i] = false;\n\n for (int i=0; i<M; i++) {\n cin >> s >> t;\n G[s].push_back(t);\n }\n\n tsort();\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6532, "score_of_the_acc": -1, "final_rank": 19 }, { "submission_id": "aoj_GRL_4_B_10866938", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int WHITE = 0;\nconst int GRAY = 1;\nconst int BLACK = 2;\n\nconst int MAX = 10000;\n\nint color[MAX];\nvector<int> g[MAX];\n\nlist<int> out;\n\nint V, E;\n\nvoid dfs(int u)\n{\n color[u] = GRAY;\n\n for (auto v : g[u])\n {\n if (color[v] == WHITE)\n dfs(v);\n }\n\n color[u] = BLACK;\n out.push_front(u);\n}\n\nvoid topologucalSort()\n{\n for (int i = 0; i < V; i++)\n {\n color[i] = WHITE;\n }\n\n for (int i = 0; i < V; i++)\n {\n if (color[i] == WHITE) dfs(i);\n }\n}\n\nint main()\n{\n cin >> V >> E;\n for (int i = 0; i < E; i++)\n {\n int s, t;\n cin >> s >> t;\n\n g[s].push_back(t);\n }\n\n topologucalSort();\n\n for (auto v : out)\n {\n cout << v << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4304, "score_of_the_acc": -0.1974, "final_rank": 14 }, { "submission_id": "aoj_GRL_4_B_10863221", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/4/GRL_4_B\n#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\nusing namespace std;\n\nusing Graph = vector<vector<size_t>>;\n\nvoid dfs(const Graph &G, size_t v, vector<bool> &used, list<size_t> &ans)\n{\n used[v] = true; // 探索済み\n for (size_t t : G[v])\n {\n if (!used[t]) // tが未探索なら\n {\n dfs(G, t, used, ans);\n }\n }\n ans.push_front(v); // 帰りがけにpush\n}\n\nlist<size_t> topological_sort(const Graph &G)\n{\n list<size_t> ans;\n size_t n = G.size();\n vector<bool> used(n, false); // 探索済みか否か\n for (size_t i = 0; i < n; i++)\n {\n // 未探索の頂点ごとにDFS\n if (!used[i])\n dfs(G, i, used, ans);\n }\n return ans;\n}\n\nint main()\n{\n size_t num_vertices; // 頂点数\n size_t num_edges; // 辺数\n cin >> num_vertices >> num_edges;\n Graph G(num_vertices); // グラフ\n\n for (size_t i = 0; i < num_edges; i++)\n {\n size_t s, t;\n cin >> s >> t;\n G[s].push_back(t);\n }\n\n // 処理順\n list<size_t> order = topological_sort(G);\n\n // 結果を出力\n for (size_t node : order)\n {\n cout << node << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4188, "score_of_the_acc": -0.1556, "final_rank": 13 }, { "submission_id": "aoj_GRL_4_B_10863171", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/4/GRL_4_B\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nusing Graph = vector<vector<size_t>>;\n\nvoid dfs(const Graph &G, int v, vector<bool> &used, vector<size_t> &ans)\n{\n used[v] = true; // 探索済み\n for (size_t t : G[v])\n {\n if (!used[t]) // tが未探索なら\n {\n dfs(G, t, used, ans);\n }\n }\n ans.push_back(v); // 帰りがけにpush_back\n}\n\nvector<size_t> topological_sort(const Graph &G)\n{\n vector<size_t> ans;\n size_t n = G.size();\n vector<bool> used(n, false); // 探索済みか否か\n for (int i = 0; i < n; i++)\n {\n // 未探索の頂点ごとにDFS\n if (!used[i])\n dfs(G, i, used, ans);\n }\n reverse(ans.begin(), ans.end()); // 逆順に\n return ans;\n}\n\nint main()\n{\n size_t num_vertices; // 頂点数\n size_t num_edges; // 辺数\n cin >> num_vertices >> num_edges;\n Graph G(num_vertices); // グラフ\n\n for (size_t i = 0; i < num_edges; i++)\n {\n size_t s, t;\n cin >> s >> t;\n G[s].push_back(t);\n }\n\n // 処理順\n vector<size_t> order = topological_sort(G);\n\n // 結果を出力\n for (size_t node : order)\n {\n cout << node << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3888, "score_of_the_acc": -0.0719, "final_rank": 6 }, { "submission_id": "aoj_GRL_4_B_10863163", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/4/GRL_4_B\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nusing Graph = vector<vector<size_t>>;\n\nvoid dfs(const Graph &G, int v, vector<bool> &used, vector<size_t> &ans)\n{\n used[v] = true; // 探索済み\n for (size_t t : G[v])\n {\n if (!used[t]) // tが未探索なら\n {\n dfs(G, t, used, ans);\n }\n }\n ans.push_back(v); // 帰りがけにpush_back\n}\n\nvector<size_t> topological_sort(const Graph &G)\n{\n vector<size_t> ans;\n size_t n = G.size();\n vector<bool> used(n, false); // 探索済みか否か\n for (int i = 0; i < n; i++)\n {\n // 未探索の頂点ごとにDFS\n if (!used[i])\n dfs(G, i, used, ans);\n }\n reverse(ans.begin(), ans.end()); // 逆向きなのでひっくり返す\n return ans;\n}\n\nint main()\n{\n size_t num_vertices; // 頂点数\n size_t num_edges; // 辺数\n cin >> num_vertices >> num_edges;\n Graph G(num_vertices); // グラフ\n\n for (size_t i = 0; i < num_edges; i++)\n {\n size_t s, t;\n cin >> s >> t;\n G[s].push_back(t);\n }\n\n // 処理順\n vector<size_t> order = topological_sort(G);\n\n // 結果を出力\n for (size_t node : order)\n {\n cout << node << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4156, "score_of_the_acc": -0.1441, "final_rank": 12 }, { "submission_id": "aoj_GRL_4_B_10855773", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/4/GRL_4_B\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Edge\n{\n size_t s, t;\n};\n\n// この頂点を処理する準備が完了しているかを判定\nbool isAvailable(size_t vertex, const vector<bool> &is_finished, const vector<Edge> &edge)\n{\n for (const Edge &e : edge)\n {\n if (e.t == vertex)\n {\n if (!is_finished[e.s]) // e.sが未処理\n {\n return false; // この頂点はまだ処理できない\n }\n }\n }\n\n return true;\n}\n\nint main()\n{\n size_t num_vertices; // 頂点数\n size_t num_edges; // 辺数\n cin >> num_vertices >> num_edges;\n vector<size_t> order; // 処理順\n vector<Edge> edge(num_edges); // 辺配列\n\n vector<bool> is_finished(num_vertices, true); // 完了済みか否か\n\n for (Edge &e : edge)\n {\n cin >> e.s >> e.t;\n is_finished[e.t] = false; // 未処理にする\n }\n\n for (size_t i = 0; i < num_vertices; i++)\n {\n if (is_finished[i])\n order.push_back(i); // 無条件で処理可能な頂点を追加\n }\n\n while (order.size() < num_vertices) // orderに全頂点が追加されるまで繰り返す\n {\n for (Edge &e : edge)\n {\n if (is_finished[e.t])\n continue;\n\n if (isAvailable(e.t, is_finished, edge)) // e.tが処理可能なら\n {\n order.push_back(e.t); // orderに追加\n is_finished[e.t] = true;\n }\n }\n }\n\n // 結果を出力\n for (size_t node : order)\n {\n cout << node << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 3944, "score_of_the_acc": -1.0677, "final_rank": 20 } ]
aoj_GRL_5_C_cpp
LCA: Lowest Common Ancestor For a rooted tree, find the lowest common ancestor of two nodes u and v . The given tree consists of n nodes and every node has a unique ID from 0 to n -1 where 0 is the root. Input n k 0 c 1 c 2 ... c k 0 k 1 c 1 c 2 ... c k 1 : k n-1 c 1 c 2 ... c k n-1 q u 1 v 1 u 2 v 2 : u q v q The first line of the input includes an integer n , the number of nodes of the tree. In the next n lines, the information of node i is given. k i is the number of children of node i , and c 1 , ... c k i are node IDs of 1st, ... k th child of node i . In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Constraints 1 ≤ n ≤ 100000 1 ≤ q ≤ 100000 Sample Input 1 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Sample Output 1 1 1 0 0
[ { "submission_id": "aoj_GRL_5_C_11049323", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//最小全域木\nll Kruskal(const WeightedGraph &G) {\n int N = G.size();\n return 0;\n}\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n, sz;\n vector<long long> node;\n function<ll(ll, ll)> op = [](ll a, ll b) {return max(a,b);}; //セグ木上の積\n ll e = 0; //セグ木上の積の単位元\n\n SegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, e);\n }\n SegTree(vector<long long> a) {\n sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, e);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = op(node[2*i+1], node[2*i+2]);\n }\n\n //a_iを取得\n long long get(int i) {\n return node[n-1+i];\n }\n //[a,b)における積\n long long prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return e;\n if(a <= l and r <= b) return node[k];\n long long vl = prod(a, b, 2*k+1, l, (l+r)/2);\n long long vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return op(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = op(node[2*i+1], node[2*i+2]);\n }\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n const ll ex = 0, //セグ木上の積の単位元\n em = 0; //遅延評価木上の積の単位元\n function<ll(ll, ll)> fx = [](ll x, ll y) {return x+y;}, //セグ木上の積\n fa = [](ll x, ll a) {return x+a;}, //遅延評価木からセグ木への作用\n fm = [](ll a, ll b) {return a+b;}, //遅延評価木上の積\n fp = [](ll a, ll n) {return a*n;}; //区間長の作用への影響\n\n LazySegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n }\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = fx(node[2*i+1], node[2*i+2]);\n }\n\n void eval(int k, int len) {\n if(lazy[k] == em) return;\n\n node[k] = fa(node[k], fp(lazy[k], len));\n if(k < n-1) {\n lazy[2*k+1] = fm(lazy[2*k+1], lazy[k]);\n lazy[2*k+2] = fm(lazy[2*k+2], lazy[k]);\n }\n lazy[k] = em;\n }\n //区間[a,b)を値xに更新\n void update(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] = fm(lazy[k], x);\n eval(k, r - l);\n }else {\n update(a, b, x, 2*k+1, l, (l+r)/2);\n update(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = fx(node[2*k+1], node[2*k+2]);\n }\n }\n //区間[a,b)の積を取得\n ll prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return ex;\n if(a <= l and r <= b) return node[k];\n \n ll vl = prod(a, b, 2*k+1, l, (l+r)/2);\n ll vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return fx(vl, vr);\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//平方分割\nstruct Backet {\n vector<ll> array;\n vector<ll> backet;\n int N, M;\n\n Backet(vector<ll> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n void add(int i, ll x) {\n array[i] += x;\n backet[i/M] += x;\n }\n //区間[i,j)の和\n ll getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n ll s = 0;\n if(l > r) {\n rep(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n rep(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n\nstruct LCA {\n Graph G;\n int N, LOG_N;\n vector<int> depth;\n vector<vector<int>> par;\n\n function<void(int)> dfs = [&](int v) {\n for(auto next_v : G[v]) {\n if(depth[next_v] != inf) continue;\n depth[next_v] = depth[v] + 1;\n par[0][next_v] = v;\n dfs(next_v);\n }\n return;\n };\n\n LCA(Graph &g) {\n G = g;\n N = G.size();\n depth.resize(N, inf);\n depth[0] = 0;\n LOG_N = 0;\n while((1<<LOG_N) < N) LOG_N++;\n par.resize(LOG_N+1, vector<int>(N));\n dfs(0);\n rep(i,1,LOG_N) {\n rep(j,0,N) {\n if(par[i-1][j] == -1) par[i][j] = -1;\n else par[i][j] = par[i-1][par[i-1][j]];\n }\n }\n }\n\n int ancestor(int u, int k) {\n int g = 0;\n while(k > 0) {\n if(k % 2 == 1) u = par[g][u];\n k /= 2;\n g++;\n }\n return u;\n }\n\n int lca(int u, int v) {\n int d1 = depth[u], d2 = depth[v];\n if(d1 < d2) v = ancestor(v, d2-d1);\n if(d1 > d2) u = ancestor(u, d1-d2);\n\n if(u == v) return u;\n for(int k = LOG_N; k >= 0; k--) {\n if(par[k][u] != par[k][v]) {\n u = par[k][u];\n v = par[k][v];\n }\n }\n return par[0][u];\n }\n\n int dist(int u, int v) {\n return depth[u] + depth[v] - 2*depth[lca(u, v)];\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N; cin >> N;\n Graph G(N);\n rep(i,0,N) {\n int k; cin >> k;\n while(k--) {\n int c; cin >> c;\n G[i].push_back(c);\n G[c].push_back(i);\n }\n }\n\n LCA tree(G);\n int Q; cin >> Q;\n while(Q--) {\n int u, v; cin >> u >> v;\n cout << tree.lca(u, v) << \"\\n\";\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 27584, "score_of_the_acc": -0.8469, "final_rank": 14 }, { "submission_id": "aoj_GRL_5_C_11048809", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> vector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> vector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> struct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> std::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> std::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> T pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> T fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> T perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> T comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> void fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> void fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> vector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> vector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> vector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n\n//最小全域木\nll Kruskal(const WeightedGraph &G) {\n return 0;\n}\n\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n, sz;\n vector<long long> node;\n function<ll(ll, ll)> op = [](ll a, ll b) {return max(a,b);}; //セグ木上の積\n ll e = 0; //セグ木上の積の単位元\n\n SegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, e);\n }\n SegTree(vector<long long> a) {\n sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, e);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = op(node[2*i+1], node[2*i+2]);\n }\n\n //a_iを取得\n long long get(int i) {\n return node[n-1+i];\n }\n //[a,b)における積\n long long prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return e;\n if(a <= l and r <= b) return node[k];\n long long vl = prod(a, b, 2*k+1, l, (l+r)/2);\n long long vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return op(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = op(node[2*i+1], node[2*i+2]);\n }\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n const ll ex = 0, //セグ木上の積の単位元\n em = 0; //遅延評価木上の積の単位元\n function<ll(ll, ll)> fx = [](ll x, ll y) {return x+y;}, //セグ木上の積\n fa = [](ll x, ll a) {return x+a;}, //遅延評価木からセグ木への作用\n fm = [](ll a, ll b) {return a+b;}, //遅延評価木上の積\n fp = [](ll a, ll n) {return a*n;}; //区間長の作用への影響\n\n LazySegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n }\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = fx(node[2*i+1], node[2*i+2]);\n }\n\n void eval(int k, int len) {\n if(lazy[k] == em) return;\n\n node[k] = fa(node[k], fp(lazy[k], len));\n if(k < n-1) {\n lazy[2*k+1] = fm(lazy[2*k+1], lazy[k]);\n lazy[2*k+2] = fm(lazy[2*k+2], lazy[k]);\n }\n lazy[k] = em;\n }\n //区間[a,b)を値xに更新\n void update(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] = fm(lazy[k], x);\n eval(k, r - l);\n }else {\n update(a, b, x, 2*k+1, l, (l+r)/2);\n update(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = fx(node[2*k+1], node[2*k+2]);\n }\n }\n //区間[a,b)の積を取得\n ll prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return ex;\n if(a <= l and r <= b) return node[k];\n \n ll vl = prod(a, b, 2*k+1, l, (l+r)/2);\n ll vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return fx(vl, vr);\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//平方分割\nstruct Backet {\n vector<ll> array;\n vector<ll> backet;\n int N, M;\n\n Backet(vector<ll> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n void add(int i, ll x) {\n array[i] += x;\n backet[i/M] += x;\n }\n //区間[i,j)の和\n ll getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n ll s = 0;\n if(l > r) {\n rep(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n rep(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N; cin >> N;\n Graph G(N);\n rep(i,0,N) {\n int k; cin >> k;\n rep(j,0,k) {\n int c; cin >> c;\n G[i].push_back(c);\n G[c].push_back(i);\n }\n }\n\n vi depth(N, inf); depth[0] = 0;\n vi par(N, -1);\n function<void(int)> dfs = [&](int v) {\n for(auto next_v : G[v]) {\n if(depth[next_v] != inf) continue;\n depth[next_v] = depth[v]+1;\n par[next_v] = v;\n dfs(next_v);\n }\n };\n dfs(0);\n \n int M = 0;\n while((1<<M) < N) M++;\n vvi ancestor(M+1, vi(N));\n rep(i,0,N) {\n ancestor[0][i] = par[i];\n }\n rep(i,1,M) {\n rep(j,0,N) {\n if(ancestor[i-1][j] == -1) ancestor[i][j] = -1;\n else ancestor[i][j] = ancestor[i-1][ancestor[i-1][j]];\n }\n }\n\n auto anc = [&](int v, int g) {\n int k = 0;\n while(g > 0) {\n if(g % 2 == 1) v = ancestor[k][v];\n k++;\n g >>= 1;\n }\n return v;\n };\n\n int Q; cin >> Q;\n while(Q--) {\n int u, v; cin >> u >> v;\n int d1 = depth[u], d2 = depth[v];\n if(d1 > d2) u = anc(u, d1-d2);\n else v = anc(v, d2-d1);\n\n if(u == v) {\n cout << u << \"\\n\";\n continue;\n }\n\n int k = M-1;\n while(par[u] != par[v]) {\n while(ancestor[k][u] == -1) k--;\n while(ancestor[k][u] == ancestor[k][v]) k--;\n u = ancestor[k][u];\n v = ancestor[k][v];\n }\n cout << par[u] << \"\\n\";\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 23052, "score_of_the_acc": -0.7287, "final_rank": 11 }, { "submission_id": "aoj_GRL_5_C_11020111", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, s, e) for (int i = (int)(s); i < (int)(e); ++i)\n\nstruct LCA {\n\tvector<vector<int>> G, table;\n\tvector<int> dep;\n\tint N, K;\n\t\n\tLCA(vector<vector<int>> &g, int root = 0) : G(g), N(G.size()) {\n\t\tK = 1;\n\t\twhile ((1 << K) < N) ++K;\n\t\ttable = vector(K, vector<int>(N, -1));\n\t\tdep = vector<int>(N, -1);\n\t\t\n\t\tdfs(root, -1, 0);\n\t\tfor (int k = 0; k < K - 1; ++k) {\n\t\t\tfor (int v = 0; v < N; ++v) {\n\t\t\t\tif (table[k][v] < 0) table[k + 1][v] = -1;\n\t\t\t\telse table[k + 1][v] = table[k][table[k][v]];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid dfs(int v, int par, int d) {\n\t\ttable[0][v] = par;\n\t\tdep[v] = d;\n\t\tfor (int to : G[v]) {\n\t\t\tif (to != par) dfs(to, v, d + 1);\n\t\t}\n\t}\n\t\n\tint query(int u, int v) {\n\t\tif (dep[u] < dep[v]) swap(u, v);\n\t\tfor (int k = 0; k < K; ++k) {\n\t\t\tif ((dep[u] - dep[v]) >> k & 1) u = table[k][u];\n\t\t}\n\t\t\n\t\tif (u == v) return u;\n\t\tfor (int k = K - 1; k >= 0; --k) {\n\t\t\tif (table[k][u] != table[k][v]) {\n\t\t\t\tu = table[k][u];\n\t\t\t\tv = table[k][v];\n\t\t\t}\n\t\t}\n\t\treturn table[0][u];\n\t}\n};\n\nint main() {\n\tcin.tie(nullptr);\n\tios_base::sync_with_stdio(false);\n\t\n\tint N;\n\tcin >> N;\n\tvector<vector<int>> G(N);\n\trep(v, 0, N) {\n\t\tint k;\n\t\tcin >> k;\n\t\trep(j, 0, k) {\n\t\t\tint to;\n\t\t\tcin >> to;\n\t\t\tG[v].push_back(to);\n\t\t\tG[to].push_back(v);\n\t\t}\n\t}\n\t\n\tLCA lca(G);\n\t\n\tint Q;\n\tcin >> Q;\n\trep(query, 0, Q) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tcout << lca.query(u, v) << '\\n';\n\t}\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 27232, "score_of_the_acc": -0.2127, "final_rank": 2 }, { "submission_id": "aoj_GRL_5_C_10993607", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\n\n\n\nvector<vector<int>> build(vector<int> par,int n)\n{\n \n vector<vector<int>> dp(18,vector<int>(n,0));\n for(int i=0;i<n;i++)\n {\n dp[0][i]=par[i];\n\n }\n for(int i=1;i<=17;i++)\n {\n for(int u=0;u<n;u++)\n {\n int par=dp[i-1][u];\n dp[i][u]=dp[i-1][par];\n }\n }\n return dp;\n}\n\nint lca(int u,int v,vector<int> &dis,vector<vector<int>> &dp)\n{\n if(dis[u]<dis[v])\n {\n swap(u,v);\n }\n int dif=dis[u]-dis[v];\n for(int i=17;i>=0;i--)\n {\n if(dif&(1<<i))\n {\n u=dp[i][u];\n }\n }\n if(u==v)\n return u;\n for (int i = 17; i >= 0; i--) {\n if (dp[i][u] != dp[i][v]) {\n u = dp[i][u];\n v = dp[i][v];\n }\n}\nreturn dp[0][u];\n\n // return u;\n}\n\n\n\nvoid dfs(int i,int par,int level,vector<vector<int>> &adj,vector<int> &p,vector<int> &dis)\n{\n \n dis[i]=level;\n for(auto it:adj[i])\n {\n if(par!=it)\n {\n p[it]=i;\n dfs(it,i,level+1,adj,p,dis);\n }\n }\n}\n\n\n\nint main()\n{\n int n;\n cin>>n;\n vector<vector<int>> adj(n);\n // vector<vector<int>> dp(18,vector<int>(n,0));\n\n for(int i=0;i<n;i++)\n {\n int sz=0;\n cin>>sz;\n for(int j=0;j<sz;j++)\n {\n int x;\n cin>>x;\n adj[i].push_back(x);\n }\n\n }\n vector<int> par(n,0);\n vector<int> dis(n,0);\n dfs(0,0,0,adj,par,dis);\n vector<vector<int>> dp=build(par,n);\n int q;\n cin>>q;\n for(int i=0;i<q;i++)\n {\n int x,y;\n cin>>x>>y;\n cout<<lca(x,y,dis,dp)<<endl;\n }\n\n\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 24860, "score_of_the_acc": -0.7133, "final_rank": 10 }, { "submission_id": "aoj_GRL_5_C_10977941", "code_snippet": "#include <bits/stdc++.h>\n\n//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"avx,avx2,fma\")\n//#pragma GCC optimization(\"unroll-loops\")\n\nusing namespace std;\n\n#define int long long\n#define double long double\n#define uint unsigned int\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define is2pow(n) (n && (!(n & (n-1))))\n#define OPTIMIZE ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n\nconst int MOD = 1e15 + 7;\nconst int MAX_N = 2e5;\nconst int MAX_K = 80;\nconst long long INF = 1e18;\nconst double EPS = 1e-6;\n\nint binPow(int base, int pow, int mod) {\n if (pow == 0)\n return 1 % mod;\n int res = 1;\n while (pow != 0) {\n if (pow & 1)\n res = res * base % mod;\n base = base * base % mod;\n pow = pow >> 1;\n }\n return res;\n}\n\nstruct LCA {\n vector<vector<int>> graph, dp;\n int n, maxK, root;\n vector<int> h;\n\n LCA(const vector<vector<int>>& g, int root = 0) :\n n(g.size()), root(root), graph(g), h(n), maxK(ceil(log2(n)) + 1) {\n dp.resize(n, vector<int>(maxK + 1, -1));\n dfs(root, root, 0);\n for (int k = 1; k <= maxK; k++)\n for (int u = 0; u < n; u++)\n if (dp[u][k - 1] != -1)\n dp[u][k] = dp[dp[u][k - 1]][k - 1];\n }\n\n void dfs(int current, int parent, int height) {\n dp[current][0] = parent, h[current] = height;\n for (const int& to: graph[current])\n if (to != parent)\n dfs(to, current, height + 1);\n }\n\n int get(int u, int v) {\n if (h[u] > h[v])\n swap(u, v);\n for (int k = maxK; k >= 0; k--)\n if (h[u] <= h[v] - (1 << k))\n v = dp[v][k];\n if (u == v)\n return u;\n for (int k = maxK; k >= 0; k--)\n if (dp[u][k] != dp[v][k])\n u = dp[u][k], v = dp[v][k];\n return dp[u][0];\n }\n};\n\nvoid solve() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n int n, q;\n cin >> n;\n vector<vector<int>> g(n);\n for (int i = 0, u, k; i < n; i++) {\n cin >> k;\n while (k--) {\n cin >> u;\n g[u].emplace_back(i);\n g[i].emplace_back(u);\n }\n }\n LCA lca(g, 0);\n cin >> q;\n while (q--) {\n int u, v;\n cin >> u >> v;\n cout << lca.get(u, v) << endl;\n }\n}\n\n#define TES\n#define LOCA\n#define FIL\n\nint32_t main() {\n OPTIMIZE\n#ifdef FILE\n freopen(\"path_easy.in\", \"r\", stdin); freopen(\"path_easy.out\", \"w\", stdout);\n#endif\n#ifdef LOCAL\n freopen(\"/home/rekname/data/C++ Projects/codedforceProject/input.txt\", \"r\", stdin);\n#endif\n int t = 1;\n#ifdef TEST\n cin >> t;\n#endif\n while (t--) {\n solve();\n }\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 36620, "score_of_the_acc": -0.77, "final_rank": 13 }, { "submission_id": "aoj_GRL_5_C_10959127", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(n);i++)\n#define all(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\nusing ll=long long;\nusing pi=pair<int,int>;\nconst int di[]={+1,-1,+0,+0};\nconst int dj[]={+0,+0,+1,-1};\nconst int INF=1e9;\n//const ll INF=1e18;\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n; cin >> n;\n vector<vector<int>> G(n);\n rep(i, n) {\n int k; cin >> k;\n rep(j, k) {\n int c; cin >> c;\n G[i].push_back(c);\n }\n }\n vector<int> dist(n, -1);\n dist[0]=0;\n const int LOG=20;\n vector<vector<int>> parent(LOG, vector<int>(n, -1));\n auto dfs=[&](auto dfs, int v, int p=-1) -> void {\n parent[0][v]=p;\n for(int nv:G[v]) {\n dist[nv]=dist[v]+1;\n dfs(dfs, nv, v);\n }\n };\n dfs(dfs, 0);\n rep(k, LOG-1) {\n rep(v, n) {\n if(parent[k][v]<0) parent[k+1][v]=-1;\n else parent[k+1][v]=parent[k][parent[k][v]];\n }\n }\n auto lca=[&](int u, int v) -> int {\n if(dist[u]<dist[v]) swap(u, v);\n int diff=dist[u]-dist[v];\n rep(k, LOG) if(diff>>k&1) u=parent[k][u];\n if(u==v) return u;\n for(int k=LOG-1; k>=0; k--) {\n if(parent[k][u]!=parent[k][v]) {\n u=parent[k][u];\n v=parent[k][v];\n }\n }\n return parent[0][u];\n };\n int q; cin >> q;\n vector<int> ans;\n while(q--) {\n int u, v; cin >> u >> v;\n ans.push_back(lca(u, v));\n }\n for(int x:ans) cout << x << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 25360, "score_of_the_acc": -0.5389, "final_rank": 7 }, { "submission_id": "aoj_GRL_5_C_10953978", "code_snippet": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n#include <queue>\n#include <stack>\nusing namespace std;\nusing ll = long long;\nstruct LCA{\n\tvector<vector<int>> par;\n\tvector<int> dist;\n\tint K = 60;\n\tvoid dfs(int v, int lat, int d, vector<vector<int>>& G) {\n\t\tdist[v] = d;\n\t\tpar[0][v] = lat;\n\t\tfor (auto nv : G[v]) {\n\t\t\tif (nv == lat) continue;\n\t\t\tdfs(nv, v, d+1, G);\n\t\t}\n\t}\n\tLCA(vector<vector<int>>& G) {\n\t\tint N = G.size();\n\t\tpar.assign(K+1, vector<int>(N, -1));\n\t\tdist.assign(N, 0);\n\t\tdfs(0, 0, 0, G);\n\t\tfor (int k = 1;k <= K;k++) for (int v = 0;v < N;v++) par[k][v] = par[k-1][par[k-1][v]];\n\t}\n\tint query(int u, int v) {\n\t\tif (dist[u] < dist[v]) swap(u, v);\n\t\tll df = dist[u] - dist[v];\n\t\tfor (int k = 0;k <= K;k++) if (df & (1LL << k)) u = par[k][u];\n\t\tif (u == v) return u;\n\t\tfor (int k = K;k >=0;k--) {\n\t\t\tif (par[k][u] != par[k][v]) {\n\t\t\t\tu = par[k][u];\n\t\t\t\tv = par[k][v];\n\t\t\t}\n\t\t}\n\t\treturn par[0][u];\n\t}\n};\nint main() {\n\tint N;cin >> N;\n\tvector<vector<int>> G(N);\n\tfor (int i = 0;i < N;i++) {\n\t\tint k;cin >> k;\n\t\twhile (k--) {\n\t\t\tint c;cin >> c;\n\t\t\tG[i].push_back(c);\n\t\t\tG[c].push_back(i);\n\t\t}\n\t}\n\tLCA LCAS(G);\n\tint Q;cin >> Q;\n\twhile (Q--) {\n\t\tint u, v;cin >> u >> v;\n\t\tcout << LCAS.query(u, v) << endl;\n\t}\n\t\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 40588, "score_of_the_acc": -1.561, "final_rank": 18 }, { "submission_id": "aoj_GRL_5_C_10953951", "code_snippet": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n#include <queue>\n#include <stack>\nusing namespace std;\nusing ll = long long;\nusing Graph = vector<vector<int>>;\nstruct LCA {\n\tvector<int> dist;\n\tvector<vector<int>> par;\n\tint K = 60;\n\tvoid dfs(int v, int lat, int d, Graph& G) {\n\t\tdist[v] = d;\n\t\tpar[0][v] = lat;\n\t\tfor (auto nv : G[v]) {\n\t\t\tif (nv == lat) continue;\n\t\t\tdfs(nv, v, d+1, G);\n\t\t}\n\t}\n\tLCA (Graph& G) {\n\t\tint N = G.size();\n\t\tpar.assign(K+1, vector<int>(N, -1));\n\t\tdist.assign(N, 0);\n\t\tdfs(0, 0, 0, G);\n\t\tfor (int k = 1;k <= K;k++) for (int v = 0;v < N;v++) par[k][v] = par[k-1][par[k-1][v]];\n\t}\n\n\tint query(int u, int v) {\n\t\tif (dist[u] < dist[v]) swap(u, v);\n\t\tll d = dist[u] - dist[v];\n\t\tfor (int k = 0;k <= K;k++) {\n\t\t\tif (d & (1LL << k)) u = par[k][u];\n\t\t}\n\t\tif (u == v) return u;\n\t\tfor (int k = K;k >= 0;k--) {\n\t\t\tif (par[k][u] != par[k][v]) {\n\t\t\t\tu = par[k][u];\n\t\t\t\tv = par[k][v];\n\t\t\t}\n\t\t}\n\t\treturn par[0][u];\n\t}\n};\nint main() {\n\tint N;cin >> N;\n\tGraph G(N);\n\tfor (int i = 0;i < N;i++) {\n\t\tint k;cin >> k;\n\t\twhile (k--) {\n\t\t\tint c;cin >> c;\n\t\t\tG[i].push_back(c);\n\t\t\tG[c].push_back(i);\n\t\t}\n\t}\n\tLCA LCAS(G);\n\tint Q;cin >> Q;\n\twhile (Q--) {\n\t\tint u, v;cin >> u >> v;\n\t\tcout << LCAS.query(u, v) << endl;\n\t}\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 40672, "score_of_the_acc": -1.5632, "final_rank": 19 }, { "submission_id": "aoj_GRL_5_C_10953939", "code_snippet": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n#include <queue>\n#include <stack>\nusing namespace std;\nusing ll = long long;\nusing Graph = vector<vector<int>>;\nstruct LCA {\n\tint K = 60;\n\tvector<vector<int>> par;\n\tvector<int> dist;\n\tvoid dfs(int v, int lat, int d, vector<vector<int>>& G) {\n\t\tpar[0][v] = lat;\n\t\tdist[v] = d;\n\t\tfor (auto nv : G[v]) {\n\t\t\tif (nv == lat) continue;\n\t\t\tdfs(nv, v, d+1, G);\n\t\t}\n\t}\n\tLCA (Graph G) {\n\t\tint N = G.size();\n\t\tpar.assign(K+1, vector<int>(N, -1));\n\t\tdist.assign(N, 0);\n\t\tdfs(0, 0, 0, G);\n\t\tfor (int k = 1;k <= K;k++) for (int v = 0;v < N;v++) par[k][v] = par[k-1][par[k-1][v]];\n\t}\n\tint query(int u, int v) {\n\t\tif (dist[u] < dist[v]) swap(u, v);\n\t\tll df = dist[u] - dist[v];\n\t\tfor (int k = 0;k <= K;k++) {\n\t\t\tif ((df) & (1LL << k)) {\n\t\t\t\tu = par[k][u];\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tif (u == v) return u;\n\t\tfor (int k = K;k >= 0;k--) {\n\t\t\tif (par[k][u] != par[k][v]) {\n\t\t\t\tu = par[k][u];\n\t\t\t\tv = par[k][v];\n\t\t\t}\n\t\t}\n\t\treturn par[0][u];\n\t}\n};\nint main() {\n\tint N;cin >> N;\n\tGraph G(N);\n\tfor (int i = 0;i < N;i++) {\n\t\tint k;cin >> k;\n\t\twhile (k--) {\n\t\t\tint c;cin >> c;\n\t\t\tG[i].push_back(c);\n\t\t\tG[c].push_back(i);\n\t\t}\n\t}\n\tLCA LCAS(G);\n\tint Q;cin >> Q;\n\twhile (Q--) {\n\t\tint u, v;cin >> u >> v;\n\t\tcout << LCAS.query(u, v) << endl;\n\t}\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 46100, "score_of_the_acc": -1.7047, "final_rank": 20 }, { "submission_id": "aoj_GRL_5_C_10895723", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nclass LCA{\n vector<vector<int>> db;\n vector<int> dist;\n\npublic:\n LCA(const vector<vector<int>>& G,int root){\n int N=G.size(),K=0;\n while((1<<K)<N) K++;\n\n db.assign(N,vector<int>(K,-1));\n dist.assign(N,-1);\n queue<int> que;\n dist[root]=0;\n que.push(0);\n while(!que.empty()){\n int cv=que.front(); que.pop();\n for(int nv:G[cv]){\n if(dist[nv]!=-1) continue;\n db[nv][0]=cv;\n dist[nv]=dist[cv]+1;\n que.push(nv);\n }\n }\n\n for(int i=1;i<K;i++){\n for(int j=0;j<N;j++){\n if(db[j][i-1]==-1) db[j][i]=-1;\n else db[j][i]=db[db[j][i-1]][i-1];\n }\n }\n }\n\n int query(int u,int v){\n if(dist[u]<dist[v]) swap(u,v);\n for(int i=0;dist[u]>dist[v];i++){\n if((dist[u]-dist[v])&(1<<i)) u=db[u][i];\n }\n\n if(u==v) return u;\n for(int i=db[0].size()-1;i>=0;i--){\n if(db[u][i]!=db[v][i]){\n u=db[u][i];\n v=db[v][i];\n }\n }\n return db[u][0];\n }\n};\n\nint main(){\n int N; cin>>N;\n vector<vector<int>> G(N);\n for(int i=0;i<N;i++){\n int k; cin>>k;\n for(int j=0;j<k;j++){\n int c; cin>>c;\n G[i].push_back(c);\n }\n }\n LCA lca(G,0);\n\n int Q; cin>>Q;\n for(int i=0;i<Q;i++){\n int u,v; cin>>u>>v;\n cout<<lca.query(u,v)<<endl;\n }\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 19076, "score_of_the_acc": -0.6875, "final_rank": 9 }, { "submission_id": "aoj_GRL_5_C_10889500", "code_snippet": "#include <bits/stdc++.h>\n//#include <windows.h>\n//#include <conio.h>\n#define N 600001\n#define M 23\n#define CODE \"\"\n#define MOD\n#define F first\n#define S second\n#define pb push_back\n#define eb emplace_back\n#define is insert\n#define pii pair<int,int>\n#define pll pair<long long,long long>\n#define mkp make_pair\n#define ll [](long long &ctrl)\ntypedef int ui;\ntypedef long long ul;\ntypedef long double ud;\nusing namespace std;\nconst int iinf=(int)1e9+7;\nconst long long linf=(long long)1e18+7;\nui n,q,h[N],up[N][M];\nvector<ui> adj[N];\nvoid dfs(ui s,ui pre)\n{\n for(ui i=0;i<(ui)adj[s].size();i++)\n {\n ui ctrl=adj[s][i];\n if(ctrl!=pre)\n {\n h[ctrl]=h[s]+1;\n up[ctrl][0]=s;\n for(ui j=1;j<=__lg(n);j++)\n up[ctrl][j]=up[up[ctrl][j-1]][j-1];\n dfs(ctrl,s);\n }\n }\n}\nui lca(ui u,ui v)\n{\n if(h[u]!=h[v])\n {\n if(h[u]<h[v]) swap(u,v);\n ui k=h[u]-h[v];\n for(ui i=0;(1<<i)<=k;i++)\n if(k>>i&1) u=up[u][i];\n }\n if(u==v) return u;\n ui k=__lg(h[u]);\n for(ui i=k;i>=0;i--)\n if(up[u][i]!=up[v][i])\n {\n u=up[u][i];\n v=up[v][i];\n }\n return up[u][0];\n}\nint32_t main()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);cout.tie(nullptr);\n #ifdef CODE\n if(fopen(CODE\".INP\",\"r\"))\n {\n freopen(CODE\".INP\",\"r\",stdin);\n freopen(CODE\".OUT\",\"w\",stdout);\n }\n #endif // CODE\n #define __FILE_CHECK__\n #ifdef __FILE_CHECK__\n if(fopen(\"inp.txt\",\"r\"))\n {\n freopen(\"inp.txt\",\"r\",stdin);\n freopen(\"out.txt\",\"w\",stdout);\n freopen(\"opu.txt\",\"w\",stderr);\n }\n #endif // __FILE_CHECK__\n cin>>n;\n for(ui i=0;i<n;i++)\n {\n ui u;\n cin>>u;\n for(ui j=1;j<=u;j++)\n {\n ui v;\n cin>>v;\n adj[i].pb(v);\n adj[v].pb(i);\n }\n }\n dfs(0,-1);\n cin>>q;\n while(q--)\n {\n ui u,v;\n cin>>u>>v;\n cout<<lca(u,v)<<\"\\n\";\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 39316, "score_of_the_acc": -0.5278, "final_rank": 6 }, { "submission_id": "aoj_GRL_5_C_10887134", "code_snippet": "#line 1 \"a.cpp\"\n#define PROBLEM \\\n \"https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/5/GRL_5_C\"\n#line 2 \"/workspaces/cp-container/libraries/template.hpp\"\n#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\nusing ll = long long;\ntemplate <typename T>\nbool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n#line 3 \"/workspaces/cp-container/libraries/data_structure/sparse_table.hpp\"\n\ntemplate <class S, S (*op)(S, S), S (*e)()>\nstruct sparse_table {\n int n;\n vector<vector<S>> st;\n\n sparse_table() : n(0) {}\n sparse_table(vector<S> v) : n(v.size()) {\n if (n == 0) return;\n int log_n = 0;\n while ((1 << log_n) <= n) ++log_n;\n st.assign(log_n, vector<S>(n));\n\n st[0] = v;\n rep(k, log_n - 1) {\n for (int i = 0; i + (1 << (k + 1)) <= n; ++i) {\n st[k + 1][i] = op(st[k][i], st[k][i + (1 << k)]);\n }\n }\n }\n\n S prod(int l, int r) {\n if (l >= r) return e();\n int k = 31 - __builtin_clz(r - l);\n return op(st[k][l], st[k][r - (1 << k)]);\n }\n};\n#line 4 \"/workspaces/cp-container/libraries/graph/lowest_common_ancestor.hpp\"\n\nstruct lowest_common_ancestor {\n using P = pair<int, int>;\n static P op(P a, P b) { return min(a, b); }\n static P e() { return {1 << 30, -1}; }\n\n int n;\n vector<vector<int>> g;\n vector<int> depth, pos;\n vector<P> tour;\n sparse_table<P, op, e> st;\n\n lowest_common_ancestor(vector<vector<int>> _g, int root = 0)\n : n(_g.size()), g(_g), depth(_g.size()), pos(_g.size()) {\n dfs(root, -1, 0);\n st = sparse_table<P, op, e>(tour);\n }\n\n void dfs(int u, int p, int d) {\n depth[u] = d;\n pos[u] = tour.size();\n tour.emplace_back(d, u);\n for (int v : g[u]) {\n if (v == p) continue;\n dfs(v, u, d + 1);\n tour.emplace_back(d, u);\n }\n }\n\n int query(int u, int v) {\n int l = pos[u];\n int r = pos[v];\n if (l > r) swap(l, r);\n return st.prod(l, r + 1).second;\n }\n\n int dist(int u, int v) {\n int l = query(u, v);\n return depth[u] + depth[v] - 2 * depth[l];\n }\n};\n#line 5 \"a.cpp\"\nsigned main() {\n cin.tie(0)->sync_with_stdio(0);\n int n;\n cin >> n;\n vector<vector<int>> g(n);\n rep(u, n) {\n int k;\n cin >> k;\n rep(_, k) {\n int v;\n cin >> v;\n g[u].emplace_back(v);\n g[v].emplace_back(u);\n }\n }\n lowest_common_ancestor lca(g);\n int q;\n cin >> q;\n rep(_, q) {\n int u, v;\n cin >> u >> v;\n cout << lca.query(u, v) << '\\n';\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 57424, "score_of_the_acc": -1, "final_rank": 17 }, { "submission_id": "aoj_GRL_5_C_10873912", "code_snippet": "#include <vector>\n#include <cmath>\n\nstruct Edge {\n int from;\n int to;\n int weight{1};\n int index{};\n int id{};\n long long capacity{};\n long long flow{};\n Edge(int from, int to) : from(from), to(to) {}\n Edge(int from, int to, int weight) : from(from), to(to), weight(weight) {}\n Edge(int from, int to, int capacity, int flow) : from(from), to(to), capacity(capacity), flow(flow) {}\n\n bool operator>(const Edge& other) const { return weight > other.weight; }\n};\n\n\nusing namespace std;\n\nstruct LCA {\n // LCA with Binary Lifting\n // Time : Preprocessing - O(n * log(n)), Query - O(log n)\n // Space : O(n * log(n))\n vector<vector<Edge>> graph;\n int vertexCount;\n const int root;\n vector<vector<int>> dp;\n vector<int> height;\n int maxK;\n bool built;\n\n LCA(const vector<vector<int>>& g, int root = 0) : vertexCount(g.size()), root(root) {\n graph.resize(vertexCount);\n for (int from = 0; from < vertexCount; from++)\n for (int to: g[from])\n addEdge(from, to);\n maxK = 0;\n while ((1 << maxK) <= vertexCount)\n maxK++;\n dp.resize(vertexCount, vector<int>(maxK + 1, -1));\n height.resize(vertexCount);\n build();\n }\n\n LCA(int vertexCount, int root = 0) : vertexCount(vertexCount), root(root), built(false) {\n graph.resize(vertexCount);\n maxK = ceil(log2(vertexCount)) + 1;\n dp.resize(vertexCount, vector<int>(maxK + 1, -1));\n height.resize(vertexCount);\n }\n\n void addEdge(int from, int to, int weight = 1) {\n graph[from].emplace_back(from, to, weight);\n graph[to].emplace_back(to, from, weight);\n }\n\n void build() {\n if (built)\n return;\n dfs(root, root, 0);\n for (int k = 1; k <= maxK; k++)\n for (int u = 0; u < vertexCount; u++)\n if (dp[u][k - 1] != -1)\n dp[u][k] = dp[dp[u][k - 1]][k - 1];\n built = true;\n }\n\n void dfs(int current, int parent, int h) {\n dp[current][0] = parent;\n height[current] = h;\n for (const Edge& edge: graph[current]) {\n if (edge.to != parent)\n dfs(edge.to, current, h + 1);\n }\n }\n\n int get(int u, int v) {\n if (!built)\n build();\n if (height[u] > height[v])\n swap(u, v);\n for (int k = maxK; k >= 0; k--)\n if (height[u] <= height[v] - (1 << k))\n v = dp[v][k];\n if (u == v)\n return u;\n\n for (int k = maxK; k >= 0; k--) {\n if (dp[u][k] != dp[v][k]) {\n u = dp[u][k];\n v = dp[v][k];\n }\n }\n return dp[u][0];\n }\n};\n\n#include <bits/stdc++.h>\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/all/GRL_5_C\"\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n int n, q;\n cin >> n;\n LCA lca(n, 0);\n for (int i = 0, u, k; i < n; i++) {\n cin >> k;\n while (k--) {\n cin >> u;\n lca.addEdge(u, i);\n }\n }\n cin >> q;\n while (q--) {\n int u, v;\n cin >> u >> v;\n cout << lca.get(u, v) << endl;\n }\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 33172, "score_of_the_acc": -0.8676, "final_rank": 15 }, { "submission_id": "aoj_GRL_5_C_10849709", "code_snippet": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int max_nodes = 100005, log_max_nodes = 20;\nint num_nodes, log_num_nodes, root;\n\nvector<int> children[max_nodes];\nint A[max_nodes][log_max_nodes+1];\nint L[max_nodes];\n\nint lb(unsigned int n)\n{\n if(n == 0) return -1;\n int p = 0;\n if(n >= (1 << 16)) { n >>= 16; p += 16; }\n if(n >= (1 << 8)) { n >>= 8; p += 8; }\n if(n >= (1 << 4)) { n >>= 4; p += 4; }\n if(n >= (1 << 2)) { n >>= 2; p += 2; }\n if(n >= (1 << 1)) { p += 1; }\n return p;\n}\n\nvoid DFS(int i, int l)\n{\n L[i] = l;\n for(int j = 0; j < children[i].size(); j++)\n DFS(children[i][j], l + 1);\n}\n\nint LCA(int p, int q)\n{\n if(L[p] < L[q]) swap(p, q);\n\n for(int i = log_num_nodes; i >= 0; i--){\n if(L[p] - (1 << i) >= L[q]) p = A[p][i];\n }\n if(p == q) return p;\n for(int i = log_num_nodes; i >= 0; i--){\n if(A[p][i] != -1 && A[p][i] != A[q][i]){\n p = A[p][i];\n q = A[q][i];\n }\n }\n return A[p][0];\n}\n\nbool findroot[max_nodes] = {false};\n\nint main()\n{\n int n;\n cin >> n;\n num_nodes = n;\n log_num_nodes = lb(num_nodes);\n for(int i = 0; i < n; ++i){\n int k;\n cin >> k;\n int now;\n for(int j = 0; j < k; ++j){\n cin >> now;\n children[i].push_back(now);\n A[now][0] = i;\n findroot[now] = true;\n }\n }\n int root;\n for(int i = 0; i < n; ++i){\n if(!findroot[i]){\n root = i;\n break;\n }\n }\n for(int j = 1; j <= log_num_nodes; ++j){\n for(int i = 0; i < num_nodes; ++i){\n if(A[i][j - 1] != -1){\n A[i][j] = A[A[i][j - 1]][j - 1];\n } else {\n A[i][j] = -1;\n }\n }\n }\n DFS(root, 0);\n int q;\n cin >> q;\n int u, v;\n for(int i = 0; i < q; ++i){\n cin >> u >> v;\n cout << LCA(u, v) << endl;\n }\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 20424, "score_of_the_acc": -0.6602, "final_rank": 8 }, { "submission_id": "aoj_GRL_5_C_10827410", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (n); ++i)\n\nint main() {\n int n;\n cin >> n;\n vector<vector<int>> g(n);\n rep(i, n) {\n int k;\n cin >> k;\n rep(j, k) {\n int c;\n cin >> c;\n g[i].push_back(c);\n g[c].push_back(i);\n }\n }\n\n int K = 1;\n while ((1 << K) < n) K++;\n vector<vector<int>> parent(K, vector<int>(n, -1));\n vector<int> dist(n, -1);\n auto dfs = [&](auto dfs, int v, int d, int p = -1) -> void {\n parent[0][v] = p;\n dist[v] = d;\n for (auto nv : g[v])\n if (nv != p) dfs(dfs, nv, d + 1, v);\n };\n dfs(dfs, 0, 0);\n rep(k, K - 1) rep(v, n) if (parent[k][v] < 0) parent[k + 1][v] = -1;\n else parent[k + 1][v] = parent[k][parent[k][v]];\n auto query = [&](int u, int v) -> int {\n if (dist[u] < dist[v]) swap(u, v);\n rep(k, K) if ((dist[u] - dist[v]) >> k & 1) u = parent[k][u];\n if (u == v) return u;\n for (int k = K - 1; k >= 0; k--)\n if (parent[k][u] != parent[k][v])\n u = parent[k][u], v = parent[k][v];\n return parent[0][u];\n };\n\n int q;\n cin >> q;\n rep(iq, q) {\n int u, v;\n cin >> u >> v;\n cout << query(u, v) << endl;\n }\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 23320, "score_of_the_acc": -0.7357, "final_rank": 12 }, { "submission_id": "aoj_GRL_5_C_10826347", "code_snippet": "#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC target(\"avx,avx2\")\n#include <bits/stdc++.h>\n#define INF 1000000001LL\n#define LNF 1000000000000000001LL\n#define MOD 1000000007LL\n#define MAX 200000\n#define long long long\n#define all(x) x.begin(),x.end()\nusing namespace std;\n\nint dp[100000][20];\nint depth[100000];\nvector<int> graph[100000];\nvoid dfs(int x, int d)\n{\n depth[x] = d;\n for(int y : graph[x])\n dfs(y,d+1);\n}\n\nint lca(int x, int y)\n{\n if(depth[x] < depth[y])\n swap(x,y);\n int diff = depth[x]-depth[y];\n\n for(int i = 0; i<20; i++)\n {\n if(diff&(1<<i))\n x = dp[x][i];\n }\n\n if(x == y)\n return x;\n\n for(int i = 19; i>=0; i--)\n {\n if(dp[x][i] != dp[y][i])\n {\n x = dp[x][i];\n y = dp[y][i];\n }\n }\n return dp[x][0];\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); \n cin.tie(0);\n\n int n;\n cin >> n;\n\n for(int i = 0; i<n; i++)\n {\n int m;\n cin >> m;\n\n for(int j = 0; j<m; j++)\n {\n int x;\n cin >> x;\n dp[x][0] = i;\n graph[i].push_back(x);\n }\n }\n\n for(int k = 1; k<20; k++)\n {\n for(int i = 0; i<n; i++)\n {\n dp[i][k] = dp[dp[i][k-1]][k-1];\n }\n }\n\n dfs(0,0);\n\n int q;\n cin >> q;\n\n while(q--)\n {\n int a,b;\n cin >> a >> b;\n cout << lca(a,b) << \"\\n\";\n }\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 21748, "score_of_the_acc": -0.0697, "final_rank": 1 }, { "submission_id": "aoj_GRL_5_C_10822950", "code_snippet": "#include<bits/stdc++.h>\n//#include <atcoder/all>\nusing namespace std;\n//using namespace atcoder;\n\n#define all(v) v.begin(),v.end()\nusing ll = long long;\nusing ull = unsigned long long;\nusing lll = __int128;\nusing vll=vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing P = pair<ll,ll>;\nusing vp=vector<pair<ll, ll>>;\n//using mint=modint1000000007;\n//using mint=modint998244353;\n\nconst ll INF=1ll<<60;\nll mod10=1e9+7;\nll mod99=998244353;\nconst double PI = acos(-1);\n\n#define rep(i,n) for (ll i=0;i<n;++i)\n#define per(i,n) for(ll i=n-1;i>=0;--i)\n#define rep2(i,a,n) for (ll i=a;i<n;++i)\n#define per2(i,a,n) for (ll i=a;i>=n;--i)\n\ntemplate<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }\ntemplate<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }\n\ntemplate<typename Monoid, typename Operator, auto mapping>\nstruct SegTreeLazy {\n using MonoidType=typename Monoid::Type;\n using OperatorType=typename Operator::Type;\n SegTreeLazy()=default;\n\n /// @brief 要素数 n の遅延セグ木を構築する\n SegTreeLazy(int n) {\n this->n=n;\n dat=vector<MonoidType>(n<<1,Monoid::id());\n lazy=vector<OperatorType>(n<<1,Operator::id());\n }\n\n /// @brief 配列 v から遅延セグ木を構築する\n SegTreeLazy(const vector<MonoidType>& v) {\n this->n=v.size();\n dat=vector<MonoidType>(n<<1,Monoid::id());\n lazy=vector<OperatorType>(n<<1,Operator::id());\n for(int i=0; i<n; i++) dat[i+n]=v[i];\n for(int i=n-1; i>0; i--) dat[i]=Monoid::op(dat[i<<1],dat[i<<1|1]);\n }\n\n /// @brief i 番目の要素を x に更新する\n void set(int i, MonoidType x) {\n generate_indices(i,i+1);\n pushdown();\n i+=n;\n dat[i]=x;\n while(i>>=1) dat[i]=Monoid::op(dat[i<<1],dat[i<<1|1]);\n }\n\n /// @brief 区間 [l, r) に x を作用させる\n void apply(int l, int r, OperatorType x) {\n if(l==r) return;\n generate_indices(l,r);\n pushdown();\n l+=n; r+=n;\n while(l<r) {\n if(l&1) {\n lazy[l]=Operator::op(lazy[l],x);\n dat[l]=mapping(dat[l],x);\n l++;\n }\n if(r&1) {\n r--;\n lazy[r]=Operator::op(lazy[r],x);\n dat[r]=mapping(dat[r],x);\n }\n l>>=1; r>>=1;\n }\n pushup();\n }\n\n /// @brief 区間 [l, r) のモノイド積を返す\n MonoidType fold(int l, int r) {\n if(l==r) return Monoid::id();\n generate_indices(l,r);\n pushdown();\n MonoidType retl=Monoid::id(),retr=Monoid::id();\n l+=n; r+=n;\n while(l<r) {\n if(l&1) retl=Monoid::op(retl,dat[l++]);\n if(r&1) retr=Monoid::op(dat[--r],retr);\n l>>=1; r>>=1;\n }\n return Monoid::op(retl,retr);\n }\n\n /// @brief 区間 [l, x) のモノイド積が f を満たすような最大の x >= l を返す\n /// @attention `f(Monoid::id())=true` が成り立つ必要がある\n /// @note O(log(N))\n template<typename F>\n int find_right(int l, F f) {\n assert(f(Monoid::id()));\n if(l==n) return n;\n generate_indices(l,n);\n pushdown();\n l+=n;\n int r=n+n;\n vector<int> cand_l,cand_r;\n while(l<r) {\n if(l&1) cand_l.push_back(l++);\n if(r&1) cand_r.push_back(--r);\n l>>=1; r>>=1;\n }\n vector<int> cand=cand_l;\n reverse(cand_r.begin(),cand_r.end());\n cand.insert(cand.end(),cand_r.begin(),cand_r.end());\n MonoidType val=Monoid::id();\n for(int i:cand) {\n if(f(Monoid::op(val,dat[i]))) {\n val=Monoid::op(val,dat[i]);\n } else {\n while(i<n) {\n propagate(i);\n i<<=1;\n if(f(Monoid::op(val,dat[i]))) {\n val=Monoid::op(val,dat[i]);\n i|=1;\n }\n }\n return i-n;\n }\n }\n return n;\n }\n\n /// @brief 区間 [x, r) のモノイド積が f を満たすような最小の x<=r を返す\n /// @attention `f(Monoid::id())=true` が成り立つ必要がある\n /// @note O(log(N))\n template<typename F>\n int find_left(int r, F f) {\n assert(f(Monoid::id()));\n if(r==0) return 0;\n generate_indices(0,r);\n pushdown();\n r+=n;\n int l=n;\n vector<int> cand_l,cand_r;\n while(l<r) {\n if(l&1) cand_l.push_back(l++);\n if(r&1) cand_r.push_back(--r);\n l>>=1; r>>=1;\n }\n vector<int> cand=cand_r;\n reverse(cand_l.begin(),cand_l.end());\n cand.insert(cand.end(),cand_l.begin(),cand_l.end());\n MonoidType val=Monoid::id();\n for(int i:cand) {\n if(f(Monoid::op(dat[i],val))) {\n val=Monoid::op(dat[i],val);\n } else {\n while(i<n) {\n propagate(i);\n i=(i<<1)|1;\n if(f(Monoid::op(dat[i],val))) {\n val=Monoid::op(dat[i],val);\n i^=1;\n }\n }\n return i-n+1;\n }\n }\n return 0;\n }\n\n int size() { return n; }\n MonoidType operator[](int i) { return fold(i,i+1); }\n\nprivate:\n int n;\n vector<MonoidType> dat;\n vector<OperatorType> lazy;\n vector<int> indices;\n void generate_indices(int l, int r) {\n indices.clear();\n l+=n; r+=n;\n int lm=(l/(l&-l))>>1,rm=(r/(r&-r))>>1;\n while(l<r) {\n if(l<=lm) indices.push_back(l);\n if(r<=rm) indices.push_back(r);\n l>>=1; r>>=1;\n }\n while(l) {\n indices.push_back(l);\n l>>=1;\n }\n }\n void propagate(int i) {\n if(i<n) {\n lazy[i<<1]=Operator::op(lazy[i<<1],lazy[i]);\n lazy[i<<1|1]=Operator::op(lazy[i<<1|1],lazy[i]);\n dat[i<<1]=mapping(dat[i<<1],lazy[i]);\n dat[i<<1|1]=mapping(dat[i<<1|1],lazy[i]);\n }\n lazy[i]=Operator::id();\n }\n void pushdown() {\n for(int j=(int)indices.size()-1; j>=0; j--) {\n int i=indices[j];\n propagate(i);\n }\n }\n void pushup() {\n for(int j=0; j<(int)indices.size(); j++) {\n int i=indices[j];\n dat[i]=Monoid::op(dat[i<<1],dat[i<<1|1]);\n }\n }\n};\n\n\n/// @brief モノイド\nnamespace Monoid {\n\n \n /// @brief (和,区間の長さ)\n template<typename T>\n struct SumPair {\n using Type=pair<T,int>;\n static Type id() { return make_pair(T(0),0); }\n static Type op(const Type& a, const Type& b) { return {(a.first+b.first),a.second+b.second}; }\n };\n}\n\n\n/// @brief 作用素\nnamespace Operator {\n /// @brief 更新\n template<typename T, T not_exist>\n struct Update {\n using Type=T;\n static Type id() { return not_exist; }\n static Type op(const Type& a, const Type& b) { return (b==id()?a:b); }\n };\n\n \n}\n\n\nnamespace RangeQuery {\n\n\n /// @brief 区間更新 / 区間和\n /// @tparam not_exist 存在しない値\n template<typename T, T not_exist>\n struct ApplyUpdate_GetSum {\n using S=typename Monoid::SumPair<T>::Type;\n static S mapping(const S& a, const T& b) { return b==not_exist?a:S{b,a.second}; }\n using Type=struct SegTreeLazy<Monoid::SumPair<T>,Operator::Update<T,not_exist>,mapping>;\n };\n\n \n \n\n \n}\n\n\n\n\n//----------------------------------------------------------\n\n\n\n\n\nstruct HLD{\n int N;\n vector<int> si,par,head,dep;\n vector<int> hld;//ならべたやつ\n vector<int> idx;//hldの何番目にいるか\n vector<int> L,R;//[L[i],R[i])でiの部分木がとれる\n vector<vector<long long>>& ab;\n\n void dfs1(ll a,ll b){\n for(int i=0;i<ab[a].size();i++){\n int to=ab[a][i];\n if(to==b) continue;\n dep[to]=dep[a]+1;\n dfs1(to,a);\n si[a]+=si[to];\n }\n \n for(int i=0;i<ab[a].size();i++){\n if((ab[a][0]==b)||(ab[a][i]!=b&&si[ab[a][0]]<si[ab[a][i]])) swap(ab[a][0],ab[a][i]);\n }\n }\n\n void dfs2(ll a,ll b,ll h){\n idx[a]=hld.size();\n L[a]=hld.size();\n hld.emplace_back(a);\n head[a]=h;\n par[a]=b;\n for(int i=0;i<ab[a].size();i++){\n if(ab[a][i]==b) continue;\n if(i==0) dfs2(ab[a][i],a,h);\n else dfs2(ab[a][i],a,ab[a][i]);\n }\n R[a]=hld.size();\n }\n\n HLD(vector<vector<long long>>& ab2):ab(ab2){\n N=ab2.size();\n si.assign(N,1);\n par.assign(N,0);\n head.assign(N,0);\n dep.assign(N,0);\n idx.assign(N,0);\n L.assign(N,0);\n R.assign(N,0);\n dfs1(0,-1); \n dfs2(0,-1,0);\n }\n\n int lca(int a,int b){\n while(head[a]!=head[b]){\n if(dep[head[a]]>dep[head[b]]) swap(a,b);\n b=par[head[b]]; \n }\n return (dep[a]<dep[b]?a:b);\n }\n\n //a-bの辺をどのindexにsetすればいいかかえす 子から親に辺を張る\n int edgeid(ll a,ll b){\n if(dep[a]>dep[b]) swap(a,b);\n return idx[b];\n }\n //辺に対するクエリ 子から親に辺を張る\n void edgequery(ll a,ll b,vector<pair<ll,ll>>& R){\n while(head[a]!=head[b]){\n \n if(dep[head[a]]>dep[head[b]]) swap(a,b);\n R.emplace_back(idx[head[b]],idx[b]+1);\n b=par[head[b]];\n }\n if(dep[a]>dep[b]) swap(a,b);\n R.emplace_back(idx[a]+1,idx[b]+1);\n }\n\n //頂点をsetするときのindex\n int nodeid(ll a){\n return idx[a];\n }\n\n void nodequery(ll a,ll b,vector<pair<ll,ll>>& R){\n while(head[a]!=head[b]){\n if(dep[head[a]]>dep[head[b]]) swap(a,b);\n R.emplace_back(idx[head[b]],idx[b]+1);\n b=par[head[b]];\n }\n if(dep[a]>dep[b]) swap(a,b);\n R.emplace_back(idx[a],idx[b]+1);\n }\n\n};\n\n\nbool solve(){\n ll N;cin>>N;\n \n vvll ab(N);\n \n rep(i,N){\n ll k;cin>>k;\n rep(j,k){\n ll a;cin>>a;\n ab[a].emplace_back(i);\n ab[i].emplace_back(a);\n }\n }\n\n HLD hld(ab);\n ll Q;cin>>Q;\n\n rep(i,Q){\n ll u,v;cin>>u>>v;\n cout<<hld.lca(u,v)<<endl;\n\n }\n return 0;\n}\n\n \n \n \n\n\nint main(){\n cin.tie(0);\n ios::sync_with_stdio(false);\n ll T=1;//cin>>T;\n rep(i,T) solve();\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 19784, "score_of_the_acc": -0.3935, "final_rank": 4 }, { "submission_id": "aoj_GRL_5_C_10807897", "code_snippet": "// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C&lang=en\n#include <cassert>\n#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nclass Node {\npublic:\n vector<int> child;\n vector<int> pow2_ancestor;\n int depth;\n bool is_visited;\n Node()\n {\n depth = -1;\n is_visited = false;\n }\n};\n\nvoid dfs(vector<Node>& tree, vector<int>& parent, int cur)\n{\n if (tree.at(cur).is_visited)\n {\n return;\n }\n tree.at(cur).is_visited = true;\n int depth = (int)parent.size();\n tree.at(cur).depth = depth;\n\n for (int i = 0; (1 << i) <= depth; i++)\n {\n tree.at(cur).pow2_ancestor.push_back(parent.at(depth - (1 << i)));\n }\n\n parent.push_back(cur);\n for (auto x : tree.at(cur).child)\n {\n dfs(tree, parent, x);\n }\n parent.pop_back();\n}\n\nint get_nth_ancestor(const vector<Node>& tree, int cur, int nth)\n{\n for (int i = 0; (1 << i) <= nth; i++)\n {\n if ((1 << i) & nth)\n {\n cur = tree.at(cur).pow2_ancestor.at(i);\n }\n }\n return cur;\n}\n\nvoid record_ancestor(vector<Node>& tree)\n{\n vector<int> parent;\n dfs(tree, parent, 0);\n}\n\nint compute_lca(const vector<Node>& tree, int u, int v)\n{\n // align depth\n int u_depth = tree.at(u).depth;\n int v_depth = tree.at(v).depth;\n int diff = 0;\n if (u_depth < v_depth)\n {\n diff = v_depth - u_depth;\n v = get_nth_ancestor(tree, v, diff);\n v_depth = tree.at(v).depth;\n }\n else if (v_depth < u_depth)\n {\n diff = u_depth - v_depth;\n u = get_nth_ancestor(tree, u, diff);\n u_depth = tree.at(u).depth;\n }\n\n assert(v_depth == u_depth);\n assert(tree.at(u).pow2_ancestor.size() == tree.at(v).pow2_ancestor.size());\n\n if (u == v)\n {\n return u;\n }\n\n // move to ancestor if they have different ones\n int max_idx = (int)tree.at(u).pow2_ancestor.size()-1;\n for (int i = max_idx; 0 <= i; i--)\n {\n if (tree.at(u).pow2_ancestor.size() <= i)\n {\n continue;\n }\n if (tree.at(u).pow2_ancestor.at(i) != tree.at(v).pow2_ancestor.at(i))\n {\n u = tree.at(u).pow2_ancestor.at(i);\n v = tree.at(v).pow2_ancestor.at(i);\n }\n }\n return tree.at(u).pow2_ancestor.at(0);\n}\n\nint main()\n{\n int nnode;\n scanf(\"%d\", &nnode);\n vector<Node> tree(nnode);\n for (int i = 0; i < nnode; i++)\n {\n int nchild;\n scanf(\"%d\", &nchild);\n for (int c = 0; c < nchild; c++)\n {\n int child_id;\n scanf(\"%d\", &child_id);\n tree.at(i).child.push_back(child_id);\n }\n }\n record_ancestor(tree);\n\n int nquery;\n scanf(\"%d\", &nquery);\n for (int i = 0; i < nquery; i++)\n {\n int u, v;\n scanf(\"%d %d\", &u, &v);\n int result = compute_lca(tree, u, v);\n printf(\"%d\\n\", result);\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 27832, "score_of_the_acc": -0.2908, "final_rank": 3 }, { "submission_id": "aoj_GRL_5_C_10792715", "code_snippet": "#include<bits/stdc++.h>\n//#include <atcoder/all>\nusing namespace std;\n//using namespace atcoder;\n\n#define all(v) v.begin(),v.end()\nusing ll = long long;\nusing ull = unsigned long long;\nusing lll = __int128;\nusing vll=vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing P = pair<ll,ll>;\nusing vp=vector<pair<ll, ll>>;\n//using mint=modint1000000007;\n//using mint=modint998244353;\n\nconst ll INF=1ll<<60;\nll mod10=1e9+7;\nll mod99=998244353;\nconst double PI = acos(-1);\n\n#define rep(i,n) for (ll i=0;i<n;++i)\n#define per(i,n) for(ll i=n-1;i>=0;--i)\n#define rep2(i,a,n) for (ll i=a;i<n;++i)\n#define per2(i,a,n) for (ll i=a;i>=n;--i)\n\ntemplate<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }\ntemplate<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }\n\nstruct LCA {\n vector<vector<int>> par;\n vector<int> dep;\n\n void dfs(const vector<vector<long long>>& ab,int now,int pre){\n par[0][now]=pre;dep[now]=(pre==-1?0:dep[pre]+1);\n for(int nxt:ab[now]) if(nxt!=pre) dfs(ab,nxt,now);\n }\n\n LCA(const vector<vector<long long>>& ab,int root =0){\n int N=ab.size(),k=1;\n while((1<<k)<N) k++;\n par=vector<vector<int>>(k,vector<int>(N,-1)),dep=vector<int>(N);\n dfs(ab,0,-1);\n\t\tfor(int i=0;i<k-1;i++) for(int j=0;j<N;j++) par[i+1][j]=(par[i][j]==-1?-1:par[i][par[i][j]]);\n }\n\n int lca(int u,int v){\n if(dep[u]<dep[v]) swap(u,v);\n int k=par.size();\n for(int i=0;i<k;i++) if((dep[u]-dep[v])>>i&1) u=par[i][u];\n if(u==v) return u;\n for(int i=k-1;i>=0;i--) if(par[i][u]!=par[i][v]) u=par[i][u],v=par[i][v];\n return par[0][u];\n }\n\n int dist(int u,int v){return dep[u]+dep[v]-2*dep[lca(u,v)];}\n\n bool is_on_path(int u,int v,int x){return dist(u,x)+dist(x,v)==dist(u,v);}\n\n bool cilmb(int u,int d){\n int k=par.size();\n for(int i=k-1;i>=0;i--) if(d>>i&1) u=par[i][u];\n return u;\n }\n\n\n};\n\nbool solve(){\n\tll N;cin>>N;\n\tvvll ab(N);\n\trep(i,N){\n\t\tll k;cin>>k;\n\t\trep(j,k){\n\t\t\tll c;cin>>c;\n\t\t\tab[i].push_back(c);\n\t\t\tab[c].push_back(i);\n\t\t}\n\t}\n\tLCA lc(ab,0);\n\tll q;cin>>q;\n\t\n\twhile(q--){\n\t\tll a,b;cin>>a>>b;\n\t\tcout<<lc.lca(a,b)<<endl;\n\t}\n\treturn 0;\n}\n\n\n\n\nint main(){\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tll T=1;//cin>>T;\n\trep(i,T) solve();\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 21548, "score_of_the_acc": -0.502, "final_rank": 5 }, { "submission_id": "aoj_GRL_5_C_10751669", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nint timer=0;\nvector<int>tin,tout;\nvector<vector<int>>graph,anc;\nint l=21;\n\nvoid build(vector<vector<int>>&graph,int node, int par){\n anc[node][0]=par;\n tin[node]=timer;\n timer++;\n for(int i=1;i<l;i++){\n anc[node][i]=anc[anc[node][i-1]][i-1];\n } \n for(auto child:graph[node]){\n if(child!=par){\n build(graph,child,node);\n }\n }\n tout[node]=timer;\n timer++;\n}\nbool is_anc(int b, int a){\n if(tin[a]>=tin[b] and tout[a]<=tout[b]){\n return true;\n }return false;\n}\nint lca(int u, int v){\n if (is_anc(u, v)) return u;\n if (is_anc(v, u)) return v;\n for (int i = l - 1; i >= 0; i--) {\n if (!is_anc(anc[u][i], v)) {\n u = anc[u][i];\n }\n }\n return anc[u][0];\n}\nint main(){\n int n;\n cin>>n;\n vector<vector<int>>graph(n);\n for(int i=0;i<n;i++){\n int len;\n cin>>len;\n for(int j=0;j<len;j++){\n int child;cin>>child;\n graph[child].push_back(i);\n graph[i].push_back(child);\n }\n }\n timer=0;\n int root=0;\n tin.resize(n);\n tout.resize(n);\n anc.resize(n,vector<int>(l,0));\n build(graph,root,root);\n int q;\n cin>>q;\n while(q--){\n int u,v;\n cin>>u>>v;\n cout<<lca(u,v)<<endl;\n }\n\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 27336, "score_of_the_acc": -0.9654, "final_rank": 16 } ]
aoj_DPL_1_B_cpp
0-1 Knapsack Problem You have N items that you want to put them into a knapsack. Item i has value v i and weight w i . You want to find a subset of items to put such that: The total value of the items is as large as possible. The items have combined weight at most W , that is capacity of the knapsack. Find the maximum total value of items in the knapsack. Input N W v 1 w 1 v 2 w 2 : v N w N The first line consists of the integers N and W . In the following lines, the value and weight of the i -th item are given. Output Print the maximum total values of the items in a line. Constraints 1 ≤ N ≤ 100 1 ≤ v i ≤ 1000 1 ≤ w i ≤ 1000 1 ≤ W ≤ 10000 Sample Input 1 4 5 4 2 5 2 2 1 8 3 Sample Output 1 13 Sample Input 2 2 20 5 9 4 10 Sample Output 2 9
[ { "submission_id": "aoj_DPL_1_B_11009038", "code_snippet": "/*\nAllaih is Almighty\nBismillahhi Rahmanir Rahim\nBaishakh\n*/\n#include<bits/stdc++.h>\n#include<ext/pb_ds/assoc_container.hpp>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\n#define ll long long\nconst int mod = 1e9+7;\n// s.order_of_key(x) -> values total are small than x\n// *s.find_by_order(x) -> kth small elemnt (index) in pbds\nll dp[102][10002];\nll knap(vector<ll>cost,vector<ll>weight,ll w,ll ind,int n)\n{\n if(w == 0 || ind == n) return 0;\n if(dp[ind][w] != -1) return dp[ind][w];\n if(weight[ind] <= w)\n {\n return dp[ind][w] = max(cost[ind] + knap(cost,weight,w - weight[ind],ind + 1,n),\n knap(cost,weight,w,ind + 1,n));\n }\n dp[ind][w] = knap(cost,weight,w,ind+1,n);\n return dp[ind][w];\n}\nint main()\n{\n memset(dp,-1,sizeof(dp));\n ll n,w;\n cin>>n>>w;\n vector<ll>cost(n),weight(n);\n for(int i = 0;i<n;i++)\n {\n cin>>cost[i]>>weight[i];\n }\n cout<<knap(cost,weight,w,0,n)<<endl;\n return 0;\n}\n\n\n//Tata Goodbye Khatam", "accuracy": 1, "time_ms": 130, "memory_kb": 11600, "score_of_the_acc": -0.3333, "final_rank": 1 }, { "submission_id": "aoj_DPL_1_B_10780482", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing Graph = vector<vector<int>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(int i = a; i < b; i++)\n#define all(v) v.begin(), v.end()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define inf 1070000000\n#define INF 4500000000000000000\n#define MOD 998244353\n//#define MOD 1000000007\n#define pi 3.14159265358979\n\ntemplate<class T> inline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<class T> inline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\n\n//xのn乗\nll llpow(ll x, ll n) {\n ll ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\nll modpow(ll x, ll n, ll mod) {\n ll ans = 1;\n while(n > 0) {\n if(n & 1) ans = ans * x % mod;\n x = x * x % mod;\n n >>= 1;\n }\n return ans;\n}\n//nの階乗\nll fact(ll n) {\n if(n == 0) return 1;\n else return n * fact(n-1);\n}\n//素数判定\nbool is_prime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n\n//座標圧縮\nvector<int> compress(vector<int> A) {\n vector<int> B = A;\n\n sort(B.begin(), B.end());\n B.erase(unique(B.begin(), B.end()), B.end());\n\n vector<int> res(A.size());\n for(int i = 0; i < (int)A.size(); i++) {\n res[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin();\n }\n return res;\n}\n\n//正方形グリッドの右回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\n//左回転\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\ndouble dist(ll a, ll b, ll x, ll y) {\n return sqrt((a-x)*(a-x) + (b-y)*(b-y));\n}\nint man(int a, int b, int x, int y) {\n return abs(a-x) + abs(b-y);\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n rep(i,0,H) rep(j,0,W) dist[i][j] = inf;\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvoid floyd(vector<vector<ll>> &G) {\n int N = G.size();\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(G[i][j] > G[i][k] + G[k][j]) {\n G[i][j] = G[i][k] + G[k][j];\n }\n }\n }\n }\n}\n\nvoid solve() {\n}\n\nint main() {\n int N, W; cin >> N >> W;\n vector<vector<int>> dp(N+1, vector<int>(100200, 0));\n rep(i,0,N) {\n int v, w; cin >> v >> w;\n rep(j,0,W+1) {\n chmax(dp[i+1][j], dp[i][j]);\n chmax(dp[i+1][j+w], dp[i][j] + v);\n }\n }\n for(int i = W; i >= 0; i--) {\n if(dp[N][i] != 0) {\n cout << dp[N][i] << \"\\n\";\n return 0;\n }\n }\n cout << 0 << \"\\n\";\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 42988, "score_of_the_acc": -0.7121, "final_rank": 2 }, { "submission_id": "aoj_DPL_1_B_10529677", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n//#include <atcoder/all>\n//using namespace atcoder;\n//#include <unordered_set>\n//#include <boost/multiprecision/cpp_int.hpp>\n//using namespace boost::multiprecision;\nusing ll = long long;\nusing ld = long double;\nusing ull = unsigned long long;\nusing P = pair<ll,ll>;\n\n#define rep(i,n) for (ll i = 0; i < ll(n); ++i)\n#define REP(i,x,n) for (ll i = x; i < ll(n); ++i)\n#define DREP(i, r, l) for (ll i = (ll)(r)-1; i >= (ll)(l); --i)\n#define drep(i,n) DREP(i, n, 0)\n#define all(x) begin(x), end(x)\n#define rall(x) rbegin(x), rend(x)\n#define MAX *max_element\n#define MIN *min_element\n#define pb push_back\n#define pf push_front\n#define ppb pop_back\n#define eb emplace_back\n#define fi first\n#define se second\n#define p_queue priority_queue\n\nusing namespace std; // std::を省略するために追加\n\n/* ========== UNIVERSAL DEBUG ========== */\n#ifdef LOCAL\n#define dbg(...) cerr << \"\\e[33m[ \" << #__VA_ARGS__ << \" ] = \", debug_out(__VA_ARGS__), cerr << \" (\" << __LINE__ << \")\\e[0m\\n\"\n#else\n#define dbg(...) (void)0\n#endif\n\n// 型がイテラブル(反復可能)かどうかを判定するためのヘルパー\ntemplate<class T, class = void> struct is_iterable : false_type {};\ntemplate<class T>\nstruct is_iterable<T, std::void_t<decltype(std::begin(std::declval<T>())), decltype(std::end(std::declval<T>()))>> : true_type {};\ntemplate<class T> constexpr bool is_iterable_v = is_iterable<T>::value;\n\n// 様々なデータ型を出力するための関数たち\n\n// 基本的な型(int, doubleなど)を出力\n// より特定のオーバーロードが適用されない場合の最終的なフォールバック\ntemplate<class T>\nstd::enable_if_t<!is_iterable_v<T> && !std::is_pointer_v<T> && !std::is_same_v<T, std::string>, void>\ndebug_pr(const T& x){\n cerr << x;\n}\n\n// string型を出力(引用符で囲む)\ninline void debug_pr(const string& s){ cerr << '\"' << s << '\"'; }\n\n// char* などのCスタイル文字列を出力\ninline void debug_pr(const char* s) { cerr << '\"' << s << '\"'; }\n\n// pair型を出力 (first, second) の形式\ntemplate<class A,class B> void debug_pr(const pair<A,B>& p){ cerr << '('; debug_pr(p.first); cerr << \", \"; debug_pr(p.second); cerr << ')'; }\n\n// tuple型を出力するためのヘルパー(再帰的に要素を出力)\ntemplate<size_t I=0,class... Ts>\nstd::enable_if_t<I==sizeof...(Ts)> debug_tuple(const tuple<Ts...>&) {} // タプルの要素をすべて処理したら終了\ntemplate<size_t I=0,class... Ts>\nstd::enable_if_t<I<sizeof...(Ts)> debug_tuple(const tuple<Ts...>& t){\n if(I) cerr << \", \"; // 2番目以降の要素の前にカンマを追加\n debug_pr(std::get<I>(t)); // 現在の要素を出力\n debug_tuple<I+1>(t); // 次の要素を処理\n}\n\n// tuple型を出力\ntemplate<class... Ts> void debug_pr(const tuple<Ts...>& t){\n cerr << '('; debug_tuple(t); cerr << ')'; // (要素1, 要素2, ...) の形式\n}\n\n// イテラブルな型(vector, listなど、ただしstringは除く)を出力\n// このオーバーロードが選ばれるように、SFINAEで制約を追加\ntemplate<class T>\nstd::enable_if_t<is_iterable_v<T> && !std::is_same_v<T,string>, void>\ndebug_pr(const T& v){\n cerr << '['; bool f=0; // 最初だけスペースを入れないためのフラグ\n for(const auto& x:v){\n if(f) cerr << ' '; // 2番目以降の要素の前にスペースを追加\n debug_pr(x); // 各要素を出力\n f=1; // フラグを立てる\n }\n cerr << ']'; // [要素1 要素2 ...] の形式\n}\n\n// ポインタを出力 (アドレスではなく、指し示す値を出力)\n// nullptr_t は std::nullptr の型です\ninline void debug_pr(std::nullptr_t) { cerr << \"nullptr\"; }\ntemplate<class T>\nstd::enable_if_t<std::is_pointer_v<T>, void>\ndebug_pr(const T& p) {\n if (p == nullptr) {\n cerr << \"nullptr\";\n } else {\n cerr << '*'; // ポインタが指す値であることを示す\n debug_pr(*p); // ポインタが指す値を出力\n }\n}\n\n\n// 可変長引数を処理するための関数\nvoid debug_out(){ } // 引数がない場合の終端\ntemplate<class Head,class... Tail>\nvoid debug_out(const Head& h,const Tail&... tl){\n debug_pr(h); // 最初の引数を出力\n if constexpr(sizeof...(tl)) { cerr << \", \"; debug_out(tl...); } // 残りの引数があれば、カンマの後に再帰呼び出し\n}\n\n\ntemplate<typename T, typename U>\nostream& operator<<(ostream& os, const pair<T, U>& p) {\n os << \"(\" << p.first << \", \" << p.second << \")\";\n return os;\n}\n\ntemplate<typename T, typename U> inline void println(const vector<pair<T,U>>& vec) { for(auto& [x,y]:vec) cout<<\"(\"<<x<<\",\"<<y<<\") \"; cout<<\"\\n\"; }\ninline void print(vector<char>& v) { for (char c : v) cout << c; }\ninline void println(vector<char>& v) { print(v); cout << '\\n'; }\ntemplate<class T> inline bool chmax(T &a, T b) { return a < b ? a = b, 1 : 0; }\ntemplate<class T> inline bool chmin(T &a, T b) { return a > b ? a = b, 1 : 0; }\nvoid dprint(ld x) { printf(\"%.30Lf\\n\",x); }\ntemplate<class... T> inline void input(T&... a) { ((cin >> a), ...); }\ntemplate <class T> inline void input(vector<T> &v) { for (T &x : v) cin >> x; }\ntemplate<class T, class... U> inline void print(const T& a, const U&... b) { cout << a; ((cout << b), ...); }\ntemplate<class T, class... U> inline void println(const T& a, const U&... b) { print(a, b...); cout << '\\n'; }\ninline void println() { cout << '\\n'; }\ntemplate<class T> inline void print(vector<T>& A) { rep(i, A.size()) { if (i) cout << ' '; cout << A[i]; } }\ntemplate<class T> inline void println(vector<T>& A) { print(A); cout << '\\n'; }\ninline void yn(bool ok) { cout << (ok ? \"Yes\\n\" : \"No\\n\"); }\n\nconst ll INF = (1LL << 62) - (1LL << 31) - 1;\nconst ll mod = 1e9 + 7;\n\nconst ll dx[] = {-1,1,0,0,1,1,-1,-1};\nconst ll dy[] = {0,0,-1,1,1,-1,1,-1};\n\n// 2次元累積和のライブラリ貼ってる\n// 2^nの数え上げはDPで解けるかも?\n// 全探索の高速化といえばDP\n// DPは配る遷移ともらう遷移の両方を考察する\n// 問題の振り返り書け\n// めんどくさい計算とかは関数にしたら楽\n// 誤差などが怖いときは移項などをして整数で考えるようにする \n// 式変形をしたら見通しが良くなる\n// 問題を分解する\n// すべての問題を解けると思って考える\n// ゲームをしているならDPを考える\n\n// alias xx='g++ -D_GLIBCXX_DEBUG -fsanitize=undefined,address -fno-sanitize-recover=all -Wall -Wextra -Wshadow'\n\nvoid solve() {\n\tll n,w;\n\tinput(n,w);\n\tvector<ll> v(n),u(n);\n\trep(i,n) input(v[i],u[i]);\n\tmap<P,ll> memo;\n\tauto f = [&](auto self,ll d,ll now) -> ll {\n\t\tif(d >= n) return 0;\n\t\tif(memo.count(P(d,now))) return memo[P(d,now)];\n\t\tll res = 0;\n\t\tif(now+u[d] <= w) {\n\t\t\tres = max(self(self,d+1,now+u[d])+v[d],self(self,d+1,now));\n\t\t}else {\n\t\t\tres = max(res,self(self,d+1,now));\n\t\t}\n\t\treturn memo[P(d,now)] = res;\n\t};\n\n\tprintln(f(f,0,0));\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n cin.tie(nullptr);\n\tsolve();\n return 0;\n}", "accuracy": 1, "time_ms": 370, "memory_kb": 55680, "score_of_the_acc": -2, "final_rank": 4 }, { "submission_id": "aoj_DPL_1_B_10475901", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main() {\n int N,W;\n cin >> N >> W;\n vector<int>v(N);\n vector<int>w(N);\n for(int i = 0; i < N; i++){\ncin >> v[i] >> w[i];\n }\n\n vector<vector<int>>DP(N+10,vector<int>(100100,0));\n for(int i = 0; i < N; i++){\n\n for(int sum_w = 0; sum_w <= W ; sum_w++){\n\n if(sum_w >= w[i]){\nDP[i+1][sum_w] = max(DP[i+1][sum_w],DP[i][sum_w-w[i]]+v[i]);\n }\n DP[i+1][sum_w] = max(DP[i+1][sum_w],DP[i][sum_w]);\n }\n }\n cout << DP[N][W] << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 46644, "score_of_the_acc": -0.795, "final_rank": 3 } ]
aoj_GRL_6_B_cpp
Minimum Cost Flow Find the minimum cost to send a certain amount of flow through a flow network. The flow network is a directed graph where each edge $e$ has capacity $c(e)$ and cost $d(e)$. Each edge $e$ can send an amount of flow $f(e)$ where $f(e) \leq c(e)$. Find the minimum value of $\sum_{e} (f(e) \times d(e))$ to send an amount of flow $F$ from source $s$ to sink $t$. Input A flow network $G(V,E)$ is given in the following format. $|V|\;|E|\;F$ $u_0\;v_0\;c_0\;d_0$ $u_1\;v_1\;c_1\;d_1$ : $u_{|E|1}\;v_{|E|-1}\;c_{|E|-1}\;d_{|E|-1}$ $|V|$, $|E|$, $F$ are the number of vertices, the number of edges, and the amount of flow of the flow network respectively. The vertices in $G$ are named with the numbers $0, 1,..., |V|−1$. The source is $0$ and the sink is $|V|−1$. $u_i$, $v_i$, $c_i$, $d_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$, and $c_i$ and $d_i$ are the capacity and the cost of $i$-th edge respectively. Output Print the minimum value in a line. If it is impossible to send the flow from the source $s$ to the sink $t$, print -1 . Constraints 2 ≤ $|V|$ ≤ 100 1 ≤ $|E|$ ≤ 1000 0 ≤ $F$ ≤ 1000 0 ≤ $c_i$, $d_i$ ≤ 1000 $u_i$ $\ne$ $v_i$ If there is an edge from vertex $x$ to vertex $y$, there is no edge from vertex $y$ to vertex $x$. Sample Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Sample Output 6
[ { "submission_id": "aoj_GRL_6_B_8449576", "code_snippet": "#line 1 \"playspace/main.cpp\"\n#include <bits/stdc++.h>\n#line 2 \"library/gandalfr/graph/flow_graph.hpp\"\n\n#line 7 \"library/gandalfr/graph/base_graph.hpp\"\n\nnamespace internal {\ntemplate <class Weight> struct _base_edge {\n int v[2];\n Weight cost;\n int id;\n _base_edge() {}\n _base_edge(int from, int to, Weight cost, int id)\n : v{from, to}, cost(cost), id(id) {}\n\n // x から見た反対側の端点を返す\n int opp(int x) {\n if (x == v[0]) {\n return v[1];\n } else if (x == v[1]) {\n return v[0];\n } else {\n std::abort();\n }\n }\n\n friend std::ostream &operator<<(std::ostream &os,\n const _base_edge<Weight> &e) {\n e.print(os);\n return os;\n }\n\n protected:\n virtual void print(std::ostream &os) const = 0;\n};\n} // namespace internal\n\ntemplate <class Weight> struct edge : public internal::_base_edge<Weight> {\n using internal::_base_edge<Weight>::_base_edge;\n\n edge reverse() const {\n return {this->v[1], this->v[0], this->cost, this->id};\n }\n\n protected:\n void print(std::ostream &os) const override {\n os << this->v[0] << \" \" << this->v[1] << \" \" << this->cost;\n }\n};\n\ntemplate <> struct edge<int> : public internal::_base_edge<int> {\n static inline const int cost = 1;\n using internal::_base_edge<int>::_base_edge;\n edge(int _from, int _to, int _id) : _base_edge<int>(_from, _to, 1, _id) {}\n\n edge reverse() const { return {v[1], v[0], 1, id}; }\n\n protected:\n void print(std::ostream &os) const override {\n os << this->v[0] << \" \" << this->v[1];\n }\n};\n\ntemplate <class Cost, class Flow>\nstruct flow_edge : public internal::_base_edge<Cost> {\n private:\n Flow res, cap;\n using internal::_base_edge<Cost>::cost;\n\n public:\n flow_edge() {}\n flow_edge(int from, int to, Flow res, Flow cap, int id)\n : internal::_base_edge<Cost>(from, to, 1, id), res(res), cap(cap) {}\n flow_edge(int from, int to, Flow res, Flow cap, Cost cost, int id)\n : internal::_base_edge<Cost>(from, to, cost, id), res(res), cap(cap) {\n }\n\n // x から見たコスト\n Cost get_cost(int x) {\n if (x == this->v[0]) {\n return this->cost;\n } else if (x == this->v[1]) {\n return -this->cost;\n } else {\n std::abort();\n }\n }\n\n flow_edge reverse() const {\n return {this->v[1], this->v[0], cap - res, cap, this->cost, this->id};\n }\n\n // x から見た残余\n Flow residual(int x) const {\n if (x == this->v[0]) {\n return res;\n } else if (x == this->v[1]) {\n return cap - res;\n } else {\n std::abort();\n }\n }\n\n // x から見て残余がゼロか?\n Flow is_full(int x) const {\n if (x == this->v[0]) {\n return res == 0;\n } else if (x == this->v[1]) {\n return cap - res == 0;\n } else {\n std::abort();\n }\n }\n\n // x から流量を d だけ追加\n void add_flow(int x, Flow d) {\n if (x == this->v[0]) {\n res -= d;\n } else if (x == this->v[1]) {\n res += d;\n } else {\n std::abort();\n }\n }\n\n protected:\n void print(std::ostream &os) const override {\n os << this->v[0] << \" \" << this->v[1] << \" \" << cap - res << \"/\" << cap;\n }\n};\n\nnamespace internal {\n\ntemplate <typename Edge> class _base_graph {\n protected:\n int N;\n std::vector<std::vector<Edge *>> G;\n std::vector<std::unique_ptr<Edge>> E;\n\n public:\n _base_graph(){};\n _base_graph(int n) : N(n), G(n){};\n _base_graph(int n, int m) : N(n), G(n) { E.reserve(m); };\n\n /**\n * @return ノードの数\n */\n int count_nodes() const { return N; }\n\n /**\n * @return 辺の数\n */\n int count_edges() const { return E.size(); }\n\n /**\n * @param n ノード番号\n * @return ノード n からの隣接頂点のリストの const 参照\n */\n const std::vector<Edge *> &operator[](int n) const { return G[n]; }\n\n /**\n * @return グラフ全体の辺のポインタのリストの const 参照\n */\n const std::vector<std::unique_ptr<Edge>> &edges() const { return E; }\n\n void print() const {\n std::cout << this->N << \" \" << this->E.size() << std::endl;\n for (auto &e : this->E)\n std::cout << *e << std::endl;\n }\n};\n} // namespace internal\n#line 4 \"library/gandalfr/graph/flow_graph.hpp\"\n\ntemplate <typename Cost, typename Flow>\nclass flow_graph : public internal::_base_graph<flow_edge<Cost, Flow>> {\n public:\n using internal::_base_graph<flow_edge<Cost, Flow>>::_base_graph;\n flow_graph(const flow_graph &other) : flow_graph(other.N) {\n for (auto &e : other.E) {\n add_edge(*e);\n }\n }\n\n /**\n * @brief ノードの数をn個まで増やす\n * @param n サイズ\n * @attention 今のノード数より小さい数を渡したとき、変化なし\n */\n void expand(int n) {\n if (n <= this->N)\n return;\n this->N = n;\n this->G.resize(n);\n }\n\n /**\n * @attention 辺の id は保持される\n */\n void add_edge(const flow_edge<Cost, Flow> &e) {\n this->E.emplace_back(std::make_unique<flow_edge<Cost, Flow>>(e));\n this->G[e.v[0]].push_back(this->E.back().get());\n this->G[e.v[1]].push_back(this->E.back().get());\n }\n\n /**\n * @attention 辺の id は、(現在の辺の本数)番目 が振られる\n */\n void add_edge(int from, int to, Flow capacity) {\n int id = (int)this->E.size();\n flow_edge<Cost, Flow> e(from, to, capacity, capacity, id);\n this->E.emplace_back(std::make_unique<flow_edge<Cost, Flow>>(e));\n this->G[from].push_back(this->E.back().get());\n this->G[to].push_back(this->E.back().get());\n }\n\n /**\n * @attention 辺の id は、(現在の辺の本数)番目 が振られる\n */\n void add_edge(int from, int to, Cost cost, Flow capacity) {\n int id = (int)this->E.size();\n flow_edge<Cost, Flow> e(from, to, capacity, capacity, cost, id);\n this->E.emplace_back(std::make_unique<flow_edge<Cost, Flow>>(e));\n this->G[from].push_back(this->E.back().get());\n this->G[to].push_back(this->E.back().get());\n }\n\n Flow Ford_Fulkerson(int s, int t) {\n static_assert(std::is_integral<Flow>::value,\n \"Flow must be an integer type\");\n Flow flow = 0;\n while (true) {\n std::vector<bool> vis(this->N, false);\n auto dfs = [&](auto self, int cur, Flow f) -> Flow {\n if (cur == t)\n return f;\n vis[cur] = true;\n for (auto &e : this->G[cur]) {\n if (vis[e->opp(cur)] || e->is_full(cur))\n continue;\n Flow tmp = self(self, e->opp(cur),\n std::min<Flow>(e->residual(cur), f));\n if (tmp > static_cast<Flow>(0)) {\n e->add_flow(cur, tmp);\n return tmp;\n }\n }\n return static_cast<Flow>(0);\n };\n Flow inc = dfs(dfs, s, std::numeric_limits<Flow>::max());\n if (inc == 0)\n break;\n flow += inc;\n }\n return flow;\n }\n\n Flow Dinic(int s, int t) {\n const int invalid = std::numeric_limits<int>::max();\n Flow flow = 0;\n while (true) {\n std::vector<int> dist(this->N, invalid);\n dist[s] = 0;\n std::queue<int> q;\n q.push(s);\n while (!q.empty()) {\n int cur = q.front();\n q.pop();\n for (auto &e : this->G[cur]) {\n int to = e->opp(cur);\n if (dist[to] != invalid || e->is_full(cur))\n continue;\n dist[to] = dist[cur] + 1;\n q.push(to);\n }\n }\n if (dist[t] == invalid)\n break;\n\n while (true) {\n auto dfs = [&](auto self, int cur, Flow f) -> Flow {\n if (cur == s)\n return f;\n for (auto &e : this->G[cur]) {\n int to = e->opp(cur);\n if (dist[to] != dist[cur] - 1 || e->is_full(to))\n continue;\n Flow tmp =\n self(self, to, std::min<Flow>(e->residual(to), f));\n if (tmp > static_cast<Flow>(0)) {\n e->add_flow(to, tmp);\n return tmp;\n }\n }\n return static_cast<Flow>(0);\n };\n Flow inc = dfs(dfs, t, std::numeric_limits<Flow>::max());\n if (inc == 0)\n break;\n flow += inc;\n }\n }\n return flow;\n }\n\n Flow primal_dual(int s, int t, Flow F) {\n const Cost invalid = std::numeric_limits<Cost>::max();\n Cost cst = 0;\n while (F) {\n std::vector<int> prev_path(this->N, -1);\n std::vector<Cost> min_cost(this->N, invalid);\n min_cost[s] = 0;\n \n for (int i = 0; i < this->N; ++i) {\n for (int j = 0; j < this->E.size(); ++j) {\n auto e = &(this->E[j]);\n int src = (*e)->v[0], dst = (*e)->v[1];\n for (int k = 0; k < 2; ++k) {\n if (min_cost[src] != invalid && !(*e)->is_full(src)) {\n Cost alt = min_cost[src] + (*e)->get_cost(src);\n if (min_cost[dst] > alt) {\n min_cost[dst] = alt; \n prev_path[dst] = j;\n }\n }\n std::swap(src, dst);\n }\n }\n }\n if (min_cost[t] == invalid) return -1;\n\n Flow f = F;\n int cur = t;\n while (cur != s) {\n auto e = &(this->E[prev_path[cur]]);\n int src = (*e)->v[(*e)->v[0] == cur];\n f = std::min(f, (*e)->residual(src));\n cur = src;\n }\n F -= f;\n\n cur = t;\n while (cur != s) {\n auto e = &(this->E[prev_path[cur]]);\n int src = (*e)->v[(*e)->v[0] == cur];\n (*e)->add_flow(src, f);\n cst += f * (*e)->get_cost(src);\n cur = src;\n }\n }\n return cst;\n }\n\n\n};\n#line 3 \"playspace/main.cpp\"\nusing namespace std;\nusing ll = long long;\nconst int INF = 1001001001;\nconst ll INFLL = 1001001001001001001;\nconst ll MOD = 1000000007;\nconst ll _MOD = 998244353;\n#define rep(i, j, n) for(ll i = (ll)(j); i < (ll)(n); i++)\n#define rrep(i, j, n) for(ll i = (ll)(n-1); i >= (ll)(j); i--)\n#define all(a) (a).begin(),(a).end()\n#define debug(a) std::cerr << #a << \": \" << a << std::endl\n#define LF cout << endl\ntemplate<typename T1, typename T2> inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }\ntemplate<typename T1, typename T2> inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }\nvoid Yes(bool ok){ std::cout << (ok ? \"Yes\" : \"No\") << std::endl; }\n\nint main(void){\n\n int N, M, F;\n cin >> N >> M >> F;\n flow_graph<int, int> G(N);\n rep(i,0,M) {\n int a, b, c, d;\n cin >> a >> b >> c >> d;\n G.add_edge(a, b, d, c);\n }\n cout << G.primal_dual(0, N-1, F) << endl;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3452, "score_of_the_acc": -0.0003, "final_rank": 1 }, { "submission_id": "aoj_GRL_6_B_8423038", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1012345678;\n\nstruct edge {\n\tint to, cap, rev, cost;\n};\n\nint mincostflow(int V, int S, int T, int F, vector<vector<edge> >& G) {\n\tint ans = 0;\n\tfor (int rep = 0; rep < F; rep++) {\n\t\tvector<int> dist(V, INF);\n\t\tvector<edge> pre(V, edge{-1, -1});\n\t\tdist[S] = 0;\n\t\tint counter = 0;\n\t\twhile (counter != V) {\n\t\t\tvector<int> ndist = dist;\n\t\t\tfor (int i = 0; i < V; i++) {\n\t\t\t\tif (dist[i] != INF) {\n\t\t\t\t\tfor (edge e : G[i]) {\n\t\t\t\t\t\tif (e.cap > 0 && ndist[e.to] > dist[i] + e.cost) {\n\t\t\t\t\t\t\tndist[e.to] = dist[i] + e.cost;\n\t\t\t\t\t\t\tpre[e.to] = G[e.to][e.rev];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dist == ndist) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdist = ndist;\n\t\t\tcounter += 1;\n\t\t}\n\t\tassert(counter != V);\n\t\tif (dist[T] == INF) {\n\t\t\treturn INF;\n\t\t}\n\t\tans += dist[T];\n\t\tint pos = T;\n\t\twhile (pos != S) {\n\t\t\tedge& e = G[pre[pos].to][pre[pos].rev];\n\t\t\te.cap -= 1;\n\t\t\tG[e.to][e.rev].cap += 1;\n\t\t\tpos = pre[pos].to;\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint V, E, F;\n\tcin >> V >> E >> F;\n\tvector<vector<edge> > G(V);\n\tauto add_edge = [&](int va, int vb, int cap, int cost) -> void {\n\t\tG[va].push_back(edge{vb, cap, int(G[vb].size()), cost});\n\t\tG[vb].push_back(edge{va, 0, int(G[va].size()) - 1, -cost});\n\t};\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\tint ans = mincostflow(V, 0, V - 1, F, G);\n\tcout << (ans != INF ? ans : -1) << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3500, "score_of_the_acc": -0.0014, "final_rank": 2 }, { "submission_id": "aoj_GRL_6_B_8396399", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1012345678;\n\nstruct edge {\n\tint to, cap, rev, cost;\n};\n\nint mincostflow(int V, int S, int T, int F, vector<vector<edge> >& G) {\n\tint ans = 0;\n\tfor (int rep = 0; rep < F; rep++) {\n\t\tvector<int> dist(V, INF);\n\t\tvector<edge> pre(V);\n\t\tdist[S] = 0;\n\t\tint counter = 0;\n\t\twhile (counter != V) {\n\t\t\tvector<int> ndist = dist;\n\t\t\tfor (int i = 0; i < V; i++) {\n\t\t\t\tfor (edge e : G[i]) {\n\t\t\t\t\tif (dist[i] != INF && e.cap > 0 && ndist[e.to] > dist[i] + e.cost) {\n\t\t\t\t\t\tndist[e.to] = dist[i] + e.cost;\n\t\t\t\t\t\tpre[e.to] = G[e.to][e.rev];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dist == ndist) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdist = ndist;\n\t\t\tcounter += 1;\n\t\t}\n\t\tassert(counter != V);\n\t\tif (dist[T] == INF) {\n\t\t\treturn INF;\n\t\t}\n\t\tans += dist[T];\n\t\tint pos = T;\n\t\twhile (pos != S) {\n\t\t\tedge &e = G[pre[pos].to][pre[pos].rev];\n\t\t\te.cap -= 1;\n\t\t\tG[e.to][e.rev].cap += 1;\n\t\t\tpos = pre[pos].to;\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint V, E, F;\n\tcin >> V >> E >> F;\n\tvector<vector<edge> > G(V);\n\tauto add_edge = [&](int a, int b, int c, int d) -> void {\n\t\tG[a].push_back(edge{b, c, int(G[b].size()), d});\n\t\tG[b].push_back(edge{a, 0, int(G[a].size()) - 1, -d});\n\t};\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\tint ans = mincostflow(V, 0, V - 1, F, G);\n\tcout << (ans != INF ? ans : -1) << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3484, "score_of_the_acc": -0.1121, "final_rank": 7 }, { "submission_id": "aoj_GRL_6_B_8384119", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1012345678;\n\nstruct edge_data {\n\tint a, b, cap, cost; // a -> b\n};\n\nstruct edge {\n\tint to, id;\n};\n\nint mincostflow(int V, int S, int T, int F, const vector<edge_data>& es) {\n\tconst int E = es.size();\n\tvector<vector<edge> > G(V);\n\tvector<int> cap(2 * E, 0);\n\tfor (int i = 0; i < E; i++) {\n\t\tedge_data e = es[i];\n\t\tG[e.a].push_back(edge{e.b, i});\n\t\tG[e.b].push_back(edge{e.a, i + E});\n\t\tcap[i] = e.cap;\n\t}\n\tint ans = 0;\n\tfor (int rep = 0; rep < F; rep++) {\n\t\tvector<int> dist(V, INF);\n\t\tvector<int> pre(V, -1);\n\t\tdist[S] = 0;\n\t\tint counter = 0;\n\t\twhile (counter != V) {\n\t\t\tvector<int> ndist = dist;\n\t\t\tfor (int i = 0; i < V; i++) {\n\t\t\t\tfor (edge e : G[i]) {\n\t\t\t\t\tint ncost = (e.id < E ? es[e.id].cost : -es[e.id - E].cost);\n\t\t\t\t\tif (cap[e.id] > 0 && dist[i] != INF && ndist[e.to] > dist[i] + ncost) {\n\t\t\t\t\t\tndist[e.to] = dist[i] + ncost;\n\t\t\t\t\t\tpre[e.to] = e.id;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dist == ndist) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdist = ndist;\n\t\t\tcounter += 1;\n\t\t}\n\t\tassert(counter != V);\n\t\tif (dist[T] == INF) {\n\t\t\treturn INF;\n\t\t}\n\t\tans += dist[T];\n\t\tint pos = T;\n\t\twhile (pos != S) {\n\t\t\tint id = pre[pos];\n\t\t\tcap[id] -= 1;\n\t\t\tcap[(id + E) % (2 * E)] += 1;\n\t\t\tpos ^= es[id % E].a ^ es[id % E].b;\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint V, E, F;\n\tcin >> V >> E >> F;\n\tvector<edge_data> es(E);\n\tfor (int i = 0; i < E; i++) {\n\t\tcin >> es[i].a >> es[i].b >> es[i].cap >> es[i].cost;\n\t}\n\tint ans = mincostflow(V, 0, V - 1, F, es);\n\tcout << (ans != INF ? ans : -1) << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3476, "score_of_the_acc": -0.112, "final_rank": 6 }, { "submission_id": "aoj_GRL_6_B_8372243", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1012345678;\n\nstruct edge {\n\tint to, cap, rev, cost;\n};\n\nint mincostflow(int V, int S, int T, int F, vector<vector<edge> >& G) {\n\tint ans = 0;\n\tfor (int rep = 0; rep < F; rep++) {\n\t\tvector<int> dist(V, INF);\n\t\tvector<edge> pre(V);\n\t\tdist[S] = 0;\n\t\tint counter = 0;\n\t\twhile (counter != V) {\n\t\t\tvector<int> ndist = dist;\n\t\t\tfor (int i = 0; i < V; i++) {\n\t\t\t\tfor (edge e : G[i]) {\n\t\t\t\t\tif (dist[i] != INF && e.cap > 0 && ndist[e.to] > dist[i] + e.cost) {\n\t\t\t\t\t\tndist[e.to] = dist[i] + e.cost;\n\t\t\t\t\t\tpre[e.to] = G[e.to][e.rev];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dist == ndist) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdist = ndist;\n\t\t\tcounter += 1;\n\t\t}\n\t\tassert(counter != V);\n\t\tif (dist[T] == INF) {\n\t\t\treturn INF;\n\t\t}\n\t\tans += dist[T];\n\t\tint pos = T;\n\t\twhile (pos != S) {\n\t\t\tedge& e = G[pre[pos].to][pre[pos].rev];\n\t\t\te.cap -= 1;\n\t\t\tG[e.to][e.rev].cap += 1;\n\t\t\tpos = pre[pos].to;\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint V, E, F;\n\tcin >> V >> E >> F;\n\tvector<vector<edge> > G(V);\n\tauto add_edge = [&](int a, int b, int c, int d) -> void {\n\t\tG[a].push_back(edge{b, c, int(G[b].size()), d});\n\t\tG[b].push_back(edge{a, 0, int(G[a].size()) - 1, -d});\n\t};\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\tint ans = mincostflow(V, 0, V - 1, F, G);\n\tcout << (ans != INF ? ans : -1) << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3440, "score_of_the_acc": -0.1112, "final_rank": 4 }, { "submission_id": "aoj_GRL_6_B_8326938", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1012345678;\n\nstruct edge {\n\tint to, cap, rev, cost;\n};\n\nint mincostflow(int V, int S, int T, int F, vector<vector<edge> >& G) {\n\tint ans = 0;\n\tfor (int rep = 0; rep < F; rep++) {\n\t\tvector<int> dist(V, INF);\n\t\tvector<edge> pre(V);\n\t\tdist[S] = 0;\n\t\tint counter = 0;\n\t\twhile (true) {\n\t\t\tvector<int> ndist = dist;\n\t\t\tfor (int i = 0; i < V; i++) {\n\t\t\t\tif (dist[i] != INF) {\n\t\t\t\t\tfor (edge e : G[i]) {\n\t\t\t\t\t\tif (e.cap > 0 && ndist[e.to] > dist[i] + e.cost) {\n\t\t\t\t\t\t\tndist[e.to] = dist[i] + e.cost;\n\t\t\t\t\t\t\tpre[e.to] = G[e.to][e.rev];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dist == ndist) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdist = ndist;\n\t\t}\n\t\tif (dist[T] == INF) {\n\t\t\treturn INF;\n\t\t}\n\t\tans += dist[T];\n\t\tint pos = T;\n\t\twhile (pos != S) {\n\t\t\tedge &e = G[pre[pos].to][pre[pos].rev];\n\t\t\te.cap -= 1;\n\t\t\tG[e.to][e.rev].cap += 1;\n\t\t\tpos = pre[pos].to;\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint V, E, F;\n\tcin >> V >> E >> F;\n\tvector<vector<edge> > G(V);\n\tauto add_edge = [&](int va, int vb, int cap, int cost) -> void {\n\t\tG[va].push_back(edge{vb, cap, int(G[vb].size()), cost});\n\t\tG[vb].push_back(edge{va, 0, int(G[va].size()) - 1, -cost});\n\t};\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\tint ans = mincostflow(V, 0, V - 1, F, G);\n\tcout << (ans != INF ? ans : -1) << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3440, "score_of_the_acc": -0.1112, "final_rank": 4 }, { "submission_id": "aoj_GRL_6_B_8325592", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1012345678;\n\nstruct edge {\n\tint to, cap, rev, cost;\n};\n\nint mincostflow(int V, int S, int T, int F, vector<vector<edge> >& G) {\n\tint ans = 0;\n\tfor (int id = 0; id < F; id++) {\n\t\tvector<int> dist(V, INF);\n\t\tvector<edge> pre(V);\n\t\tdist[S] = 0;\n\t\tint counter = 0;\n\t\twhile (counter != V) {\n\t\t\tvector<int> ndist = dist;\n\t\t\tfor (int i = 0; i < V; i++) {\n\t\t\t\tfor (edge e : G[i]) {\n\t\t\t\t\tif (e.cap > 0 && dist[i] != INF && ndist[e.to] > dist[i] + e.cost) {\n\t\t\t\t\t\tndist[e.to] = dist[i] + e.cost;\n\t\t\t\t\t\tpre[e.to] = G[e.to][e.rev];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dist == ndist) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdist = ndist;\n\t\t\tcounter += 1;\n\t\t}\n\t\tif (counter == V) {\n\t\t\treturn -2;\n\t\t}\n\t\tif (dist[T] == INF) {\n\t\t\treturn INF; // no flow of size F\n\t\t}\n\t\tint pos = T;\n\t\twhile (pos != S) {\n\t\t\tedge &e = G[pre[pos].to][pre[pos].rev];\n\t\t\te.cap -= 1;\n\t\t\tG[e.to][e.rev].cap += 1;\n\t\t\tpos = pre[pos].to;\n\t\t}\n\t\tans += dist[T];\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint V, E, F;\n\tcin >> V >> E >> F;\n\tvector<vector<edge> > G(V);\n\tauto add_edge = [&](int va, int vb, int cap, int cost) -> void {\n\t\tG[va].push_back(edge{vb, cap, int(G[vb].size()), cost});\n\t\tG[vb].push_back(edge{va, 0, int(G[va].size()) - 1, -cost});\n\t};\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\tint ans = mincostflow(V, 0, V - 1, F, G);\n\tcout << (ans != INF ? ans : -1) << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3436, "score_of_the_acc": -0.1111, "final_rank": 3 }, { "submission_id": "aoj_GRL_6_B_7967924", "code_snippet": "#include<iostream>\n#include<cstdio>\n#include<string>\n#include<cmath>\n#include<algorithm>\n#include<map>\n#include<vector>\n#include<stack>\n#include<iomanip>\n#include<queue>\n#include<set>\n#include<functional>\n#include<tuple>\n#include<bitset>\n#include<cassert>\n#include<cstdint>\n#include<complex>\n#include<random>\nusing namespace std;\nbool printb(bool f) {\n\tif (f)printf(\"Yes\\n\");\n\telse printf(\"No\\n\");\n\treturn f;\n}\ntemplate<class T>\nvoid prt(T t = \"\", string sep = \"\\n\") { cout << t << sep; return; }\ntemplate<class T>\nvoid printl(vector<T> a, string sep = \" \") {\n\tfor (int i = 0; i < a.size(); i++) {\n\t\tcout << a[i];\n\t\tif (i != a.size() - 1)cout << sep;\n\t}\n\tif (sep != \"\\n\")cout << \"\\n\";\n\treturn;\n}\nbool prt_isfixed = false;\ntemplate<class T>\nvoid prt_fix(T t, string sep = \"\\n\") {\n\tif (!prt_isfixed) {\n\t\tcout << fixed << setprecision(15);\n\t\tprt_isfixed = true;\n\t}\n\tprt(t, sep);\n}\n#define all(a) a.begin(),a.end()\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\nusing uint = unsigned int;\nusing llong = long long;\nusing ullong = unsigned long long;\nusing pii = pair<int, int>;\nusing pll = pair<llong, llong>;\nusing pli = pair<llong, int>;\nusing pil = pair<int, llong>;\ntemplate<typename T> using vec2 = vector<vector<T>>;\ntemplate<typename T> inline bool chmin(T& a, T b) { return (a > b) ? (a = b, true) : false; }\ntemplate<typename T> inline bool chmax(T& a, T b) { return (a < b) ? (a = b, true) : false; }\nbool bitIn(llong a, int b) { return ((a >> b) & 1); }\nint bitCnt(llong a) {\n\tint re = 0;\n\twhile (a > 0) {\n\t\tif (a & 1)re++;\n\t\ta >>= 1;\n\t}\n\treturn re;\n}\nllong powL(llong n, llong i) {\n\tllong re = 1;\n\twhile (i >= 1) {\n\t\tif (i & 1) re *= n;\n\t\tn *= n;\n\t\ti >>= 1;\n\t}\n\treturn re;\n}\n\nllong powL_M(llong n, llong i, llong mod) {\n\tllong re = 1;\n\twhile (i >= 1) {\n\t\tif (i & 1) {\n\t\t\tre *= n;\n\t\t\tre %= mod;\n\t\t}\n\t\tn *= n;\n\t\tn %= mod;\n\t\ti >>= 1;\n\t}\n\treturn re;\n}\n\nstruct point {\n\tllong x = 0, y = 0;\n};\nint dx[4] = { 0,1,0,-1 }, dy[4] = { 1,0,-1,0 };\n\nstruct edge {\n\tint to, co;\n};\n\n\nint main() {\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tvector<int> re(m, 0);\n\tvector<tuple<int, int, int, int>> e(m);\n\trep(i, m) {\n\t\tint u, v, c, d;\n\t\tscanf(\"%d %d %d %d\", &u, &v, &c, &d);\n\t\te[i] = { u,v,c,d };\n\t}\n\trep(l, k) {\n\n\t\tvector<int>\tprev(n, -1);\n\t\tvector<int> dis(n, 1e9);\n\t\tdis[0] = 0;\n\t\trep(i, n - 1) {\n\t\t\trep(j, m) {\n\t\t\t\tauto [u, v, c, d] = e[j];\n\t\t\t\tif (re[j] != c) {\n\t\t\t\t\tif (chmin(dis[v], dis[u] + d))prev[v] = j;\n\t\t\t\t}\n\t\t\t\tif (re[j] != 0) {\n\t\t\t\t\tif (chmin(dis[u], dis[v] - d))prev[u] = j + m;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (prev[n - 1] == -1) {\n\t\t\tprt(-1); return 0;\n\t\t}\n\t\tint\tnv = n - 1;\n\t\twhile (nv != 0) {\n\t\t\tif (prev[nv] >= m) {\n\t\t\t\t//逆辺のとき\n\t\t\t\tre[prev[nv] - m]--;\n\t\t\t\tnv = get<1>(e[prev[nv] - m]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tre[prev[nv]]++;\n\t\t\t\tnv = get<0>(e[prev[nv]]);\n\t\t\t}\n\t\t}\n\t}\n\tint ans = 0;\n\trep(i, m) {\n\t\tauto [u, v, c, d] = e[i];\n\t\tans += re[i] * d;\n\t}\n\tprt(ans);\n\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 3532, "score_of_the_acc": -1.0021, "final_rank": 19 }, { "submission_id": "aoj_GRL_6_B_7098827", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\nstruct edge { int to, cap, cost, rev; };\n\nint V, E, F;\nvector<edge> G[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N];\nint preve[MAX_N];\n\nvoid add_edge(int f, int t, int cap, int cost) {\n\tedge e1;\n\te1.to = t;\n\te1.cap = cap;\n\te1.cost = cost;\n\te1.rev = G[t].size();\n\tG[f].push_back(e1);\n\tedge e2;\n\te2.to = f;\n\te2.cap = 0;\n\te2.cost = -cost;\n\te2.rev = G[f].size() - 1;\n\tG[t].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\tint res = 0;\n\twhile (f > 0) {\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tbool update = true;\n\t\twhile (update) {\n\t\t\tupdate = false;\n\t\t\tfor (int v = 0; v < V; v++) {\n\t\t\t\tif (dist[v] == INF) continue;\n\t\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\t\tedge& e = G[v][i];\n\t\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {\n\t\t\t\t\t\tdist[e.to] = dist[v] + e.cost;\n\t\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\n\t\tf -= d;\n\t\tres += d * dist[t];\n\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\t}\n\treturn res;\n}\n\n\nint main() {\n\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint from, to, c, d;\n\n\t\tcin >> from >> to >> c >> d;\n\t\tadd_edge(from, to, c, d);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50112, "score_of_the_acc": -1, "final_rank": 17 }, { "submission_id": "aoj_GRL_6_B_6824659", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\ntypedef pair<int, int> P;\n\nint V, E, F;\nstruct edge { int to, cap, cost, rev; };\nvector<edge> G[MAX_N];\nint h[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1 = { to, cap, cost, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, -cost, G[from].size() - 1 };\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\t\n\tint res = 0;\n\tfill(h, h + V, 0);\n\twhile (f > 0) {\n\t\tfill(dist, dist + V, INF);\n\t\tpriority_queue<P, vector<P>, greater<P> > que;\n\t\tdist[s] = 0;\n\t\tque.push(P(0, s));\n\t\twhile (!que.empty()) {\n\t\t\tP p = que.top(); que.pop();\n\t\t\tint v = p.second;\n\t\t\tif (dist[v] < p.first) continue;\n\t\t\tfor (int u = 0; u < G[v].size(); u++) {\n\t\t\t\tedge& e = G[v][u];\n\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {\n\t\t\t\t\tdist[e.to] = dist[v] + e.cost + h[v] - h[e.to];\n\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\tpreve[e.to] = u;\n\t\t\t\t\tque.push(P(dist[e.to], e.to));\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tfor (int v = 0; v < V; v++) {\n\t\t\th[v] += dist[v];\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\n\t\tf -= d;\n\t\tres += d * h[t];\n\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\n\t}\n\treturn res;\n}\n\nint main() {\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50064, "score_of_the_acc": -0.999, "final_rank": 8 }, { "submission_id": "aoj_GRL_6_B_6824633", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\nint V, E, F;\nstruct edge { int to, cap, cost, rev; };\nvector<edge> G[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1 = { to, cap, cost, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, -cost, G[from].size() - 1 };\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\t\n\tint res = 0;\n\twhile (f > 0) {\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tbool update = true;\n\t\twhile (update) {\n\t\t\tupdate = false;\n\t\t\tfor (int v = 0; v < V; v++) {\n\t\t\t\tif (dist[v] == INF) continue;\n\t\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\t\tedge& e = G[v][i];\n\t\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {\n\t\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\t\tdist[e.to] = dist[v] + e.cost;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\n\t\tf -= d;\n\t\tres += d * dist[t];\n\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\n\t}\n\treturn res;\n}\n\nint main() {\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50104, "score_of_the_acc": -0.9998, "final_rank": 14 }, { "submission_id": "aoj_GRL_6_B_6815734", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\nint V, E, F;\ntypedef pair<int, int> P;\nstruct edge { int to, cap, cost, rev; };\nvector<edge> G[MAX_N];\nbool used[MAX_N];\nint dist[MAX_N];\nint h[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1 = { to, cap, cost, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, -cost, G[from].size() - 1 };\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\n\tint res = 0;\n\tfill(h, h + V, 0);\n\twhile (f > 0) {\n\t\tpriority_queue < P, vector<P>, greater<P> > que;\n\t\tfill(dist, dist + V, INF);\n\t\tque.push(make_pair(0, s));\n\t\tdist[s] = 0;\n\t\twhile (!que.empty()) {\n\t\t\tP p = que.top(); que.pop();\n\t\t\tint v = p.second;\n\t\t\tif (dist[v] < p.first) continue;\n\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\tedge& e = G[v][i];\n\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {\n\t\t\t\t\tdist[e.to] = dist[v] + e.cost + h[v] - h[e.to];\n\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\tque.push(make_pair(dist[e.to], e.to));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (dist[t] == INF) return -1;\n\n\t\tfor (int v = 0; v < V; v++) {\n\t\t\th[v] += dist[v];\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\t\tf -= d;\n\t\tres += d * h[t];\n\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\n\t}\n\treturn res;\n}\n\n\nint main() {\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50100, "score_of_the_acc": -0.9997, "final_rank": 13 }, { "submission_id": "aoj_GRL_6_B_6815732", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\nint V, E, F;\ntypedef pair<int, int> P;\nstruct edge { int to, cap, cost, rev; };\nvector<edge> G[MAX_N];\nbool used[MAX_N];\nint dist[MAX_N];\nint h[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1 = { to, cap, cost, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, -cost, G[from].size() - 1 };\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\n\tint res = 0;\n\tfill(h, h + V, 0);\n\twhile (f > 0) {\n\t\tpriority_queue < P, vector<P>, greater<P> > que;\n\t\tfill(dist, dist + V, INF);\n\t\tque.push(make_pair(0, s));\n\t\tdist[s] = 0;\n\t\twhile (!que.empty()) {\n\t\t\tP p = que.top(); que.pop();\n\t\t\tint v = p.second;\n\t\t\tif (dist[v] < p.first) continue;\n\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\tedge& e = G[v][i];\n\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {\n\t\t\t\t\tdist[e.to] = dist[v] + e.cost + h[v] - h[e.to];\n\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\tque.push(make_pair(dist[e.to], e.to));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (dist[t] == INF) return -1;\n\n\t\tfor (int v = 0; v < V; v++) {\n\t\t\th[v] += dist[v];\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != t; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\t\tf -= d;\n\t\tres += d * h[t];\n\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\n\t}\n\treturn res;\n}\n\n\nint main() {\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 0.03125, "time_ms": 10, "memory_kb": 49996, "score_of_the_acc": -0.9975, "final_rank": 20 }, { "submission_id": "aoj_GRL_6_B_6815713", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\nint V, E, F;\nstruct edge { int to, cap, cost, rev; };\nvector<edge> G[MAX_N];\nbool used[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1 = { to, cap, cost, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, -cost, G[from].size() - 1 };\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\n\tint res = 0;\n\twhile (f > 0) {\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tbool update = true;\n\t\twhile (update) {\n\t\t\tupdate = false;\n\t\t\tfor (int v = 0; v < V; v++) {\n\t\t\t\tif (dist[v] == INF) continue;\n\t\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\t\tedge& e = G[v][i];\n\t\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {\n\t\t\t\t\t\tdist[e.to] = dist[v] + e.cost;\n\t\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\t\tf -= d;\n\t\tres += d * dist[t];\n\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\n\t}\n\treturn res;\n}\n\n\nint main() {\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b, c, d;\n\t\tcin >> a >> b >> c >> d;\n\t\tadd_edge(a, b, c, d);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50092, "score_of_the_acc": -0.9996, "final_rank": 11 }, { "submission_id": "aoj_GRL_6_B_6811224", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\ntypedef pair<int, int> P;\n\nint V, E, F;\nstruct edge { int to, cap, cost, rev; };\nvector<edge> G[MAX_N];\nint h[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1;\n\te1.to = to; e1.cap = cap; e1.cost = cost; e1.rev = G[to].size();\n\tG[from].push_back(e1);\n\tedge e2;\n\te2.to = from; e2.cap = 0; e2.cost = -cost; e2.rev = G[from].size() - 1;\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\tint res = 0;\n\tfill(h, h + V, 0);\n\twhile (f > 0) {\n\t\tpriority_queue<P, vector<P>, greater<P> > que;\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tque.push(make_pair(0, s));\n\t\twhile (!que.empty()) {\n\t\t\tP p = que.top(); que.pop();\n\t\t\tint v = p.second;\n\t\t\tif (dist[v] < p.first) continue;\n\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\tedge& e = G[v][i];\n\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {\n\t\t\t\t\tdist[e.to] = dist[v] + e.cost + h[v] - h[e.to];\n\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\tque.push(make_pair(dist[e.to], e.to));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tfor (int v = 0; v < V; v++) {\n\t\t\th[v] += dist[v];\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(G[prevv[v]][preve[v]].cap, d);\n\t\t}\n\t\tf -= d;\n\t\tres += d * h[t];\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\t}\n\treturn res;\n\n}\n\nint main() {\n\n\tcin >> V >> E >> F;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, c, d;\n\t\tcin >> u >> v >> c >> d;\n\t\tadd_edge(u, v, c, d);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50108, "score_of_the_acc": -0.9999, "final_rank": 16 }, { "submission_id": "aoj_GRL_6_B_6811193", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\nint V, E, F;\nstruct edge { int to, cap, cost, rev; };\nvector<edge> G[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1;\n\te1.to = to; e1.cap = cap; e1.cost = cost; e1.rev = G[to].size();\n\tG[from].push_back(e1);\n\tedge e2;\n\te2.to = from; e2.cap = 0; e2.cost = -cost; e2.rev = G[from].size() - 1;\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\tint res = 0;\n\twhile (f > 0) {\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tbool update = true;\n\t\twhile (update) {\n\t\t\tupdate = false;\n\t\t\tfor (int v = 0; v < V; v++) {\n\t\t\t\tif (dist[v] == INF) continue;\n\t\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\t\tedge &e = G[v][i];\n\t\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {\n\t\t\t\t\t\tdist[e.to] = dist[v] + e.cost;\n\t\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\t\tf -= d;\n\t\tres += d * dist[t];\n\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\n\t\t}\n\t}\n\treturn res;\n\n}\n\nint main() {\n\n\tcin >> V >> E >> F;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, c, d;\n\t\tcin >> u >> v >> c >> d;\n\t\tadd_edge(u, v, c, d);\n\t}\n\n\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50068, "score_of_the_acc": -0.9991, "final_rank": 9 }, { "submission_id": "aoj_GRL_6_B_6803292", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\ntypedef pair<int, int> P;\nstruct edge { int to, cap, cost, rev; };\n\nint V, E, F;\nvector<edge> G[MAX_N];\nint h[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1;\n\te1.to = to; e1.cap = cap; e1.cost = cost; e1.rev = G[to].size();\n\tG[from].push_back(e1);\n\tedge e2;\n\te2.to = from; e2.cap = 0; e2.cost = -cost; e2.rev = G[from].size() - 1;\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\tint res = 0;\n\tfill(h, h + V, 0);\n\n\twhile (f > 0) {\n\t\tpriority_queue<P, vector<P>, greater<P> > que;\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tque.push(P(0, s));\n\t\twhile (!que.empty()) {\n\t\t\tP p = que.top(); que.pop();\n\t\t\tint v = p.second;\n\t\t\tif (dist[v] < p.first) continue;\n\t\t\t\n\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\tedge& e = G[v][i];\n\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {\n\t\t\t\t\tdist[e.to] = dist[v] + e.cost + h[v] - h[e.to];\n\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\tque.push(P(dist[e.to], e.to));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (int v = 0; v < V; v++) h[v] += dist[v];\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\t\tf -= d;\n\n\t\tres += d * h[t];\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\t}\n\treturn res;\n}\n\n\n\nint main() {\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, c, cost;\n\t\tcin >> u >> v >> c >> cost;\n\t\tadd_edge(u, v, c, cost);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50112, "score_of_the_acc": -1, "final_rank": 17 }, { "submission_id": "aoj_GRL_6_B_6802929", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\nstruct edge { int to, cap, cost, rev; };\n\nint V, E, F;\nvector<edge> G[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1;\n\te1.to = to; e1.cap = cap; e1.cost = cost; e1.rev = G[to].size();\n\tG[from].push_back(e1);\n\tedge e2;\n\te2.to = from; e2.cap = 0; e2.cost = -cost; e2.rev = G[from].size() - 1;\n\tG[to].push_back(e2);\n}\n\nint min_cost_flow(int s, int t, int f) {\n\tint res = 0;\n\twhile (f > 0) {\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tbool update = true;\n\t\twhile (update) {\n\t\t\tupdate = false;\n\t\t\tfor (int v = 0; v < V; v++) {\n\t\t\t\tif (dist[v] == INF) continue;\n\t\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\t\tedge& e = G[v][i];\n\t\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {\n\t\t\t\t\t\tdist[e.to] = dist[v] + e.cost;\n\t\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\t\tf -= d;\n\n\t\tres += d * dist[t];\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\n\t}\n\treturn res;\n}\n\n\n\nint main() {\n\n\tcin >> V >> E >> F;\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, c, cost;\n\t\tcin >> u >> v >> c >> cost;\n\t\tadd_edge(u, v, c, cost);\n\t}\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50092, "score_of_the_acc": -0.9996, "final_rank": 11 }, { "submission_id": "aoj_GRL_6_B_6791615", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n// Minimum Cost Flow (Dijkstra)\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B&lang=ja\n// 蟻本 p. 203\n// 始点0, 終点V-1\n\nint V, E, F;\nstruct edge { int to, cap, cost, rev; };\ntypedef pair<int, int> P;\n\nvector<edge> G[MAX_N];\nint h[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\n// from からtoへ向かう容量cap, コストcostの辺をグラフに追加する\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1 = { to, cap, cost, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, -cost, G[from].size() - 1 };\n\tG[to].push_back(e2);\n}\n\n// sからtへの流量f最小費用流を求める\n// 流せない場合は-1を返す\nint min_cost_flow(int s, int t, int f) {\n\tint res = 0;\n\tfill(h, h + V, 0);\n\twhile (f > 0) {\n\t\t// ダイクストラ法を用いてhを更新する\n\t\tpriority_queue<P, vector<P>, greater<P> > que;\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tque.push(P(0, s));\n\t\twhile (!que.empty()) {\n\t\t\tP p = que.top(); que.pop();\n\t\t\tint v = p.second;\n\t\t\tif (dist[v] < p.first) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\tedge& e = G[v][i];\n\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {\n\t\t\t\t\tdist[e.to] = dist[v] + e.cost + h[v] - h[e.to];\n\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\tque.push(P(dist[e.to], e.to));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (int v = 0; v < V; v++) {\n\t\t\th[v] += dist[v];\n\t\t}\n\n\t\t// s-t間最短路に沿って目一杯流す\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\t\tf -= d;\n\t\tres += (d * h[t]);\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\t}\n\n\treturn res;\n\n}\n\nint main() {\n\t\n\tcin >> V >> E >> F;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, cap, cost;\n\t\tcin >> u >> v >> cap >> cost;\n\t\tadd_edge(u, v, cap, cost);\n\t}\n\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50104, "score_of_the_acc": -0.9998, "final_rank": 14 }, { "submission_id": "aoj_GRL_6_B_6791045", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n// Minimum Cost Flow (Bellman Ford)\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B&lang=ja\n// 蟻本 p. 200\n// 始点0, 終点V-1\n\nint V, E, F;\nstruct edge { int to, cap, cost, rev; };\n\nvector<edge> G[MAX_N];\nint dist[MAX_N];\nint prevv[MAX_N], preve[MAX_N];\n\n// from からtoへ向かう容量cap, コストcostの辺をグラフに追加する\nvoid add_edge(int from, int to, int cap, int cost) {\n\tedge e1 = { to, cap, cost, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, -cost, G[from].size() - 1 };\n\tG[to].push_back(e2);\n\n}\n\n// sからtへの流量f最小費用流を求める\n// 流せない場合は-1を返す\nint min_cost_flow(int s, int t, int f) {\n\tint res = 0;\n\twhile (f > 0) {\n\t\t//ベルマンフォードにより、s-t間最短路を求める\n\t\tfill(dist, dist + V, INF);\n\t\tdist[s] = 0;\n\t\tbool update = true;\n\t\twhile (update) {\n\t\t\tupdate = false;\n\t\t\tfor (int v = 0; v < V; v++) {\n\t\t\t\tif (dist[v] == INF) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\t\t\tedge& e = G[v][i];\n\t\t\t\t\tif (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {\n\t\t\t\t\t\tdist[e.to] = dist[v] + e.cost;\n\t\t\t\t\t\tprevv[e.to] = v;\n\t\t\t\t\t\tpreve[e.to] = i;\n\t\t\t\t\t\tupdate = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (dist[t] == INF) {\n\t\t\treturn -1;\n\t\t}\n\n\t\t// s-t間最短路に沿って目一杯流す。\n\t\tint d = f;\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\td = min(d, G[prevv[v]][preve[v]].cap);\n\t\t}\n\n\t\tf -= d;\n\t\tres += (d * dist[t]);\n\t\tfor (int v = t; v != s; v = prevv[v]) {\n\t\t\tedge& e = G[prevv[v]][preve[v]];\n\t\t\te.cap -= d;\n\t\t\tG[v][e.rev].cap += d;\n\t\t}\n\t}\n\n\treturn res;\n\n}\n\nint main() {\n\t\n\tcin >> V >> E >> F;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, cap, cost;\n\t\tcin >> u >> v >> cap >> cost;\n\t\tadd_edge(u, v, cap, cost);\n\t}\n\n\n\tcout << min_cost_flow(0, V - 1, F) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50084, "score_of_the_acc": -0.9994, "final_rank": 10 } ]
aoj_DPL_1_C_cpp
Knapsack Problem You have N kinds of items that you want to put them into a knapsack. Item i has value v i and weight w i . You want to find a subset of items to put such that: The total value of the items is as large as possible. The items have combined weight at most W , that is capacity of the knapsack. You can select as many items as possible into a knapsack for each kind. Find the maximum total value of items in the knapsack. Input N W v 1 w 1 v 2 w 2 : v N w N The first line consists of the integers N and W . In the following lines, the value and weight of the i -th item are given. Output Print the maximum total values of the items in a line. Constraints 1 ≤ N ≤ 100 1 ≤ v i ≤ 1000 1 ≤ w i ≤ 1000 1 ≤ W ≤ 10000 Sample Input 1 4 8 4 2 5 2 2 1 8 3 Sample Output 1 21 Sample Input 2 2 20 5 9 4 10 Sample Output 2 10 Sample Input 3 3 9 2 1 3 1 5 2 Sample Output 3 27
[ { "submission_id": "aoj_DPL_1_C_10925361", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define all(T) T.begin(), T.end()\nusing ll = long long;\nusing P = pair<int, int>;\nconst int di[] = {-1, 0, 1, 0};\nconst int dj[] = {0, -1, 0, 1};\nvoid chmax(ll& x, ll y) { x = max(x, y); }\nvoid chmin(ll& x, ll y) { x = min(x, y); }\n\nint main() {\n // 0-1knapsack\n ll n, W;\n cin >> n >> W;\n vector<ll> w(n), v(n);\n rep(i, n) cin >> v[i] >> w[i];\n // dp[i][j]=iまでえらんで重さがjのときの価値の最大\n const ll inf = 2e18;\n vector dp(n + 1, vector<ll>(W + 1, -inf));\n dp[0][0] = 0;\n rep(i, n) {\n rep(j, W + 1) {\n chmax(dp[i + 1][j], dp[i][j]);\n // 何回も試すことができる\n for (int k = 1; k <= 1000; k++) {\n ll add = w[i] * k;\n if (add + j <= W)\n chmax(dp[i + 1][j + add], dp[i][j] + v[i] * k);\n else\n break;\n }\n }\n }\n\n ll ans = 0;\n rep(j, W + 1) chmax(ans, dp[n][j]);\n cout << ans << endl;\n}", "accuracy": 0.35, "time_ms": 10, "memory_kb": 4352, "score_of_the_acc": -0.1126, "final_rank": 6 }, { "submission_id": "aoj_DPL_1_C_10804649", "code_snippet": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <cmath>\nusing namespace std;\n\n\nvoid dp(int w, vector<int> &memo, const vector<pair<int, int>> &things) {\n if (w == 0) memo[0] = 0;\n else {\n int result = 0;\n for (int i = 0; i <= w; ++i) {\n result = max(result, memo[i] + memo[w-i]);\n }\n memo[w] = result;\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n //重さをidxとして持つメモを使うDP\n\n int N, W;\n cin >> N >> W;\n vector<int> memo(W+1, 0);\n vector<pair<int, int>> things(N);\n for (int i = 0; i < N; ++i) {\n int v, w;\n cin >> v >> w;\n things[i] = {v, w};\n }\n sort(things.begin(), things.end());\n reverse(things.begin(), things.end());\n\n //初期埋め\n int idx = 0;\n while (idx != N) {\n auto [v, w] = things[idx];\n for (int i = w; i <= W; ++i) {\n if (!memo[i]) {\n memo[i] = v;\n }\n else break;\n }\n ++idx;\n }\n\n //bottom_up!\n for (int i = 0; i <=W; ++i) {\n dp(i, memo, things);\n }\n cout << memo[W] << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3504, "score_of_the_acc": -0.1667, "final_rank": 1 }, { "submission_id": "aoj_DPL_1_C_10481210", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\ntemplate<class T> void chmax(T& a, T b) {\n if (a < b)\n a = b;\n}\n\nstruct Item {\n int value;\n int weight;\n double gd;\n};\n\nbool comp(const Item& a, Item& b) {\n return a.gd > b.gd;\n}\n\nint main()\n{\n int N, W;\n std::cin >> N >> W;\n std::vector<Item> item(N);\n for (int i = 0; i < N; i++) {\n std::cin >> item[i].value >> item[i].weight;\n item[i].gd = (double)item[i].value / item[i].weight;\n }\n std::sort(item.begin(), item.end(), comp);\n\n if (W % item[0].weight == 0) {\n std::cout << (W / item[0].weight) * item[0].value << std::endl;\n }\n else {\n std::vector<std::vector<long long>> dp(N + 1, std::vector<long long>(W + 1, 0));\n\n for (int i = 0; i < N; i++)\n for (int j = 0; j <= W; j++) {\n for (int k = 1; k <= W / item[i].weight; k++)\n if (j - k * item[i].weight >= 0)\n chmax(dp[i + 1][j],\n dp[i][j - k * item[i].weight] + item[i].value * k);\n chmax(dp[i + 1][j], dp[i][j]);\n }\n\n std::cout << dp[N][W] << std::endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 11032, "score_of_the_acc": -2, "final_rank": 5 }, { "submission_id": "aoj_DPL_1_C_10343345", "code_snippet": "#include<iostream>\n#include<map>\n#include<iomanip>\nvoid _main();int main(){std::cin.tie(0);std::ios::sync_with_stdio(0);\nstd::cout<<std::fixed<<std::setprecision(12);\nint _T=1;\n//std::cin>>_T;\nfor(;_T--;)_main();}\n#include<algorithm>\n#include<vector>\ntemplate<class T>using V=std::vector<T>;\n#define eb emplace_back\nusing ll=long long;\ntemplate<class S,class T>bool chmin(S&a,T b){return(a>b?a=b,1:0);}\ntemplate<class S,class T>bool chmax(S&a,T b){return(a<b?a=b,1:0);}\n#define lep(a,b,c) for(int a=b;a<c;a++)\n#define rep(a,b) lep(a,0,b)\nusing namespace std;\nusing pp=pair<ll,ll>;\nvoid _main(){\n\tint n,limit;\n\tcin>>n>>limit;\n\tmap<int,int>m;\n\trep(i,n){\n\t\tint v,w;cin>>v>>w;\n\t\tchmax(m[w],v);\n\t}\n\tV<int>v,w;\n\trep(i,10001)if(m[i])v.eb(m[i]),w.eb(i);\n\tn=v.size();\n\tV<V<int>>dp(n+1,V<int>(limit+1));\n\trep(i,n)rep(j,limit+1)for(int k=0;j+k*w[i]<=limit;k++)chmax(dp[i+1][j+k*w[i]],dp[i][j]+k*v[i]);\n\tcout<<dp[n][limit]<<\"\\n\";\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 6924, "score_of_the_acc": -1.2876, "final_rank": 4 }, { "submission_id": "aoj_DPL_1_C_10199009", "code_snippet": "#include <any>\n#include <cassert>\n#include <cfenv>\n#include <cfloat>\n#include <charconv>\n#include <cinttypes>\n#include <ciso646>\n#include <clocale>\n#include <codecvt>\n#include <condition_variable>\n#include <csetjmp>\n#include <csignal>\n#include <cstdbool>\n#include <ctgmath>\n#include <forward_list>\n#include <fstream>\n#include <future>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <queue>\n#include <random>\n#include <regex>\n#include <scoped_allocator>\n#include <set>\n#include <shared_mutex>\n#include <typeindex>\n#include <unordered_map>\n#include <unordered_set>\n#include <valarray>\n#include <variant>\n\nusing namespace std;\n\nint main() {\n int N, W;\n cin >> N >> W;\n vector<int> v(N), w(N);\n map<int, int> mp;\n for (int i = 0; i < N; i++) {\n cin >> v[i] >> w[i];\n mp[w[i]] = max(mp[w[i]], v[i]);\n }\n\n vector<int> v2, w2;\n for (auto [weight, value] : mp) {\n v2.push_back(value);\n w2.push_back(weight);\n }\n\n vector<vector<int>> dp(v2.size() + 1, vector<int>(W + 1, -1));\n dp[0][0] = 0;\n for (int i = 0; i < v2.size(); i++) {\n for (int j = 0; j <= W; j++) {\n if (dp[i][j] == -1) {\n continue;\n }\n for (int k = 0; j + k * w2[i] <= W; k++) {\n dp[i + 1][j + k * w2[i]] =\n max(dp[i + 1][j + k * w2[i]], dp[i][j] + k * v2[i]);\n }\n }\n }\n\n int ans = 0;\n for (int j = 0; j <= W; j++) {\n ans = max(ans, dp[v2.size()][j]);\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 6232, "score_of_the_acc": -1.029, "final_rank": 2 }, { "submission_id": "aoj_DPL_1_C_9969947", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,a,b) for(int i=a;i<b;i++)\n#define rrep(i,a,b) for(int i=a;i>=b;i--)\n#define fore(i,a) for(auto &i:a)\n#define all(x) (x).begin(),(x).end()\n\nusing ll = long long;\nusing ui = unsigned int;\n\nvoid _main(istream& is);\nint main(void) {\n#ifdef OFFLINE_JUDGE\n ifstream ifs = ifstream(\"input.txt\");\n _main(ifs);\n#else\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n _main(cin);\n#endif\n}\n\nll fact(int n) { return n <= 1 ? n : n * fact(n-1); }\n\nvoid _main(istream& is) {\n int N, W;\n is >> N >> W;\n map<int, int> weightCheck;\n rep(i, 0, N) {\n int v, w;\n is >> v >> w;\n\n if (weightCheck.find(w) == weightCheck.end()) {\n weightCheck[w] = v;\n }\n else {\n if (weightCheck[w] < v) {\n weightCheck[w] = v;\n }\n }\n }\n vector<int> value;\n vector<int> weight;\n fore(i, weightCheck) {\n value.push_back(i.second);\n weight.push_back(i.first);\n }\n\n N = value.size();\n\n vector<vector<int>> dp(N + 1, vector<int>(W + 1, 0));\n rep(n, 1, N + 1) {\n rep(w, 0, W + 1) {\n if (weight[n - 1] > w) {\n dp[n][w] = dp[n - 1][w];\n }\n else {\n dp[n][w] = dp[n - 1][w];\n int i = 0;\n while (w - i * weight[n - 1] >= 0) {\n dp[n][w] = max(dp[n][w], i * value[n - 1] + dp[n - 1][w - i * weight[n - 1]]);\n i++;\n }\n }\n }\n }\n\n cout << dp[N][W] << endl;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 6512, "score_of_the_acc": -1.2329, "final_rank": 3 } ]
aoj_DPL_1_A_cpp
Coin Changing Problem Find the minimum number of coins to make change for n cents using coins of denominations d 1 , d 2 ,.., d m . The coins can be used any number of times. Input n m d 1 d 2 ... d m Two integers n and m are given in the first line. The available denominations are given in the second line. Output Print the minimum number of coins in a line. Constraints 1 ≤ n ≤ 50000 1 ≤ m ≤ 20 1 ≤ denomination ≤ 10000 The denominations are all different and contain 1. Sample Input 1 55 4 1 5 10 50 Sample Output 1 2 Sample Input 2 15 6 1 2 7 8 12 50 Sample Output 2 2 Sample Input 3 65 6 1 2 7 8 12 50 Sample Output 3 3
[ { "submission_id": "aoj_DPL_1_A_10998405", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\n#include <random>\n#include <chrono>\nusing namespace std;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 5000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\nconst int INF = 2147483647;\n//using ll = long long;\n\nint N, M;\nint c[25];\n\nbool has_bit(int n, int i) {\n\treturn (n & (1 << i)) > 0;\n}\n\nint main() {\n\n\tcin >> N >> M;\n\tfor (int i = 0; i < M; i++) {\n\t\tcin >> c[i];\n\t}\n\n\tint ALL = (1 << M);\n\n\tint ans = N;\n\tfor (int n = 0; n < ALL; n++) {\n\t\t\n\t\tvector<int> v;\n\t\tfor (int i = 0; i < M; i++) {\n\t\t\tif (has_bit(n, i)) {\n\t\t\t\tv.push_back(c[i]);\n\t\t\t}\n\t\t}\n\n\t\tsort(v.begin(), v.end(), greater<int>());\n\n\t\tint cnt = 0;\n\t\tint val = N;\n\t\tfor (int i = 0; i < v.size(); i++) {\n\t\t\tcnt += (val / v[i]);\n\t\t\tval %= v[i];\n\t\t}\n\n\t\tif (val == 0) {\n\t\t\tans = min(ans, cnt);\n\t\t}\n\n\t}\n\tcout << ans << endl;\n\t\n\n\treturn 0;\n}", "accuracy": 0.4, "time_ms": 210, "memory_kb": 3424, "score_of_the_acc": -0.2419, "final_rank": 8 }, { "submission_id": "aoj_DPL_1_A_10804682", "code_snippet": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <cmath>\nusing namespace std;\n\nconst int INF = (1<<29);\n\nvoid dp(int v, vector<int> &memo, const vector<int> &value) {\n if (memo[v] == INF) {\n for (int i = 0; i < v; ++i) {\n memo[v] = min(memo[v], memo[i]+memo[v-i]);\n }\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n //値段をidxとして持つメモを使うDP\n\n int N, M;\n cin >> N >> M;\n vector<int> memo(N+1, INF);\n vector<int> value(M);\n for (int i = 0; i < M; ++i) {\n cin >> value[i];\n }\n\n //初期埋め\n for (auto v : value) {\n memo[v] = 1;\n }\n\n //bottom_up!\n for (int i = 0; i <= N; ++i) {\n dp(i, memo, value);\n }\n cout << memo[N] << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 560, "memory_kb": 3460, "score_of_the_acc": -0.661, "final_rank": 2 }, { "submission_id": "aoj_DPL_1_A_10739830", "code_snippet": "#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <algorithm>\n#include <tuple>\n#include <set>\n#include <map>\n#include <bitset>\n#include <cmath>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <cassert>\n#include <unordered_set>\n#include <unordered_map>\n#include <cmath>\nusing namespace std;\ntypedef long long ll;\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)\n#define all(v) v.begin(), v.end()\n\nll llpow(ll a, ll t)\n{\n ll res = 1;\n rep(i, t) res *= a;\n return res;\n}\n\nll inf = std::numeric_limits<ll>::max();\n\nint main()\n{\n ll n, m;\n cin >> n >> m;\n vector<ll> vec(m);\n rep(i, m)\n {\n cin >> vec[i];\n }\n sort(all(vec));\n vector<vector<ll>> dp(m, vector<ll>(n + 1, 10e6));\n rep(i, m)\n {\n rep(j, n + 1)\n {\n if (!j)\n {\n dp[i][j] = 0;\n continue;\n }\n if (!i)\n {\n if (!(j % vec[i]))\n {\n dp[i][j] = j / vec[i];\n }\n continue;\n }\n dp[i][j] = min(dp[i - 1][j], min(dp[i - 1][j - vec[i] * (j / vec[i])] + (j / vec[i]), dp[i - 1][j - vec[i] * min(j / vec[i], (ll)1)] + min(j / vec[i], (ll)1)));\n }\n }\n // rep(i, m)\n // {\n // rep(j, n + 1)\n // {\n // if (j)\n // {\n // cout << \" \";\n // }\n // cout << dp[i][j];\n // }\n // cout << endl;\n // }\n cout << dp[m - 1][n] << endl;\n}", "accuracy": 0.4, "time_ms": 10, "memory_kb": 11228, "score_of_the_acc": -0.5294, "final_rank": 9 }, { "submission_id": "aoj_DPL_1_A_10726263", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\ntypedef pair<int,int> PII;\nconst int INF=2e18;\nvoid solve(){\n\tint n,m;cin>>n>>m;\n\tvector<PII>nums;\n\tfor(int i=0;i<m;i++){\n\t \tint x;cin>>x;\n\t \tint c=1;\n\t \twhile(x<=n){\n\t \t \tnums.push_back({x,c});\n\t \t \tx<<=1;\n\t \t \tc<<=1;\n\t \t}\n\t}\n\tm=nums.size();\n\tint dp[2][n+1];\n\tint now=0,pre=1;\n\tfor(int i=0;i<=n;i++) dp[now][i]=INF;\n\tdp[now][0]=0;\n\tfor(int i=0;i<m;i++){\n\t \tswap(now,pre);\n\t \tint x=nums[i].first,c=nums[i].second;\n\t \tfor(int j=0;j<=n;j++){\n\t\t\tdp[now][j]=dp[pre][j];\n\t\t\tif(j-x>=0) dp[now][j]=min(dp[now][j],dp[now][j-x]+c);\t \t \t\n\t \t}\n\t}\n\tint ans=dp[now][n];\n\tcout<<ans<<endl;\n}\nsigned main(){\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tsolve();\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4244, "score_of_the_acc": -0.059, "final_rank": 1 }, { "submission_id": "aoj_DPL_1_A_10527897", "code_snippet": "//written by: tettyあ\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <map>\n#include <cstring>\n#include <utility>\n#include <set>\n#include <numeric>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n\n#include <iomanip>\n#include <bitset>\n#include <math.h>\n#include <list>\n#include <limits.h>\n#include <stack>\n#include <deque>\n#include <functional> // std::greater\n\n#include <random>\nusing namespace std;\n\n\ntypedef unsigned short ushort;\ntypedef unsigned int uint;\ntypedef unsigned long ulong;\ntypedef long long llong;\ntypedef unsigned long long ullong;\n\n#define int llong\n\nstruct HashPair {\n\n static size_t m_hash_pair_random;\n\n template<class T1, class T2>\n size_t operator()(const pair<T1, T2>& p) const {\n\n auto hash1 = hash<T1>{}(p.first);\n auto hash2 = hash<T2>{}(p.second);\n\n size_t seed = 0;\n seed ^= hash1 + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n seed ^= hash2 + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n seed ^= m_hash_pair_random + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n return seed;\n }\n};\n\nsize_t HashPair::m_hash_pair_random = (size_t)random_device()();\n\n\ntemplate<class T>istream& operator>>(istream& is, vector<T>& vec) { for (T& e : vec)is >> e; return is; }\n\nstruct OmomiEdge { int to, cost; };\nstruct FromToEdge { int from, to; };\nstruct OmomiFromToEdge {\n int from, to, cost;\n bool operator<(const OmomiFromToEdge& e) {\n return cost < e.cost;\n }\n};\n\nstruct point { int x, y; };\nusing OmomiGraph = vector<vector<OmomiEdge>>;\nusing OmomiFromToGraph = vector<OmomiFromToEdge>;\n\n// 辺の情報\nstruct Edge\n{\n // 行先\n int to;\n\n // コスト\n int cost;\n};\n\nusing Graph = std::vector<std::vector<Edge>>;\n\n#define vecALL(vveecc) (vveecc).begin() , (vveecc).end() \n#define vecSORT(vveecc) sort((vveecc).begin(),(vveecc).end())\n#define vecrSORT(vveecc) sort((vveecc).rbegin(),(vveecc).rend())\n\n\nuint64_t uint64_floor_sqrt(uint64_t n) {\n if (n == 0) return 0;\n uint64_t tmp_m1 = std::sqrt(n) - 1;\n return tmp_m1 * (tmp_m1 + 2) < n ? tmp_m1 + 1 : tmp_m1;\n}\n\n// 1 以上 N 以下の整数が素数かどうかを返す\nvoid Eratosthenes(int N,vector<int>&primes) {\n // テーブル\n vector<bool> isprime(N + 1, true);\n \n // 0, 1 は予めふるい落としておく\n isprime[0] = isprime[1] = false;\n\n // ふるい\n for (int p = 2; p <= N; ++p) {\n // すでに合成数であるものはスキップする\n if (!isprime[p]) continue;\n\n // p 以外の p の倍数から素数ラベルを剥奪\n for (int q = p * 2; q <= N; q += p) {\n isprime[q] = false;\n }\n }\n for (int i = 0; i <= N; i++) {\n\n if (isprime[i]) {\n primes.emplace_back(i);\n }\n }\n // 1 以上 N 以下の整数が素数かどうか\n // return isprime;\n}\nsigned main() {\n\tint N, M; cin>> N >> M;\n vector<int>c(M); cin >> c;\n\n //dp[n][m] := m種類のコインを使用し、n円を支払う時のコインの最小枚数\n\tvector<vector<int>>dp(N + 10005, vector<int>(M + 1+5, 9999999));\n\n for(int m = 0; m <= M; m++) {\n dp[0][m] = 0; \n\t}\n for(int m=1;m <= M; m++) {\n for (int n = 0; n <= N; n++) {\n if (n - c[m - 1] < 0) {\n dp[n][m] = dp[n][m - 1]; // コインを使わない場合\n\t\t\t\tcontinue;\n }\n dp[n][m] = min(dp[n][m - 1], dp[n - c[m - 1]][m] + 1);\n }\n\t}\n\n cout << dp[N][M] << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 17636, "score_of_the_acc": -0.9609, "final_rank": 4 }, { "submission_id": "aoj_DPL_1_A_10506990", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\ntemplate<class T> void chmin(T& a, T b) {\n if (a > b)\n a = b;\n}\n\nconst int INF = 1000000000;\n\nint main()\n{\n int N, M;\n std::cin >> N >> M;\n std::vector<int> C(M), D(M);\n for (int i = 0; i < M; i++)\n std::cin >> C[i];\n std::sort(C.rbegin(), C.rend());\n for (int i = 0; i < M; i++)\n if (i == 0)\n D[i] = N / C[i];\n else\n D[i] = C[0] / C[i] + 1;\n\n std::vector<std::vector<int>> dp(M + 1, std::vector<int>(N + 1, INF));\n\n for (int i = 1; i <= M; i++) {\n for (int j = 0; j <= N; j++) {\n if (j > 0 && j % C[i - 1] == 0)\n chmin(dp[i][j], j / C[i - 1]);\n chmin(dp[i][j], dp[i - 1][j]);\n if (i > 1)\n for (int k = 1; k <= D[i - 1] + 1; k++) {\n if (j - k * C[i - 1] > 0)\n chmin(dp[i][j], dp[i - 1][j - k * C[i - 1]] + k);\n }\n }\n }\n\n std::cout << dp[M][N] << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 510, "memory_kb": 7368, "score_of_the_acc": -0.8646, "final_rank": 3 }, { "submission_id": "aoj_DPL_1_A_10489807", "code_snippet": "#include <bits/stdc++.h>\n#include<iostream>\n#include<vector>\n#include<string>\n#include<cstring>\nusing namespace std;\n#define ll long long\n#define F first\n#define S second\n#define PII pair<int,int>\nlong long memo[30][50010];\n long long solve(int i,int amount,vector<int>&coins)\n {\n if (amount==0){return 0;}\n if(i==coins.size()||amount<0){return INT_MAX;}\n long long &ret=memo[i][amount];\n if(~ret){return ret;}\n return ret=min(solve(i,amount-coins[i],coins)+1,solve(i+1,amount,coins));\n }\nint main() {\n\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n vector<int>coins;\n int amount,n;\n cin>>amount>>n;\n for (int i=0;i<n;i++)\n {\n int x;\n cin>>x;\n coins.push_back(x);\n }\n memset(memo,-1,sizeof(memo));\n\n cout<<solve(0,amount,coins)<<endl;\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18216, "score_of_the_acc": -1, "final_rank": 5 }, { "submission_id": "aoj_DPL_1_A_10324447", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nint main(){\n int n, m;\n cin>>n>>m;\n vector<int> k(m);\n for(int i = 0; i < m; i++) cin>>k[i];\n sort(k.rbegin(), k.rend());\n int ans = 1e9;\n for(int i = 0; i < (1 << m); i++){\n int temp = n;\n int cnt = 0;\n for(int j = 0; j < m; j++){\n if(i & (1 << j)){\n int t = temp / k[j];\n cnt += t;\n temp -= (t * k[j]);\n }\n }\n if(temp == 0){\n ans = min(ans, cnt);\n }\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 0.4, "time_ms": 60, "memory_kb": 3368, "score_of_the_acc": -0.0595, "final_rank": 7 }, { "submission_id": "aoj_DPL_1_A_9988781", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n int n,m;\n cin >> n >> m;\n int MAX_COINS = m + 10;\n\n vector<int> coins(m+1);//dpテーブルを作る際、0indexの時の処理がめんどうなので\n\n for(int i = 1; i <= m; i++){\n cin >> coins[i];\n }\n\n vector<vector<int>> dp(m + 1, vector<int>(n + 1, MAX_COINS));\n //dp[][0]の時は0枚で作れることが確定\n for(int t=0; t<= m; t++){\n dp[t][0] = 0;\n }\n\n //dp[0][]の時はあり得ないのでMAX_COINSで埋めておく\n for(int x=1; x<=n; x++){\n dp[0][x] = MAX_COINS;\n }\n\n for(int t = 1; t <=m; t++){\n for(int x = 1; x <= n; x++){\n int v = dp[t - 1][x];\n for(int u = 1; u <= x / coins[t]; u++){\n int tmp = dp[t-1][x -u*coins[t]] + u;\n v = min(v, tmp);\n }\n dp[t][x] = v;\n }\n }\n cout << dp[m][n] << endl;\n}\n\n//正しい解き方の方針\n//次元を減らす→時間軸を無くすor\n//時間軸を無くすとは?→一発の計算でどのコインを採用するのかを考える。すべてのインデックスを考慮してその1枚を加えるか加えないのかで考える\n//どのインデックスかは関係なく、どれか壱枚を採用した際、というのを再帰で考える\n//\n\n\n/*\n// Value関数の次元が大きすぎてTLEになる例\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main () {\n int n, m;\n cin >> n >> m;\n vector<int> coins(m+1);\n for(int i = 1; i <= m; i++) cin >> coins[i];\n // dpテーブルは小さい値からボトムアップに構築していくので,コインの額面を小さい順にしておく\n // コインの順番は3重ループの一番内側なのでこのソートは不要\n // sort(coins.begin(), coins.end());\n\n int MAX_COIN_NUMS = n + 100;\n vector<vector<int>> dp(m+1, vector<int>(n+1, MAX_COIN_NUMS));\n\n for(int t = 0; t <= m; t++) dp[t][0] = 0;\n for(int t = 1; t <= m; t++) {\n for(int sum = 1; sum <= n; sum++) {\n int res = dp[t-1][sum];\n for(int z = 1; z <= sum / coins[t]; z++)\n res = min(res, dp[t-1][sum - coins[t]*z] + z);\n dp[t][sum] = res;\n }\n } \n\n cout << dp[m][n] << endl;\n return 0;\n}\n*/", "accuracy": 0.6, "time_ms": 850, "memory_kb": 7116, "score_of_the_acc": -1.2524, "final_rank": 6 } ]
aoj_GRL_7_A_cpp
Bipartite Matching A bipartite graph G = (V, E) is a graph in which the vertex set V can be divided into two disjoint subsets X and Y such that every edge e ∈ E has one end point in X and the other end point in Y . A matching M is a subset of edges such that each node in V appears in at most one edge in M . Given a bipartite graph, find the size of the matching which has the largest size. Input |X| |Y| |E| x 0 y 0 x 1 y 1 : x |E|-1 y |E|-1 |X| and |Y| are the number of vertices in X and Y respectively, and |E| is the number of edges in the graph G . The vertices in X are named with the numbers 0, 1,..., |X| -1, and vertices in Y are named with the numbers 0, 1,..., |Y| -1, respectively. x i and y i are the node numbers from X and Y respectevely which represent the end-points of the i -th edge. Output Print the largest size of the matching. Constraints 1 ≤ |X| , |Y| ≤ 100 0 ≤ |E| ≤ 10,000 Sample Input 1 3 4 6 0 0 0 2 0 3 1 1 2 1 2 3 Sample Output 1 3
[ { "submission_id": "aoj_GRL_7_A_8843369", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct io_setup {\n io_setup() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout << fixed << setprecision(15);\n }\n} io_setup;\n\ntemplate <typename T>\nvoid print(const vector<T> &v, T x = 0) {\n int n = v.size();\n for (int i = 0; i < n; i++) cout << v[i] + x << (i == n - 1 ? '\\n' : ' ');\n if (v.empty()) cout << '\\n';\n}\n\nconstexpr int MOD = 998244353;\n\ntemplate <bool directed = false>\nstruct Graph {\n using L = int;\n\n struct edge {\n int to, id;\n\n edge(int to, int id) : to(to), id(id) {}\n\n L get_len() const { return 1; }\n };\n\n vector<vector<edge>> es;\n const int n;\n int m;\n\n Graph(int n) : es(n), n(n), m(0) {}\n\n bool is_directed() { return directed; }\n\n inline const vector<edge> &operator[](int k) const { return es[k]; }\n\n inline vector<edge> &operator[](int k) { return es[k]; }\n\n void add_edge(int from, int to) {\n es[from].emplace_back(to, m);\n if (!directed) es[to].emplace_back(from, m);\n m++;\n }\n\n void read(int m, int margin = -1) {\n for (int i = 0; i < m; i++) {\n int u, v;\n cin >> u >> v;\n add_edge(u + margin, v + margin);\n }\n }\n\n void read_rooted_tree(int margin = -1) {\n for (int i = 1; i < n; i++) {\n int p;\n cin >> p;\n add_edge(p + margin, i);\n }\n }\n};\n\ntemplate <typename T, bool directed = false>\nstruct Weighted_Graph {\n using L = T;\n\n struct edge {\n int to, id;\n T len;\n\n edge(int to, int id, T len) : to(to), id(id), len(len) {}\n\n L get_len() const { return len; }\n };\n\n vector<vector<edge>> es;\n const int n;\n int m;\n\n Weighted_Graph(int n) : es(n), n(n), m(0) {}\n\n bool is_directed() { return directed; }\n\n inline const vector<edge> &operator[](int k) const { return es[k]; }\n\n inline vector<edge> &operator[](int k) { return es[k]; }\n\n void add_edge(int from, int to, T len) {\n es[from].emplace_back(to, m, len);\n if (!directed) es[to].emplace_back(from, m, len);\n m++;\n }\n\n void read(int m, int margin = -1) {\n for (int i = 0; i < m; i++) {\n int u, v;\n T w;\n cin >> u >> v >> w;\n add_edge(u + margin, v + margin, w);\n }\n }\n\n void read_rooted_tree(int margin = -1) {\n for (int i = 1; i < n; i++) {\n int p;\n T w;\n cin >> p >> w;\n add_edge(p + margin, i, w);\n }\n }\n};\n\ntemplate <typename G>\nstruct BFS {\n vector<int> d;\n vector<int> pre_v, pre_e;\n const int s;\n\n BFS(const G &g, int s) : d(g.n, infty()), pre_v(g.n), pre_e(g.n), s(s) {\n queue<int> que;\n d[s] = 0;\n que.push(s);\n while (!que.empty()) {\n int i = que.front();\n que.pop();\n for (auto &e : g[i]) {\n if (d[i] + 1 < d[e.to]) {\n d[e.to] = d[i] + 1;\n pre_v[e.to] = i, pre_e[e.to] = e.id;\n que.push(e.to);\n }\n }\n }\n }\n\n inline int infty() { return (1 << 30) - 1; }\n\n inline const int &operator[](int i) const { return d[i]; }\n\n // s-t 最短路の (頂点、辺)\n pair<vector<int>, vector<int>> shortest_path(int t) {\n if (d[t] == infty()) return make_pair(vector<int>{}, vector<int>{});\n vector<int> path_v, path_e;\n for (int now = t; now != s; now = pre_v[now]) {\n path_v.push_back(now);\n path_e.push_back(pre_e[now]);\n }\n path_v.push_back(s);\n reverse(begin(path_v), end(path_v));\n reverse(begin(path_e), end(path_e));\n return make_pair(path_v, path_e);\n }\n};\n\nstruct Partition_Matroid {\n const int m; // |E|\n const int n; // 分割の個数\n vector<vector<int>> ids;\n vector<int> belong;\n vector<int> d, cnt;\n vector<vector<int>> used;\n\n Partition_Matroid(int m, int n, const vector<vector<int>> &ids, const vector<int> &d) : m(m), n(n), ids(ids), d(d), cnt(n), used(n) {\n assert((int)ids.size() == n && (int)d.size() == n);\n belong.assign(m, -1);\n for (int i = 0; i < n; i++) {\n for (auto &e : ids[i]) belong[e] = i;\n }\n }\n\n int size() { return m; }\n\n // X∈F 計算量 O(m+n)\n template <typename T>\n void set(const vector<T> &X) {\n fill(begin(cnt), end(cnt), 0);\n for (int i = 0; i < n; i++) used[i].clear();\n for (int i = 0; i < m; i++) {\n if (X[i]) cnt[belong[i]]++;\n }\n for (int i = 0; i < n; i++) {\n assert(cnt[i] <= d[i]);\n if (cnt[i] == d[i]) {\n for (auto &e : ids[i]) {\n if (X[e]) used[i].push_back(e);\n }\n }\n }\n }\n\n // C(X,y) 計算量 O(max d_i)\n vector<int> circuit(int y) const {\n int p = belong[y];\n if (cnt[p] == d[p]) {\n vector<int> ret = used[p];\n ret.push_back(y);\n return ret;\n }\n return {};\n }\n};\n\ntemplate <typename Matroid_1, typename Matroid_2>\npair<int, vector<int>> matroid_intersection(Matroid_1 M1, Matroid_2 M2) {\n assert(M1.size() == M2.size());\n const int m = M1.size();\n vector<bool> X(m, false);\n for (int i = 0;; i++) {\n M1.set(X), M2.set(X);\n Graph<true> G(m + 2);\n int s = m, t = m + 1;\n for (int y = 0; y < m; y++) {\n if (X[y]) continue;\n vector<int> c1 = M1.circuit(y), c2 = M2.circuit(y);\n if (c1.empty()) G.add_edge(s, y);\n for (auto &x : c1) {\n if (x != y) G.add_edge(x, y);\n }\n if (c2.empty()) G.add_edge(y, t);\n for (auto &x : c2) {\n if (x != y) G.add_edge(y, x);\n }\n }\n BFS B(G, s); // 最短路を求める\n vector<int> path = B.shortest_path(t).first;\n if (path.empty()) break;\n for (auto &e : path) {\n if (e != s && e != t) X[e] = !X[e];\n }\n }\n vector<int> ret;\n for (int i = 0; i < m; i++) {\n if (X[i]) ret.push_back(i);\n }\n return make_pair((int)ret.size(), ret);\n};\n\nint main() {\n int L, R, E;\n cin >> L >> R >> E;\n\n vector<vector<int>> idL(L), idR(R);\n\n for (int i = 0; i < E; i++) {\n int u, v;\n cin >> u >> v;\n idL[u].push_back(i);\n idR[v].push_back(i);\n }\n\n Partition_Matroid PL(E, L, idL, vector<int>(L, 1)), PR(E, R, idR, vector<int>(R, 1));\n\n cout << matroid_intersection(PL, PR).first << '\\n';\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 4808, "score_of_the_acc": -0.5624, "final_rank": 7 }, { "submission_id": "aoj_GRL_7_A_8395137", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<ll, ll> pr;\ntypedef pair<pr, ll> prpl;\ntypedef pair<ll, pr> prlp;\n\nconst ll INF = (ll)1e9;\n\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++) // for文の省略\n#define all(v) v.begin(), v.end() // 配列範囲の指定の省略。reverse()やsort()に入れる時便利\n\n// 変数を宣言して入力を代入する所の省略\ntemplate<class... T>\nvoid input(T&... a){\n (cin >> ... >> a);\n}\n#define llin(...) ll __VA_ARGS__; input(__VA_ARGS__)\nvoid input_vector(vector<ll>& v, ll N){\n rep(i, N){\n cin >> v[i];\n }\n}\n#define vectin(v, N) vector<ll> v(N); input_vector(v, N)\ntemplate<class U>\nvoid input_graph(vector<vector<U>>& G, ll M, bool directed = false, bool weighted = false){\n rep(i, M){\n if(!weighted){\n ll A, B; cin >> A >> B;\n if(!directed){\n G[A].push_back(B);\n G[B].push_back(A);\n } else {\n G[A].push_back(B);\n }\n } else {\n ll A, B, cost; cin >> A >> B >> cost;\n if(!directed){\n G[A].push_back({B, cost});\n G[B].push_back({A, cost});\n } else {\n G[A].push_back({B, cost});\n }\n }\n }\n}\n#define graphin(G, N, M) vector<vector<ll>> G(N); input_graph(G, M)\n#define graphin_directed(G, N, M) vector<vector<ll>> G(N); input_graph(G, M, directed = true)\n#define graphin_weighted(G, N, M) vector<vector<pr>> G(N); input_graph(G, M, weighted = true)\n#define graphin_directed_weighted(G, N, M) vector<vector<pr>> G(N); input_graph(G, M, directed = true, weighted = true)\ntemplate<class U>\nvoid input_edge(vector<U> E, ll M, bool weighted = false){\n rep(i, M){\n if(!weighted){\n ll A, B; cin >> A >> B;\n E[i] = {A, B};\n } else {\n ll A, B, cost; cin >> A >> B >> cost;\n E[i] = {cost, {A, B}};\n }\n }\n if(weighted){\n sort(all(E));\n }\n}\n#define edgein(E, M) vector<pr> E(M); input_edge(E, M)\n#define edgein_weighted(E, M) vector<prlp> E(M); input_edge(E, M, weighted = true)\n\n\n// デバッグ処理の簡略化。「#define _DEBUG」行をコメントアウトするかどうかで処理を行うかどうか変えられる\nvoid debug_out() { cout << endl; }\ntemplate <typename Head, typename... Tail>\nvoid debug_out(Head H, Tail... T) {\n cout << H << \" \";\n debug_out(T...);\n}\n#define _DEBUG\n#ifdef _DEBUG\n#define debug(...) debug_out(__VA_ARGS__)\n#else\n#define debug(...) \n#endif\n\n#ifndef H_make_vector\n#define H_make_vector\n\n/**\n * @brief 多次元 vector の作成\n * @author えびちゃん\n */\n\n#include <cstddef>\n#include <type_traits>\n#include <vector>\n\nnamespace detail {\n template <typename Tp, ll Nb>\n auto make_vector(std::vector<ll>& sizes, Tp const& x) {\n if constexpr (Nb == 1) {\n return vector(sizes[0], x);\n } else {\n ll size = sizes[Nb-1];\n sizes.pop_back();\n return vector(size, make_vector<Tp, Nb-1>(sizes, x));\n }\n }\n} // detail::\n\ntemplate <typename Tp, ll Nb>\nauto make_vector(ll const(&sizes)[Nb], Tp const& x = Tp()) {\n vector<ll> s(Nb);\n for (ll i = 0; i < Nb; ++i) s[i] = sizes[Nb-i-1];\n return detail::make_vector<Tp, Nb>(s, x);\n}\n\n#endif /* !defined(H_make_vector) */\n\ntemplate <typename S, typename T>\npair<S, T> operator+(const pair<S, T> &p, const pair<S, T> &q) {\n return make_pair(p.first + q.first, p.second + q.second);\n}\n \ntemplate <typename S, typename T>\npair<S, T> operator-(const pair<S, T> &p, const pair<S, T> &q) {\n return make_pair(p.first - q.first, p.second - q.second);\n}\n\nll Max_V = 100000;\nstruct edge{\n ll to, cap, rev;\n};\nvector<vector<edge>> G(Max_V);\nvector<bool> used(Max_V, false);\n\nvoid add_edge(ll from, ll to, ll cap){\n if(to < 0) return;\n G[from].push_back((edge){to, cap, (ll)G[to].size()});\n G[to].push_back((edge){from, 0, (ll)G[from].size() - 1});\n}\n\nll find_aug_path_DFS(ll v, ll t, ll f){\n if(v == t) return f;\n used[v] = true;\n rep(i, G[v].size()){\n edge& e = G[v][i];\n if(!used[e.to] && e.cap > 0){\n ll d = find_aug_path_DFS(e.to, t, min(f, e.cap));\n if(d > 0){\n e.cap -= d;\n G[e.to][e.rev].cap += d;\n return d;\n }\n }\n }\n return 0;\n}\n\nll max_flow_FF(ll s, ll t){\n ll flow = 0;\n while(true){\n rep(i, Max_V){\n used[i] = false;\n }\n ll f = find_aug_path_DFS(s, t, INF);\n if(f == 0) return flow;\n flow += f;\n }\n}\n\nint main(void){\n llin(X, Y, E);\n ll s = X + Y, t = s + 1;\n rep(x, X){\n add_edge(s, x, 1);\n }\n rep(y, Y){\n add_edge(y + X, t, 1);\n }\n rep(i, E){\n ll x, y; cin >> x >> y;\n add_edge(x, y + X, 1);\n }\n cout << max_flow_FF(s, t) << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6164, "score_of_the_acc": -0.0388, "final_rank": 3 }, { "submission_id": "aoj_GRL_7_A_8234962", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#ifdef LOCAL\n#include \"dbg.h\"\n#else\n#define dbg(...) 14122021\n#endif\n\ntemplate <typename T>\nbool chmax(T &x, T y) {\n return x < y and (x = y, true);\n}\n\ntemplate <typename T>\nbool chmin(T &x, T y) {\n return x > y and (x = y, true);\n}\n\nstruct flow_edge {\n int u;\n int v;\n int64_t cap;\n int64_t flow;\n\n explicit flow_edge(int u, int v, int64_t cap) : u(u), v(v), cap(cap), flow(0) {}\n};\n\nostream &operator<<(ostream &os, const flow_edge &e) {\n return os << e.u << \"->\" << e.v << '(' << e.flow << '/' << e.cap << ')';\n}\n\nstruct residual_edge {\n int u;\n int v;\n int64_t val;\n bool forward;\n\n explicit residual_edge(int u, int v, int64_t val, bool forward) : u(u), v(v), val(val), forward(forward) {}\n};\n\nostream &operator<<(ostream &os, const residual_edge &e) {\n return os << e.u << \"->\" << e.v << '(' << e.val << ',' << (e.forward ? \"F\" : \"B\") << ')';\n}\n\nstruct flow_graph {\n flow_graph(int);\n\n void addEdge(int, int, int64_t);\n void updateEdge(int, int, int64_t);\n void fordFulkerson(int, int);\n\n int V;\n vector<vector<flow_edge>> adj;\n};\n\nstruct residual_graph {\n residual_graph(const flow_graph &);\n\n vector<residual_edge> findAugmentingPath(int, int);\n\n int V;\n vector<vector<residual_edge>> adj;\n};\n\nflow_graph::flow_graph(int V) : V(V) {\n adj.resize(V);\n}\n\nvoid flow_graph::addEdge(int u, int v, int64_t cap) {\n if (cap == 0) return;\n adj[u].emplace_back(u, v, cap);\n}\n\nvoid flow_graph::updateEdge(int u, int v, int64_t flow) {\n for (auto &e : adj[u]) {\n if (e.v == v) {\n e.flow += flow;\n return;\n }\n }\n}\n\nvoid flow_graph::fordFulkerson(int s, int t) {\n while (true) {\n residual_graph rg{*this};\n auto path = rg.findAugmentingPath(s, t);\n if (path.empty()) break;\n int64_t bottleneck = numeric_limits<int64_t>::max();\n for (auto &e : path) {\n chmin(bottleneck, e.val);\n }\n for (auto &e : path) {\n if (e.forward) {\n updateEdge(e.u, e.v, bottleneck);\n } else {\n updateEdge(e.v, e.u, -bottleneck);\n }\n }\n }\n}\n\nresidual_graph::residual_graph(const flow_graph &fg) {\n V = fg.V;\n adj.resize(V);\n for (auto &x : fg.adj) {\n for (auto &e : x) {\n int u = e.u;\n int v = e.v;\n int64_t cap = e.cap;\n int64_t flow = e.flow;\n if (flow == 0) {\n adj[u].emplace_back(u, v, cap, true);\n } else if (flow == cap) {\n adj[v].emplace_back(v, u, cap, false);\n } else {\n adj[u].emplace_back(u, v, cap - flow, true);\n adj[v].emplace_back(v, u, flow, false);\n }\n }\n }\n}\n\nvector<residual_edge> residual_graph::findAugmentingPath(int s, int t) {\n vector<bool> vis(V);\n vector<residual_edge> path;\n vector<residual_edge> ret;\n auto dfs = [&](auto &&self, int u) -> void {\n vis[u] = true;\n if (u == t) {\n ret = path;\n }\n for (auto &e : adj[u]) {\n int v = e.v;\n if (!vis[v]) {\n path.push_back(e);\n self(self, v);\n path.pop_back();\n }\n }\n };\n dfs(dfs, s);\n return ret;\n}\n\nint main() {\n cin.tie(nullptr)->sync_with_stdio(false);\n\n int x, y, e;\n cin >> x >> y >> e;\n\n int n = x + y + 2;\n flow_graph fg(n);\n\n while (e--) {\n int u, v;\n cin >> u >> v;\n v += x;\n fg.addEdge(u, v, 1);\n }\n\n for (int i = 0; i < x; ++i) {\n fg.addEdge(n - 2, i, 1);\n }\n\n for (int i = x; i < n - 2; ++i) {\n fg.addEdge(i, n - 1, 1);\n }\n\n fg.fordFulkerson(n - 2, n - 1);\n\n int ans = 0;\n for (auto &e : fg.adj[n - 2]) {\n ans += e.flow;\n }\n\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4076, "score_of_the_acc": -0.0052, "final_rank": 1 }, { "submission_id": "aoj_GRL_7_A_8025285", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define rep(i,n) for(int i = 0;i < n;i++)\n\n#define int ll\n\nstack<int> dfs(vector<set<int>> &adj,map<pair<int,int>,int> &omomi,vector<bool> &used,stack<int> path,int now,int goal){\n stack<int> ans;\n if(used.at(now)) return ans;\n used.at(now) = true;\n path.push(now);\n\n if(now == goal) return path;\n\n for(int nxt:adj.at(now)){\n if( !used.at(nxt) && omomi[make_pair(now,nxt)] >= 1){\n stack<int> tem = dfs(adj,omomi,used,path,nxt,goal);\n if(!tem.empty()) return tem;\n }\n }\n\n return ans;\n}\n\nint maxFlow(vector<set<pair<int,int>>> aadj,int n,int s,int t){\n vector<set<int>> adj(n);\n map<pair<int,int>,int> omomi;\n\n for(int i = 0;i < n;i++){\n for(pair<int,int> p:aadj.at(i)){\n adj.at(i).insert(p.first);\n adj.at(p.first).insert(i);\n\n omomi[ make_pair(i,p.first) ] += p.second;\n omomi[ make_pair(p.first,i ) ] += 0;\n }\n }\n\n\n int ans = 0;\n\n while(true){\n vector<bool> used(n,0);\n stack<int> rpath = dfs(adj,omomi,used,stack<int>(),s,t);\n if(rpath.empty()) break;\n\n stack<int> tem;\n while(!rpath.empty()){\n tem.push(rpath.top());\n rpath.pop();\n }\n vector<int> path;\n while(!tem.empty()){\n path.push_back(tem.top());\n tem.pop();\n }\n\n int upd = omomi[ make_pair(path.at(0),path.at(1))];\n for(int i = 0;i < path.size() - 1;i++){\n upd = min(upd,omomi[make_pair( path.at(i) , path.at(i + 1))]);\n }\n\n for(int i = 0;i < path.size() - 1;i++){\n omomi[make_pair( path.at(i) , path.at(i + 1))] -= upd;\n omomi[make_pair(path.at(i + 1),path.at(i))] += upd;\n }\n\n// cout << \"path\" << endl;\n// for(int i:path) cout << i << \" \";\n// cout << upd << endl;\n\n ans += upd;\n }\n\n return ans;\n}\n\nint maxMatching(int x,int y,int e,vector<pair<int,int>> edges){\n vector<set<pair<int,int>>> adj(x + y + 2);\n for(int i = 1;i <= x;i++){\n adj.at(0).insert(make_pair(i,1));\n }\n\n for(pair<int,int> p:edges){\n adj.at(p.first + 1).insert(make_pair(x + 1 + p.second,1));\n }\n\n for(int i = x + 1;i <= x + y;i++){\n adj.at(i).insert(make_pair(x+y+1,1));\n }\n\n return maxFlow(adj,x + y + 2,0, x + y + 1);\n}\n\nvoid main_() {\n int x,y,e;\n cin >> x >> y >> e;\n vector<pair<int,int>> edges;\n rep(i,e){\n int a,b;\n cin >> a >> b;\n edges.push_back(make_pair(a,b));\n }\n cout << maxMatching(x,y,e,edges) << endl;\n}\n\nsigned main(){\n main_();\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7440, "score_of_the_acc": -0.1503, "final_rank": 5 }, { "submission_id": "aoj_GRL_7_A_7060186", "code_snippet": "//Atcoderならこれ使わずにac-library使おうね\n\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nvector<vector<int>> G;\nmap<pair<int,int>,int> edges;\nvector<int> visited; \nint X,Y,E,N;\n// Ford-Fullkerson法 O(max_flow*E)\nbool dfs(int now){\n if(now == N-1){\n return true;\n }\n for(int next : G[now]){\n if(visited[next])continue;\n if(edges[make_pair(now,next)]>0){\n visited[next]=true;\n if(dfs(next)){\n edges[make_pair(now,next)]--;\n edges[make_pair(next,now)]++;\n return true;\n }\n }\n }\n return false;\n}\n\nint main(){\n cin >> X >> Y >> E;\n N = X+Y+2;\n G.resize(N);\n for(int i = 1 ; i <= X ; i++){\n G[0].push_back(i);\n G[i].push_back(0);\n edges[make_pair(0,i)]=1;\n edges[make_pair(i,0)]=0;\n }\n for(int i = X+1 ; i <= X+Y ; i++){\n G[i].push_back(N-1);\n G[N-1].push_back(i);\n edges[make_pair(i,N-1)]=1;\n edges[make_pair(N-1,i)]=0;\n }\n for(int i = 0 ; i < E ; i++){\n int x,y;\n cin >> x >> y;\n x+=1;\n y+=1;\n y+=X;\n G[x].push_back(y);\n G[y].push_back(x);\n edges[make_pair(x,y)]=1;\n edges[make_pair(y,x)]=0;\n }\n bool b = true;\n int flow = -1;\n while(b){\n visited.assign(N,false);\n visited[0]=true;\n flow++;\n b = dfs(0);\n }\n cout << flow << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4844, "score_of_the_acc": -0.0175, "final_rank": 2 }, { "submission_id": "aoj_GRL_7_A_6962824", "code_snippet": "#include <iostream>\n#include <cassert>\n#include <queue>\nusing namespace std;\n\ntemplate <typename T>\nstruct Edge\n{\n int to;\n T cap;\n int rev;\n int id;\n};\n\ntemplate <typename T>\nstruct Flow\n{\n int n;\n int source;\n int sink;\n T current_flow;\n std::vector<int> d;\n std::vector<int> nx;\n std::vector<std::vector<Edge<T>>> g;\n std::vector<std::pair<int, int>> epos;\n\n Flow() {}\n\n Flow(int n, int source, int sink) : n(n), source(source), sink(sink), current_flow(0)\n {\n d.resize(n);\n nx.resize(n);\n g.resize(n);\n }\n\n void add_edge(int from, int to, T cap)\n {\n epos.push_back(std::pair<int, int>(from, (int)g[from].size()));\n g[from].push_back((Edge<T>){to, cap, (int)g[to].size(), (int)epos.size() - 1});\n g[to].push_back((Edge<T>){from, 0, (int)g[from].size() - 1, -1});\n }\n\n T delete_edge(int id)\n {\n Edge<T> &e = g[epos[id].first][epos[id].second];\n Edge<T> &re = g[e.to][e.rev];\n int u = re.to, v = e.to;\n T delete_f = re.cap;\n e.cap = 0;\n re.cap = 0;\n T reverse_f = delete_f - add_flow(u, v, delete_f);\n add_flow(u, source, reverse_f);\n add_flow(sink, v, reverse_f);\n current_flow -= reverse_f;\n return current_flow;\n }\n\n void bfs(int s)\n {\n fill(d.begin(), d.end(), -1);\n std::queue<int> que;\n d[s] = 0;\n que.push(s);\n while (que.size())\n {\n int u = que.front();\n que.pop();\n for (Edge<T> &e : g[u])\n {\n int v = e.to;\n Edge<T> &re = g[v][e.rev];\n if (re.cap > 0 && d[v] == -1)\n {\n d[v] = d[u] + 1;\n que.push(v);\n }\n }\n }\n }\n\n T dfs(int u, int s, T f)\n {\n if (u == s)\n {\n return f;\n }\n for (int &i = nx[u]; i < (int)g[u].size(); i++)\n {\n Edge<T> &e = g[u][i];\n int v = e.to;\n if (d[v] >= d[u] || e.cap == 0)\n {\n continue;\n }\n if (f == -1)\n {\n f = e.cap;\n }\n else\n {\n f = std::min(f, e.cap);\n }\n T fl = dfs(v, s, f);\n if (fl > 0)\n {\n e.cap -= fl;\n g[e.to][e.rev].cap += fl;\n return fl;\n }\n }\n return 0;\n }\n\n T add_flow(int r, int s, T max_f)\n {\n T res = 0;\n while (true)\n {\n if (max_f == 0)\n {\n return res;\n }\n bfs(s);\n if (d[r] == -1)\n {\n return res;\n }\n for (int i = 0; i < n; i++)\n {\n nx[i] = 0;\n }\n for (T f; (f = dfs(r, s, max_f)) > 0;)\n {\n res += f;\n if (max_f != -1)\n {\n max_f -= f;\n }\n }\n }\n }\n\n T max_flow(T max_f = -1)\n {\n if (max_f != -1)\n {\n max_f -= current_flow;\n if (max_f < 0)\n {\n current_flow -= add_flow(sink, source, -max_f);\n return current_flow;\n }\n }\n current_flow += add_flow(source, sink, max_f);\n return current_flow;\n }\n\n int get_flow(int id)\n {\n Edge<T> &e = g[epos[id].first][epos[id].second];\n Edge<T> &re = g[e.to][e.rev];\n return re.cap;\n }\n};\n\nstruct BipartiteMatching\n{\n int p;\n int q;\n Flow<int> g;\n\n BipartiteMatching() {}\n\n BipartiteMatching(int p, int q) : p(p), q(q)\n {\n Flow<int> _g(p + q + 2, p + q, p + q + 1);\n for (int i = 0; i < p; i++)\n _g.add_edge(p + q, i, 1);\n for (int i = p; i < p + q; i++)\n _g.add_edge(i, p + q + 1, 1);\n std::swap(g, _g);\n }\n\n void add_edge(int u, int v)\n {\n g.add_edge(u, v + p, 1);\n }\n\n int delete_edge(int id)\n {\n return g.delete_edge(id + p + q);\n }\n\n int max_matching()\n {\n return g.max_flow();\n }\n\n bool is_used(int id)\n {\n return g.get_flow(id + p + q);\n }\n};\n\nint main()\n{\n int x, y, e;\n cin >> x >> y >> e;\n BipartiteMatching g(x, y);\n for (int i = 0; i < e; i++)\n {\n int u, v;\n cin >> u >> v;\n g.add_edge(u, v);\n g.max_matching();\n }\n cout << g.max_matching() << endl;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 3756, "score_of_the_acc": -1, "final_rank": 13 }, { "submission_id": "aoj_GRL_7_A_6810732", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n\nint V, E;\nvector<int> G[MAX_N];\nbool used[MAX_N];\nint match[MAX_N];\n\nvoid add_edge(int from, int to) {\n\tG[from].push_back(to);\n\tG[to].push_back(from);\n}\n\n\nbool dfs(int v) {\n\tused[v] = true;\n\tfor (int i = 0; i < G[v].size(); i++) {\n\t\tint u = G[v][i];\n\t\tint w = match[u];\n\t\tif (w < 0 || (!used[w] && dfs(w))) {\n\t\t\tmatch[v] = u;\n\t\t\tmatch[u] = v;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nint bipartite_matching() {\n\tint res = 0;\n\tmemset(match, -1, sizeof(match));\n\tfor (int v = 0; v < V; v++) {\n\t\tif (match[v] < 0) {\n\t\t\tmemset(used, 0, sizeof(used));\n\t\t\tif (dfs(v)) {\n\t\t\t\tres++;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\treturn res;\n}\n\n\nint main() {\n\n\tint X, Y;\n\tcin >> X >> Y >> E;\n\n\tV = X + Y;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tadd_edge(a, b + X);\n\t}\n\n\tcout << bipartite_matching() << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 59908, "score_of_the_acc": -0.9966, "final_rank": 11 }, { "submission_id": "aoj_GRL_7_A_6810718", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n\nint V, E;\nstruct edge { int to, cap, rev; };\nvector<edge> G[MAX_N];\nbool used[MAX_N];\n\nvoid add_edge(int from, int to, int cap) {\n\tedge e1;\n\te1.to = to, e1.cap = cap; e1.rev = G[to].size();\n\tG[from].push_back(e1);\n\tedge e2;\n\te2.to = from, e2.cap = 0; e2.rev = G[from].size() - 1;\n\tG[to].push_back(e2);\n}\n\nint dfs(int v, int t, int f) {\n\tif (v == t) return f;\n\tused[v] = true;\n\tfor (int i = 0; i < G[v].size(); i++) {\n\t\tedge& e = G[v][i];\n\t\tif (!used[e.to] && e.cap > 0) {\n\t\t\tint d = dfs(e.to, t, min(e.cap, f));\n\t\t\tif (d > 0) {\n\t\t\t\te.cap -= d;\n\t\t\t\tG[e.to][e.rev].cap += d;\n\t\t\t\treturn d;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint max_flow(int s, int t) {\n\tint flow = 0;\n\twhile (true) {\n\t\tmemset(used, 0, sizeof(used));\n\t\tint d = dfs(s, t, INF);\n\t\tif (d > 0) {\n\t\t\tflow += d;\n\t\t}\n\t\telse {\n\t\t\treturn flow;\n\t\t}\n\t}\n}\n\nint main() {\n\n\tint X, Y;\n\tcin >> X >> Y >> E;\n\n\tint s = X + Y;\n\tint t = X + Y + 1;\n\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tadd_edge(a, b + X, 1);\n\t}\n\n\tfor (int i = 0; i < X; i++) {\n\t\tadd_edge(s, i, 1);\n\t}\n\tfor (int i = 0; i < Y; i++) {\n\t\tadd_edge(X + i, t, 1);\n\t}\n\n\tcout << max_flow(s, t) << endl;\n\n\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 52168, "score_of_the_acc": -0.8718, "final_rank": 8 }, { "submission_id": "aoj_GRL_7_A_6802772", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n\nint V;\nvector<int> G[MAX_N];\nint match[MAX_N];\nbool used[MAX_N];\n\nvoid add_edge(int u, int v) {\n\tG[u].push_back(v);\n\tG[v].push_back(u);\n}\n\nbool dfs(int v) {\n\tused[v] = true;\n\tfor (int i = 0; i < G[v].size(); i++) {\n\t\tint u = G[v][i];\n\t\tint w = match[u];\n\t\tif (w < 0 || (!used[w] && dfs(w))) {\n\t\t\tmatch[v] = u;\n\t\t\tmatch[u] = v;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nint bipartite_matching() {\n\tint res = 0;\n\tmemset(match, -1, sizeof(match));\n\tfor (int v = 0; v < V; v++) {\n\t\tif (match[v] < 0) {\n\t\t\tmemset(used, 0, sizeof(used));\n\t\t\tif (dfs(v)) {\n\t\t\t\tres++;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n\nint main() {\n\n\tint X, Y, E;\n\tcin >> X >> Y >> E;\n\tV = X + Y;\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tadd_edge(u, v + X);\n\t}\n\n\tcout << bipartite_matching() << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 59896, "score_of_the_acc": -0.9965, "final_rank": 10 }, { "submission_id": "aoj_GRL_7_A_6802696", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n\nstruct edge { int to, cap, rev; };\n\nvector<edge> G[MAX_N];\nbool used[MAX_N];\n\nvoid add_edge(int from, int to, int cap) {\n\tedge e1;\n\te1.to = to; e1.cap = cap; e1.rev = G[to].size();\n\tG[from].push_back(e1);\n\tedge e2;\n\te2.to = from; e2.cap = 0; e2.rev = G[from].size() - 1;\n\tG[to].push_back(e2);\n}\n\n// 増加パスをDFSで見つける\nint dfs(int v, int t, int f) {\n\tif (v == t) {\n\t\treturn f;\n\t}\n\tused[v] = true;\n\n\tfor (int i = 0; i < G[v].size(); i++) {\n\t\tedge& e = G[v][i];\n\t\tif (!used[e.to] && e.cap > 0) {\n\t\t\tint d = dfs(e.to, t, min(e.cap, f));\n\t\t\tif (d > 0) {\n\t\t\t\te.cap -= d;\n\t\t\t\tG[e.to][e.rev].cap += d;\n\t\t\t\treturn d;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\nint max_flow(int s, int t) {\n\tint flow = 0;\n\twhile (true) {\n\t\tmemset(used, 0, sizeof(used));\n\t\tint f = dfs(s, t, INF);\n\t\tif (f > 0) {\n\t\t\tflow += f;\n\t\t}\n\t\telse {\n\t\t\treturn flow;\n\t\t}\n\t}\n}\n\n\nint main() {\n\n\tint X, Y;\n\tint E;\n\tcin >> X >> Y >> E;\n\n\tint s = X + Y;\n\tint t = s + 1;\n\tint V = t + 1;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tadd_edge(u, v + X, 1);\n\t}\n\n\tfor (int i = 0; i < X; i++) {\n\t\tadd_edge(s, i, 1);\n\t}\n\n\tfor (int i = 0; i < Y; i++) {\n\t\tadd_edge(i + X, t, 1);\n\t}\n\n\tcout << max_flow(s, t) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 52172, "score_of_the_acc": -0.8719, "final_rank": 9 }, { "submission_id": "aoj_GRL_7_A_6791650", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n// Bipartite Matching (Simple)\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_7_A&lang=ja\n// 蟻本 p. 197\n\n\nint V, E;\nint X, Y;\nvector<int> G[MAX_N];\nint match[MAX_N];\nbool used[MAX_N];\n\n// uとvを結ぶ辺をグラフに追加する\nvoid add_edge(int u, int v) {\n\tG[u].push_back(v);\n\tG[v].push_back(u);\n}\n\n// 増加パスをDFSで探す\nbool dfs(int v) {\n\tused[v] = true;\n\tfor (int i = 0; i < G[v].size(); i++) {\n\t\tint u = G[v][i];\n\t\tint w = match[u];\n\t\tif (w < 0 || !used[w] && dfs(w)) {\n\t\t\tmatch[v] = u;\n\t\t\tmatch[u] = v;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nint bipartite_matching() {\n\tint res = 0;\n\tmemset(match, -1, sizeof(match));\n\tfor (int v = 0; v < V; v++) {\n\t\tif (match[v] < 0) {\n\t\t\tmemset(used, 0, sizeof(used));\n\t\t\tif (dfs(v)) {\n\t\t\t\tres++;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n\nint main() {\n\n\tcin >> X >> Y >> E;\n\tV = X + Y;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tadd_edge(u, X + v);\n\t}\n\n\tcout << bipartite_matching() << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 59908, "score_of_the_acc": -0.9966, "final_rank": 11 }, { "submission_id": "aoj_GRL_7_A_6790890", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n// Bipartite Matching (from Maximum flow)\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_A&lang=jp\n// 蟻本 p. 195\n// 始点0, 終点V-1\n\nint V, E;\nint X, Y;\nstruct edge { int to, cap, rev; };\n\nvector<edge> G[MAX_N];\nint level[MAX_N];\nint iter[MAX_N];\n\n// from からtoへ向かう容量capの辺をグラフに追加する\nvoid add_edge(int from, int to, int cap) {\n\tedge e1 = { to, cap, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, G[from].size() - 1 };\n\tG[to].push_back(e2);\n\n}\n\n// sからの最短距離をBFSで計算する\nvoid bfs(int s) {\n\tmemset(level, -1, sizeof(level));\n\tqueue<int> que;\n\tlevel[s] = 0;\n\tque.push(s);\n\twhile (!que.empty()) {\n\t\tint v = que.front(); que.pop();\n\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\tedge& e = G[v][i];\n\t\t\tif (e.cap > 0 && level[e.to] < 0) {\n\t\t\t\tlevel[e.to] = level[v] + 1;\n\t\t\t\tque.push(e.to);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n// 増加パスをDFSで探す\nint dfs(int v, int t, int f) {\n\tif (v == t) {\n\t\treturn f;\n\t}\n\n\tfor (int &i = iter[v]; i < G[v].size(); i++) {\n\t\tedge& e = G[v][i];\n\t\tif (e.cap > 0 && level[v] < level[e.to]) {\n\t\t\tint d = dfs(e.to, t, min(f, e.cap));\n\t\t\tif (d > 0) {\n\t\t\t\te.cap -= d;\n\t\t\t\tG[e.to][e.rev].cap += d;\n\t\t\t\treturn d;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\n\n// sからtへの最大流を求める\nint max_flow(int s, int t) {\n\tint flow = 0;\n\twhile (true) {\n\t\tbfs(s);\n\t\tif (level[t] < 0) {\n\t\t\treturn flow;\n\t\t}\n\t\tmemset(iter, 0, sizeof(iter));\n\t\tint f;\n\t\twhile ((f = dfs(s, t, INF)) > 0) {\n\t\t\tflow += f;\n\t\t}\n\t}\n}\n\nint main() {\n\t\n\tcin >> X >> Y >> E;\n\tV = X + Y + 2;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, c;\n\t\tcin >> u >> v;\n\t\tadd_edge(u, v + X, 1);\n\t}\n\t\n\tfor (int i = 0; i < X; i++) {\n\t\tadd_edge(X + Y, i, 1);\n\t}\n\n\tfor (int i = 0; i < Y; i++) {\n\t\tadd_edge(X + i, X + Y + 1, 1);\n\t}\n\n\tcout << max_flow(X + Y, X + Y + 1) << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 65752, "score_of_the_acc": -1.0909, "final_rank": 14 }, { "submission_id": "aoj_GRL_7_A_6790873", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<sstream>\n#include<list>\n#include<iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <stdlib.h>\n#include <stdio.h>\nusing namespace std;\nconst int INF = 100000000;\nconst long long LINF = 3e18 + 7;\nconst int MAX_N = 2000010;\nconst int MAX_W = 10002;\nconst int MAX_ARRAYK = 100000;\ndouble PI = 3.14159265358979323846;\n//using ll = long long;\n\n// Bipartite Matching (from Maximum flow)\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_A&lang=jp\n// 蟻本 p. 195\n// 始点0, 終点V-1\n\nint V, E;\nint X, Y;\nstruct edge { int to, cap, rev; };\n\nvector<edge> G[MAX_N];\nint level[MAX_N];\nint iter[MAX_N];\n\n// from からtoへ向かう容量capの辺をグラフに追加する\nvoid add_edge(int from, int to, int cap) {\n\tedge e1 = { to, cap, G[to].size() };\n\tG[from].push_back(e1);\n\tedge e2 = { from, 0, G[from].size() - 1 };\n\tG[to].push_back(e2);\n\n}\n\n// sからの最短距離をBFSで計算する\nvoid bfs(int s) {\n\tmemset(level, -1, sizeof(level));\n\tqueue<int> que;\n\tlevel[s] = 0;\n\tque.push(s);\n\twhile (!que.empty()) {\n\t\tint v = que.front(); que.pop();\n\t\tfor (int i = 0; i < G[v].size(); i++) {\n\t\t\tedge& e = G[v][i];\n\t\t\tif (e.cap > 0 && level[e.to] < 0) {\n\t\t\t\tlevel[e.to] = level[v] + 1;\n\t\t\t\tque.push(e.to);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n// 増加パスをDFSで探す\nint dfs(int v, int t, int f) {\n\tif (v == t) {\n\t\treturn f;\n\t}\n\n\tfor (int &i = iter[v]; i < G[v].size(); i++) {\n\t\tedge& e = G[v][i];\n\t\tif (e.cap > 0 && level[v] < level[e.to]) {\n\t\t\tint d = dfs(e.to, t, min(f, e.cap));\n\t\t\tif (d > 0) {\n\t\t\t\te.cap -= d;\n\t\t\t\tG[e.to][e.rev].cap += d;\n\t\t\t\treturn d;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\n\n// sからtへの最大流を求める\nint max_flow(int s, int t) {\n\tint flow = 0;\n\twhile (true) {\n\t\tbfs(s);\n\t\tif (level[t] < 0) {\n\t\t\treturn flow;\n\t\t}\n\t\tmemset(iter, 0, sizeof(iter));\n\t\tint f;\n\t\twhile ((f = dfs(s, t, INF)) > 0) {\n\t\t\tflow += f;\n\t\t}\n\t}\n}\n\nint main() {\n\t\n\tcin >> X >> Y >> E;\n\tV = X + Y + 2;\n\n\tfor (int i = 0; i < E; i++) {\n\t\tint u, v, c;\n\t\tcin >> u >> v;\n\t\tadd_edge(u, v + X, 1);\n\t}\n\t\n\tfor (int i = 0; i < X; i++) {\n\t\tadd_edge(X + Y, i, 1);\n\t}\n\n\tfor (int i = 0; i < Y; i++) {\n\t\tadd_edge(i, X + Y + 1, 1);\n\t}\n\n\tcout << max_flow(X + Y, X + Y + 1) << endl;\n\n\treturn 0;\n}", "accuracy": 0.05, "time_ms": 10, "memory_kb": 65608, "score_of_the_acc": -0.9977, "final_rank": 15 }, { "submission_id": "aoj_GRL_7_A_6440764", "code_snippet": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nusing Vertex = pair<char, int>;\nusing Graph = map<Vertex, map<Vertex, bool>>;\nusing Path = map<Vertex, Vertex>;\n\nconst Vertex S = {'S', 0}, T = {'T', 0};\n\nPath f(const Graph& G)\n{\n\tset<Vertex> D;\n\tPath P;\n\tqueue<Vertex> Q;\n\tfor (Q.push(S); !Q.empty(); Q.pop()) {\n\t\tauto v = Q.front();\n\t\tif (G.count(v) > 0) for (auto [w, c] : G.at(v)) if (c && D.count(w) == 0) {\n\t\t\tP[w] = v;\n\t\t\tif (w == T) continue;\n\t\t\tD.insert(w);\n\t\t\tQ.push(w);\n\t\t}\n\t}\n\treturn P;\n}\n\nint main()\n{\n\tint nX, nY, nE, x, y, r = 0;\n\tGraph G;\n\tfor (cin >> nX >> nY >> nE; nE > 0; --nE) {\n\t\tcin >> x >> y;\n\t\tG[S][{'X', x}] = G[{'X', x}][{'Y', y}] = G[{'Y', y}][T] = true;\n\t}\n\tPath P = f(G);\n\twhile (P.count(T) > 0) {\n\t\t++r;\n\t\tfor (Vertex w = T, v = P[w]; w != S; w = v, v = P[w]) {\n\t\t\tG[v][w] = false;\n\t\t\tG[w][v] = true;\n\t\t}\n\t\tP.clear();\n\t\tP = f(G);\n\t}\n\tcout << r << endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4024, "score_of_the_acc": -0.0952, "final_rank": 4 }, { "submission_id": "aoj_GRL_7_A_6401177", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct io_setup {\n io_setup() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout << fixed << setprecision(15);\n }\n} io_setup;\n\nstruct Bipartite_Matching {\n vector<vector<int>> es;\n vector<int> d, match;\n vector<bool> used, used2;\n const int n, m;\n\n Bipartite_Matching(int n, int m) : es(n), d(n), match(m), used(n), used2(n), n(n), m(m) {}\n\n void add_edge(int u, int v) { es[u].push_back(v); }\n\n void _bfs() {\n fill(begin(d), end(d), -1);\n queue<int> que;\n for (int i = 0; i < n; i++) {\n if (!used[i]) {\n que.push(i);\n d[i] = 0;\n }\n }\n while (!que.empty()) {\n int i = que.front();\n que.pop();\n for (auto &e : es[i]) {\n int j = match[e];\n if (j != -1 && d[j] == -1) {\n que.push(j);\n d[j] = d[i] + 1;\n }\n }\n }\n }\n\n bool _dfs(int now) {\n used2[now] = true;\n for (auto &e : es[now]) {\n int u = match[e];\n if (u == -1 || (!used2[u] && d[u] == d[now] + 1 && _dfs(u))) {\n match[e] = now, used[now] = true;\n return true;\n }\n }\n return false;\n }\n\n int bipartite_matching() { // 右側のiは左側のmatch[i]とマッチングする\n fill(begin(match), end(match), -1), fill(begin(used), end(used), false);\n int ret = 0;\n while (true) {\n _bfs();\n fill(begin(used2), end(used2), false);\n int flow = 0;\n for (int i = 0; i < n; i++) {\n if (!used[i] && _dfs(i)) flow++;\n }\n if (flow == 0) break;\n ret += flow;\n }\n return ret;\n }\n};\n\nstruct Dulmage_Mendelsohn_Decomposition : Bipartite_Matching {\n using BM = Bipartite_Matching;\n vector<vector<int>> rs;\n vector<vector<int>> ids_l, ids_r; // 左側と右側のブロック\n vector<int> comp_l, comp_r; // 属するブロックの番号\n vector<int> vs;\n\n Dulmage_Mendelsohn_Decomposition(int n, int m) : BM(n, m), rs(n), comp_l(n), comp_r(m) {}\n\n void _dfs(int now, int col) {\n if (comp_l[now] != n + 1) return;\n comp_l[now] = col;\n for (auto &e : this->es[now]) {\n int to = this->match[e];\n if (to != -1) _dfs(to, col);\n }\n if (col > 0) vs.push_back(now);\n }\n\n void _rdfs(int now, int col) {\n if (comp_l[now] != n + 1) return;\n comp_l[now] = col;\n for (auto &e : rs[now]) _rdfs(e, col);\n }\n\n void decompose() {\n this->bipartite_matching();\n for (int i = 0; i < n; i++) {\n for (auto &e : this->es[i]) {\n int to = this->match[e];\n if (to != -1) rs[to].push_back(i);\n }\n }\n fill(begin(comp_l), end(comp_l), n + 1);\n for (int i = 0; i < n; i++) {\n bool flag = true;\n for (auto &e : es[i]) {\n if (this->match[e] == -1) {\n _rdfs(i, 0);\n flag = false;\n } else if (this->match[e] == i) {\n flag = false;\n }\n }\n if (flag) _dfs(i, -1);\n }\n for (int i = 0; i < n; i++) _dfs(i, 1);\n for (int i = 0; i < n; i++) {\n if (comp_l[i] > 0) comp_l[i] = n + 1;\n }\n reverse(begin(vs), end(vs));\n int cnt = 1;\n for (auto &e : vs) {\n if (comp_l[e] == n + 1) _rdfs(e, cnt++);\n }\n for (int i = 0; i < n; i++) {\n if (comp_l[i] == -1) comp_l[i] = cnt;\n }\n for (int i = 0; i < m; i++) {\n if (this->match[i] == -1) {\n comp_r[i] = 0;\n } else {\n comp_r[i] = comp_l[this->match[i]];\n }\n }\n ids_l.resize(cnt + 1), ids_r.resize(cnt + 1);\n for (int i = 0; i < m; i++) {\n if (this->match[i] == -1) ids_r[0].push_back(i);\n }\n vector<bool> used(n, false);\n for (int i = 0; i < m; i++) {\n int e = this->match[i];\n if (e != -1) {\n ids_l[comp_l[e]].push_back(e);\n ids_r[comp_r[i]].push_back(i);\n used[e] = true;\n }\n }\n for (int i = 0; i < n; i++) {\n if (!used[i]) ids_l[cnt].push_back(i);\n }\n }\n};\n\ntemplate <bool directed = false>\nstruct Graph {\n struct edge {\n int to, id;\n edge(int to, int id) : to(to), id(id) {}\n };\n\n vector<vector<edge>> es;\n const int n;\n int m;\n\n vector<int> d;\n vector<int> pre_v, pre_e;\n\n Graph(int n) : es(n), n(n), m(0), d(n), pre_v(n), pre_e(n) {}\n\n void add_edge(int from, int to) {\n es[from].emplace_back(to, m);\n if (!directed) es[to].emplace_back(from, m);\n m++;\n }\n\n int bfs(int s, int t = 0) {\n fill(begin(d), end(d), -1);\n queue<int> que;\n d[s] = 0;\n que.emplace(s);\n while (!que.empty()) {\n int i = que.front();\n que.pop();\n for (auto &e : es[i]) {\n if (d[e.to] == -1) {\n d[e.to] = d[i] + 1;\n pre_v[e.to] = i, pre_e[e.to] = e.id;\n que.push(e.to);\n }\n }\n }\n return d[t];\n }\n\n vector<int> shortest_path(int s, int t, bool use_id = false) {\n if (bfs(s, t) == -1) return {};\n vector<int> ret;\n for (int now = t; now != s; now = pre_v[now]) ret.push_back(use_id ? pre_e[now] : now);\n if (!use_id) ret.push_back(s);\n reverse(begin(ret), end(ret));\n return ret;\n }\n};\n\ntemplate <typename T, bool directed = false>\nstruct Weighted_Graph {\n struct edge {\n int to;\n T cost;\n int id;\n edge(int to, T cost, int id) : to(to), cost(cost), id(id) {}\n };\n\n vector<vector<edge>> es;\n const T INF_T = numeric_limits<T>::max() / 2;\n const int n;\n int m;\n\n vector<T> d;\n vector<int> pre_v;\n\n Weighted_Graph(int n) : es(n), n(n), m(0), d(n), pre_v(n) {}\n\n void add_edge(int from, int to, T cost) {\n es[from].emplace_back(to, cost, m);\n if (!directed) es[to].emplace_back(from, cost, m);\n m++;\n }\n\n bool bellman_ford(int s) { // sから到達可能な負閉路を検出\n fill(begin(d), end(d), INF_T);\n d[s] = 0;\n bool ret = false;\n for (int i = 0; i < 2 * n; i++) {\n for (int j = 0; j < n; j++) {\n for (auto &e : es[j]) {\n if (d[j] == INF_T) continue;\n if (d[j] + e.cost < d[e.to]) {\n d[e.to] = d[j] + e.cost, pre_v[e.to] = j;\n if (i >= n - 1) d[e.to] = -INF_T, ret = true;\n }\n }\n }\n }\n return ret;\n }\n\n bool negative_loop() { //全ての負閉路を検出\n fill(begin(d), end(d), 0);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n for (auto &e : es[j]) {\n if (d[j] + e.cost < d[e.to]) {\n d[e.to] = d[j] + e.cost;\n if (i == n - 1) return true;\n }\n }\n }\n }\n }\n\n vector<int> shortest_path(int s, int t) {\n bellman_ford(s);\n if (abs(d[t]) == INF_T) return {};\n vector<int> ret;\n for (int now = t; now != s; now = pre_v[now]) ret.push_back(now);\n ret.push_back(s), reverse(begin(ret), end(ret));\n return ret;\n }\n};\n\nstruct Partition_Matroid {\n const int m; // |E|\n const int n; // 分割の個数\n vector<vector<int>> ids;\n vector<int> belong;\n vector<int> d, cnt;\n vector<vector<int>> used;\n\n Partition_Matroid(int m, int n, const vector<vector<int>> &ids, vector<int> &d) : m(m), n(n), ids(ids), d(d), cnt(n), used(n) {\n assert(ids.size() == n && d.size() == n);\n belong.assign(m, -1);\n for (int i = 0; i < n; i++) {\n for (auto &e : ids[i]) belong[e] = i;\n }\n }\n\n int size() { return m; }\n\n template <typename T>\n void set(const vector<T> &X) { // X∈F 計算量 O(m+n)\n fill(begin(cnt), end(cnt), 0);\n for (int i = 0; i < n; i++) used[i].clear();\n for (int i = 0; i < m; i++) {\n if (X[i]) cnt[belong[i]]++;\n }\n for (int i = 0; i < n; i++) {\n assert(cnt[i] <= d[i]);\n if (cnt[i] == d[i]) {\n for (auto &e : ids[i]) {\n if (X[e]) used[i].push_back(e);\n }\n }\n }\n }\n\n vector<int> circuit(int y) const { // C(X,y) 計算量 O(1)\n assert(0 <= y && y < m);\n int p = belong[y];\n assert(0 <= p && p < n);\n if (cnt[p] == d[p]) {\n vector<int> ret = used[p];\n ret.push_back(y);\n return ret;\n }\n return {};\n }\n};\n\nstruct Graphic_Matroid {\n struct edge {\n int to, id;\n edge(int to, int id) : to(to), id(id) {}\n };\n\n const int m; // |E|\n const int n; // |V|\n vector<vector<edge>> list;\n vector<pair<int, int>> es;\n vector<int> pre_v, pre_e;\n vector<int> root;\n vector<int> depth;\n\n Graphic_Matroid(int m, int n, const vector<pair<int, int>> &es) : m(m), n(n), es(es), pre_v(n), pre_e(n), root(n), depth(n) {\n list.resize(n);\n for (int i = 0; i < m; i++) {\n auto [u, v] = es[i];\n list[u].emplace_back(v, i);\n list[v].emplace_back(u, i);\n }\n }\n\n int size() { return m; }\n\n template <typename T>\n void set(const vector<T> &X) { // X∈F 計算量 O(m+n)\n fill(begin(pre_v), end(pre_v), -1);\n fill(begin(pre_e), end(pre_e), -1);\n fill(begin(root), end(root), -1);\n fill(begin(depth), end(depth), -1);\n for (int i = 0; i < n; i++) {\n if (root[i] != -1) continue;\n queue<int> que;\n que.push(i);\n depth[i] = 0;\n while (!que.empty()) {\n int j = que.front();\n que.pop();\n root[j] = i;\n for (auto &e : list[j]) {\n assert(!X[e.id] || root[e.to] == -1 || e.id == pre_e[j]);\n if (X[e.id] && root[e.to] == -1) {\n pre_v[e.to] = j;\n pre_e[e.to] = e.id;\n depth[e.to] = depth[j] + 1;\n que.emplace(e.to);\n }\n }\n }\n }\n }\n\n vector<int> circuit(int y) const { // C(X,y) 計算量 O(n)\n auto [s, t] = es[y];\n if (root[s] != root[t]) return {};\n int r = root[s];\n vector<int> ret;\n while (s != t) {\n if (depth[s] > depth[t]) {\n ret.push_back(pre_e[s]);\n s = pre_v[s];\n } else {\n ret.push_back(pre_e[t]);\n t = pre_v[t];\n }\n }\n ret.push_back(y);\n return ret;\n }\n};\n\nstruct Transversal_Matroid {\n const int m; // |L|\n const int n; // |R|\n vector<vector<int>> es;\n vector<bool> fixed;\n vector<vector<int>> res;\n\n Transversal_Matroid(int m, int n, const vector<vector<int>> &es) : m(m), n(n), es(es), fixed(n), res(m + n) {}\n\n int size() { return m; }\n\n template <typename T>\n void set(const vector<T> &X) { // X∈F 計算量 O(e√(m+n)+m+n+e)\n fill(begin(fixed), end(fixed), true);\n for (int i = 0; i < m + n; i++) res[i].clear();\n Dulmage_Mendelsohn_Decomposition DM(m, n);\n for (int i = 0; i < m; i++) {\n if (X[i]) {\n for (auto &e : es[i]) DM.add_edge(i, e);\n }\n }\n DM.decompose();\n assert(DM.ids_r.back().empty());\n for (auto &e : DM.ids_r[0]) fixed[e] = false;\n for (int i = 0; i < m; i++) {\n for (auto &e : es[i]) res[i].push_back(m + e);\n }\n for (int i = 0; i < (int)DM.ids_l.size() - 1; i++) {\n int k = DM.ids_l[i].size(), l = DM.ids_r[i].size();\n for (int j = 0; j < k; j++) {\n int u = DM.ids_l[i][j], v = DM.ids_r[i][l - k + j];\n res[m + v].push_back(u);\n }\n }\n }\n\n vector<int> circuit(int y) const { // C(X,y) 計算量 O(e+m+n)\n for (auto &e : es[y]) {\n if (!fixed[e]) return {};\n }\n vector<bool> used(m + n, false);\n used[y] = true;\n queue<int> que;\n que.push(y);\n while (!que.empty()) {\n int i = que.front();\n que.pop();\n for (auto &e : res[i]) {\n if (!used[e]) {\n used[e] = true;\n que.emplace(e);\n }\n }\n }\n vector<int> ret;\n for (int i = 0; i < m; i++) {\n if (used[i]) ret.push_back(i);\n }\n return ret;\n }\n};\n\ntemplate <typename Matroid_1, typename Matroid_2>\nint Matroid_Intersection(Matroid_1 M1, Matroid_2 M2) {\n assert(M1.size() == M2.size());\n const int m = M1.size();\n vector<bool> X(m, false);\n for (int i = 0;; i++) {\n M1.set(X), M2.set(X);\n Graph<true> G(m + 2); // 最短路を求める\n int s = m, t = m + 1;\n for (int y = 0; y < m; y++) {\n if (X[y]) continue;\n vector<int> c1 = M1.circuit(y), c2 = M2.circuit(y);\n if (c1.empty()) G.add_edge(s, y);\n for (auto &x : c1) {\n if (x != y) G.add_edge(x, y);\n }\n if (c2.empty()) G.add_edge(y, t);\n for (auto &x : c2) {\n if (x != y) G.add_edge(y, x);\n }\n }\n vector<int> path = G.shortest_path(s, t);\n if (path.empty()) return i;\n for (auto &e : path) {\n if (e != s && e != t) X[e] = !X[e];\n }\n }\n return -1;\n};\n\ntemplate <typename Matroid_1, typename Matroid_2, typename T>\nvector<T> Weighted_Matroid_Intersection(Matroid_1 M1, Matroid_2 M2, vector<T> w) {\n assert(M1.size() == M2.size());\n const int m = M1.size();\n for (int i = 0; i < m; i++) w[i] *= m + 1;\n vector<bool> X(m, false);\n vector<T> ret(m + 1, -1);\n ret[0] = 0;\n for (int i = 1; i <= m; i++) {\n M1.set(X), M2.set(X);\n Weighted_Graph<T, true> G(m + 2); // コスト最大のパスのうち通る辺数が最小のものを求める\n int s = m, t = m + 1;\n for (int y = 0; y < m; y++) {\n if (X[y]) continue;\n vector<int> c1 = M1.circuit(y), c2 = M2.circuit(y);\n if (c1.empty()) G.add_edge(s, y, 0);\n for (auto &x : c1) {\n if (x != y) G.add_edge(x, y, w[x] + 1);\n }\n if (c2.empty()) G.add_edge(y, t, -w[y]);\n for (auto &x : c2) {\n if (x != y) G.add_edge(y, x, -w[y] + 1);\n }\n }\n vector<int> path = G.shortest_path(s, t);\n if (path.empty()) break;\n for (auto &e : path) {\n if (e != s && e != t) X[e] = !X[e];\n }\n T sum = 0;\n for (int j = 0; j < m; j++) {\n if (X[j]) sum += w[j];\n }\n ret[i] = sum / (m + 1);\n }\n return ret;\n}\n\ntemplate <typename T>\nT floor_sqrt(T x) {\n T L = 0, R = x + 1;\n while (R - L > 1) {\n T M = (L + R) / 2;\n (M * M <= x ? L : R) = M;\n }\n return L;\n}\n\nint main() {\n int L, R, E;\n cin >> L >> R >> E;\n\n vector<vector<int>> ids1(L), ids2(R);\n vector<int> d1(L, 1), d2(R, 1);\n\n for (int i = 0; i < E; i++) {\n int u, v;\n cin >> u >> v;\n ids1[u].push_back(i), ids2[v].push_back(i);\n }\n\n Partition_Matroid M1(E, L, ids1, d1), M2(E, R, ids2, d2);\n\n cout << Matroid_Intersection(M1, M2) << '\\n';\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 4760, "score_of_the_acc": -0.5616, "final_rank": 6 } ]
aoj_GRL_6_A_cpp
Maximum Flow A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Constraints $2 \leq |V| \leq 100$ $1 \leq |E| \leq 1000$ $0 \leq c_i \leq 10000$ Sample Input 1 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Sample Output 1 3
[ { "submission_id": "aoj_GRL_6_A_11057074", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nconst int INF = 1e9;\n\nstruct Edge {\n int to; //行き先\n int rev; //逆辺のindex\n int cap; //容量\n};\n\nstruct MaxFlow {\n int N;\n vector<vector<Edge>> graph;\n vector<bool> used;\n\n MaxFlow(int n) : N(n), graph(n), used(n) {}\n\n void add_edge(int u, int v, int cap) {\n graph[u].push_back({v, (int)graph[v].size(), cap});\n graph[v].push_back({u, (int)graph[u].size()-1, 0});\n }\n\n int dfs(int pos, int goal, int NowFlow) {\n if (pos == goal) return NowFlow;\n used[pos] = true;\n for (auto &nex : graph[pos]) {\n if (!used[nex.to] && nex.cap > 0) {\n int d = dfs(nex.to, goal, min(NowFlow, nex.cap));\n if (d > 0) {\n nex.cap -= d;\n graph[nex.to][nex.rev].cap += d;\n return d;\n }\n }\n }\n return 0;\n }\n\n int max_flow(int start, int goal) {\n int flow = 0;\n while (true) {\n fill(used.begin(), used.end(), false);\n int f = dfs(start, goal, INF);\n if (f == 0) break;\n flow += f;\n }\n return flow;\n }\n};\n\n\nint main() {\n int N, M;\n cin >> N >> M;\n MaxFlow mf(N);\n for (int i = 0; i < M; i++) {\n int u, v, c;\n cin >> u >> v >> c;\n mf.add_edge(u, v, c);\n }\n\n int start = 0, goal = N-1;\n int ans = mf.max_flow(start, goal);\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3492, "score_of_the_acc": -0.0984, "final_rank": 3 }, { "submission_id": "aoj_GRL_6_A_10996382", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, s, e) for (int i = (int)(s); i < (int)(e); ++i)\n\ntemplate <typename Cap>\nstruct FordFulkerson {\n\tstruct edge {\n\t\tint to;\n\t\tCap cap;\n\t\tint rev;\n\t};\n\t\n\tconst Cap INF;\n\tvector<vector<edge>> G;\n\tvector<int> used;\n\tint timestamp;\n\t\n\tFordFulkerson(int N) : INF(numeric_limits<Cap>::max()), G(N), used(N, -1), timestamp(0) {}\n\t\n\tvoid add_edge(int from, int to, Cap cap) {\n\t\tG[from].push_back((edge){to, cap, (int)G[to].size()});\n\t\tG[to].push_back((edge){from, 0, (int)G[from].size() - 1});\n\t}\n\t\n\tCap find_path(int v, const int t, Cap flow) {\n\t\tif (v == t) return flow;\n\t\tused[v] = timestamp;\n\t\tfor (auto &e : G[v]) {\n\t\t\tif (e.cap > 0 && used[e.to] != timestamp) {\n\t\t\t\tCap d = find_path(e.to, t, min(flow, e.cap));\n\t\t\t\tif (d > 0) {\n\t\t\t\t\te.cap -= d;\n\t\t\t\t\tG[e.to][e.rev].cap += d;\n\t\t\t\t\treturn d;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tCap max_flow(int s, int t) {\n\t\tCap flow = 0;\n\t\tfor (Cap f; (f = find_path(s, t, INF)) > 0; ++timestamp) flow += f;\n\t\t++timestamp;\n\t\treturn flow;\n\t}\n};\n\nint main() {\n\tcin.tie(nullptr);\n\tios_base::sync_with_stdio(false);\n\t\n\tint N, M;\n\tcin >> N >> M;\n\tFordFulkerson<ll> ff(N);\n\t\n\trep(i, 0, M) {\n\t\tint u, v, c;\n\t\tcin >> u >> v >> c;\n\t\tff.add_edge(u, v, c);\n\t}\n\tcout << ff.max_flow(0, N - 1) << '\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3532, "score_of_the_acc": -0.2623, "final_rank": 6 }, { "submission_id": "aoj_GRL_6_A_10914679", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nint dfs(vector<vector<tuple<int,int,int>>>& G,vector<bool>& checked,int cv,int cf,int goal){\n if(cv==goal) return cf;\n checked[cv]=true;\n\n int ca=0;\n for(auto& nv:G[cv]){\n if(checked[get<0>(nv)]||get<1>(nv)==0) continue;\n ca=dfs(G,checked,get<0>(nv),min(get<1>(nv),cf),goal);\n if(ca>0){\n get<1>(nv)-=ca;\n get<1>(G[get<0>(nv)][get<2>(nv)])+=ca;\n return ca;\n }\n }\n\n return 0;\n}\n\nint main(){\n int V,E; cin>>V>>E;\n vector<vector<tuple<int,int,int>>> G(V); //v, c, zansa\n for(int i=0;i<E;i++){\n int u,v,c; cin>>u>>v>>c;\n G[u].push_back({v,c,G[v].size()});\n G[v].push_back({u,0,G[u].size()-1});\n }\n\n int ans=0;\n while(true){\n vector<bool> checked(V,false);\n int ca=dfs(G,checked,0,1e9,V-1);\n ans+=ca;\n if(ca==0) break;\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3468, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_GRL_6_A_10875619", "code_snippet": "#include <vector>\n#include <limits>\nusing namespace std;\n\n//流量の型がT\ntemplate<class T>\nstruct MaxFlowGraph {\nprivate:\n struct Edge {\n //to:行先\n int to;\n //cap:流量のあまり\n T cap;\n //逆辺のindex\n int rev;\n };\n vector<vector<Edge> > G;\n vector<bool> seen;\n T dfs(int v, int goal, T f) {\n //頂点tにたどり着いた\n if (v == goal) return f;\n seen[v] = true;\n for (int idx = 0; idx < (int)G[v].size(); idx++) {\n Edge& e = G[v][idx];\n if (seen[e.to]) continue;\n if (e.cap == 0) continue;\n T d = dfs(e.to, goal, min(f, e.cap));\n if (d > 0) {\n //s-tパスが見つかった\n //流量のあまりを減らす\n e.cap -= d;\n //逆辺の流量のあまりを増やす\n G[e.to][e.rev].cap += d;\n return d;\n }\n }\n return 0;\n }\npublic:\n //コンストラクタ\n MaxFlowGraph() : MaxFlowGraph(0) {}\n MaxFlowGraph(int n) {\n G.resize(n);\n seen.resize(n);\n }\n //u->vの辺を追加する\n void add_edge(int u, int v, T cap) {\n G[u].push_back(Edge{v, cap, (int)G[v].size()});\n G[v].push_back(Edge{u, 0, (int)G[u].size()-1});\n }\n //s-tの最大流を求める\n T max_flow(int s, int t) {\n T ret = 0;\n while(true) {\n seen.assign((int)seen.size(), false);\n T plus = dfs(s, t, numeric_limits<T>::max());\n if (plus == 0) break;\n else ret += plus;\n }\n return ret;\n }\n};\n\n#include <iostream>\n\nint main() {\n int V, E;\n std::cin >> V >> E;\n MaxFlowGraph<int> G(V);\n for (int i = 0; i < E; i++) {\n int u, v; std::cin >> u >> v;\n int c; std::cin >> c;\n G.add_edge(u, v, c);\n }\n std::cout << G.max_flow(0, V-1) << std::endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3472, "score_of_the_acc": -0.0581, "final_rank": 2 }, { "submission_id": "aoj_GRL_6_A_10866724", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int MAXV = 100 + 10;\nconst int INF = 1e9;\n\nstruct edge\n{\n int to, cap, rev;\n};\n\nvector<edge> G[MAXV];\nbool used[MAXV];\nint n, m;\n\n//初始化\nvoid init()\n{\n for(int i = 0; i < MAXV; i++) G[i].clear();\n}\n\n//向图中增加一条从S到T容量为CAP的边\nvoid add_edge(int from, int to, int cap)\n{\n G[from].push_back((edge){to, cap, G[to].size()});\n G[to].push_back((edge){from, 0, G[from].size()-1});\n}\n//通过DFS寻找增广路\nint dfs(int v, int t, int f)\n{\n if(v == t) return f;\n used[v] = true;\n for(int i = 0; i < G[v].size(); i++)\n {\n edge &e = G[v][i];\n if(!used[e.to] && e.cap > 0)\n {\n int d = dfs(e.to, t, min(f, e.cap));\n if(d > 0)\n {\n e.cap -= d;\n G[e.to][e.rev].cap += d;\n return d;\n }\n }\n }\n return 0;\n}\n\n//求解S到T的最大流\nint max_flow(int s, int t)\n{\n int flow = 0;\n while(1)\n {\n memset(used, 0, sizeof used);\n int f = dfs(s, t, INF);\n if(!f) return flow;\n flow += f;\n }\n}\n\nint main()\n{\n int cnt = 0;\n while(~scanf(\"%d%d\", &n, &m))\n {\n init();\n for(int i = 0; i < m; i++)\n {\n int tx, ty, cap;\n scanf(\"%d%d%d\", &tx, &ty, &cap);\n add_edge(tx, ty, cap);\n }\n cout << max_flow(0, n - 1) << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3528, "score_of_the_acc": -0.2459, "final_rank": 5 }, { "submission_id": "aoj_GRL_6_A_10569056", "code_snippet": "#line 1 \"verify/graph/max_flow.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/problems/GRL_6_A\"\n\n#include <bits/stdc++.h>\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\n/* NAMESPACE */\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n/* HASH */\n\nstruct custom_hash {\n\tstatic uint64_t splitmix64(uint64_t x) {\n\t\t// http://xorshift.di.unimi.it/splitmix64.c\n\t\tx += 0x9e3779b97f4a7c15;\n\t\tx = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n\t\tx = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n\t\treturn x ^ (x >> 31);\n\t}\n\n\tsize_t operator()(uint64_t x) const {\n\t\tstatic const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n\t\treturn splitmix64(x + FIXED_RANDOM);\n\t}\n};\n\ntemplate<class K, class V> using safe_map = unordered_map<K, V, custom_hash>;\ntemplate<class K, class V> using safe_ht = gp_hash_table<K, V, custom_hash>;\ntemplate<class K> using safe_set = unordered_set<K, custom_hash>;\ntemplate<class K> using safe_htset = gp_hash_table<K, null_type, custom_hash>;\n\n/* CLASSES */\n\nusing ll = long long;\nusing pii = pair<int, int>;\ntemplate<class T> using pp = pair<T, T>;\nusing pll = pp<ll>;\ntemplate<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate<class T> using greater_pq = priority_queue<T, vector<T>, greater<>>;\ntemplate<class T> using V = vector<T>;\nusing vi = V<int>;\nusing vvi = V<vi>;\nusing vvvi = V<vvi>;\nusing vll = V<ll>;\n\n/* FUNCTIONS */\n\ntemplate<class T, class U>\nT max(T a, U b) {\n\treturn (a > b) ? a : b;\n}\n\ntemplate<class T, class U>\nT min(T a, U b) {\n\treturn (a < b) ? a : b;\n}\n\ntemplate<class T>\nT power(T x, T y) {\n\tT res = 1;\n\tfor (T i = 0; i < y; i++) {\n\t\tres *= x;\n\t}\n\treturn res;\n}\n\ntemplate<class T>\nT nxt() {\n\tT x;\n\tcin >> x;\n\treturn x;\n}\n\n/* MACROS */\n#define clearall(arr) memset((arr), 0, sizeof (arr))\n#define clearn(arr, n) memset((arr), 0, n * sizeof (arr)[0])\n#define resetall(arr) memset((arr), -1, sizeof (arr))\n#define resetn(arr, n) memset((arr), -1, n * sizeof (arr)[0])\n#define YESNO(condition) cout << ((condition) ? \"YES\" : \"NO\")\n#define sfunc(a, b, c) ((a) = c((a), (b)))\n#define smin(a, b) sfunc((a), (b), min)\n#define smax(a, b) sfunc((a), (b), max)\n#define ALL(x) begin((x)), end((x))\n#define SZ(a) (int)(a).size()\n#define readall(arr, n) for (int i = 0; i < n; i++) cin >> (arr)[i]\n#define printall(arr, n) for (int i = 0; i < n; i++) cout << (arr)[i] << \" \"\n#define printalldel(arr, n, del) for (int i = 0; i < n; i++) cout << (arr)[i] << del\n#define mx_val(arr) (*max_element(ALL(arr)))\n\n/* DEBUG TEMPLATE*/\ntemplate<typename T, typename S>\nostream &operator<<(ostream &os, const pair<T, S> &p) { return os << \"(\" << p.first << \", \" << p.second << \")\"; }\n\ntemplate<typename C, typename T = decay<decltype(*begin(\n\t\tdeclval<C>()))>, typename enable_if<!is_same<C, string>::value>::type * = nullptr>\nostream &operator<<(ostream &os, const C &c) {\n\tbool f = true;\n\tos << \"[\";\n\tfor (const auto &x: c) {\n\t\tif (!f) os << \", \";\n\t\tf = false;\n\t\tos << x;\n\t}\n\treturn os << \"]\";\n}\n\ntemplate<typename T>\nvoid debug(string s, T x) { cerr << \"\\033[1;35m\" << s << \"\\033[0;32m = \\033[33m\" << x << \"\\033[0m\\n\"; }\n\ntemplate<typename T, typename... Args>\nvoid debug(string s, T x, Args... args) {\n\tfor (int i = 0, b = 0; i < (int) s.size(); i++)\n\t\tif (s[i] == '(' || s[i] == '{') b++;\n\t\telse if (s[i] == ')' || s[i] == '}') b--;\n\t\telse if (s[i] == ',' && b == 0) {\n\t\t\tcerr << \"\\033[1;35m\" << s.substr(0, i) << \"\\033[0;32m = \\033[33m\" << x << \"\\033[31m | \";\n\t\t\tdebug(s.substr(s.find_first_not_of(' ', i + 1)), args...);\n\t\t\tbreak;\n\t\t}\n}\n\ntemplate<typename T>\nstd::vector<T> vectorize(T *a, int n) {\n\tstd::vector<T> res;\n\tfor (int i = 0; i < n; ++i) {\n\t\tres.push_back(a[i]);\n\t}\n\treturn res;\n}\n\ntemplate<typename T, typename... Sizes>\nauto vectorize(T *a, int n, Sizes... sizes) {\n\tstd::vector<decltype(vectorize(a[0], sizes...))> res;\n\tfor (int i = 0; i < n; ++i) {\n\t\tres.push_back(vectorize(a[i], sizes...));\n\t}\n\treturn res;\n}\n\n#ifdef LOCAL\n#define DEBUG(...) debug(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define DEBUG(...) 42\n#endif\n\n/* CONSTANTS */\nconst int inf = 2e9;\nconst ll infl = 4e18;\nconst ll MOD = 998244353;\nconst ll MAXN = 2e5 + 5;\n\n#line 2 \"library/graph/max_flow.h\"\n\ntemplate<typename T>\nT max_flow(vector<vector<int>> &adj, vector<vector<T>> &capacity, int source, int sink) {\n\tint n = adj.size();\n\tint flow = 0;\n\twhile (true) {\n\t\tbool found = false;\n\t\tvector<int> prev(n, -2);\n\t\tqueue<int> q;\n\n\t\tprev[source] = -1;\n\t\tq.push(source);\n\n\t\twhile (!q.empty()) {\n\t\t\tint v = q.front();\n\t\t\tq.pop();\n\t\t\tif (v == sink) {\n\t\t\t\tfound = true;\n\t\t\t\twhile (true) {\n\t\t\t\t\tint p = prev[v];\n\t\t\t\t\tif (p == -1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcapacity[p][v]--;\n\t\t\t\t\tcapacity[v][p]++;\n\t\t\t\t\tv = p;\n\t\t\t\t}\n\t\t\t\tflow++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfor (int u: adj[v]) {\n\t\t\t\tif (prev[u] == -2 && capacity[v][u]) {\n\t\t\t\t\tprev[u] = v;\n\t\t\t\t\tq.push(u);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!found) {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn flow;\n}\n#line 156 \"verify/graph/max_flow.test.cpp\"\n\nint solve() {\n\tint n, m;\n\tcin >> n >> m;\n\tvector<vector<int>> adj(n);\n\tvector<vector<int>> capacity(n, vector<int>(n));\n\tfor (int i = 0; i < m; ++i) {\n\t\tint a, b, c;\n\t\tcin >> a >> b >> c;\n\t\tadj[a].push_back(b);\n\t\tadj[b].push_back(a);\n\t\tcapacity[a][b] = c;\n\t}\n\tcout << max_flow(adj, capacity, 0, n - 1) << '\\n';\n\treturn 0;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint T = 1;\n//\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3516, "score_of_the_acc": -0.3217, "final_rank": 8 }, { "submission_id": "aoj_GRL_6_A_10561819", "code_snippet": "#pragma GCC optimize(\"Ofast,unroll-loops\")\n#include<bits/stdc++.h>\nusing namespace std;\nnamespace io{\nconstexpr int N=1<<16;\nusing ll=long long;\ntemplate<class T>\nconstexpr T ten(int k){return k?ten<T>(k-1)*10:1;}\ntemplate<class T>\nconstexpr bool is_128=is_same_v<T,__int128>||is_same_v<T,unsigned __int128>;\nstruct I:istream{\nchar b[N],*r=b+N,*p=r;\nconstexpr inline void load(int need){\n\tif(int d=r-p;d<need){\n\t\td=fread(copy_n(p,d,b),1,p-b,stdin);\n\t\tp=b;\n\t}\n}\nvoid skip(){while(*p<=' ')++p;}\nvoid sc(char&c){\n\tload(5);\n\tskip();\n\tc=*p++;\n}\nvoid sc(string&s){\n\ts.clear();\n\tload(5);\n\tskip();\n\tdo{\n\t\ts+=*p++;\n\t\tload(1);\n\t}while(*p>' ');\n\t++p;\n}\nvoid sc(double&x){\n\tstring s;\n\tsc(s);\n\tx=stod(s);\n}\ntemplate<class T>\nenable_if_t<is_integral_v<T>&&!is_128<T>>sc(T&x){\n\tload(25);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\tbool ok=0;\n\twhile(1){\n\t\tint d=0;\n\t\tfor(int i=0;i<9;i++){\n\t\t\tif(*p<=' '){\n\t\t\t\tok=1;\n\t\t\t\tif(i)x=x*ten<int>(i)+d;\n\t\t\t\t++p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\td=d*10+(*p++-'0');\n\t\t}\n\t\tif(ok)break;\n\t\tx=x*ten<int>(9)+d;\n\t}\n\tif(neg)x=-x;\n}\ntemplate<class T>\nenable_if_t<is_128<T>>sc(T&x){\n\tload(45);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\twhile(1){\n\t\tuint64_t d;\n\t\tmemcpy(&d,p,8);\n\t\td-=0x3030303030303030;\n\t\tif(d&0x8080808080808080)break;\n\t\td=(d*10+(d>>8))&0xff00ff00ff00ff;\n\t\td=(d*100+(d>>16))&0xffff0000ffff;\n\t\td=(d*10000+(d>>32))&0xffffffff;\n\t\tx=x*100000000+d;\n\t\tp+=8;\n\t}\n\tint d=0,c=0;\n\twhile(*p>' '){\n\t\td=d*10+(*p++-'0');\n\t\t++c;\n\t}\n\t++p;\n\tif(c)x=x*ten<int>(c)+d;\n\tif(neg)x=-x;\n}\ntemplate<class T,class U>\nvoid sc(pair<T,U>&x){sc(x.first),sc(x.second);}\ntemplate<int k=0,class T>\nvoid sc_tup(T&x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tsc(std::get<k>(x));\n\t\tsc_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid sc(tuple<T...>&x){sc_tup(x);}\ntemplate<class T>\nvoid sc(vector<T>&a){for(T&x:a)sc(x);}\ntemplate<class T>I&operator>>(T&x){sc(x);return *this;}\n}_i;\nstruct O:ostream{\nchar b[N],*r=b+N,*p=b;\nconstexpr inline void flush(int need=N){\n\tif(r-p<need){\n\t\tfwrite(b,1,p-b,stdout);\n\t\tp=b;\n\t}\n}\n~O(){flush();}\nvoid pr(char c){\n\tflush(1);\n\t*p++=c;\n}\nvoid pr(bool x){pr(x?'1':'0');}\nvoid pr(const char*s){\n\tint n=strlen(s);\n\tfor(int i=0;i<n;i++)pr(s[i]);\n}\nvoid pr(string s){for(char c:s)pr(c);}\nvoid pr(double x){\n\tostringstream os;\n\tos<<setprecision(18)<<x;\n\tpr(os.str());\n}\nvoid pr(long double x){pr((double)x);}\nstatic constexpr auto num=[](){\n\tarray<array<char,4>,10000>num={};\n\tfor(int i=10000;i--;){\n\t\tint x=i;\n\t\tfor(int j=4;j--;)num[i][j]=x%10|'0',x/=10;\n\t}\n\treturn num;\n}();\nchar tmp[20];\ntemplate<class T>\nenable_if_t<is_integral_v<T>&&!is_128<T>>pr(T x){\n\tflush(20);\n\tif(x<0)*p++='-',x=-x;\n\tint i;\n\tfor(i=20;x>=10000;){\n\t\ti-=4;\n\t\tmemcpy(tmp+i,&num[x%10000][0],4);\n\t\tx/=10000;\n\t}\n\tif(x>=1000)p=copy_n(&num[x][0],4,p);\n\telse if(x>=100)p=copy_n(&num[x][1],3,p);\n\telse if(x>=10)p=copy_n(&num[x][2],2,p);\n\telse *p++=x|'0';\n\tp=copy_n(tmp+i,20-i,p);\n}\ntemplate<int k=16>\nvoid w4(ll x){\n\tif constexpr(k==4){\n\t\tp=copy_n(&num[x][0],4,p);\n\t\treturn;\n\t}else{\n\t\tp=copy_n(&num[x/ten<ll>(k-4)][0],4,p);\n\t\tw4<k-4>(x%ten<ll>(k-4));\n\t}\n}\ntemplate<class T>\nenable_if_t<is_128<T>>pr(T x){\n\tflush(40);\n\tif(x<0)*p++='-',x=-x;\n\tif(x<ten<T>(16))pr(static_cast<ll>(x));\n\telse if(x<ten<T>(32)){\n\t\tpr(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}else{\n\t\tpr(static_cast<int>(x/ten<T>(32)));\n\t\tx%=ten<T>(32);\n\t\tw4(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}\n}\ntemplate<class T,class U>\nvoid pr(pair<T,U>x){pr(x.first),pr(' '),pr(x.second);}\ntemplate<int k=0,class T>\nvoid pr_tup(T x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tif constexpr(k)pr(' ');\n\t\tpr(get<k>(x));\n\t\tpr_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid pr(tuple<T...>x){pr_tup(x);}\ntemplate<class T>\nvoid pr(vector<T>a){\n\tint n=a.size();\n\tfor(int i=0;i<n;++i){\n\t\tif(i)pr(' ');\n\t\tpr(a[i]);\n\t}\n}\ntemplate<class T>O&operator<<(T x){pr(x);return *this;}\n}_o;\nvoid flush(){_o.flush();}\n}\nusing io::flush;\n#define cin io::_i\n#define cout io::_o\nint main(){\n\tint n,m;\n\tcin>>n>>m;\n\tauto c=vector(n,vector(n,0));\n\tfor(int i=0;i<m;i++){\n\t\tint u,v,w;\n\t\tcin>>u>>v>>w;\n\t\tc[u][v]+=w;\n\t}\n\tvector<bool>vis(n);\n\tauto dfs=[&](auto dfs,int u,int in)->int{\n\t\tif(u==n-1)return in;\n\t\tif(!in||vis[u])return 0;\n\t\tvis[u]=1;\n\t\tint out=0;\n\t\tfor(int v=0;v<n;v++){\n\t\t\tint f=dfs(dfs,v,min(c[u][v],in));\n\t\t\tc[u][v]-=f;\n\t\t\tc[v][u]+=f;\n\t\t\tin-=f;\n\t\t\tout+=f;\n\t\t\tif(!in)break;\n\t\t}\n\t\treturn out;\n\t};\n\tint ans=0,f;\n\twhile(f=dfs(dfs,0,1e9))ans+=f,vis.assign(n,0);\n\tcout<<ans<<'\\n';\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 3540, "score_of_the_acc": -0.8784, "final_rank": 12 }, { "submission_id": "aoj_GRL_6_A_10561799", "code_snippet": "#pragma GCC optimize(\"Ofast,unroll-loops\")\n#include<bits/stdc++.h>\nusing namespace std;\nnamespace io{\nconstexpr int N=1<<16;\nusing ll=long long;\ntemplate<class T>\nconstexpr T ten(int k){return k?ten<T>(k-1)*10:1;}\ntemplate<class T>\nconstexpr bool is_128=is_same_v<T,__int128>||is_same_v<T,unsigned __int128>;\nstruct I:istream{\nchar b[N],*r=b+N,*p=r;\nconstexpr inline void load(int need){\n\tif(int d=r-p;d<need){\n\t\td=fread(copy_n(p,d,b),1,p-b,stdin);\n\t\tp=b;\n\t}\n}\nvoid skip(){while(*p<=' ')++p;}\nvoid sc(char&c){\n\tload(5);\n\tskip();\n\tc=*p++;\n}\nvoid sc(string&s){\n\ts.clear();\n\tload(5);\n\tskip();\n\tdo{\n\t\ts+=*p++;\n\t\tload(1);\n\t}while(*p>' ');\n\t++p;\n}\nvoid sc(double&x){\n\tstring s;\n\tsc(s);\n\tx=stod(s);\n}\ntemplate<class T>\nenable_if_t<is_integral_v<T>&&!is_128<T>>sc(T&x){\n\tload(25);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\tbool ok=0;\n\twhile(1){\n\t\tint d=0;\n\t\tfor(int i=0;i<9;i++){\n\t\t\tif(*p<=' '){\n\t\t\t\tok=1;\n\t\t\t\tif(i)x=x*ten<int>(i)+d;\n\t\t\t\t++p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\td=d*10+(*p++-'0');\n\t\t}\n\t\tif(ok)break;\n\t\tx=x*ten<int>(9)+d;\n\t}\n\tif(neg)x=-x;\n}\ntemplate<class T>\nenable_if_t<is_128<T>>sc(T&x){\n\tload(45);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\twhile(1){\n\t\tuint64_t d;\n\t\tmemcpy(&d,p,8);\n\t\td-=0x3030303030303030;\n\t\tif(d&0x8080808080808080)break;\n\t\td=(d*10+(d>>8))&0xff00ff00ff00ff;\n\t\td=(d*100+(d>>16))&0xffff0000ffff;\n\t\td=(d*10000+(d>>32))&0xffffffff;\n\t\tx=x*100000000+d;\n\t\tp+=8;\n\t}\n\tint d=0,c=0;\n\twhile(*p>' '){\n\t\td=d*10+(*p++-'0');\n\t\t++c;\n\t}\n\t++p;\n\tif(c)x=x*ten<int>(c)+d;\n\tif(neg)x=-x;\n}\ntemplate<class T,class U>\nvoid sc(pair<T,U>&x){sc(x.first),sc(x.second);}\ntemplate<int k=0,class T>\nvoid sc_tup(T&x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tsc(std::get<k>(x));\n\t\tsc_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid sc(tuple<T...>&x){sc_tup(x);}\ntemplate<class T>\nvoid sc(vector<T>&a){for(T&x:a)sc(x);}\ntemplate<class T>I&operator>>(T&x){sc(x);return *this;}\n}_i;\nstruct O:ostream{\nchar b[N],*r=b+N,*p=b;\nconstexpr inline void flush(int need=N){\n\tif(r-p<need){\n\t\tfwrite(b,1,p-b,stdout);\n\t\tp=b;\n\t}\n}\n~O(){flush();}\nvoid pr(char c){\n\tflush(1);\n\t*p++=c;\n}\nvoid pr(bool x){pr(x?'1':'0');}\nvoid pr(const char*s){\n\tint n=strlen(s);\n\tfor(int i=0;i<n;i++)pr(s[i]);\n}\nvoid pr(string s){for(char c:s)pr(c);}\nvoid pr(double x){\n\tostringstream os;\n\tos<<setprecision(18)<<x;\n\tpr(os.str());\n}\nvoid pr(long double x){pr((double)x);}\nstatic constexpr auto num=[](){\n\tarray<array<char,4>,10000>num={};\n\tfor(int i=10000;i--;){\n\t\tint x=i;\n\t\tfor(int j=4;j--;)num[i][j]=x%10|'0',x/=10;\n\t}\n\treturn num;\n}();\nchar tmp[20];\ntemplate<class T>\nenable_if_t<is_integral_v<T>&&!is_128<T>>pr(T x){\n\tflush(20);\n\tif(x<0)*p++='-',x=-x;\n\tint i;\n\tfor(i=20;x>=10000;){\n\t\ti-=4;\n\t\tmemcpy(tmp+i,&num[x%10000][0],4);\n\t\tx/=10000;\n\t}\n\tif(x>=1000)p=copy_n(&num[x][0],4,p);\n\telse if(x>=100)p=copy_n(&num[x][1],3,p);\n\telse if(x>=10)p=copy_n(&num[x][2],2,p);\n\telse *p++=x|'0';\n\tp=copy_n(tmp+i,20-i,p);\n}\ntemplate<int k=16>\nvoid w4(ll x){\n\tif constexpr(k==4){\n\t\tp=copy_n(&num[x][0],4,p);\n\t\treturn;\n\t}else{\n\t\tp=copy_n(&num[x/ten<ll>(k-4)][0],4,p);\n\t\tw4<k-4>(x%ten<ll>(k-4));\n\t}\n}\ntemplate<class T>\nenable_if_t<is_128<T>>pr(T x){\n\tflush(40);\n\tif(x<0)*p++='-',x=-x;\n\tif(x<ten<T>(16))pr(static_cast<ll>(x));\n\telse if(x<ten<T>(32)){\n\t\tpr(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}else{\n\t\tpr(static_cast<int>(x/ten<T>(32)));\n\t\tx%=ten<T>(32);\n\t\tw4(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}\n}\ntemplate<class T,class U>\nvoid pr(pair<T,U>x){pr(x.first),pr(' '),pr(x.second);}\ntemplate<int k=0,class T>\nvoid pr_tup(T x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tif constexpr(k)pr(' ');\n\t\tpr(get<k>(x));\n\t\tpr_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid pr(tuple<T...>x){pr_tup(x);}\ntemplate<class T>\nvoid pr(vector<T>a){\n\tint n=a.size();\n\tfor(int i=0;i<n;++i){\n\t\tif(i)pr(' ');\n\t\tpr(a[i]);\n\t}\n}\ntemplate<class T>O&operator<<(T x){pr(x);return *this;}\n}_o;\nvoid flush(){_o.flush();}\n}\nusing io::flush;\n#define cin io::_i\n#define cout io::_o\nint main(){\n\tint n,m;\n\tcin>>n>>m;\n\tauto c=vector(n,vector(n,0));\n\tfor(int i=0;i<m;i++){\n\t\tint u,v,w;\n\t\tcin>>u>>v>>w;\n\t\tc[u][v]+=w;\n\t}\n\tvector<bool>vis(n);\n\tauto dfs=[&](auto dfs,int u,int in)->int{\n\t\tif(!in)return 0;\n\t\tif(u==n-1)return in;\n\t\tif(vis[u])return 0;\n\t\tvis[u]=1;\n\t\tfor(int v=0;v<n;v++){\n\t\t\tint f=dfs(dfs,v,min(c[u][v],in));\n\t\t\tif(f){\n\t\t\t\tc[u][v]-=f;\n\t\t\t\tc[v][u]+=f;\n\t\t\t\treturn f;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t};\n\tint ans=0;\n\tbool upd=1;\n\twhile(upd){\n\t\tupd=0;\n\t\tvis.assign(n,0);\n\t\tint f;\n\t\twhile(f=dfs(dfs,0,1e9))ans+=f,upd=1;\n\t}\n\tcout<<ans<<'\\n';\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 3540, "score_of_the_acc": -0.9201, "final_rank": 14 }, { "submission_id": "aoj_GRL_6_A_10561775", "code_snippet": "#pragma GCC optimize(\"Ofast,unroll-loops\")\n#include<bits/stdc++.h>\nusing namespace std;\nnamespace io{\nconstexpr int N=1<<16;\nusing ll=long long;\ntemplate<class T>\nconstexpr T ten(int k){return k?ten<T>(k-1)*10:1;}\ntemplate<class T>\nconstexpr bool is_128=is_same_v<T,__int128>||is_same_v<T,unsigned __int128>;\nstruct I:istream{\nchar b[N],*r=b+N,*p=r;\nconstexpr inline void load(int need){\n\tif(int d=r-p;d<need){\n\t\td=fread(copy_n(p,d,b),1,p-b,stdin);\n\t\tp=b;\n\t}\n}\nvoid skip(){while(*p<=' ')++p;}\nvoid sc(char&c){\n\tload(5);\n\tskip();\n\tc=*p++;\n}\nvoid sc(string&s){\n\ts.clear();\n\tload(5);\n\tskip();\n\tdo{\n\t\ts+=*p++;\n\t\tload(1);\n\t}while(*p>' ');\n\t++p;\n}\nvoid sc(double&x){\n\tstring s;\n\tsc(s);\n\tx=stod(s);\n}\ntemplate<class T>\nenable_if_t<is_integral_v<T>&&!is_128<T>>sc(T&x){\n\tload(25);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\tbool ok=0;\n\twhile(1){\n\t\tint d=0;\n\t\tfor(int i=0;i<9;i++){\n\t\t\tif(*p<=' '){\n\t\t\t\tok=1;\n\t\t\t\tif(i)x=x*ten<int>(i)+d;\n\t\t\t\t++p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\td=d*10+(*p++-'0');\n\t\t}\n\t\tif(ok)break;\n\t\tx=x*ten<int>(9)+d;\n\t}\n\tif(neg)x=-x;\n}\ntemplate<class T>\nenable_if_t<is_128<T>>sc(T&x){\n\tload(45);\n\tskip();\n\tbool neg=0;\n\tif(*p=='-')neg=1,++p;\n\tx=0;\n\twhile(1){\n\t\tuint64_t d;\n\t\tmemcpy(&d,p,8);\n\t\td-=0x3030303030303030;\n\t\tif(d&0x8080808080808080)break;\n\t\td=(d*10+(d>>8))&0xff00ff00ff00ff;\n\t\td=(d*100+(d>>16))&0xffff0000ffff;\n\t\td=(d*10000+(d>>32))&0xffffffff;\n\t\tx=x*100000000+d;\n\t\tp+=8;\n\t}\n\tint d=0,c=0;\n\twhile(*p>' '){\n\t\td=d*10+(*p++-'0');\n\t\t++c;\n\t}\n\t++p;\n\tif(c)x=x*ten<int>(c)+d;\n\tif(neg)x=-x;\n}\ntemplate<class T,class U>\nvoid sc(pair<T,U>&x){sc(x.first),sc(x.second);}\ntemplate<int k=0,class T>\nvoid sc_tup(T&x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tsc(std::get<k>(x));\n\t\tsc_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid sc(tuple<T...>&x){sc_tup(x);}\ntemplate<class T>\nvoid sc(vector<T>&a){for(T&x:a)sc(x);}\ntemplate<class T>I&operator>>(T&x){sc(x);return *this;}\n}_i;\nstruct O:ostream{\nchar b[N],*r=b+N,*p=b;\nconstexpr inline void flush(int need=N){\n\tif(r-p<need){\n\t\tfwrite(b,1,p-b,stdout);\n\t\tp=b;\n\t}\n}\n~O(){flush();}\nvoid pr(char c){\n\tflush(1);\n\t*p++=c;\n}\nvoid pr(bool x){pr(x?'1':'0');}\nvoid pr(const char*s){\n\tint n=strlen(s);\n\tfor(int i=0;i<n;i++)pr(s[i]);\n}\nvoid pr(string s){for(char c:s)pr(c);}\nvoid pr(double x){\n\tostringstream os;\n\tos<<setprecision(18)<<x;\n\tpr(os.str());\n}\nvoid pr(long double x){pr((double)x);}\nstatic constexpr auto num=[](){\n\tarray<array<char,4>,10000>num={};\n\tfor(int i=10000;i--;){\n\t\tint x=i;\n\t\tfor(int j=4;j--;)num[i][j]=x%10|'0',x/=10;\n\t}\n\treturn num;\n}();\nchar tmp[20];\ntemplate<class T>\nenable_if_t<is_integral_v<T>&&!is_128<T>>pr(T x){\n\tflush(20);\n\tif(x<0)*p++='-',x=-x;\n\tint i;\n\tfor(i=20;x>=10000;){\n\t\ti-=4;\n\t\tmemcpy(tmp+i,&num[x%10000][0],4);\n\t\tx/=10000;\n\t}\n\tif(x>=1000)p=copy_n(&num[x][0],4,p);\n\telse if(x>=100)p=copy_n(&num[x][1],3,p);\n\telse if(x>=10)p=copy_n(&num[x][2],2,p);\n\telse *p++=x|'0';\n\tp=copy_n(tmp+i,20-i,p);\n}\ntemplate<int k=16>\nvoid w4(ll x){\n\tif constexpr(k==4){\n\t\tp=copy_n(&num[x][0],4,p);\n\t\treturn;\n\t}else{\n\t\tp=copy_n(&num[x/ten<ll>(k-4)][0],4,p);\n\t\tw4<k-4>(x%ten<ll>(k-4));\n\t}\n}\ntemplate<class T>\nenable_if_t<is_128<T>>pr(T x){\n\tflush(40);\n\tif(x<0)*p++='-',x=-x;\n\tif(x<ten<T>(16))pr(static_cast<ll>(x));\n\telse if(x<ten<T>(32)){\n\t\tpr(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}else{\n\t\tpr(static_cast<int>(x/ten<T>(32)));\n\t\tx%=ten<T>(32);\n\t\tw4(static_cast<ll>(x/ten<T>(16)));\n\t\tw4(static_cast<ll>(x%ten<T>(16)));\n\t}\n}\ntemplate<class T,class U>\nvoid pr(pair<T,U>x){pr(x.first),pr(' '),pr(x.second);}\ntemplate<int k=0,class T>\nvoid pr_tup(T x){\n\tif constexpr(k<tuple_size<T>::value){\n\t\tif constexpr(k)pr(' ');\n\t\tpr(get<k>(x));\n\t\tpr_tup<k+1>(x);\n\t}\n}\ntemplate<class...T>\nvoid pr(tuple<T...>x){pr_tup(x);}\ntemplate<class T>\nvoid pr(vector<T>a){\n\tint n=a.size();\n\tfor(int i=0;i<n;++i){\n\t\tif(i)pr(' ');\n\t\tpr(a[i]);\n\t}\n}\ntemplate<class T>O&operator<<(T x){pr(x);return *this;}\n}_o;\nvoid flush(){_o.flush();}\n}\nusing io::flush;\n#define cin io::_i\n#define cout io::_o\nint main(){\n\tint n,m;\n\tcin>>n>>m;\n\tauto c=vector(n,vector(n,0));\n\tfor(int i=0;i<m;i++){\n\t\tint u,v,w;\n\t\tcin>>u>>v>>w;\n\t\tc[u][v]+=w;\n\t}\n\tvector<bool>vis(n);\n\tauto dfs=[&](auto dfs,int u)->bool{\n\t\tif(u==n-1)return 1;\n\t\tif(vis[u])return 0;\n\t\tvis[u]=1;\n\t\tfor(int v=0;v<n;v++)if(c[u][v]&&dfs(dfs,v)){\n\t\t\tc[u][v]--;\n\t\t\tc[v][u]++;\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t};\n\tint ans=0;\n\tbool upd=1;\n\twhile(upd){\n\t\tupd=0;\n\t\tvis.assign(n,0);\n\t\twhile(dfs(dfs,0))ans++,upd=1;\n\t}\n\tcout<<ans<<'\\n';\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 3524, "score_of_the_acc": -1.1045, "final_rank": 20 }, { "submission_id": "aoj_GRL_6_A_10527107", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing vb=vector<bool>;\n#define rep(i,s,e) for(int i=s;i<e;i++)\n#define in(v,seq) for(auto v:seq)\n#define print(s) cout << s << endl;\nconst int I_INF=1<<30;\n\nstruct Edge{\n int to; // 行先\n int rem; // 残余\n int rev; // 逆辺のindex\n Edge(int t,int rm,int rv):to(t),rem(rm),rev(rv){}\n};\nusing Graph=vector<vector<Edge>>;\n\nint vertex,edge;\nGraph G;\nvb seen;\n\n// v:現在の頂点 t:ゴール f:そのパスに流せる水量\nint dfs(int v,int t,int f){\n if(v==t) return f; // ゴールしたら一気にreturn開始\n\n seen[v]=true;\n in(&e,G[v]){\n if(seen[e.to] || e.rem==0) continue;\n\n int res=dfs(e.to,t,min(f,e.rem));\n if(res<=0) continue;\n e.rem-=res;\n G[e.to][e.rev].rem+=res;\n return res;\n }\n\n return 0; // パスが存在しない\n}\n\nint main(){\n cin >> vertex >> edge;\n G.resize(vertex);\n rep(i,0,edge){\n int s,e,r; cin >> s >> e >> r;\n G[s].emplace_back(e,r,G[e].size()); //sizeが逆辺のindexになることに注意\n G[e].emplace_back(s,0,G[s].size()-1); // 逆辺 \"-1\"が必要なことに注意\n }\n\n int ans=0;\n while(true){\n seen.assign(vertex,false);\n int flow=dfs(0,vertex-1,I_INF);\n if(flow==0) break; // パスがなかったら終わり\n ans+=flow;\n }\n\n print(ans);\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3584, "score_of_the_acc": -0.5171, "final_rank": 10 }, { "submission_id": "aoj_GRL_6_A_10447925", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint dfs(int s, int t, int flow_amount, vector<vector<int>>& capacity, vector<bool>& used) {\n if (s == t) return flow_amount;\n used[s] = true;\n\n for (int i = 0; i < capacity.size(); i++) {\n if (capacity[s][i] > 0 && !used[i]) {\n int possible_flow = dfs(i, t, min(flow_amount, capacity[s][i]), capacity, used);\n if (possible_flow > 0) {\n capacity[s][i] -= possible_flow;\n capacity[i][s] += possible_flow;\n return possible_flow;\n }\n }\n }\n return 0;\n}\n\n\nint main() {\n int v, e;\n cin >> v >> e;\n vector<vector<int>> capacity(v, vector<int>(v,0));\n for (int i = 0; i < e; i++) {\n int a, b, c;\n cin >> a >> b >> c;\n capacity[a][b] = c;\n }\n\n int source = 0;\n int sink = v-1;\n int max_flow = 0;\n\n while (true) {\n vector<bool> used(v,false);\n int f = dfs(source, sink, INT_MAX, capacity, used);\n if (f == 0) break;\n max_flow += f;\n }\n\n cout << max_flow << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3488, "score_of_the_acc": -0.2903, "final_rank": 7 }, { "submission_id": "aoj_GRL_6_A_10375594", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define all(v) v.begin(),v.end()\n#define resort(v) sort(v.rbegin(),v.rend())\nusing ll = long long;\nusing ull = unsigned long long;\nusing vll=vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing P = pair<ll,ll>;\nusing vp=vector<pair<ll, ll>>;\nusing djks=priority_queue<P, vp, greater<P>>;\n\nconst ll inf=1ll<<60;\n#define mod10 (ll)1e9+7\n#define mod99 (ll)998244353\nconst double PI = acos(-1);\n\n#define rep(i,n) for (ll i=0;i<n;++i)\n#define per(i,n) for(ll i=n-1;i>=0;--i)\n#define rep2(i,a,n) for (ll i=a;i<n;++i)\n#define per2(i,a,n) for (ll i=n-1;i>=a;--i)\n\n\ntemplate<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }\ntemplate<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }\n\nll dx[] = {1, 0, -1, 0, -1, 1, -1, 1};\nll dy[] = {0, 1, 0, -1, -1, 1, 1, -1};\n\nvoid solve() {\n int n, m; cin >> n >> m;\n vvll g(n, vll(n, 0)); // g_i,j := 頂点iから頂点jへ向かう容量の最大\n int u, v, w;\n rep(_,m){\n cin >> u >> v >> w;\n g[u][v] += w;\n }\n\n ll sum = 0;\n rep(i,n) sum+=g[0][i];\n\n vector<pair<int, int>> tracking;\n vector<bool> seen(n, false);\n while(true) {\n stack<pair<int, int>> stk;\n \n // dfs\n stk.push({0, 1<<30});\n \n while(!stk.empty() && !seen[n-1]) {\n auto [p, flow] = stk.top(); stk.pop();\n\n if(p<0||p>=n) {\n // 帰りがけ\n assert(!tracking.empty());\n tracking.pop_back();\n } else {\n if(seen[p]) { continue; }\n seen[p] = true;\n \n // 行きがけ\n tracking.push_back({p, flow});\n stk.push({~p, 0});\n\n rep(i, n) {\n if(g[p][i] > 0 && !seen[i]) {\n stk.push({ i, g[p][i] });\n }\n }\n }\n }\n\n if(tracking.empty()) break; // 路が存在しない\n\n int flow = 1<<30;\n for(auto[_, s]: tracking) {\n chmin(flow, s);\n }\n \n rep(i, tracking.size()-1) {\n auto [from, _] = tracking[i];\n auto [to, __] = tracking[i+1];\n\n g[from][to] -= flow;\n g[to][from] += flow;\n\n assert(g[from][to] >= 0);\n }\n tracking.clear();\n fill(all(seen), false);\n }\n\n ll d = 0;\n rep(i,n) d += g[0][i];\n cout << sum - d << '\\n';\n}\n\nint main() {\n cin.tie(0);\n ios::sync_with_stdio(false);\n int t=1;\n //cin >> t;\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3552, "score_of_the_acc": -0.3859, "final_rank": 9 }, { "submission_id": "aoj_GRL_6_A_10374532", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nstruct maxflow{\n\tint n;\n\tvector<vector<int>>c;\n\tvector<bool>vis;\n\tmaxflow(int n):n(n),c(n,vector<int>(n)){}\n\tvoid add_edge(int u,int v,int w){c[u][v]+=w;}\n\tbool dfs(int u,int t){\n\t\tif(u==t)return 1;\n\t\tif(vis[u])return 0;vis[u]=1;\n\t\tfor(int v=0;v<n;v++)if(c[u][v]&&dfs(v,t)){c[u][v]--,c[v][u]++;return 1;}\n\t\treturn 0;\n\t}\n\tint flow(int s,int t){int f=0;while(vis.assign(n,0),dfs(s,t))f++;return f;}\n};\nint main(){\n\tios::sync_with_stdio(0),cin.tie(0);\n\tint n,m;\n\tcin>>n>>m;\n\tmaxflow mf(n);\n\twhile(m--){\n\t\tint u,v,w;\n\t\tcin>>u>>v>>w;\n\t\tmf.add_edge(u,v,w);\n\t}\n\tcout<<mf.flow(0,n-1)<<'\\n';\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 3500, "score_of_the_acc": -0.8811, "final_rank": 13 }, { "submission_id": "aoj_GRL_6_A_10313605", "code_snippet": "#include <bits/stdc++.h>\n//#include <atcoder/all>\nusing namespace std;\n//using namespace atcoder;\nusing ll = long long;\nusing ld = long double;\n#define m_p make_pair\n#define pii pair<int,int>\n#define pll pair<ll,ll>\n#define pil pair<int,ll>\n#define pli pair<ll,int>\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)\n#define grep(i, k, n) for(ll i=(ll)(k); i<(ll)(n); i++)\n#define all(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend() //降順\ntemplate<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }\n//using mint = modint998244353;\n//using mint = modint1000000007;\n\nclass MaxFlow{\nprivate:\n constexpr static long long int LINF = 2e18;\n int V, E;\n struct edge {int to; long long int cap; int rev;};\n vector<vector<edge>> g;\n vector<bool> vis;\n\npublic:\n MaxFlow(int V_, int E_) : V(V_), E(E_), g(V_), vis(V_, false) {};\n\n void add_edge(int from, int to, long long int cap){\n g[from].push_back((edge){to, cap, int(g[to].size())});\n g[to].push_back((edge){from, 0, int(g[from].size()) - 1});\n }\n\nprivate:\n long long int dfs(int u, int t, long long int f){\n if(u == t) return f;\n vis[u] = true;\n for(int i=0; i<g[u].size(); i++){\n edge e = g[u][i];\n if(!vis[e.to] && e.cap>0){\n long long int d = dfs(e.to, t, min(f, e.cap));\n if(d > 0){\n g[u][i].cap -= d;\n g[e.to][e.rev].cap += d;\n return d;\n }\n }\n }\n return 0;\n }\n\npublic:\n long long int max_flow(int s, int t){\n int flow = 0;\n while(true){\n vis.assign(V, false);\n long long int f = dfs(s, t, LINF);\n if(f == 0) return flow;\n flow += f;\n }\n }\n};\n\nint main(){\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int v,e;cin>>v>>e;\n MaxFlow mf(v, e);\n rep(i,e){\n int u,v;ll c;cin>>u>>v>>c;\n mf.add_edge(u,v,c);\n }\n cout<<mf.max_flow(0,v-1)<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3516, "score_of_the_acc": -0.1967, "final_rank": 4 }, { "submission_id": "aoj_GRL_6_A_10256855", "code_snippet": "#include <iostream>\n#include <stack>\nusing namespace std;\n\nint main()\n{\n int V, E;\n cin >> V >> E;\n\n int G[100][100] = {{0}};\n\n for(int i=0; i<E; i++){\n int u, v, c;\n cin >> u >> v >> c;\n G[u][v] = c;\n }\n\n int F = 0;\n\n while(true){\n stack<int> S;\n int d[100] = {0};\n S.push(0);\n d[0] = 1;\n\n while(!S.empty()){\n int u = S.top();\n int v = -1;\n\n for(int j=0; j<V; j++){\n if(G[u][j]>0 && d[j]==0){\n v = j;\n break;\n }\n }\n if(v!=-1){\n S.push(v);\n d[v] = 1;\n }\n else{\n S.pop();\n }\n if(v==V-1){\n break;\n }\n }\n if(S.empty()){\n cout << F << endl;\n return 0;\n }\n F++;\n\n int s, t;\n s = S.top();\n S.pop();\n\n while(!S.empty()){\n t = s;\n s = S.top();\n S.pop();\n \n G[s][t]--;\n G[t][s]++;\n }\n }\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 3484, "score_of_the_acc": -1.0656, "final_rank": 18 }, { "submission_id": "aoj_GRL_6_A_10143566", "code_snippet": "#if __has_include(<atcoder/all>)\n#include<atcoder/all>\nusing namespace atcoder;\nusing mint=modint998244353;\nusing mint1=modint1000000007;\n#endif\n#if __has_include(<ext/pb_ds/assoc_container.hpp>) && __has_include(<ext/pb_ds/tree_policy.hpp>)\n#include<ext/pb_ds/assoc_container.hpp>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\ntemplate<class s,class t>using __gnu_map=tree<s,t,std::less<s>,rb_tree_tag,tree_order_statistics_node_update>;\ntemplate<class s,class t>struct gnu_map:public __gnu_map<s,t>{\n\tusing iterator=typename __gnu_map<s,t>::iterator;\n\titerator get(int64_t idx){return this->find_by_order(idx<0?this->size()-idx:idx);}\n\tsize_t ord(const s&key){return this->order_of_key(key);}\n};\ntemplate<class s>struct gnu_set:public gnu_map<s,null_type>{gnu_map<s,null_type>::iterator operator[](int64_t i){return this->get(i);}};\n#endif\n#include <bits/stdc++.h>\nusing namespace std;\nusing std::cin;\nusing std::cout;\nusing sstream=stringstream;\n#define RET return\n#define int long long\n#define itn long long\n#define fi first\n#define se second\n#define endl '\\n'\n#define sn(i,c) \" \\n\"[i==c];\n#define rsv(n) reserve(n)\n#define pf(a) push_front(a)\n#define pb(a) push_back(a)\n#define eb(...) emplace_back(__VA_ARGS__)\n#define ppf() pop_front()\n#define ppb() pop_back()\n#define pp() pop()\n#define ins(a) insert(a)\n#define emp(...) emplace(__VA_ARGS__)\n#define ers(a) erase(a)\n#define cont(a) contains(a)\n#define mp(f,s) make_pair(f,s)\n#define A(a) begin(a),end(a)\n#define I(a,i) begin(a),begin(a)+(i)\n#define elif(c) else if(c)\n#define _SEL4(_1,_2,_3,_4,name,...) name\n#define _SEL3(_1,_2,_3,name,...) name\n#define _REP4(i,s,n,st) for(int i=(s);i<(n);i+=(st))\n#define _REP3(i,s,n) _REP4(i,s,n,1)\n#define _REP2(i,n) _REP3(i,0,n)\n#define _REP1(n) _REP2(_,n)\n#define _RREP4(i,n,t,s) for(int i=(n);i>=(t);i-=(s))\n#define _RREP3(i,n,t) _RREP4(i,n,t,1)\n#define _RREP2(i,n) _RREP3(i,n,0)\n#define _ITER2(x,a) for(auto&x:a)\n#define _ITER3(x,y,a) for(auto&[x,y]:a)\n#define _CTER2(x,a) for(const auto&x:a)\n#define _CTER3(x,y,a) for(const auto&[x,y]:a)\n#define rep(...) _SEL4(__VA_ARGS__,_REP4,_REP3,_REP2,_REP1)(__VA_ARGS__)\n#define rrep(...) _SEL4(__VA_ARGS__,_RREP4,_RREP3,_RREP2,_REP1)(__VA_ARGS__)\n#define forif(c,...) rep(__VA_ARGS__)if(c)\n#define iter(...) _SEL3(__VA_ARGS__,_ITER3,_ITER2)(__VA_ARGS__)\n#define cter(...) _SEL3(__VA_ARGS__,_CTER3,_CTER2)(__VA_ARGS__)\n#define _LB_BEX(b,e,x) lower_bound(b,e,x)\n#define _LB_BEXG(b,e,x,g) lower_bound(b,e,x,g)\n#define _UB_BEX(b,e,x) upper_bound(b,e,x)\n#define _UB_BEXG(b,e,x,g) upper_bound(b,e,x,g)\n#define lb(...) _SEL4(__VA_ARGS__,_LB_BEXG,_LB_BEX)(__VA_ARGS__)\n#define ub(...) _SEL4(__VA_ARGS__,_UB_BEXG,_UB_BEX)(__VA_ARGS__)\n#define rev(a) reverse(A(a))\n#define minel(a) min_element(A(a))\n#define maxel(a) max_element(A(a))\n#define acm(a) accumulate(A(a),0ll)\n#define nxpm(a) next_permutation(A(a))\n#define Sort(a) sort(A(a))\n#define uni(a) Sort(a);a.erase(unique(A(a)),a.end())\n#define swapcase(a) a=(isalpha(a)?a^32:a)\n#define NL cout<<'\\n'\ntemplate<class f>using gr=greater<f>;\ntemplate<class f>using vc=vector<f>;\ntemplate<class f>using vv=vc<vc<f>>;\ntemplate<class f>using v3=vv<vc<f>>;\ntemplate<class f>using v4=vv<vv<f>>;\ntemplate<class f>using pq=priority_queue<f>;\ntemplate<class f>using pqg=priority_queue<f, vc<f>, gr<f>>;\n#define uset unordered_set\n#define umap unordered_map\nusing i8=int8_t; using i16=int16_t; using i32=int32_t; using i64=int64_t; using i128=__int128_t;\nusing u8=uint8_t;using u16=uint16_t;using u32=uint32_t;using u64=uint64_t;using u128=__uint128_t;\nusing intw=__int128_t;using uintw=__uint128_t; using it=i32;\nusing f32=float;using f64=double;using f128=long double;\nusing vi=vc<int>;using vb=vc<bool>;\nusing pi=pair<int,int>;\nusing str=string;using vs=vc<str>;\nusing pqgp=pqg<pi>;\n#define double f128\nconstexpr int inf=1ll<<60,minf=-inf;\nconstexpr char sep='\\n';\nconstexpr array<pi,8>dc={{{1,0},{0,1},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}};\ntemplate<class T,class U>inline void chmax(T&a,const U&b){if(a<b)a=b;}\ntemplate<class T,class U>inline void chmin(T&a,const U&b){if(a>b)a=b;}\n#define yes cout<<\"Yes\\n\"\n#define no cout<<\"No\\n\"\n#define yn(c) (c)?yes:no\n#if __cplusplus <= 202002L\n#else\n#define C const\nnamespace vies=std::views;\n#define DR(i) views::drop(i)\n#define TK(i) views::take(i)\n#define RV views::reverse\n#define IOTA vies::iota\n#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)\n#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)\n#define STR(...) str __VA_ARGS__;in(__VA_ARGS__)\n#define VI(a,n) vi a(n);in(a)\n#define VS(a,n) vs a(n);in(a)\n#define UV(u,v) INT(u,v);u--,v--\n#define UVW(u,v,w) INT(u,v,w);u--,v--\ntemplate<integral T,integral U>inline auto ceil(C T a,C U b){return(a+b-1)/b;}\ntemplate<integral T,integral U>inline auto floor(C T a,C U b){return a/b-(a%b&&(a^b)<0);}\ntemplate<class T,class U>concept LUBI= same_as<T,vc<U>>||same_as<T,deque<U>>||is_array_v<T>;\n#define TP template<class T,class U,typename cp=less<U>>\n#define RL requires LUBI<T,U>\nTP u64 lbi(C T&v,C U&x,cp cmp=cp())RL{RET lb(A(v),x,cmp)-begin(v);}\nTP u64 ubi(C T&v,C U&x,cp cmp=cp())RL{RET ub(A(v),x,cmp)-begin(v);}\nTP u64 lbi(u64 i,C T&v,C U&x,cp cmp=cp())RL{RET lb(i+A(v),x,cmp)-begin(v);}\nTP u64 ubi(u64 i,C T&v,C U&x,cp cmp=cp())RL{RET ub(i+A(v),x,cmp)-begin(v);}\nTP u64 lbi(C T&v,u64 i,C U&x,cp cmp=cp())RL{RET lb(I(v,i),x,cmp)-begin(v);}\nTP u64 ubi(C T&v,u64 i,C U&x,cp cmp=cp())RL{RET ub(I(v,i),x,cmp)-begin(v);}\nTP u64 lbi(u64 i,C T&v,u64 e,C U&x,cp cmp=cp())RL{RET lb(i+I(v,e),x,cmp)-begin(v);}\nTP u64 ubi(u64 i,C T&v,u64 e,C U&x,cp cmp=cp())RL{RET ub(i+I(v,e),x,cmp)-begin(v);}\n#undef TP\n#undef RL\n#define TP template\nTP<class T>concept Lint=is_integral_v<T>&&sizeof(T)>8;\nTP<Lint T>ostream&operator<<(ostream&dst,T val){\n\tostream::sentry s(dst);\n\tif(!s)return dst;\n\tchar _O128[64];\n\tchar*d=end(_O128);\n\tbool vsign=val<0;\n\tuintw v=val;\n\tif(vsign&&val!=numeric_limits<T>::min())v=1+~(uintw)val;\n\tdo{\n\t\t*(--d)=\"0123456789\"[v%10];\n\t\tv/=10;\n\t}while(v!=0);\n\tif(vsign)*(--d)='-';\n\tsize_t len=end(_O128)-d;\n\tif(dst.rdbuf()->sputn(d,len)!=len)dst.setstate(ios_base::badbit);\n\treturn dst;\n}\nTP<Lint T>istream&operator>>(istream&src,T&val) {\n\tstr s;src>>s;\n\tbool is_neg=numeric_limits<T>::is_signed&&s.size()>0&&s[0]=='-';\n\tfor(val=0;C auto&x:s|views::drop(is_neg))val=10*val+x-'0';\n\tif(is_neg)val*=-1;\n\treturn src;\n}\n#define MUT make_unsigned_t\nTP<integral T>i32 pcnt(T p){return popcount(MUT<T>(p));}\nTP<integral T>i32 lsb(T p){return countl_zero(MUT<T>(p));}\nTP<integral T>i32 msb(T p){return countr_zero(MUT<T>(p));}\nTP<i32 N,integral T>void putbit(T s){\n\tchar buf[N+1]={0};\n\tfor(char*itr=buf+N-1;itr>=buf;itr--,s>>=1)\n\t\t*itr='0'+(s&1);\n\tcout<<buf<<sep;\n}\nTP<class T>concept Itrabl=requires(C T&x){x.begin();x.end();}&&!std::is_same_v<T,string>;\nTP<class T>concept IItrabl=Itrabl<T>&&Itrabl<typename T::value_type>;\nTP<class T>concept ModInt=requires(C T&x){x.val();};\nTP<class T>concept NLobj=Itrabl<T>||std::is_same_v<T,string>;\nTP<ModInt T>istream&operator>>(istream&is,T&v){int x;is>>x;v=x;return is;}\nTP<Itrabl T>istream&operator>>(istream&is,T&v){iter(x,v)is>>x;return is;}\nTP<class T,class U>istream&operator>>(istream&is,pair<T,U>&v){return is>>v.first>>v.second;}\nTP<class T>void in(T&a){cin>>a;}\nTP<class T,class... Ts>void in(T&a,Ts&... b){in(a);in(b...);}\nTP<class T,class U>vc<pair<T,U>>zip(size_t n,size_t m){\n\tvc<pair<T,U>>r(min(n,m));\n\titer(x,y,r)in(x);\n\titer(x,y,r)in(y);\n\treturn move(r);\n}\nTP<class T,class U>vc<pair<T,U>>zip(size_t n){return move(zip<T,U>(n,n));}\nTP<ModInt T>ostream&operator<<(ostream&os,const T&v){return os<<v.val(); }\nTP<Itrabl T>ostream&operator<<(ostream&os,const T&v){int cnt=0;cter(x,v)os<<x<<(++cnt<v.size()?\" \":\"\");return os;}\nTP<IItrabl T>ostream&operator<<(ostream&os,const T&v){int cnt=0;cter(x,v)os<<x<<(++cnt<v.size()?\"\\n\":\"\");return os;}\nTP<class T,class U>ostream&operator<<(ostream&os,const pair<T,U>&v){return os<<'('<<v.first<<','<<v.second<<')';}\nostream*dos=&cout;\nint32_t OFLG; // 0:first, 1:notNLobj, 2:NLobj\nTP<class T>void _out(const T&a){if(OFLG)(*dos)<<\"0 \\n\"[OFLG]<<a;else(*dos)<<a;OFLG=1;}\nTP<NLobj T>void _out(const T&a){(*dos)<<(OFLG?\"\\n\":\"\")<<a;OFLG=2;}\nTP<class T,class...Ts>void _out(const T&a,const Ts&... b){_out(a);_out(b...);}\nTP<class... Ts>void out(const Ts&... v){OFLG=0;_out(v...);(*dos)<<sep;}\n#undef TP\n#undef C\n#endif\n#ifdef LOCAL\n#define dput(...) dos=&cerr;putv(__VA_ARGS__);dos=&cout\n#else\n#define dput(...)\n#endif\n\n#undef rev\n\ntemplate<class type>\nclass max_flow{\n\tclass edge {\n\t\tpublic:\n\t\t\tedge(int64_t u, type c, int64_t r):to(u),cap(c),rev(r) {}\n\t\t\tint64_t to, rev;\n\t\t\ttype cap;\n\t};\n\tvector<vector<edge>>e;\n\tvector<bool>seen;\n\tint64_t g,r;\n\tint64_t dfs(int64_t now,type ret){\n\t\tif(now==g)return ret;\n\t\tseen[now]=true;\n\t\tfor(auto&x:e[now]){\n\t\t\tif(x.cap==0||seen[x.to])continue;\n\t\t\tint64_t p=dfs(x.to,min(x.cap,ret));\n\t\t\tif(p){\n\t\t\t\tx.cap-=p;\n\t\t\t\te[x.to][x.rev].cap+=p;\n\t\t\t\treturn p;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\tpublic:\n\t\tmax_flow(int64_t n){ e.resize(n), seen.resize(n); }\n\t\tvoid add(int64_t u,int64_t v,type c){\n\t\t\tint64_t ru=e[u].size(),rv=e[v].size();\n\t\t\te[u].pb(edge(v,c,rv)), e[v].pb(edge(u,static_cast<type>(0),ru));\n\t\t}\n\t\tint64_t flow(int64_t s,int64_t t){\n\t\t\tg=t,r=0;\n\t\t\twhile(1){\n\t\t\t\tfill(A(seen),false);\n\t\t\t\tint64_t p=dfs(s,1ll<<62);\n\t\t\t\tif(p)r+=p;\n\t\t\t\telse break;\n\t\t\t}\n\t\t\treturn r;\n\t\t}\n};\nvoid slv(){\n\tINT(n,m);\n\t::max_flow<int>mf(n);\n\trep(m){\n\t\tINT(a,b,c);\n\t\tmf.add(a,b,c);\n\t}\n\tout(mf.flow(0,n-1));\n}\n\nsigned main(){\n\tcin.tie(0)->sync_with_stdio(0);\n\tcout<<fixed<<setprecision(15);\n\tslv();\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3712, "score_of_the_acc": -1.0417, "final_rank": 17 }, { "submission_id": "aoj_GRL_6_A_10132697", "code_snippet": "#include <iostream>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <algorithm>\n#include <climits>\n\nclass MaximumFlow{\n std::unordered_map<int, std::unordered_map<int,int>> mFlowNetwork;\n int mSource;\n int mSink;\n\n std::unordered_map<int, std::unordered_map<int,int>> mResidualNetwork;\n std::vector<int> mAugmentationPath;\n int mAddedFlow;\n\n std::unordered_map<int, std::unordered_map<int,int>> mFlow;\n int mFlowValue;\n\n void updateFlowNetwork(){\n int from = mSource;\n for (int to : mAugmentationPath){\n mResidualNetwork.at(from).at(to) -= mAddedFlow;\n mResidualNetwork.at(to).at(from) += mAddedFlow;\n\n from = to;\n }\n }\n\n bool dfs(int currentVertex, std::unordered_map<int,bool>& isVisited, int currentMaxCapacity){\n auto iter = mResidualNetwork.at(currentVertex).find(mSink);\n if (iter != mResidualNetwork.at(currentVertex).end() && (*iter).second > 0){\n mAugmentationPath.push_back(mSink);\n mAddedFlow = std::min(currentMaxCapacity, (*iter).second);\n return true;\n }\n\n for (std::pair<int,int> edge : mResidualNetwork.at(currentVertex)){\n int to = edge.first;\n int capacity = edge.second;\n\n if (!isVisited.at(to) && capacity > 0){\n isVisited.at(to) = true;\n mAugmentationPath.push_back(to);\n if (dfs(to, isVisited, std::min(currentMaxCapacity, capacity))){\n return true;\n } else {\n mAugmentationPath.pop_back();\n }\n }\n }\n\n return false;\n }\n\n bool FindAugmentationPath(){\n mAugmentationPath.clear();\n mAddedFlow = 0;\n\n std::unordered_map<int,bool> isVisited;\n for (const std::pair<int,std::unordered_map<int,int>>& edge : mResidualNetwork){\n isVisited[edge.first] = false;\n }\n\n isVisited.at(mSource) = true;\n return dfs(mSource, isVisited, INT_MAX);\n }\n\n void calcFlow(){\n for (std::pair<int, std::unordered_map<int,int>> edgeSet : mFlowNetwork){\n int from = edgeSet.first;\n mFlow[from] = std::unordered_map<int,int>();\n for (std::pair<int,int> edge : edgeSet.second){\n int to = edge.first;\n mFlow.at(from)[to] = mFlowNetwork.at(from).at(to) - mResidualNetwork.at(from).at(to);\n }\n }\n\n mFlowValue = 0;\n for (std::pair<int,int> edge : mFlow.at(mSource)){\n mFlowValue += edge.second;\n }\n }\n\npublic:\n MaximumFlow(std::unordered_map<int, std::unordered_map<int,int>> flowNetwork, int source, int sink)\n : mFlowNetwork(flowNetwork), mSource(source), mSink(sink), mResidualNetwork(flowNetwork) {\n for (std::pair<int, std::unordered_map<int,int>> edgeSet : mFlowNetwork){\n int from = edgeSet.first;\n for (std::pair<int,int> edge : edgeSet.second){\n int to = edge.first;\n mResidualNetwork.at(to)[from] = 0;\n }\n }\n mAugmentationPath.clear();\n mAddedFlow = 0;\n }\n\n void FordFulkerson(){\n bool existsAugmentationPath = true;\n\n while (existsAugmentationPath){\n updateFlowNetwork();\n existsAugmentationPath = FindAugmentationPath();\n }\n\n calcFlow();\n }\n\n int getFlowValue() const { return mFlowValue; }\n};\n\nint main(){\n std::unordered_map<int, std::unordered_map<int,int>> flowNetwork;\n int N, M;\n std::cin >> N >> M;\n for (int n = 0; n < N; ++n){\n flowNetwork[n] = std::unordered_map<int,int>();\n }\n\n for (int m = 0; m < M; ++m){\n int u, v, c;\n std::cin >> u >> v >> c;\n flowNetwork.at(u)[v] = c;\n }\n\n MaximumFlow mf(flowNetwork, 0, N-1);\n mf.FordFulkerson();\n std::cout << mf.getFlowValue() << std::endl;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 3608, "score_of_the_acc": -0.8654, "final_rank": 11 }, { "submission_id": "aoj_GRL_6_A_10105990", "code_snippet": "#include <iostream>\n#include <stack>\nusing namespace std;\n\nint main(){\n int V, E;\n cin >> V >> E;\n int G[100][100] = {{0}};\n for(int i=0; i<E; i++){\n int u, v, c;\n cin >> u >> v >> c;\n G[u][v] = c;\n }\n int F = 0;\n while(true){\n stack<int> S;\n int d[100] = {0};\n S.push(0);\n d[0] = 1;\n while(!S.empty()){\n int u = S.top();\n int v = -1;\n for(int j=0; j<V; j++){\n if(G[u][j]>0 && d[j]==0){\n v = j;\n break;\n }\n }\n if(v!=-1){\n S.push(v);\n d[v] = 1;\n }else{\n S.pop();\n }\n if(v==V-1){\n break;\n }\n }\n if(S.empty()){\n cout << F << endl;\n return 0;\n }\n F++;\n int s, t;\n s = S.top();\n S.pop();\n while(!S.empty()){\n t = s;\n s = S.top();\n S.pop();\n G[s][t]--;\n G[t][s]++;\n }\n }\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 3468, "score_of_the_acc": -1, "final_rank": 15 }, { "submission_id": "aoj_GRL_6_A_10083042", "code_snippet": "// 2025/01/09 Tazoe\n\n#include <iostream>\n#include <stack>\nusing namespace std;\n\nint main()\n{\n\tint V, E;\n\tcin >> V >> E;\n\t\n\tint G[100][100] = {{0}};\n\tfor(int i=0; i<E; i++){\n\t\tint u, v, c;\n\t\tcin >> u >> v >> c;\n\t\t\n\t\tG[u][v] = c;\n\t}\n\t\n\tint F = 0;\t\t\t// フロー\n\t\n\twhile(true){\n\t\t// 深さ優先探索\n\t\tstack<int> S;\n\t\tint d[100] = {0};\n\t\t\n\t\tS.push(0);\n\t\td[0] = 1;\n\t\t\n\t\twhile(!S.empty()){\n\t\t\tint u = S.top();\n\t\t\t\n\t\t\tint v = -1;\n\t\t\tfor(int j=0; j<V; j++){\n\t\t\t\tif(G[u][j]>0 && d[j]==0){\n\t\t\t\t\tv = j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(v!=-1){\n\t\t\t\tS.push(v);\n\t\t\t\td[v] = 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tS.pop();\n\t\t\t}\n\t\t\t\n\t\t\tif(v==V-1){\t\t\t\t// 終点に辿りついたら\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(S.empty()){\t\t\t// 終点に辿りつけなかったら終了\n\t\t\tcout << F << endl;\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tF++;\t\t\t// フローを増やす\n\t\t\n\t\t// 行列を書き換える\n\t\tint s, t;\n\t\ts = S.top();\n\t\tS.pop();\n\t\t\n\t\twhile(!S.empty()){\n\t\t\tt = s;\n\t\t\ts = S.top();\n\t\t\tS.pop();\n\t\t\t\n\t\t\tG[s][t]--;\n\t\t\tG[t][s]++;\n\t\t}\n\t}\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 3484, "score_of_the_acc": -1.0656, "final_rank": 18 }, { "submission_id": "aoj_GRL_6_A_10081529", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing pint = pair<int,int>;\nusing pll = pair<long long, long long>;\n\n#define v(a,i,b) vector<ll> a(i,b)\n#define vv(a,i,j,b) vector<vector<ll>> a(i, vector<ll>(j,b))\n#define vp(a,i,b,c) vector<pll>> a(i,{b,c})\n#define vvp(a,i,j,b,c) vector<vector<pll>> a(i, vector<>>(j,{b,c}))\n\n#define rrep1(a) for(ll i = (ll)(a-1); i >= (ll)0 ; i--)\n#define rrep2(i, a) for(ll i = (ll)(a-1); i >= (ll)0; i--)\n#define rrep3(i, a, b) for(ll i = (ll)(a-1); i >=(b); i--)\n#define rrep4(i, a, b, c) for(ll i = (ll)(a-1); i >=(b); i -= (c))\n#define overload4(a, b, c, d, e, ...) e\n#define rrep(...) overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)\n\n#define rep1(a) for(ll i = 0; i < (ll)(a); i++)\n#define rep2(i, a) for(ll i = 0; i < (ll)(a); i++)\n#define rep3(i, a, b) for(ll i = (a); i < (ll)(b); i++)\n#define rep4(i, a, b, c) for(ll i = (a); i < (ll)(b); i += (c))\n#define overload4(a, b, c, d, e, ...) e\n#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)\n\n#define fi first\n#define se second\n#define pb push_back\n#define spa \" \"\n\n//!?!?\n#define O print\n\ninline void scan(){}\ntemplate<class Head,class... Tail>\ninline void scan(Head&head,Tail&... tail){std::cin>>head;scan(tail...);}\n#define LL(...) ll __VA_ARGS__;scan(__VA_ARGS__)\n#define STR(...) string __VA_ARGS__;scan(__VA_ARGS__)\n\n//vectorのcin,cout\ntemplate<typename T>\nstd::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?\" \":\"\");}return os;}\n//dequeのcin,cout\ntemplate<typename T>\nstd::istream &operator>>(std::istream&is,std::deque<T>&v){for(T &in:v){is>>in;}return is;}\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream&os,const std::deque<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?\" \":\"\");}return os;}\n//pairのcin,cout\ntemplate<typename T,typename U>\nstd::ostream &operator<<(std::ostream&os,const std::pair<T,U>&p){os<<p.first<<\" \"<<p.second;return os;}\ntemplate<typename T,typename U>\nstd::istream &operator>>(std::istream&is,std::pair<T,U>&p){is>>p.first>>p.second;return is;}\n//vector<vector<T>>のcout\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<std::vector<T>> &v) {\nfor (const auto &row : v) {for (auto it = row.begin(); it != row.end(); ++it) { os << *it; if (std::next(it) != row.end()) { os << \" \"; } } os << \"\\n\";} return os;}\n\n#pragma GCC diagnostic ignored \"-Wunused-value\"\nvoid print(){cout << '\\n';}\ntemplate<class T, class... Ts>\nvoid print(const T& a, const Ts&... b){cout << a;(std::cout << ... << (cout << ' ', b));cout << '\\n';}\n#pragma GCC diagnostic warning \"-Wunused-value\"\n\nint inf = 2147483647; // おおよそ2*10^9\nll INF = 9223372036854775807; //おおよそ9*10^18\n//ull UINF == おおよそ1.8*10^19\n\nstruct edge{\n //rev: toから行ける頂点のうち、toから見てfromが何番目に位置するか\n //G[from].size() == rev \n ll rev, from, to, cap;\n};\n\nclass fordFulkerson{\npublic:\n vector<vector<edge>> g;\n vector<bool> used;\n\n int size = 0;\n void init(int n) {\n g.resize(n);\n used.resize(n);\n size = n;\n }\n\n void add_edge(ll u, ll v, ll cost){\n g[u].pb({(ll)g[v].size(), u, v, cost});\n g[v].pb({(ll)g[u].size()-1, v, u, 0});\n }\n\n ll dfs(ll pos, ll goal, ll F){\n if(pos == goal) return F;\n used[pos] = true;\n\n for(auto &x : g[pos]){\n if(used[x.to] || x.cap <= 0) continue;\n ll d = dfs(x.to, goal, min(F, x.cap));\n if(d > 0){\n x.cap -= d;\n g[x.to][x.rev].cap += d;\n return d;\n }\n }\n return 0;\n }\n\n ll max_frow(ll start, ll goal){\n ll flow = 0;\n while(true){\n fill(used.begin(), used.end(), false);\n ll f = dfs(start, goal, INF);\n if(f == 0) return flow;\n flow += f;\n }\n return flow;\n }\n};\n\nll n,m;\n\nfordFulkerson ff;\n\nint main(){\n cin >> n >> m;\n ff.init(n);\n rep(m){\n LL(a,b,c);\n ff.add_edge(a,b,c);\n }\n cout << ff.max_frow(0,n-1) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3712, "score_of_the_acc": -1, "final_rank": 15 } ]
aoj_DPL_2_B_cpp
Chinese Postman Problem For a given weighted undirected graph G(V, E) , find the distance of the shortest route that meets the following criteria: It is a closed cycle where it ends at the same point it starts. The route must go through every edge at least once. Input |V| |E| s 0 t 0 d 0 s 1 t 1 d 1 : s |E|-1 t |E|-1 d |E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V| -1 respectively. s i and t i represent source and target verticess of i -th edge (undirected) and d i represents the distance between s i and t i (the i -th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Constraints 2 ≤ |V| ≤ 15 0 ≤ |E| ≤ 1,000 0 ≤ d i ≤ 1,000 s i ≠ t i The graph is connected Sample Input 1 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Sample Output 1 10 Sample Input 2 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Sample Output 2 18 Sample Input 3 2 3 0 1 1 0 1 2 0 1 3 Sample Output 3 7
[ { "submission_id": "aoj_DPL_2_B_6761389", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std ;\n#define MAX 1000000001\n#define NIL -2000000002\n#define INF 1e9\n#define MAXN 20\ntypedef long long int ll;\nconst int debug = 0 ; \nconst int debug1 = 0 ; \n#define REP(i,n) for(int i=0; i<(int)n; i++)\n\nint WF[1<<MAXN][MAXN] ; // DP[Sの部分集合][最後に訪問する頂点]\nint G[MAXN][MAXN];\nint edge[MAXN];\n\nint V, E;\nint ans;\nint S;\nvector<int> oddlist ; \nint M;\n\nvoid init() {\n REP (i,1<<MAXN) REP (j,MAXN) { WF[i][j] = INF; }\n REP (i,MAXN) REP (j,MAXN) {G[i][j]=INF;}\n // G[0][0]=0;\n REP (i,MAXN) WF[i][i] = 0 ;\n}\n\n\nint calc_cost(){\n // DPに各点間の距離\n for (int k=0; k< V ; k++) { \n for (int i=0 ; i<V ; i++) {\n for (int j=0; j<V; j++) { \n if (WF[i][k] ==INF || WF[k][j] ==INF ) continue;\n WF[i][j] = min (WF[i][j] , WF[i][k] + WF[k][j] ) ; \n }\n }\n } \n return 0;\n} \n\nint main(){\n cin >> V >> E ;\n //頂点の番号は 0からV-1; \n int tmp ,tmp2 , tmp3; \n int edgetotal=0;\n init();\n for (int i=1 ; i<= E ; i++){\n cin >> tmp >> tmp2 >> tmp3 ;\n // VS[tmp].edge.push_back(make_pair(tmp3, tmp2));\n G[tmp][tmp2]=tmp3;\n G[tmp2][tmp]=tmp3;\n if( tmp3 < WF[tmp][tmp2] ) {\n WF[tmp][tmp2]=tmp3;\n WF[tmp2][tmp]=tmp3; }\n edge[tmp]++; edge[tmp2]++;\n edgetotal += tmp3 ;\n }\n calc_cost(); // WF法\n REP(i,MAXN){\n if (edge[i]%2 != 0) { oddlist.push_back(i); }\n }\n M = oddlist.size();\n const int siz = 1<<M ;\n int combi_min[siz] ;\n REP (i, (1<<M)) { combi_min[i] = INF;}\n combi_min[0] = 0;\n REP (k,(1<<M)) {\n REP (i, M) {\n REP(j, M) {\n if ( ! (k & (1<<i)) || !(k &(1<<j) )) { // \n //printf (\"here k=%d i=%d j=%d\",k,i,j); \n continue;}\n if (i <= j) {continue;}\n int k_ = k ^ ( (1<<i) | (1<<j) );\n combi_min[k] = min(combi_min[k], combi_min[k_]+WF[oddlist.at(i)][oddlist.at(j)] );\n //printf(\"combi_min[k] = %d , min(combi_min[%d], combi_min[%d]=%d+WF[%d][%d]=%d ) \\n\", combi_min[k], k, k_, combi_min[k_],\\\n oddlist.at(i),oddlist.at(j),WF[oddlist.at(i)][oddlist.at(j)] );\n }\n }\n }\n ans = ( combi_min[(1<<M)-1] >= INF? INF :combi_min[(1<<M)-1] + edgetotal );\n\n if (ans == INF) {ans = -1;}\n printf(\"%d\\n\",ans ) ;\n \n /*REP (i, V) {\n cout << i << \" : \" ;\n REP (j, V) { cout << WF[i][j]<< \" \"; }\n cout << endl; }*/\n \n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 85488, "score_of_the_acc": -1, "final_rank": 6 }, { "submission_id": "aoj_DPL_2_B_6317985", "code_snippet": "// #include <bits/stdc++.h>\n#include <set>\n#include <map>\n#include <cmath>\n#include <deque>\n#include <queue>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\nusing ll = long long;\nusing VI = vector<int>;\nusing VL = vector<ll>;\nusing VD = vector<double>;\nusing VS = vector<string>;\nusing VB = vector<bool>;\nusing VVB = vector<vector<bool>>;\nusing VVI = vector<VI>;\nusing VVL = vector<VL>;\nusing VVD = vector<VD>;\nusing VVVI = vector<VVI>;\nusing VVVL = vector<VVL>;\nusing VVVD = vector<VVD>;\nusing PII = std::pair<int, int>;\nusing VPII = std::vector<std::pair<int, int>>;\nusing PLL = std::pair<ll, ll>;\nusing VPLL = std::vector<std::pair<ll, ll>>;\nusing TI3 = std::tuple<int, int, int>;\nusing TI4 = std::tuple<int, int, int, int>;\nusing TL3 = std::tuple<ll, ll, ll>;\nusing TL4 = std::tuple<ll, ll, ll, ll>;\n\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define repr(i, n) for (int i = (int)(n)-1; i >= 0; i--)\n#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)\n#define repr2(i, g, n) for (int i = (int)(n)-1; i >= (g); i--)\n#define rep3(i, s, n, d) for (int i = (s); i < (int)(n); i += (d))\n#define repr3(i, g, n, d) for (int i = (int)(n)-1; i >= (g); i -= (d))\n#define allpt(v) (v).begin(), (v).end()\n#define allpt_c(v) (v).cbegin(), (v).cend()\n#define allpt_r(v) (v).rbegin(), (v).rend()\n#define allpt_cr(v) (v).crbegin(), (v).crend()\n\nconst int mod1 = 1e9 + 7, mod2 = 998244353, mod3 = 1e9 + 9;\nconst int mod = mod1;\nconst ll inf = 1e18;\nconst int infint = 1e9;\n\nconst string wsp = \" \";\nconst string tb = \"\\t\";\nconst string rt = \"\\n\";\nconst string alphabets = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate <typename T>\nvoid show1dvec(const vector<T> &v)\n{\n if (v.size() == 0)\n return;\n int n = v.size() - 1;\n rep(i, n) cout << v[i] << wsp;\n cout << v[n] << rt;\n return;\n}\n\nint get1dcoodinate(int w, int i, int j) { return i * w + j; }\n\ntemplate <typename T, typename S>\nistream &operator>>(istream &is, pair<T, S> &v)\n{\n is >> v.first >> v.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v)\n{\n if (v.size() == 0)\n return os;\n int n = (int)v.size() - 1;\n rep(i, n) os << v[i] << wsp;\n os << v[n] << rt;\n return os;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v)\n{\n if (v.size() == 0)\n return is;\n int n = v.size();\n rep(i, n) is >> v[i];\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<vector<T>> &v)\n{\n if (v.size() == 0)\n return os;\n int n = (int)v.size();\n rep(i, n) os << v[i];\n return os;\n}\n\ntemplate <typename T>\nistream &operator>>(istream &is, vector<vector<T>> &v)\n{\n if (v.size() == 0)\n return is;\n int n = v.size();\n rep(i, n) is >> v[i];\n return is;\n}\n\ntemplate <typename T, typename S>\nistream &operator>>(istream &is, vector<pair<T, S>> &v)\n{\n if (v.size() == 0)\n return is;\n int n = v.size();\n rep(i, n) is >> v[i].first >> v[i].second;\n return is;\n}\n\ntemplate <typename T, typename S>\nostream &operator<<(ostream &os, const vector<pair<T, S>> &v)\n{\n if (v.size() == 0)\n return os;\n int n = v.size();\n rep(i, n) os << v[i].first << wsp << v[i].second << rt;\n return os;\n}\n\nvoid show2dvec(const vector<string> &v)\n{\n int n = (int)v.size();\n rep(i, n) cout << v[i] << rt;\n}\n\ntemplate <typename T>\nvoid show2dvec(const vector<vector<T>> &v)\n{\n int n = v.size();\n rep(i, n) show1dvec(v[i]);\n}\n\ntemplate <typename T>\nvoid range_sort(vector<T> &arr, int l, int r)\n{\n sort(arr.begin() + l, arr.begin() + r);\n}\n\ntemplate <typename T, typename S>\nvoid show1dpair(const vector<pair<T, S>> &v)\n{\n int n = v.size();\n rep(i, n) cout << v[i].first << v[i].second << rt;\n return;\n}\n\ntemplate <typename T, typename S>\nvoid pairzip(const vector<pair<T, S>> &v, vector<T> &t, vector<T> &s)\n{\n int n = v.size();\n rep(i, n)\n {\n t.push_back(v[i].first);\n s.push_back(v[i].second);\n }\n return;\n}\n\ntemplate <typename T>\nvoid maxvec(vector<T> &v)\n{\n T s = v[0];\n int n = v.size();\n rep(i, n - 1)\n {\n if (s > v[i + 1])\n {\n v[i + 1] = s;\n }\n s = v[i + 1];\n }\n}\n\ntemplate <typename T, typename S>\nbool myfind(T t, S s)\n{\n return find(t.cbegin(), t.cend(), s) != t.cend();\n}\n\nbool check(int y, int x, int h, int w)\n{\n return 0 <= y && y < h && 0 <= x && x < w;\n}\n\nbool check(int y, int x, int h1, int h2, int w1, int w2)\n{\n return h1 <= y && y < h2 && w1 <= x && x < w2;\n}\n\nbool iskadomatsu(int a, int b, int c)\n{\n return (a != b && b != c && c != a) &&\n ((a > b && b < c) || (a < b && b > c));\n}\n\ntemplate <typename T>\nbool iskadomatsu(vector<T> v)\n{\n T a = v[0], b = v[1], c = v[2];\n return (a != b && b != c && c != a) &&\n ((a > b && b < c) || (a < b && b > c));\n}\n\ndouble euc_dist(PII a, PII b)\n{\n return sqrt(pow(a.first - b.first, 2) + pow(a.second - b.second, 2));\n}\n\n// VS split(string s, char c) {\n// VS ret;\n// string part;\n// s += c;\n// rep(i, s.length()) {\n// if (s[i] == c) {\n// if (part != \"\") ret.emplace_back(part);\n// part = \"\";\n// } else if (s[i] != c) {\n// part += s[i];\n// }\n// }\n// return ret;\n// }\n\nVS split(string s, char c, char d = ' ')\n{\n VS ret;\n // reverse(allpt(s));\n string part;\n s += c;\n rep(i, s.length())\n {\n if (s[i] == c)\n {\n if (part != \"\")\n {\n // string t;\n // t += c;\n // ret.emplace_back(t);\n ret.emplace_back(part);\n }\n part = \"\";\n }\n else\n {\n part += s[i];\n }\n }\n return ret;\n}\n\ntemplate <typename T, typename S, typename R>\nll pow_mod(T p, S q, R _mod = 1ll)\n{\n ll ret = 1, r = p;\n while (q)\n {\n if (q % 2)\n ret *= r, ret %= _mod;\n r = (r * r) % _mod, q /= 2;\n }\n return ret % _mod;\n}\n\ntemplate <typename T, typename S>\nll pow_no_mod(T p, S q)\n{\n ll ret = 1, r = p;\n while (q)\n {\n if (q % 2)\n ret *= r;\n r = (r * r), q /= 2;\n }\n return ret;\n}\n\nvoid make_frac_tables(VL &frac_list, VL &frac_inv_list)\n{\n rep(i, frac_list.size() - 1)\n {\n frac_list[i + 1] *= frac_list[i] * (i + 1);\n frac_list[i + 1] %= mod;\n frac_inv_list[i + 1] *= frac_inv_list[i] * pow_mod(i + 1, mod - 2, mod);\n frac_inv_list[i + 1] %= mod;\n }\n}\n\npair<VL, VL> make_frac_tables(int n)\n{\n VL frac_list(n + 1, 1), frac_inv_list(n + 1, 1);\n rep(i, n)\n {\n frac_list[i + 1] *= frac_list[i] * (i + 1);\n frac_list[i + 1] %= mod;\n frac_inv_list[i + 1] *= frac_inv_list[i] * pow_mod(i + 1, mod - 2, mod);\n frac_inv_list[i + 1] %= mod;\n }\n return make_pair(frac_list, frac_inv_list);\n}\n\nll perm(int a, int b, const VL &frac_list, const VL &frac_inv_list)\n{\n if (a < b)\n return 0;\n if (b < 0)\n return 0;\n ll ret = frac_list[a];\n ret *= frac_inv_list[a - b];\n ret %= mod;\n return ret;\n}\n\nll comb(int a, int b, const VL &frac_list, const VL &frac_inv_list)\n{\n if (a < b)\n return 0;\n if (b < 0)\n return 0;\n ll ret = frac_list[a];\n ret *= frac_inv_list[b];\n ret %= mod;\n ret *= frac_inv_list[a - b];\n ret %= mod;\n return ret;\n}\n\nstruct vec2d\n{\n ll x;\n ll y;\n vec2d(ll _x, ll _y)\n {\n x = _x;\n y = _y;\n }\n ll dot(vec2d p) { return x * p.x + y * p.y; }\n vec2d diff(vec2d p) { return vec2d(x - p.x, y - p.y); }\n};\n\nstruct node\n{\n int parent = -1;\n ll weight = 0;\n int depth = 0;\n int degree = -1;\n int subtree = 1;\n int check = 0;\n int scc = -1;\n VPLL children;\n VI parent_list;\n VPLL connect;\n ll visitfee;\n vector<TL3> max_cost_from_children;\n ll max_cost_from_parent;\n\n node()\n {\n parent = -1;\n weight = 0;\n depth = 0;\n degree = -1;\n subtree = 1;\n check = 0;\n children;\n parent_list;\n connect;\n max_cost_from_parent = 0;\n }\n};\n\nstruct graph\n{\n int _n;\n int root = 0;\n vector<node> nodes;\n graph(int n)\n {\n _n = n;\n rep(i, _n) nodes.emplace_back(node());\n }\n void getconnect_nocost()\n {\n ll a, b;\n cin >> a >> b;\n nodes[a].connect.emplace_back(b, 1);\n nodes[b].connect.emplace_back(a, 1);\n }\n void getconnect_cost()\n {\n ll a, b, c;\n cin >> a >> b >> c;\n nodes[a].connect.emplace_back(b, c);\n nodes[b].connect.emplace_back(a, c);\n }\n void getconnect_increment_nocost()\n {\n ll a, b;\n cin >> a >> b;\n a--, b--;\n nodes[a].connect.emplace_back(b, 1);\n nodes[b].connect.emplace_back(a, 1);\n }\n void getconnect_increment_cost()\n {\n ll a, b, c;\n cin >> a >> b >> c;\n a--, b--;\n nodes[a].connect.emplace_back(b, c);\n nodes[b].connect.emplace_back(a, c);\n }\n void showparent()\n {\n rep(i, _n - 1) cout << nodes[i].parent << wsp;\n cout << nodes[_n - 1].parent << rt;\n }\n void showweight()\n {\n rep(i, _n - 1) cout << nodes[i].weight << wsp;\n cout << nodes[_n - 1].weight << rt;\n }\n void showsubtree()\n {\n rep(i, _n - 1) cout << nodes[i].subtree << wsp;\n cout << nodes[_n - 1].subtree << rt;\n }\n void showdepth()\n {\n rep(i, _n - 1) cout << nodes[i].depth << wsp;\n cout << nodes[_n - 1].depth << rt;\n }\n};\n\nstruct point\n{\n int x;\n int y;\n point()\n {\n x = 0;\n y = 0;\n }\n point(int _x, int _y)\n {\n x = _x;\n y = _y;\n }\n void pointinput()\n {\n int _x, _y;\n cin >> _x >> _y;\n x = _x;\n y = _y;\n }\n void pointinv() { swap(x, y); }\n};\n\nistream &operator>>(istream &is, point &p)\n{\n is >> p.x >> p.y;\n return is;\n}\n\nostream &operator<<(ostream &os, point &p)\n{\n os << p.x << wsp << p.y << rt;\n return os;\n}\n\ndouble pointseuc(point a, point b)\n{\n ll ax = a.x, bx = b.x, ay = a.y, by = b.y;\n return sqrt(pow(ax - bx, 2) + pow(ay - by, 2));\n}\n\nll pointseucsquare(point a, point b)\n{\n ll ax = a.x, bx = b.x, ay = a.y, by = b.y;\n return (ax - bx) * (ax - bx) + (ay - by) * (ay - by);\n}\n\nint pointsmanhattan(point a, point b)\n{\n return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\ndouble dist_segment_point(TL3 segment, point p)\n{\n double a = get<0>(segment);\n double b = get<1>(segment);\n double c = get<2>(segment);\n return abs(a * p.x + b * p.y - c) / sqrt(a * a + b * b);\n}\n\nTL3 segment_parameter(point p, point q)\n{\n ll a, b, c;\n a = q.y - p.y;\n b = p.x - q.x;\n c = a * p.x + b * p.y;\n TL3 ret = (TL3){a, b, c};\n // cout << a << b << c << rt;\n return ret;\n}\n\nint cross_check(TL3 segment, point p)\n{\n ll a = get<0>(segment);\n ll b = get<1>(segment);\n ll c = get<2>(segment);\n\n auto f = a * p.x + b * p.y - c;\n int ret;\n if (f > 0)\n ret = 1;\n if (f == 0)\n ret = 0;\n if (f < 0)\n ret = -1;\n return ret;\n}\n\nVI shave(int n)\n{\n VI v;\n if (n <= 1)\n return v;\n vector<bool> w(n + 1, true);\n int x;\n w[0] = w[1] = false;\n rep2(i, 2, n + 1)\n {\n if (w[i])\n {\n x = i * 2;\n while (x <= n)\n {\n w[x] = false;\n x += i;\n }\n }\n }\n rep(i, n + 1) if (w[i]) v.emplace_back(i);\n return v;\n}\n\nbool iscross(point p1, point p2, point p3, point p4)\n{\n auto segment_1 = segment_parameter(p1, p2);\n auto segment_2 = segment_parameter(p3, p4);\n const double eps = 1e-6;\n bool ans{false};\n if (cross_check(segment_1, p3) * cross_check(segment_1, p4) == 0 &&\n cross_check(segment_2, p1) * cross_check(segment_2, p2) == 0)\n {\n auto xmin_1 = min(p1.x, p2.x) - eps;\n auto xmin_2 = min(p3.x, p4.x) - eps;\n auto xmax_1 = max(p1.x, p2.x) + eps;\n auto xmax_2 = max(p3.x, p4.x) + eps;\n auto ymin_1 = min(p1.y, p2.y) - eps;\n auto ymin_2 = min(p3.y, p4.y) - eps;\n auto ymax_1 = max(p1.y, p2.y) + eps;\n auto ymax_2 = max(p3.y, p4.y) + eps;\n\n if (xmin_1 <= p3.x && p3.x <= xmax_1 && ymin_1 <= p3.y && p3.y <= ymax_1)\n ans = true;\n if (xmin_1 <= p4.x && p4.x <= xmax_1 && ymin_1 <= p4.y && p4.y <= ymax_1)\n ans = true;\n if (xmin_2 <= p1.x && p1.x <= xmax_2 && ymin_2 <= p1.y && p1.y <= ymax_2)\n ans = true;\n if (xmin_2 <= p2.x && p2.x <= xmax_2 && ymin_2 <= p2.y && p2.y <= ymax_2)\n ans = true;\n }\n else if (cross_check(segment_1, p3) * cross_check(segment_1, p4) <= 0 &&\n cross_check(segment_2, p1) * cross_check(segment_2, p2) <= 0)\n {\n ans = true;\n }\n return ans;\n}\n\nint on_the_segment(point p, point q1, point q2)\n{\n auto [a, b, c] = segment_parameter(q1, q2);\n\n if (p.x < min(q1.x, q2.x) || max(q1.x, q2.x) < p.x)\n return 0;\n if (p.y < min(q1.y, q2.y) || max(q1.y, q2.y) < p.y)\n return 0;\n\n auto f = a * p.x + b * p.y - c;\n return f == 0;\n}\n\nvoid shave(vector<int> &v, int n)\n{\n if (n <= 1)\n return;\n vector<bool> w(n + 1, true);\n int x;\n w[0] = w[1] = false;\n rep2(i, 2, n + 1)\n {\n if (w[i])\n {\n x = i * 2;\n while (x <= n)\n {\n w[x] = false;\n x += i;\n }\n }\n }\n rep(i, n + 1) if (w[i]) v.emplace_back(i);\n}\n\ntemplate <typename T>\nvoid coordinate_compress(vector<T> &x, map<T, int> &zip, int &xs)\n{\n sort(x.begin(), x.end());\n x.erase(unique(x.begin(), x.end()), x.end());\n xs = x.size();\n for (int i = 0; i < xs; i++)\n {\n zip[x[i]] = i;\n }\n}\n\n// ll getpalindrome(int l, int r, const string &s, VL &memo) {\n// if (r - l <= 1) return 1;\n// if (memo[l] != -1) return memo[l];\n// ll ret{1};\n// int n = (r - l) / 2;\n// string sl, sr;\n// rep(i, n) {\n// sl += s[l + i];\n// sr += s[r - 1 - i];\n// string rsr(i + 1, '0');\n// reverse_copy(allpt_c(sr), rsr.begin());\n// // cout << sl << wsp << sr << wsp << rsr << rt;\n// if (sl == rsr) {\n// ret += getpalindrome(l + i + 1, r - i - 1, s, memo);\n// ret %= mod;\n// }\n// }\n// memo[l] = ret;\n// return ret;\n// }\n\nvoid getpalindrome(int l, int r, int n, const string &s, VVB &memo)\n{\n if (r - l <= 1 || s[l] == s[r - 1])\n {\n memo[l][r] = true;\n if (l > 0 && r < n)\n {\n getpalindrome(l - 1, r + 1, n, s, memo);\n }\n }\n return;\n}\n\n// void djcstra(graph graphs, int s, int t)\n// {\n// const int n = graphs._n;\n// VL shortest(n, inf);\n// shortest[s] = 0;\n// priority_queue<pair<ll, int>> pq;\n// pq.push(make_pair(0, s));\n// while (!pq.empty())\n// {\n// auto [t, v] = pq.top();\n// pq.pop();\n// t = -t;\n// if (shortest[v] != t)\n// continue;\n// for (auto [u, c] : graphs.nodes[v].connect)\n// {\n// if (t + c < shortest[u])\n// {\n// shortest[u] = t + c;\n// pq.push(make_pair(-(t + c), u));\n// }\n// }\n// }\n// }\n\nclass Unionfind\n{\n vector<int> p;\n\npublic:\n Unionfind(int n)\n {\n for (int i = 0; i < n; i++)\n {\n p.push_back(i);\n }\n }\n int find(int x)\n {\n while (p[x] != x)\n {\n p[x] = p[p[x]];\n x = p[x];\n }\n return x;\n }\n int getval(int x) { return p[x]; }\n void unite(int x, int y)\n {\n x = find(x);\n y = find(y);\n if (x != y)\n {\n p[x] = y;\n }\n }\n\n bool isunion(int x, int y) { return find(x) == find(y); }\n void showtree() { cout << p; }\n};\n\ntemplate <typename T>\nclass RangeMinorMaxorSumQuery // 0-index\n{\n T const intmax = infint;\n T const intmin = 0;\n vector<T> sgt;\n int n;\n int k;\n\npublic:\n RangeMinorMaxorSumQuery(int n1, T f)\n {\n int na = 1;\n int ka = 0;\n while (na < n1)\n {\n na *= 2;\n ka++;\n }\n for (int i = 0; i < 2 * na; i++)\n sgt.push_back(f);\n n = na;\n k = ka;\n }\n\n void update_min(int i, T x)\n {\n i += n;\n sgt[i] = x;\n while (i > 1)\n {\n i /= 2;\n sgt[i] = min(sgt[2 * i], sgt[2 * i + 1]);\n }\n }\n void update_max(int i, T x)\n {\n i += n;\n sgt[i] = x;\n while (i > 1)\n {\n i /= 2;\n sgt[i] = max(sgt[2 * i], sgt[2 * i + 1]);\n }\n }\n void update_sum(int i, T x)\n {\n i += n;\n sgt[i] = x;\n while (i > 1)\n {\n i /= 2;\n sgt[i] = sgt[2 * i] + sgt[2 * i + 1];\n }\n }\n\n void add_sum(int i, T x)\n {\n i += n;\n sgt[i] += x;\n while (i > 1)\n {\n i /= 2;\n sgt[i] = sgt[2 * i] + sgt[2 * i + 1];\n }\n }\n\n void add_min(int i, T x)\n {\n i += n;\n sgt[i] += x;\n while (i > 1)\n {\n i /= 2;\n sgt[i] = min(sgt[2 * i], sgt[2 * i + 1]);\n }\n }\n\n void add_max(int i, T x)\n {\n i += n;\n sgt[i] += x;\n while (i > 1)\n {\n i /= 2;\n sgt[i] = max(sgt[2 * i], sgt[2 * i + 1]);\n }\n }\n\n T get_min(int a, int b, int k = 1, int l = 0,\n int r = -1) //閉区間 l <= x < r とする\n {\n if (r == -1)\n r = n;\n if (r <= a || b <= l)\n return 0;\n if (a == l && b == r)\n return sgt[k];\n else\n return min(\n get_min(a, min(b, (l + r) / 2), 2 * k, l, (l + r) / 2),\n get_min(max(a, (l + r) / 2), b, 2 * k + 1, (l + r) / 2, r));\n }\n T get_max(int a, int b, int k = 1, int l = 0,\n int r = -1) //閉区間 l <= x < r とする\n {\n if (r == -1)\n r = n;\n if (r <= a || b <= l)\n return 0;\n if (a == l && b == r)\n return sgt[k];\n else\n return max(\n get_max(a, min(b, (l + r) / 2), 2 * k, l, (l + r) / 2),\n get_max(max(a, (l + r) / 2), b, 2 * k + 1, (l + r) / 2, r));\n }\n T get_sum(int a, int b, int k = 1, int l = 0,\n int r = -1) //閉区間 l <= x < r とする\n {\n if (r == -1)\n r = n;\n if (r <= a || b <= l)\n return intmin;\n if (a == l && b == r)\n return sgt[k];\n else\n return get_sum(a, min(b, (l + r) / 2), 2 * k, l, (l + r) / 2) +\n get_sum(max(a, (l + r) / 2), b, 2 * k + 1, (l + r) / 2, r);\n }\n\n T operator[](int i) { return sgt[i + n]; }\n\n void printsegtree()\n {\n for (int i = 0; i < 2 * n; i++)\n {\n cout << sgt[i] << \" \";\n }\n cout << endl;\n }\n};\n\ntemplate <typename T>\nclass Bit_Index_Tree // 1-index\n\n{\n int n = 0;\n vector<T> v;\n\npublic:\n Bit_Index_Tree(int _n, T x = 0)\n {\n n = _n;\n v.resize(n + 1);\n fill(allpt(v), x);\n }\n Bit_Index_Tree(vector<T> _v)\n {\n n = _v.size();\n v = _v;\n }\n void add(int i, T x)\n {\n while (i <= n)\n {\n v[i] += x;\n i += i & -i;\n }\n }\n T get_sum(int i)\n {\n T ret = 0;\n while (i > 0)\n {\n ret += v[i];\n i -= i & -i;\n }\n return ret;\n }\n T get_range_sum(int l, int r)\n { // 半開区間 l <= x < r\n return get_sum(r) - get_sum(l);\n }\n};\n\n// #define DEBUG\n\nVI smallest_prime_factors(int n)\n{\n VI ret(n + 1);\n iota(allpt(ret), 0);\n for (int i = 2; i * i <= n; i++)\n {\n if (ret[i] == i)\n {\n for (int j = i * i; j <= n; j += i)\n {\n if (ret[j] == j)\n ret[j] = i;\n }\n }\n }\n return ret;\n}\n\ntemplate <typename T>\nT mex(vector<T> v)\n{\n sort(allpt(v));\n v.erase(unique(v.begin(), v.end()), v.end());\n int ret = 0;\n for (auto x : v)\n {\n if (ret < x)\n return ret;\n ret++;\n }\n return ret;\n}\n\nint main()\n{\n cin.tie(0);\n ios::sync_with_stdio(false);\n // リアクティブ問題のときはコメントアウト\n\n#ifdef DEBUG\n cout << \"DEBUG MODE\" << endl;\n // ifstream in(\"input.txt\"); // for debug\n // cin.rdbuf(in.rdbuf()); // for debug\n chrono::system_clock::time_point timestart, timeend; // for debug\n timestart = std::chrono::system_clock::now(); // for debug\n\n#endif\n\n int n, m, s, t, d;\n ll ans{0};\n cin >> n >> m;\n VI deg(n, 0), odd_node;\n VVL dist_list(n, VL(n, inf));\n rep(i, n) dist_list[i][i] = 0;\n rep(_, m)\n {\n cin >> s >> t >> d;\n dist_list[s][t] = dist_list[t][s] = min<ll>(d, dist_list[s][t]);\n deg[s]++, deg[t]++;\n ans += d;\n }\n\n rep(k, n) rep(i, n) rep(j, n) if (dist_list[i][j] >= dist_list[i][k] + dist_list[k][j])\n dist_list[i][j] = dist_list[i][k] + dist_list[k][j];\n\n rep(i, n) if (deg[i] % 2 == 1)\n {\n odd_node.emplace_back(i);\n }\n\n n = odd_node.size();\n VVL dist_list_2(n, VL(n));\n rep(i, n) rep(j, n) dist_list_2[i][j] = dist_list[odd_node[i]][odd_node[j]];\n\n // cout << deg << dist_list_2;\n\n VVL dp(n / 2 + 1, VL(1 << n, inf));\n dp[0][0] = 0;\n\n rep(i, n / 2) rep(x, 1 << n) rep2(j, 0, n - 1) rep2(k, j + 1, n)\n {\n int y = (1 << j) + (1 << k);\n if ((x & y) == 0) {\n dp[i + 1][x | y] = min(dp[i + 1][x | y], dp[i][x] + dist_list_2[j][k]);\n }\n }\n\n cout << ans + dp[n / 2][(1 << n) - 1] << rt;\n\n#ifdef DEBUG\n timeend = chrono::system_clock::now();\n auto elapsed =\n chrono::duration_cast<chrono::milliseconds>(timeend - timestart)\n .count();\n cout << \"Time is \" << elapsed << \"ms\" << std::endl;\n#endif\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4404, "score_of_the_acc": -0.0371, "final_rank": 4 }, { "submission_id": "aoj_DPL_2_B_6037039", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned int ull;\ntypedef pair<ll, ll> pil;\nconst ll ll_INF = 0x3f3f3f3f3f3f3f3f;\nconst ll ll_MAX = 0x7fffffffffffffff;\nconst int int_INF = 0x3f3f3f3f;\nconst int int_MAX = 0x7fffffff;\nconst double EPS = 1e-7;\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\n#define R register\n#define _max(a, b) ((a) > (b) ? (a) : (b))\n#define _min(a, b) ((a) < (b) ? (a) : (b))\n#define _abs(a) ((a) > 0 ? (a) : -(a))\n#define _swap(a, b) ((a) ^= (b) ^= (a) ^= (b))\n#define _eql(x, y) (_abs((x) - (y)) < EPS)\nconst int MX = 1000100;\nstruct Node {\n int u, v, val;\n int _next;\n} e[1000];\nint dis[20][20] = {0};\nint head[20], ind[20], cnt = 0;\nint n, m, ans, sum;\nvoid addedge(int u, int v, int val) {\n e[++cnt].v = v;\n e[cnt].u = u;\n e[cnt].val = val;\n e[cnt]._next = head[u];\n head[u] = cnt;\n}\nbool Init() {\n cin >> n >> m;\n if((n | m) == 0)\n return 0;\n int u, v, val;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n dis[i][j] = int_INF;\n }\n dis[i][i] = 0;\n }\n sum = 0;\n for(int i = 0; i < m; i++) {\n cin >> u >> v >> val;\n dis[u][v] = dis[v][u] = _min(val, dis[u][v]);\n sum += val;\n ind[u]++;\n ind[v]++;\n }\n\n return 1;\n}\nint odd[20] = {0};\nint dp[1 << 16] = {0};\nvoid DFS(int now, int sta, int last) {\n if(now > dp[(1 << odd[0]) - 1])\n return;\n if(sta == (1 << odd[0]) - 1) {\n dp[(1 << odd[0]) - 1] = now;\n return;\n }\n for(int i = last; i <= cnt; i++) {\n if((sta & (1 << e[i].u)) || (sta & (1 << e[i].v)))\n continue;\n sta ^= (1 << e[i].u);\n sta ^= (1 << e[i].v);\n DFS(now + e[i].val, sta, i + 1);\n sta ^= (1 << e[i].u);\n sta ^= (1 << e[i].v);\n }\n}\n\nvoid solve() {\n for(int k = 0; k < n; k++) {\n for(int i = 0; i < n; i++) {\n if(dis[i][k] ^ int_INF)\n for(int j = 0; j < n; j++) {\n if((dis[k][j] ^ int_INF))\n dis[i][j] = _min(dis[i][j], dis[i][k] + dis[k][j]);\n }\n }\n }\n odd[0] = 0;\n for(int i = 0; i < n; i++)\n if(ind[i] & 1)\n odd[++odd[0]] = i;\n for(int i = 1; i <= odd[0]; i++) {\n for(int j = i + 1; j <= odd[0]; j++) {\n addedge(i - 1, j - 1, dis[odd[i]][odd[j]]);\n }\n }\n for(int i = 1; i < (1 << odd[0]); i++)\n dp[i] = int_INF;\n\n DFS(0, 0, 0);\n // cout << \"<<<<<<<<<<\" << sum << \" \" << dp[(1 << odd[0]) - 1] << endl;\n cout << sum + dp[(1 << odd[0]) - 1] << endl;\n}\n\nint main() {\n std::ios::sync_with_stdio(false);\n#ifdef LOCAL\n freopen(\"data.in\", \"r\", stdin);\n freopen(\"data.out\", \"w\", stdout);\n#endif\n int t = 1;\n while(t--) {\n if(Init())\n solve();\n else\n break;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3464, "score_of_the_acc": -0.0362, "final_rank": 3 }, { "submission_id": "aoj_DPL_2_B_4825630", "code_snippet": "#include <cmath>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <set>\n#include <iomanip>\n#include <numeric>\n#include <queue>\n#include <string>\n#include <map>\n#include <fstream>\n#include <cassert>\n#include <stack>\n#include <climits>\n#include <array>\n#include <unordered_set>\n#include <unordered_map>\n#include <memory>\n#include <functional>\nvoid split(std::vector<int>& source, std::vector<int>& left, std::vector<int>& right, const std::function<void(const std::vector<int>, std::vector<int>)>& func) {\n\tif (source.empty()) {\n\t\treturn func(left, right);\n\t}\n\tconst auto back = source.back(); source.pop_back();\n\tif (right.size() + source.size() > left.size()) {\n\t\tleft.push_back(back);\n\t\tsplit(source, left, right, func);\n\t\tleft.pop_back();\n\t}\n\tif (left.size() + source.size() > right.size()) {\n\t\tright.push_back(back);\n\t\tsplit(source, left, right, func);\n\t\tright.pop_back();\n\t}\n\tsource.push_back(back);\n}\nint factorial(const int n) {\n\treturn n <= 1 ? 1 : n * factorial(n - 1);\n}\nint main() {\n\tint v, e; std::cin >> v >> e;\n\tstd::vector<std::vector<int>> min_distance(v, std::vector<int>(v, 15000));\n\tstd::vector<int> degree(v, 0);\n\tint sum_distance{ 0 };\n\tfor (auto i = 0; i < e; ++i) {\n\t\tint s, t, d; std::cin >> s >> t >> d;\n\t\tmin_distance[s][t] = min_distance[t][s] = std::min(min_distance[s][t], d);\n\t\tsum_distance += d;\n\t\t++degree[s]; ++degree[t];\n\t}\n\tfor (auto j = 0; j < v; ++j) {\n\t\tfor (auto i = 0; i < v; ++i) {\n\t\t\tfor (auto k = 0; k < v; ++k) {\n\t\t\t\tmin_distance[i][k] = std::min(min_distance[i][j] + min_distance[j][k], min_distance[i][k]);\n\t\t\t}\n\t\t}\n\t}\n\tstd::vector<int> odd;\n\tfor (auto i = 0; i < v; ++i) {\n\t\tif ((degree[i] & 1) == 1) {\n\t\t\todd.push_back(i);\n\t\t}\n\t}\n\tif (odd.empty()) {\n\t\tstd::cout << sum_distance << '\\n';\n\t}\n\telse {\n\t\tstd::vector<int> left, right;\n\t\tint min_cost{ INT_MAX };\n\t\tsplit(odd, left, right, [&min_cost, &min_distance](const std::vector<int> a, std::vector<int> b) {\n\t\t\tfor (auto i = factorial(b.size()); i > 0; --i) {\n\t\t\t\tstd::next_permutation(b.begin(), b.end());\n\t\t\t\tint cost{ 0 };\n\t\t\t\tfor (auto j = 0; j < a.size(); ++j) {\n\t\t\t\t\tcost += min_distance[b[j]][a[j]];\n\t\t\t\t}\n\t\t\t\tmin_cost = std::min(min_cost, cost);\n\t\t\t}\n\t\t\t});\n\t\tstd::cout << sum_distance + min_cost << '\\n';\n\t}\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 3180, "score_of_the_acc": -0.1359, "final_rank": 5 }, { "submission_id": "aoj_DPL_2_B_2825509", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nusing Int = long long;\n\ntemplate<typename T>\nvector<T> make_v(size_t a){return vector<T>(a);}\n\ntemplate<typename T,typename... Ts>\nauto make_v(size_t a,Ts... ts){\n return vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));\n}\n\ntemplate<typename T,typename V>\ntypename enable_if<is_class<T>::value==0>::type\nfill_v(T &t,const V &v){t=v;}\n\ntemplate<typename T,typename V>\ntypename enable_if<is_class<T>::value!=0>::type\nfill_v(T &t,const V &v){\n for(auto &e:t) fill_v(e,v);\n}\n\n\ntemplate<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}\ntemplate<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}\n\n//INSERT ABOVE HERE\nsigned main(){\n Int n,m;\n cin>>n>>m;\n \n auto G=make_v<Int>(n,n);\n const Int INF = 1e15;\n fill_v(G,INF);\n for(Int i=0;i<n;i++) G[i][i]=0;\n\n Int ans=0;\n vector<Int> c(n);\n for(Int i=0;i<m;i++){\n Int s,t,d;\n cin>>s>>t>>d;\n chmin(G[s][t],d);\n chmin(G[t][s],d);\n c[s]++;c[t]++;\n ans+=d;\n }\n \n for(Int k=0;k<n;k++)\n for(Int i=0;i<n;i++)\n for(Int j=0;j<n;j++)\n\tchmin(G[i][j],G[i][k]+G[k][j]);\n\n vector<Int> dp(1<<n,INF);\n Int x=0;\n for(Int i=0;i<n;i++) x|=(c[i]&1)<<i;\n dp[x]=0;\n for(Int b=(1<<n)-1;b>=0;b--){\n for(Int i=0;i<n;i++){\n for(Int j=0;j<i;j++){\n\tif((~b>>i)&1) continue;\n\tif((~b>>j)&1) continue;\n\tchmin(dp[b^(1<<i)^(1<<j)],dp[b]+G[i][j]);\n }\n }\n }\n \n cout<<ans+dp[0]<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3228, "score_of_the_acc": -0.0231, "final_rank": 2 }, { "submission_id": "aoj_DPL_2_B_1801360", "code_snippet": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nint dp[16][65536];\nint a[16], b[16], c[16], n, m;\nint main() {\n\tcin >> n >> m;\n\tfor (int i = 0; i < m; i++) {\n\t\tcin >> a[i] >> b[i] >> c[i];\n\t}\n\tint minx = 1000000000;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int i = 0; i < 16; i++) {\n\t\t\tfor (int j = 0; j < 65536; j++)dp[i][j] = 1000000000;\n\t\t}\n\t\tdp[i][0] = 0;\n\t\tfor (int j = 0; j < 8; j++) {\n\t\t\tfor (int k = 0; k < n; k++) {\n\t\t\t\tfor (int l = 0; l < (1 << m); l++) {\n\t\t\t\t\tint bit[16];\n\t\t\t\t\tfor (int o = 0; o < m; o++) {\n\t\t\t\t\t\tbit[o] = (l / (1 << o)) % 2;\n\t\t\t\t\t}\n\t\t\t\t\tfor (int o = 0; o < m; o++) {\n\t\t\t\t\t\tif (a[o] != k)goto H;\n\t\t\t\t\t\tif (bit[o] == 1)dp[b[o]][l] = min(dp[b[o]][l], dp[k][l] + c[o]);\n\t\t\t\t\t\telse dp[b[o]][l + (1 << o)] = min(dp[b[o]][l + (1 << o)], dp[k][l] + c[o]);\n\t\t\t\t\tH:;\n\t\t\t\t\t\tif (b[o] != k)continue;\n\t\t\t\t\t\tif (bit[o] == 1)dp[a[o]][l] = min(dp[a[o]][l], dp[k][l] + c[o]);\n\t\t\t\t\t\telse dp[a[o]][l + (1 << o)] = min(dp[a[o]][l + (1 << o)], dp[k][l] + c[o]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tminx = min(minx, dp[i][(1 << m) - 1]);\n\t}\n\tcout << minx << endl;\n\treturn 0;\n}", "accuracy": 0.35, "time_ms": 980, "memory_kb": 7196, "score_of_the_acc": -1.0702, "final_rank": 7 }, { "submission_id": "aoj_DPL_2_B_1801357", "code_snippet": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nint dp[16][65536];\nint a[16], b[16], c[16], n, m;\nint main() {\n\tcin >> n >> m;\n\tfor (int i = 0; i < m; i++) {\n\t\tcin >> a[i] >> b[i] >> c[i];\n\t}\n\tint minx = 1000000000;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int i = 0; i < 16; i++) {\n\t\t\tfor (int j = 0; j < 65536; j++)dp[i][j] = 1000000000;\n\t\t}\n\t\tdp[i][0] = 0;\n\t\tfor (int j = 0; j < 4; j++) {\n\t\t\tfor (int k = 0; k < n; k++) {\n\t\t\t\tfor (int l = 0; l < (1 << m); l++) {\n\t\t\t\t\tint bit[16];\n\t\t\t\t\tfor (int o = 0; o < m; o++) {\n\t\t\t\t\t\tbit[o] = (l / (1 << o)) % 2;\n\t\t\t\t\t}\n\t\t\t\t\tfor (int o = 0; o < m; o++) {\n\t\t\t\t\t\tif (a[o] != k)goto H;\n\t\t\t\t\t\tif (bit[o] == 1)dp[b[o]][l] = min(dp[b[o]][l], dp[k][l] + c[o]);\n\t\t\t\t\t\telse dp[b[o]][l + (1 << o)] = min(dp[b[o]][l + (1 << o)], dp[k][l] + c[o]);\n\t\t\t\t\tH:;\n\t\t\t\t\t\tif (b[o] != k)continue;\n\t\t\t\t\t\tif (bit[o] == 1)dp[a[o]][l] = min(dp[a[o]][l], dp[k][l] + c[o]);\n\t\t\t\t\t\telse dp[a[o]][l + (1 << o)] = min(dp[a[o]][l + (1 << o)], dp[k][l] + c[o]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tminx = min(minx, dp[i][(1 << m) - 1]);\n\t}\n\tcout << minx << endl;\n\treturn 0;\n}", "accuracy": 0.15, "time_ms": 160, "memory_kb": 7200, "score_of_the_acc": -0.2249, "final_rank": 8 }, { "submission_id": "aoj_DPL_2_B_1370734", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint minimum_weight_matching(const vector<vector<int>>& weight) {\n const int INF = 1e9;\n vector<int> dp(1 << weight.size(), INF);\n dp[0] = 0;\n for(int bit = 0; bit < (1 << weight.size()); ++bit)\n for(int u = 0; u < weight.size(); ++u) if(!((bit >> u) & 1))\n for(int v = 0; v < weight.size(); ++v) if(!((bit >> v) & 1))\n dp[bit | (1 << u) | (1 << v)] = min(dp[bit | (1 << u) | (1 << v)], dp[bit] + weight[u][v]);\n return dp[(1 << weight.size()) - 1];\n}\nstruct Edge {int from, to, weight;};\nint chinese_postman_problem(const vector<vector<Edge>>& edge) {\n const int NIL = -1;\n const int INF = 1e9;\n int total = 0;\n vector<int> odd, odd_index(edge.size(), NIL);\n for(int v = 0; v < edge.size(); ++v) {\n for(const auto& e: edge[v]) total += e.weight;\n if(edge[v].size() & 1) {\n odd_index[v] = odd.size();\n odd.push_back(v);\n }\n }\n // Warshall-Floyd\n vector<vector<int>> wf(edge.size(), vector<int>(edge.size(), INF));\n for(int v = 0; v < edge.size(); ++v) for(const auto& e: edge[v]) wf[e.from][e.to] = min(wf[e.from][e.to], e.weight);\n// for(int v = 0; v < edge.size(); ++v) wf[v][v] = 0;\n for(int k = 0; k < edge.size(); ++k)\n for(int i = 0; i < edge.size(); ++i)\n for(int j = 0; j < edge.size(); ++j)\n wf[i][j] = min(wf[i][j], wf[i][k] + wf[k][j]);\n // make odd vertices graph\n vector<vector<int>> weight(odd.size(), vector<int>(odd.size(), INF));\n for(const auto& u: odd) for(const auto& v: odd) if(u != v) weight[odd_index[u]][odd_index[v]] = wf[u][v];\n // minimum weight matching\n return total / 2 + minimum_weight_matching(weight);\n}\nint main() {\n int V, E;\n cin >> V >> E;\n vector<vector<Edge>> edge(V);\n for(int i = 0; i < E; ++i) {\n int s, t, d;\n cin >> s >> t >> d;\n edge[s].push_back({s, t, d});\n edge[t].push_back({t, s, d});\n }\n cout << chinese_postman_problem(edge) << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1284, "score_of_the_acc": 0, "final_rank": 1 } ]
aoj_DPL_2_A_cpp
Traveling Salesman Problem For a given weighted directed graph G(V, E) , find the distance of the shortest route that meets the following criteria: It is a closed cycle where it ends at the same point it starts. It visits each vertex exactly once. Input |V| |E| s 0 t 0 d 0 s 1 t 1 d 1 : s |E|-1 t |E|-1 d |E|-1 |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V| -1 respectively. s i and t i represent source and target vertices of i -th edge (directed) and d i represents the distance between s i and t i (the i -th edge). Output Print the shortest distance in a line. If there is no solution, print -1. Constraints 2 ≤ |V| ≤ 15 0 ≤ d i ≤ 1,000 There are no multiedge Sample Input 1 4 6 0 1 2 1 2 3 1 3 9 2 0 1 2 3 6 3 2 4 Sample Output 1 16 Sample Input 2 3 3 0 1 1 1 2 1 0 2 1 Sample Output 2 -1
[ { "submission_id": "aoj_DPL_2_A_11044370", "code_snippet": "// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_2_A&lang=ja\n#include <iostream>\n#include <vector>\n#include <climits>\n\nusing namespace std;\n\nint main(){\n int node, edge;\n cin >> node >> edge;\n vector<vector<int>> G(node, vector<int>(node, -1));\n\n int s,t,d;\n for (int i=0; i<edge; i++){\n cin >> s >> t >> d;\n G[s][t] = d;\n }\n\n int FULL = (1<<node);\n vector<vector<int>> dp(FULL+1, vector<int>(node, 20000));\n // for (int to=0; to<node; to++) dp[1<<to][to] = 0;\n // サイクルは回転不変:どこを視点にしても最小コストは変わらない。\n dp[1<<0][0] = 0;\n\n for (int search_range_bit=1; search_range_bit<FULL; search_range_bit++){\n for (int to=0; to<node; to++){\n if (!(search_range_bit & (1<<to))) continue;\n\n int explored_node_bit = search_range_bit ^ (1<<to);\n if (explored_node_bit == 0) continue;\n\n for (int from=0; from<node; from++){\n if (G[from][to] < 0) continue;\n if (!(explored_node_bit & (1<<from))) continue;\n dp[search_range_bit][to] = min(dp[search_range_bit][to], dp[explored_node_bit][from]+G[from][to]);\n }\n }\n }\n\n int ans = 20000;\n for (int to=0; to<node; to++){\n if (G[to][0] < 0) continue;\n ans = min(ans, dp[FULL-1][to] + G[to][0]);\n }\n if (ans == 20000) ans = -1;\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6516, "score_of_the_acc": -0.0422, "final_rank": 6 }, { "submission_id": "aoj_DPL_2_A_11016080", "code_snippet": "#include <bits/stdc++.h>\n#define LOOP(n) for (int _i = 0; _i < (n); _i++)\n#define REP(i, n) for (int i = 0; i < (n); ++i)\n#define RREP(i, n) for (int i = (n); i >= 0; --i)\n#define FOR(i, r, n) for (int i = (r); i < (n); ++i)\n#define ALL(obj) begin(obj), end(obj)\nusing namespace std;\nusing ll = long long;\nconst int INF = 1000100100;\n\ntemplate <class T>\nbool chmin(T &a, const T &b) {\n if (b < a) {\n a = b;\n return 1;\n }\n return 0;\n}\n\nint V, E;\nint G[20][20]; // グラフ\nint dp[50000][20];\n// メモ化再帰\nint rec(int S, int v) { \n if (S == 0) {\n if (v == 0) {\n return 0;\n } else {\n return INF;\n }\n }\n if ((S & (1 << v)) == 0) { // Sに{v}が含まれていない\n return INF;\n }\n\n int &ret = dp[S][v];\n if (ret != 0) return ret;\n\n ret = INF;\n REP(u, V) { chmin(ret, rec(S ^ (1 << v), u) + G[u][v]); }\n return ret;\n}\n\nint main() {\n cin >> V >> E;\n\n // グラフの初期化\n REP(i, 20) {\n REP(j, 20) { G[i][j] = INF; }\n }\n REP(i, E) {\n int s, t, d;\n cin >> s >> t >> d;\n G[s][t] = d;\n }\n\n int ans = rec((1 << V) - 1, 0);\n\n if (ans != INF) {\n cout << ans << endl;\n } else {\n cout << -1 << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5904, "score_of_the_acc": -0.0216, "final_rank": 3 }, { "submission_id": "aoj_DPL_2_A_10934038", "code_snippet": "#include \"bits/stdc++.h\"\nusing namespace std;\n\n#define ll long long\n#define lb long double\n\nconst int MOD = 1e9+7;\nconst int INF = 1e9;\n\nconst int N = 15;\nint dp[1 << N][N];\n\nvoid solve() {\n int v, e;\n cin >> v >> e;\n vector<array<int, 2>> rg[v];\n for (int i = 0; i < e; i++) {\n int s, t, d;\n cin >> s >> t >> d;\n rg[t].push_back({s, d});\n }\n for (int mk = 0; mk < (1 << v); mk++) {\n for (int i = 0; i < v; i++) {\n dp[mk][i] = INF;\n }\n }\n dp[1][0] = 0;\n for (int mk = 1; mk < (1 << v); mk++) {\n for (int i = 0; i < v; i++) {\n if (((mk >> i) & 1) == 0) continue;\n int prev = mk ^ (1 << i);\n for (auto [u, t] : rg[i]) {\n if (((prev >> u) & 1) == 0) continue;\n dp[mk][i] = min(dp[mk][i], dp[prev][u] + t);\n }\n }\n }\n int ans = INF;\n for (auto [u, t] : rg[0]) {\n ans = min(ans, dp[(1 << v) - 1][u] + t);\n }\n cout << (ans == INF ? -1 : ans) << '\\n';\n}\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n // freopen(\"input.txt\", \"r\", stdin);\n // freopen(\"output.txt\", \"w\", stdout);\n\n // freopen(\"input.in\", \"r\", stdin);\n // freopen(\"output.out\", \"w\", stdout);\n\n // int T = 1;\n // cin >> T;\n // while (T--) {\n solve();\n // }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5260, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DPL_2_A_10934016", "code_snippet": "#include \"bits/stdc++.h\"\nusing namespace std;\n\n#define ll long long\n#define lb long double\n\nconst int MOD = 1e9+7;\nconst int INF = 1e9;\n\nconst int N = 15;\nint dp[1 << N][N];\n\nvoid solve() {\n int v, e;\n cin >> v >> e;\n vector<array<int, 2>> rg[v];\n for (int i = 0; i < e; i++) {\n int s, t, d;\n cin >> s >> t >> d;\n rg[t].push_back({s, d});\n }\n for (int mk = 0; mk < (1 << v); mk++) {\n for (int i = 0; i < v; i++) {\n dp[mk][i] = INF;\n }\n }\n dp[1][0] = 0;\n for (int mk = 1; mk < (1 << v); mk++) {\n for (int i = 0; i < v; i++) {\n if (((mk >> i) & 1) == 0) continue;\n int prev = mk ^ (1 << i);\n for (int j = 0; j < v; j++) {\n if (((prev >> j) & 1) == 0) continue;\n for (auto [u, d] : rg[i]) {\n if (u != j || dp[prev][u] == INF) continue;\n dp[mk][i] = dp[prev][u] + d;\n }\n }\n }\n }\n int ans = INF;\n for (int i = 0; i < v; i++) {\n for (auto [u, t] : rg[0]) {\n ans = min(ans, dp[(1 << v) - 1][u] + t);\n }\n }\n cout << (ans == INF ? -1 : ans) << '\\n';\n}\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n // freopen(\"input.txt\", \"r\", stdin);\n // freopen(\"output.txt\", \"w\", stdout);\n\n // freopen(\"input.in\", \"r\", stdin);\n // freopen(\"output.out\", \"w\", stdout);\n\n // int T = 1;\n // cin >> T;\n // while (T--) {\n solve();\n // }\n\n return 0;\n}", "accuracy": 0.375, "time_ms": 10, "memory_kb": 5300, "score_of_the_acc": -0.0013, "final_rank": 20 }, { "submission_id": "aoj_DPL_2_A_10934010", "code_snippet": "#include \"bits/stdc++.h\"\nusing namespace std;\n\n#define ll long long\n#define lb long double\n\nconst int MOD = 1e9+7;\nconst int INF = 1e9;\n\nconst int N = 15;\nint dp[1 << N][N];\n\nvoid solve() {\n int v, e;\n cin >> v >> e;\n vector<array<int, 2>> rg[v];\n for (int i = 0; i < e; i++) {\n int s, t, d;\n cin >> s >> t >> d;\n rg[t].push_back({s, d});\n }\n for (int mk = 0; mk < (1 << v); mk++) {\n for (int i = 0; i < v; i++) {\n dp[mk][i] = INF;\n }\n }\n dp[1][0] = 0;\n for (int mk = 1; mk < (1 << v); mk++) {\n for (int i = 0; i < v; i++) {\n if (((mk >> i) & 1) == 0) continue;\n int prev = mk ^ (1 << i);\n for (int j = 0; j < v; j++) {\n if (((prev >> j) & 1) == 0) continue;\n for (auto [u, d] : rg[i]) {\n if (u != j || dp[prev][u] == INF) continue;\n dp[mk][i] = dp[prev][u] + d;\n }\n }\n }\n }\n int ans = INF;\n for (auto [u, t] : rg[0]) {\n ans = min(ans, dp[(1 << v) - 1][u] + t);\n }\n cout << (ans == INF ? -1 : ans) << '\\n';\n}\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n // freopen(\"input.txt\", \"r\", stdin);\n // freopen(\"output.txt\", \"w\", stdout);\n\n // freopen(\"input.in\", \"r\", stdin);\n // freopen(\"output.out\", \"w\", stdout);\n\n // int T = 1;\n // cin >> T;\n // while (T--) {\n solve();\n // }\n\n return 0;\n}", "accuracy": 0.375, "time_ms": 10, "memory_kb": 5276, "score_of_the_acc": -0.0005, "final_rank": 19 }, { "submission_id": "aoj_DPL_2_A_10934003", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1e9;\nconst int N = 15;\nint dp[1 << N][N];\n\nvoid solve() {\n int v, e;\n cin >> v >> e;\n vector<vector<pair<int,int>>> g(v); // adjacency list: g[u] = {v, cost}\n\n for (int i = 0; i < e; i++) {\n int s, t, d;\n cin >> s >> t >> d;\n g[s].push_back({t, d}); // outgoing edge\n }\n\n // initialize DP table\n for (int mk = 0; mk < (1 << v); mk++)\n for (int i = 0; i < v; i++)\n dp[mk][i] = INF;\n\n dp[1][0] = 0; // start at vertex 0\n\n for (int mk = 1; mk < (1 << v); mk++) {\n for (int u = 0; u < v; u++) {\n if (!(mk & (1 << u))) continue; // u not in mask\n for (auto [v2, cost] : g[u]) {\n if (mk & (1 << v2)) continue; // already visited\n int nxt = mk | (1 << v2);\n dp[nxt][v2] = min(dp[nxt][v2], dp[mk][u] + cost);\n }\n }\n }\n\n int ans = INF;\n for (int u = 1; u < v; u++) {\n for (auto [v2, cost] : g[u]) {\n if (v2 == 0)\n ans = min(ans, dp[(1 << v) - 1][u] + cost);\n }\n }\n\n cout << (ans == INF ? -1 : ans) << '\\n';\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n solve();\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5288, "score_of_the_acc": -0.0009, "final_rank": 2 }, { "submission_id": "aoj_DPL_2_A_10889023", "code_snippet": "#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n// #include <atcoder/all>\n// using namespace atcoder;\n\nusing ll = long long; // 2^63-1まで 負の値は可\nusing ull = unsigned long long; // 0<= ull <=2^64-1の範囲 負の値は不可\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing P = pair<ll, ll>;\ntemplate <typename T>\nusing MNPQ = priority_queue<T, vector<T>, greater<T>>;\ntemplate <typename T>\nusing MXPQ = priority_queue<T, vector<T>, less<T>>;\n\n#define rep(i, n) for (int i = 0; i < n; i++)\n#define srep(i, s, n) for (int i = s; i < n; i++)\n#define rrep(i, s, n) for (int i = s; i > n; i--)\n#define chmax(x, y) x = max(x, y)\n#define chmin(x, y) x = min(x, y)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define vunique(v) v.erase(unique(nall(v)), v.end())\n#define IN(a, x) find(nall(a), x) != a.end()\n#define YN(flg) cout << (flg ? \"Yes\" : \"No\") << \"\\n\"\n#define out_grid(x, y, h, w) !(0 <= x && x < h && 0 <= y && y < w)\n#define lmd(...) [&](__VA_ARGS__)\n#define debug(x) cerr << #x << \" = \" << x << endl;\nconst ll INF = 2e18;\n\ntemplate <typename T>\nistream& operator>>(istream& is, vector<T>& a) {\n for (auto& x : a) is >> x;\n return is;\n}\n\ntemplate <typename T>\nostream& operator<<(ostream& os, vector<T>& a) {\n for (int i = 0; i < (int)a.size(); i++) os << a[i] << \" \";\n return os;\n}\n\ntemplate <typename T1, typename T2>\nostream& operator<<(ostream& os, pair<T1, T2>& p) {\n os << \"{\" << p.first << \",\" << p.second << \"}\";\n return os;\n}\n\ntemplate <typename K, typename V>\nostream& operator<<(ostream& os, map<K, V>& a) {\n for (auto& [k, v] : a) os << \"{key:\" << k << \", item:\" << v << \"} \";\n return os;\n}\n\nstruct Edge {\n ll to, w;\n};\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n ll v, e;\n cin >> v >> e;\n\n vector<vector<Edge>> graph(v);\n rep(i, e) {\n ll s, t, d;\n cin >> s >> t >> d;\n graph[s].push_back({t, d});\n }\n\n vector dp(1 << v, vector<ll>(v, INF));\n dp[1][0] = 0;\n\n rep(i, 1 << v) {\n rep(j, v) {\n if (i >> j & 1) {\n for (auto edge : graph[j]) {\n chmin(dp[i][j], dp[i - (1 << j)][edge.to] + edge.w);\n }\n }\n }\n }\n\n ll ans = INF;\n for (auto edge : graph[0]) chmin(ans, dp.back()[edge.to] + edge.w);\n cout << (ans == INF ? -1 : ans) << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 9216, "score_of_the_acc": -0.6885, "final_rank": 14 }, { "submission_id": "aoj_DPL_2_A_10889014", "code_snippet": "#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n// #include <atcoder/all>\n// using namespace atcoder;\n\nusing ll = long long; // 2^63-1まで 負の値は可\nusing ull = unsigned long long; // 0<= ull <=2^64-1の範囲 負の値は不可\nusing vl = vector<ll>;\nusing vvl = vector<vl>;\nusing P = pair<ll, ll>;\ntemplate <typename T>\nusing MNPQ = priority_queue<T, vector<T>, greater<T>>;\ntemplate <typename T>\nusing MXPQ = priority_queue<T, vector<T>, less<T>>;\n\n#define rep(i, n) for (int i = 0; i < n; i++)\n#define srep(i, s, n) for (int i = s; i < n; i++)\n#define rrep(i, s, n) for (int i = s; i > n; i--)\n#define chmax(x, y) x = max(x, y)\n#define chmin(x, y) x = min(x, y)\n#define nall(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define vunique(v) v.erase(unique(nall(v)), v.end())\n#define IN(a, x) find(nall(a), x) != a.end()\n#define YN(flg) cout << (flg ? \"Yes\" : \"No\") << \"\\n\"\n#define out_grid(x, y, h, w) !(0 <= x && x < h && 0 <= y && y < w)\n#define lmd(...) [&](__VA_ARGS__)\n#define debug(x) cerr << #x << \" = \" << x << endl;\nconst ll INF = 2e18;\n\ntemplate <typename T>\nistream& operator>>(istream& is, vector<T>& a) {\n for (auto& x : a) is >> x;\n return is;\n}\n\ntemplate <typename T>\nostream& operator<<(ostream& os, vector<T>& a) {\n for (int i = 0; i < (int)a.size(); i++) os << a[i] << \" \";\n return os;\n}\n\ntemplate <typename T1, typename T2>\nostream& operator<<(ostream& os, pair<T1, T2>& p) {\n os << \"{\" << p.first << \",\" << p.second << \"}\";\n return os;\n}\n\ntemplate <typename K, typename V>\nostream& operator<<(ostream& os, map<K, V>& a) {\n for (auto& [k, v] : a) os << \"{key:\" << k << \", item:\" << v << \"} \";\n return os;\n}\n\nstruct Edge {\n ll to, w;\n};\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n ll v, e;\n cin >> v >> e;\n\n vector<vector<Edge>> graph(v);\n rep(i, e) {\n ll s, t, d;\n cin >> s >> t >> d;\n graph[s].push_back({t, d});\n }\n\n vector dp(1 << v, vector<ll>(v, INF));\n dp[1][0] = 0;\n\n rep(i, 1 << v) {\n rep(j, v) {\n if (i >> j & 1) {\n for (auto edge : graph[j]) {\n if (i & (1 << j))\n chmin(dp[i][j], dp[i - (1 << j)][edge.to] + edge.w);\n }\n }\n }\n }\n\n ll ans = INF;\n for (auto edge : graph[0]) chmin(ans, dp.back()[edge.to] + edge.w);\n cout << (ans == INF ? -1 : ans) << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 9216, "score_of_the_acc": -0.6885, "final_rank": 14 }, { "submission_id": "aoj_DPL_2_A_10886476", "code_snippet": "#include <bits/stdc++.h>\n#define int long long\nusing namespace std;\n\nvoid solve() {\n int n, m; cin >> n >> m;\n vector<vector<int>> dist(n, vector<int>(n, 1e9));\n for (int i = 0; i < m; i ++) {\n int a, b, d; cin >> a >> b >> d;\n dist[a][b] = min(dist[a][b], d);\n }\n vector<vector<int>> dp(1 << n, vector<int>(n, 1e9));\n dp[1][0] = 0;\n for (int mask = 1; mask < (1 << n); mask ++) {\n for (int u = 0; u < n; u ++) {\n if (!(mask & (1 << u))) {\n continue;\n }\n for (int v = 0; v < n; v ++) {\n if (mask & (1 << v)) {\n continue;\n }\n dp[mask | (1 << v)][v] = min(dp[mask | (1 << v)][v], dp[mask][u] + dist[u][v]);\n }\n }\n }\n int ans = 1e9;\n for (int u = 0; u < n; u ++) {\n ans = min(ans, dp[(1 << n) - 1][u] + dist[u][0]);\n }\n if (ans != 1e9) {\n cout << ans << endl;\n } else {\n cout << -1 << endl;\n }\n}\n\nsigned main() {\n// #ifndef ONLINE_JUDGE\n// freopen(\"in.txt\", \"rt\", stdin);\n// freopen(\"out.txt\", \"wt\", stdout);\n// #endif\n int T = 1; // cin >> T;\n while (T --) solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8192, "score_of_the_acc": -0.0985, "final_rank": 10 }, { "submission_id": "aoj_DPL_2_A_10880658", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int N, E;\n cin >> N >> E;\n int INF=1e9;\n vector<vector<int>> dist(N,vector<int>(N,INF));\n for(int i=0; i<E; i++){\n int s, t, d;\n cin >> s >> t >> d;\n dist[s][t]=d;\n }\n\n vector<vector<int>> dp((1<<N), vector<int>(N,INF));\n dp[0][0]=0;\n for(int i=0; i<(1<<N); i++){\n for(int j=0; j<N; j++){\n if(i==0 || (i&(1<<j))){\n for(int k=0; k<N; k++){\n if(!(i&(1<<k)) && dist[j][k]!=INF){\n int ni=(i|(1<<k));\n dp[ni][k]=min(dp[ni][k],dp[i][j]+dist[j][k]);\n }\n }\n }\n }\n }\n\n if(dp[(1<<N)-1][0]==INF){\n cout << -1 << endl;\n }\n else{\n cout << dp[(1<<N)-1][0] << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6364, "score_of_the_acc": -0.0371, "final_rank": 4 }, { "submission_id": "aoj_DPL_2_A_10855902", "code_snippet": "#include <iostream>\n#include <utility>\n#include <vector>\n\nint main()\n{\n unsigned int V, E, s, t, d;\n std::cin >> V >> E;\n std::vector<std::vector<unsigned int>> G(V, std::vector<unsigned int>(V, -1));\n for (auto i = 0u; i < E; i++) {\n std::cin >> s >> t >> d;\n G[s][t] = d;\n }\n\n constexpr unsigned int INF = 1'000'000'000;\n std::vector<std::vector<unsigned int>> DP(1 << V, std::vector<unsigned int>(V, INF));\n DP[0][0] = 0;\n\n for (auto set = 0u; set < (1u << V); set++) {\n for (auto prev = 0u; prev < V; prev++) {\n for (auto next = 0u; next < V; next++) {\n if ((set & (1 << next)) ||\n (prev == next) ||\n (G[prev][next] == static_cast<unsigned int>(-1))\n ) {\n continue;\n }\n\n DP[set | (1 << next)][next] = std::min(\n DP[set | (1 << next)][next],\n DP[set][prev] + G[prev][next]\n );\n }\n }\n }\n\n unsigned int ans = DP[(1 << V) - 1][0];\n std::cout << (ans == INF ? -1 : static_cast<int>(ans)) << std::endl;\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6656, "score_of_the_acc": -0.0469, "final_rank": 7 }, { "submission_id": "aoj_DPL_2_A_10854419", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n int V, E; cin >> V >> E;\n vector<vector<int>> G(V, vector<int>(V, -1));\n for (int _ = 0; _ < E; ++_) {\n int s, t, d; cin >> s >> t >> d;\n G[s][t] = d;\n }\n\n vector<vector<int>> dp((1<<V), vector<int>(V, -1)); //dp[S][v] = 訪問した集合がSで現在vにいるときの最小移動距離\n dp[1][0] = 0;\n for (int S = 1; S < (1 << V); ++S) {\n for (int v = 0; v < V; ++v) {\n //vは今回訪問するところ\n if (!(S & (1 << v))) continue;\n int prevS = S ^ (1 << v);\n for (int u = 0; u < V; ++u) {\n //uはひとつ前に訪問したところ\n if (!(prevS & (1 << u))) continue; //uがprevSに含まれない\n if (G[u][v] == -1) continue; //uからvには行けない\n if (dp[prevS][u] == -1) continue; //uが前回の訪問先になることはない\n int cost = dp[prevS][u] + G[u][v];\n if (dp[S][v] == -1 || dp[S][v] > cost) {\n dp[S][v] = cost;\n }\n }\n }\n }\n\n int ans = INT_MAX;\n for (int v = 1; v < V; ++v) {\n if (G[v][0] == -1) continue;\n if (dp[(1 << V) - 1][v] == -1) continue;\n ans = min(ans, dp[(1 << V) -1][v] + G[v][0]);\n }\n if (ans == INT_MAX) cout << -1 << endl;\n else cout << ans << endl;\n return 0;\n \n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6380, "score_of_the_acc": -0.0376, "final_rank": 5 }, { "submission_id": "aoj_DPL_2_A_10852684", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <set>\n#include <climits>\n#include <queue>\n#include <map>\n#include <cmath>\n#include <sstream>\n#include <bitset>\nusing namespace std;\ntypedef long long int ll;\n#define MAX_V 16\nint adjMat[MAX_V][MAX_V];\nbool visited[MAX_V][1<<MAX_V];//visited存的並非節點是否有訪問過,而是這個狀態是否有出現過\nint dp[MAX_V][1<<MAX_V];//DP表格,第一個中括號代表目前所在的點\n//第二個中括號代表目前節點的狀態(ex:0101011,表示1,3,5節點還沒走過,可以直接用bitwise操作來判斷狀態)\n//因為DP表格是N*2^N次方,所以時間複雜度就是O(N*2^N)\nint v,e;\n\nconst char *byte_to_binary(int x)\n{\n static char b[9];\n b[0] = '\\0';\n\n int z;\n for (z = 128; z > 0; z >>= 1)\n {\n strcat(b, ((x & z) == z) ? \"1\" : \"0\");\n }\n\n return b;\n}\nint TSP(int at,int state)\n{\n // printf(\"at=%d,state=%s\\n\",at, byte_to_binary(state));\n if(state == (1<<v)-1 && at==0){ //全部的狀態都走完而且回到起點惹\n visited[at][state]=true;\n return dp[at][state];\n }\n if(dp[at][state]) //出現過的狀態,直接回傳結果\n return dp[at][state];\n int ans = INT_MAX>>1;\n int cost;\n for(int i=0;i<v;i++){\n //state&(1<<i)==0表示判斷右邊數過來第i個bit是否為0,用來判斷該節點是否有走過\n //state|(1<<i)表示將該節點設成走過\n if(adjMat[at][i]!=-1 && (state & (1<<i))==0){\n // printf(\"at=%d->i=%d\\n\",at,i);\n cost = TSP(i,state|(1<<i)) + adjMat[at][i];//往每種可以走的路線都走下去\n // printf(\"at=%d->i=%d,cost=%d\\n\",at,i,cost);\n ans = min(ans,cost);//求出最小值\n }\n }\n return dp[at][state] = ans;\n}\n//\nint main()\n{ \n // freopen(\"in\",\"r\",stdin);\n while(~scanf(\"%d %d\",&v,&e)){\n memset(adjMat,-1,sizeof(adjMat));\n for(int i=0;i<e;i++){\n int u,v,w;\n scanf(\"%d%d%d\",&u,&v,&w);\n adjMat[u][v]=w;\n }\n memset(dp,0,sizeof(dp));\n memset(visited,0,sizeof(visited));\n int ans = TSP(0,0);\n if(ans>=INT_MAX>>1)\n puts(\"-1\");\n else\n printf(\"%d\\n\",ans);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8688, "score_of_the_acc": -0.1152, "final_rank": 11 }, { "submission_id": "aoj_DPL_2_A_10807816", "code_snippet": "#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <queue>\n#include <algorithm>\n#include <set>\nusing namespace std;\n\nconst int INF = 10000000;\nconst int VISITED = 100000;\n\nint dp(int from, int to, int bit, vector<vector<int>> &memo, const vector<vector<pair<int, int>>> &adj) {\n if (memo[from][bit] != INF) return memo[from][bit];\n if ((1<<from) == bit) {\n bit -= (1<<from);\n for (auto con : adj[from]) {\n auto [u, w] = con;\n if (u == to) memo[from][bit] = w;\n }\n if (memo[from][bit] == INF) memo[from][bit] = VISITED;\n return memo[from][bit];\n }\n for (auto con : adj[from]) {\n auto [nxt, w] = con;\n if (((1<<nxt) & bit) && nxt != to) {\n int nxt_bit = bit - (1<<from);\n if (memo[nxt][nxt_bit] == INF) memo[nxt][nxt_bit] = dp(nxt, to, nxt_bit, memo, adj);\n memo[from][bit] = min(memo[from][bit], memo[nxt][nxt_bit] + w);\n }\n }\n return memo[from][bit];\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int V, E;\n cin >> V >> E;\n \n vector<vector<pair<int,int>>> adj(V);\n for (int i = 0; i < E; ++i) {\n int s, t, w;\n cin >> s >> t >> w;\n adj[s].emplace_back(make_pair(t, w));\n }\n\n int bit = (1<<V);\n vector<vector<int>> memo(V, vector<int>(bit, INF));\n\n int result = INF;\n for (int i = 0; i < V; ++i) {\n vector<vector<int>> now_memo = memo;\n result = min(result, dp(i, i, bit-1, now_memo, adj));\n }\n \n // for (auto m : memo) {\n // for (auto i : m) {\n // cout << i << \" \";\n // }\n // cout << endl;\n // }\n\n if (VISITED <= result) cout << -1 << endl;\n else cout << result << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 7040, "score_of_the_acc": -0.6154, "final_rank": 12 }, { "submission_id": "aoj_DPL_2_A_10807771", "code_snippet": "#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <queue>\n#include <algorithm>\n#include <set>\nusing namespace std;\n\nconst int INF = 10000000;\nconst int VISITED = 100000;\n\nint dp(int from, int to, int bit, vector<vector<vector<int>>> &memo, const vector<vector<pair<int, int>>> &adj) {\n if (memo[from][to][bit] != INF) return memo[from][to][bit];\n if ((1<<from) + (1<<to) == bit) {\n for (auto con : adj[from]) {\n auto [u, w] = con;\n if (u == to) memo[from][to][bit] = w;\n }\n if (memo[from][to][bit] == INF) memo[from][to][bit] = VISITED;\n return memo[from][to][bit];\n }\n for (auto con : adj[from]) {\n auto [nxt, w] = con;\n if (((1<<nxt) & bit) && nxt != to) {\n int nxt_bit = bit - (1<<from);\n if (from == to) nxt_bit += (1<<to);\n if (memo[nxt][to][nxt_bit] == INF) memo[nxt][to][nxt_bit] = dp(nxt, to, nxt_bit, memo, adj);\n memo[from][to][bit] = min(memo[from][to][bit], memo[nxt][to][nxt_bit] + w);\n }\n }\n return memo[from][to][bit];\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int V, E;\n cin >> V >> E;\n \n vector<vector<pair<int,int>>> adj(V);\n for (int i = 0; i < E; ++i) {\n int s, t, w;\n cin >> s >> t >> w;\n adj[s].emplace_back(make_pair(t, w));\n }\n\n int bit = (1<<V);\n vector<vector<vector<int>>> memo(V, vector<vector<int>>(V, vector<int>(bit,INF)));\n\n int result = INF;\n for (int i = 0; i < V; ++i) {\n result = min(result, dp(i, i, bit-1, memo, adj));\n }\n \n // for (auto m : memo) {\n // for (auto n : m) {\n // for (auto i : n) {\n // cout << i << \" \";\n // }\n // cout << endl;\n // }\n // cout << endl;\n // }\n\n if (VISITED <= result) cout << -1 << endl;\n else cout << result << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 35020, "score_of_the_acc": -1.6667, "final_rank": 18 }, { "submission_id": "aoj_DPL_2_A_10803245", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nstruct Edge{\n\n int to;\n ll cost;\n\n Edge( int _to, ll _cost ){\n\n to = _to;\n cost = _cost;\n\n }\n\n};\n\nstruct Graph{\n\n int size;\n vector< vector<Edge> > adj;\n\n Graph( int _size ){\n\n size = _size;\n for( int i = 0 ; i < size ; i++ ){\n vector<Edge> tmp;\n adj.push_back( tmp );\n }\n\n }\n\n ll tsp(){\n\n vector<vector<ll>> dp;\n for( int i = 0 ; i < ( 1 << size ) ; i++ ){\n vector<ll> v;\n for( int j = 0 ; j < size ; j++ )\n v.push_back( INF );\n dp.push_back( v );\n }\n dp[(1<<size)-1][0] = 0;\n for( int i = ( 1 << size ) - 1 ; i >= 0 ; i-- ){\n for( int j = 0 ; j < size ; j++ ){\n for( int k = 0 ; k < adj[j].size() ; k++ ){\n Edge e = adj[j][k];\n if( ( ( i >> e.to ) & 1 ) == 0 )\n dp[i][j] = min( dp[i][j], dp[i|(1 << e.to)][e.to] + e.cost );\n }\n }\n }\n return dp[0][0] == INF ? -1 : dp[0][0];\n\n }\n \n};\n\nint main(){\n\n int V, E, s, t;\n ll d;\n\n cin >> V >> E;\n Graph g( V );\n for( int i = 0 ; i < E ; i++ ){\n cin >> s >> t >> d;\n Edge e( t, d );\n g.adj[s].push_back( e );\n }\n\n cout << g.tsp() << endl;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8036, "score_of_the_acc": -0.0933, "final_rank": 9 }, { "submission_id": "aoj_DPL_2_A_10767523", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n int64_t v, e, ans = 1000000, goal = 1;\n ans++;\n cin >> v >> e;\n vector<vector<int64_t>> dp(v, vector<int64_t> (32800, 100000));\n vector<int64_t> vp(v, 1);//場所の数字\n \n queue<int64_t> qp;//今いる場所place\n queue<int64_t> qhis;//すでに通った場所history\n \n for(int64_t i = 1; i < v; i++){\n vp.at(i) = vp.at(i - 1) * 2;\n goal *= 2;\n }\n goal *= 2;\n goal--;///goalは2^v-1\n \n vector<vector<int64_t>> path(v, vector<int64_t> (v, 10000000));//道の長さ1,2,3...v\n for(int64_t i = 0; i < e; i++){\n int64_t s, t, d;\n cin >> s >> t >> d;\n t--;\n s--;\n if(t == -1){\n t += v;\n }\n if(s == -1){\n dp.at(t).at(vp.at(t)) = d;\n qp.push(t);\n qhis.push(vp.at(t));\n } else{\n path.at(s).at(t) = d;\n }\n }\n \n /*debug*///////////////////////////////////////////\n /*cout <<\"goal\" << goal << endl;\n cout << \"path\" << endl;\n for(int64_t i = 0; i < v; i++){\n for(int64_t j = 0; j < v; j++){\n if(path.at(i).at(j) != 10000000){\n cout << path.at(i).at(j) << \"_\";\n } else{\n cout << \"x_\";\n }\n }\n cout << endl;\n }\n cout << \"vp dp\" << endl;\n for(int64_t i = 0; i < v; i++){\n cout << vp.at(i) << \"to\";\n for(int64_t j = 0; j < goal + 1; j++){\n if(dp.at(i).at(j) != 100000){\n cout << dp.at(i).at(j) << \" \";\n } else{\n cout << \"x\" << \" \";\n }\n }\n cout << endl;\n }*/\n /////////////////////////////////////////////////////\n \n while(!qp.empty()){\n bitset<15> bitto(qhis.front());\n ///////////////////////////////////cout <<\"qp\" << qp.front() << \"qhis\" << bitto << endl;\n int64_t ima = qp.front(), tootta = qhis.front(), mtnr = dp.at(ima).at(tootta);\n for(int64_t i = 0; i < v; i++){\n int64_t d = path.at(ima).at(i), Mtnr = mtnr + d, ikisaki = tootta + vp.at(i);\n if(ikisaki / vp.at(i) % 2 == 1){\n if(dp.at(i).at(ikisaki) > Mtnr){\n dp.at(i).at(ikisaki) = Mtnr;\n qp.push(i);\n qhis.push(ikisaki);\n }\n } else{\n ///////////////////////////cout << ikisaki << endl;\n }\n }\n qp.pop();\n qhis.pop();\n }\n \n /*for(int64_t i = 0; i < v; i++){\n dp.at(vp.at(i)).at(i) = 0;\n int64_t ic;\n ic = path.at(i).size();\n for(int64_t j = 0; j < ic; j++){\n q.push((path.at(i).at(j) % 100) + vp.at(i) * 10000 + 100 * i);//下2桁が行先、下3,4桁が今いる場所、それ以外がすでに経由した場所\n }\n while(!q.empty()){\n int64_t stl, frm, to1, res;\n stl = q.front() / 10000;//すでに経由した場所\n frm = (q.front() % 10000) / 100;\n to1 = q.front() % 100;//行先\n \n bitset<15> zo(stl);\n res = stl + vp.at(to1);\n if(dp.at(to1).at(res) > dp.at(frm).at(stl)){\n \n }\n \n q.pop();\n }\n }*/ \n /*for(int64_t i = 0; i < v; i++){\n cout << vp.at(i) << \"to\";\n for(int64_t j = 0; j < goal + 1; j++){\n if(dp.at(i).at(j) != 100000){\n cout << dp.at(i).at(j) << \" \";\n } else{\n cout << \"x\" << \" \";\n }\n }\n cout << endl;\n }*/\n if(dp.at(v - 1).at(goal) == 100000){\n cout << -1 << endl;\n return 0;\n }\n cout << dp.at(v-1).at(goal) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 8000, "score_of_the_acc": -0.6476, "final_rank": 13 }, { "submission_id": "aoj_DPL_2_A_10764664", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing P = pair<int, int>;\n#define chmin(x, y) x = min(x, y)\n#define chmax(x, y) x = max(x, y)\n\nint inf = 10010010;\n\nint main()\n{\n int v, e;\n cin >> v >> e;\n vector<vector<pair<int, int>>> box(v + 5);\n vector<vector<int>> box2(v + 5, vector<int>(v + 5, -1));\n for (int i = 0; i < e; ++i)\n {\n int s, t, d;\n cin >> s >> t >> d;\n box[s].emplace_back(t, d);\n box2[s][t] = d;\n }\n int ans = inf;\n for (int i = 0; i < v; ++i)\n {\n vector<vector<int>> dp((1 << v) + 5, vector<int>(v + 5, inf));\n dp[1 << i][i] = 0;\n for (int j = 1 << i; j < (1 << v); ++j)\n {\n for (int k = 0; k < v; ++k)\n {\n if (dp[j][k] == inf)\n continue;\n for (const auto &edge : box[k])\n\n {\n int t = edge.first;\n int d = edge.second;\n if ((j & (1 << t)) != 0)\n continue;\n int visited = j | (1 << t);\n dp[visited][t] = min(dp[visited][t], dp[j][k] + d);\n }\n }\n }\n for (int j = 0; j < v; ++j)\n {\n if (box2[j][i] == -1)\n continue;\n ans = min(ans, dp[(1 << v) - 1][j] + box2[j][i]);\n }\n }\n if (ans == inf)\n {\n ans = -1;\n }\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 6940, "score_of_the_acc": -1.0565, "final_rank": 16 }, { "submission_id": "aoj_DPL_2_A_10761012", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nint main() {\n int v, e;\n cin >> v >> e;\n\n const int INF = 1e9;\n vector<vector<pair<int, int>>> box(v + 5); // 隣接リスト\n vector<vector<int>> box2(v + 5, vector<int>(v + 5, -1)); // 辺の重み\n\n for (int i = 0; i < e; ++i) {\n int s, t, d;\n cin >> s >> t >> d;\n box[s].emplace_back(t, d);\n box2[s][t] = d;\n }\n\n int ans = INF;\n for (int i = 0; i < v; ++i) {\n vector<vector<int>> dp((1 << v) + 5, vector<int>(v + 5, INF));\n dp[1 << i][i] = 0;\n\n for (int j = 0; j < (1 << v); ++j) {\n for (int k = 0; k < v; ++k) {\n if (dp[j][k] == INF) continue;\n\n for (auto& [t, d] : box[k]) {\n if (j & (1 << t)) continue;\n\n int visited = j | (1 << t);\n dp[visited][t] = min(dp[visited][t], dp[j][k] + d);\n }\n }\n }\n\n for (int j = 0; j < v; ++j) {\n if (box2[j][i] == -1) continue;\n\n int cost = dp[(1 << v) - 1][j] + box2[j][i];\n ans = min(ans, cost);\n }\n }\n\n if (ans == INF) ans = -1;\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 7040, "score_of_the_acc": -1.0598, "final_rank": 17 }, { "submission_id": "aoj_DPL_2_A_10750212", "code_snippet": "#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <algorithm>\n#include <tuple>\n#include <set>\n#include <map>\n#include <bitset>\n#include <cmath>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <cassert>\n#include <unordered_set>\n#include <unordered_map>\n#include <cmath>\nusing namespace std;\ntypedef long long ll;\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)\n#define all(v) v.begin(), v.end()\n\nll llpow(ll a, ll t)\n{\n ll res = 1;\n rep(i, t) res *= a;\n return res;\n}\n\nll inf = std::numeric_limits<ll>::max();\n\nint main()\n{\n ll v, e;\n cin >> v >> e;\n vector<vector<ll>> g(v, vector<ll>(v, 10e8));\n rep(i, e)\n {\n ll s, t, d;\n cin >> s >> t >> d;\n g[s][t] = d;\n }\n vector<vector<ll>> dp(llpow(2, v), vector<ll>(v, 10e8));\n dp[1 << 0][0] = 0;\n rep(i, 1 << v) // llpow(2,v) と同意\n {\n rep(j, v)\n {\n rep(k, v)\n {\n if ((i >> j & 1) && !(i >> k & 1) && g[j][k] != 10e8)\n {\n dp[i | 1 << k][k] = min(dp[i | 1 << k][k], dp[i][j] + g[j][k]);\n }\n }\n }\n }\n ll ans = 10e8;\n rep(i, v)\n {\n ans = min(ans, dp[(1 << v) - 1][i] + g[i][0]);\n }\n if (ans == 10e8)\n {\n cout << -1 << endl;\n }\n else\n {\n cout << ans << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7796, "score_of_the_acc": -0.0852, "final_rank": 8 } ]
aoj_DPL_3_A_cpp
Largest Square Given a matrix ( H × W ) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s. Input H W c 1,1 c 1,2 ... c 1,W c 2,1 c 2,2 ... c 2,W : c H,1 c H,2 ... c H,W In the first line, two integers H and W separated by a space character are given. In the following H lines, c i , j , elements of the H × W matrix, are given. Output Print the area (the number of 0s) of the largest square. Constraints 1 ≤ H , W ≤ 1,400 Sample Input 4 5 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 Sample Output 4
[ { "submission_id": "aoj_DPL_3_A_11010294", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std ;\n#define pb push_back\n#define ll long long \nconst ll mod = 1e9+7;\n\nbool check(ll x , ll n, ll m, vector<vector<ll>>&ps){\n for(ll i=0;i+x-1<n;i++){\n for(ll j=0;j+x-1<m;j++){\n ll x1 = i, y1 = j, x2 = x1+x-1, y2 = y1+x-1;\n ll sum = ps[x2][y2];\n if(y1)sum -= ps[x2][y1-1];\n if(x1)sum -= ps[x1-1][y2];\n if(x1 and y1) sum += ps[x1-1][y1-1];\n if(!sum)return 1;\n }\n }\n return 0;\n}\n\n\nvoid solve(){\n ll n,m;\n cin>>n>>m;\n\n vector<vector<ll>>arr(n,vector<ll>(m));\n vector<vector<ll>>ps(n,vector<ll>(m));\n\n\n for(ll i=0;i<n;i++){\n for(ll j=0;j<m;j++){\n cin>>arr[i][j];\n if(j)arr[i][j] += arr[i][j-1];\n }\n }\n\n for(ll i=0;i<n;i++){\n for(ll j=0;j<m;j++){\n ps[i][j] = arr[i][j];\n if(i) ps[i][j] += ps[i-1][j];\n }\n }\n\n\n ll lo = 1, hi = min(n,m), ans = 0;\n\n while(lo<=hi){\n ll mid = (lo+hi)/2;\n if(check(mid,n,m,ps)){\n ans = mid;\n lo = mid+1;\n }\n else {\n hi = mid-1;\n }\n }\n\n cout<<ans * ans <<endl;\n\n\n \n}\n\n\nint main(){\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n\n int t =1;\n // cin>>t;\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 33964, "score_of_the_acc": -1.0844, "final_rank": 14 }, { "submission_id": "aoj_DPL_3_A_10988187", "code_snippet": "#include <cstdio>\n#include <algorithm>\nusing namespace std;\nconst int maxv=1401;\nint dp[maxv][maxv];\nint c[maxv][maxv];\nint H,W;\nint maxsquare(){\n int maxwidth=0;\n for(int i=1;i<=H;i++){\n for(int j=1;j<=W;j++){\n if(c[i][j]){\n dp[i][j]=0;\n }else {\n dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;\n maxwidth=max(maxwidth,dp[i][j]);\n }\n }\n }\n return maxwidth;\n}\nint main(){\n scanf(\"%d %d\",&H,&W);\n for(int i=0;i<=H;i++){\n dp[i][0]=0;\n }\n for(int i=0;i<=W;i++){\n dp[0][i]=0;\n }\n for(int i=1;i<=H;i++){\n for(int j=1;j<=W;j++){\n int g;\n scanf(\"%d\",&g);\n c[i][j]=g;\n }\n }\n int l=maxsquare();\n printf(\"%d\\n\",l*l);\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 18288, "score_of_the_acc": -0.5329, "final_rank": 8 }, { "submission_id": "aoj_DPL_3_A_10862256", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int h, w;\n cin >> h >> w;\n int grid[h][w];\n for (int i = 0; i < h; i++)\n {\n for (int j = 0; j < w; j++)\n {\n cin >> grid[i][j];\n }\n }\n\n int dp[h][w];\n\n int ans = 0;\n\n for (int i = 0; i < h; i++)\n {\n for (int j = 0; j < w; j++)\n {\n dp[i][j] = (grid[i][j] == 1 ? 0 : 1);\n ans |= dp[i][j];\n }\n }\n\n for (int j = 0; j < w; j++)\n {\n dp[0][j] = (grid[0][j] == 1 ? 0 : 1);\n }\n\n for (int i = 1; i < h; i++)\n {\n for (int j = 1; j < w; j++)\n {\n if (grid[i][j] == 1)\n {\n dp[i][j] = 0;\n }\n else\n {\n dp[i][j] = min( min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1] ) + 1;\n ans = max(ans, dp[i][j]);\n }\n }\n }\n\n cout << (ans*ans) << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 18636, "score_of_the_acc": -0.6346, "final_rank": 10 }, { "submission_id": "aoj_DPL_3_A_10862252", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int h, w;\n cin >> h >> w;\n int grid[h][w];\n for (int i = 0; i < h; i++)\n {\n for (int j = 0; j < w; j++)\n {\n cin >> grid[i][j];\n }\n }\n\n int dp[h][w];\n\n int ans = (grid[0][0] == 1 ? 0 : 1);\n\n for (int i = 0; i < h; i++)\n {\n dp[i][0] = (grid[i][0] == 1 ? 0 : 1);\n }\n\n for (int j = 0; j < w; j++)\n {\n dp[0][j] = (grid[0][j] == 1 ? 0 : 1);\n }\n\n for (int i = 1; i < h; i++)\n {\n for (int j = 1; j < w; j++)\n {\n if (grid[i][j] == 1)\n {\n dp[i][j] = 0;\n }\n else\n {\n dp[i][j] = min( min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1] ) + 1;\n ans = max(ans, dp[i][j]);\n }\n }\n }\n\n cout << (ans*ans) << endl;\n\n return 0;\n}", "accuracy": 0.775, "time_ms": 30, "memory_kb": 6420, "score_of_the_acc": -0.0738, "final_rank": 19 }, { "submission_id": "aoj_DPL_3_A_10851196", "code_snippet": "#include <iostream>\n#include <cstdio>\nusing namespace std;\n\nconst int maxn = 1400 + 5;\n\nint Getint(){\n\tchar c = getchar();\n\tbool flag = false;\n\tint ans = 0;\n\twhile(c != '-' && (c < '0' || c > '9'))c = getchar();\n\tif(c == '-')flag = true,c = getchar();\n\twhile(c >= '0' && c <= '9')ans = ans*10 + c-'0',c = getchar();\n\treturn (flag == true) ? - ans : ans;\n}\n\nint N,M;\nint ch[maxn][maxn];\nint f[maxn][maxn];\n\nint DP(){\n\tint ans = 0;\n\t\n\tfor(int i = 1;i <= N; i++){\n\t\tfor(int j = 1;j <= M; j++){\n\t\t\tf[i][j] = (ch[i][j] + 1) % 2;\n\t\t\tans |= f[i][j];\n\t\t}\n\t}\n\t\n\tfor(int i = 1;i <= N; i++){\n\t\tfor(int j = 1;j <= M; j++){\n\t\t\tif(ch[i][j] == 1)f[i][j] = 0;\n\t\t\telse ans = max(ans,f[i][j] = min(f[i-1][j],min(f[i][j-1],f[i-1][j-1]))+1);\n\t\t}\n\t}\n\t\n\treturn ans*ans;\n}\n\nint main(){\n\tN = Getint();\n\tM = Getint();\n\tfor(int i = 1;i <= N; i++){\n\t\tfor(int j = 1;j <= M; j++){\n\t\t\tch[i][j] = Getint();\n\t\t}\n\t}\n\tint ans = DP();\n\tprintf(\"%d\\n\",ans);\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18968, "score_of_the_acc": -0.4793, "final_rank": 5 }, { "submission_id": "aoj_DPL_3_A_10796694", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nbool c[1405][1405];\nint dp[1405][1405];\nint main(){\n\tint h,w;\n\tcin>>h>>w;\n\tint i,j;\n\tfor(i=1;i<=h;i++){\n\t\tfor(j=1;j<=w;j++){\n\t\t\tcin>>c[i][j];\n\t\t\tif(!c[i][j]){\n\t\t\t\tdp[i][j]=1;\n\t\t\t}\n\t\t}\n\t}\n\tint ans=0;\n\tfor(i=1;i<=h;i++){\n\t\tfor(j=1;j<=w;j++){\n\t\t\tif(!c[i][j]){\n\t\t\t\tdp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;\n\t\t\t}\n\t\t\tans=max(ans,dp[i][j]);\n\t\t}\n\t}\n\tcout<<ans*ans<<endl;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 12796, "score_of_the_acc": -0.4467, "final_rank": 4 }, { "submission_id": "aoj_DPL_3_A_10726388", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long \n#define endl '\\n'\nvoid solve(){\n int n,m;cin>>n>>m;\n int c[n+1][m+1];\n for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) cin>>c[i][j];\n\tint dp[n+1][m+1];\n\tfor(int i=0;i<=n;i++) for(int j=0;j<=m;j++) dp[i][j]=0;\n\tfor(int i=1;i<=n;i++){\n\t\tfor(int j=1;j<=m;j++){\n\t\t \tif(c[i][j]) dp[i][j]=0;\n\t\t \telse if(dp[i-1][j]!=dp[i][j-1]) dp[i][j]=min(dp[i-1][j],dp[i][j-1])+1;\n\t\t \telse if(c[i-dp[i-1][j]][j-dp[i-1][j]]) dp[i][j]=dp[i-1][j];\n\t\t \telse dp[i][j]=dp[i-1][j]+1;\n\t\t}\n \t}\n \tint ans=0;\n \tfor(int i=1;i<=n;i++) for(int j=1;j<=m;j++) ans=max(ans,dp[i][j]);\n \tans=ans*ans;\n \tcout<<ans<<endl;\n}\nsigned main(){\n \tios::sync_with_stdio(false);\n \tcin.tie(0),cout.tie(0);\n \tint t=1;\n \t//cin>>t;\n \twhile(t--){\n \t\tsolve();\n \t}\n \treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 34120, "score_of_the_acc": -1.0641, "final_rank": 13 }, { "submission_id": "aoj_DPL_3_A_10694639", "code_snippet": "#include<iostream>\n#include<cmath>\nusing namespace std;\nbool hw[1405][1405];\nlong long dp[1405][1405];\nint main()\n{\n\tint h;\n\tint w;\n\tcin>>h>>w;\n\tfor(int i=1;i<=h;i++)\n\t{\n\t\tfor(int j=1;j<=w;j++)\n\t\t{\n\t\t\tcin>>hw[i][j];\n\t\t}\n\t}\n\tfor(int i=1;i<=h;i++)\n\t{\n\t\tfor(int j=1;j<=w;j++)\n\t\t{\n\t\t\tif(hw[i][j]==0)\n\t\t\t\tdp[i][j]=1;\n\t\t\telse\n\t\t\t\tdp[i][j]=0;\n\t\t}\n\t}\n\tfor(int i=2;i<=h;i++)\n\t{\n\t\tfor(int j=2;j<=w;j++)\n\t\t{\n\t\t\tif(hw[i][j]==0)\n\t\t\t\tdp[i][j]=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1;\n\t\t\telse\n\t\t\t\tdp[i][j]=0;\n\t\t}\n\t}\n\tlong long maxx=0;\n\tfor(int i=1;i<=h;i++)\n\t{\n\t\tfor(int j=1;j<=w;j++)\n\t\t{\n\t\t\t\n\t\t\t\tmaxx=max(dp[i][j],maxx);\n\t\t\t\n\t\t}\n\t}\n\tcout<<pow(maxx,2)<<endl;\n\treturn 0;\n}", "accuracy": 0.85, "time_ms": 110, "memory_kb": 20512, "score_of_the_acc": -0.6606, "final_rank": 17 }, { "submission_id": "aoj_DPL_3_A_10694635", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint dp[1400][1400],g[1400][1400];\nint main(){\n\t\tint h,w;\n\t\tcin>>h>>w;\n\t\tfor(int i=1;i<=h;i++)\n\t\t\tfor(int j=1;j<=w;j++)\n\t\t\t\tcin>>g[i][j];\n\t\tint maxwidth=0;\n\t\tfor(int i=1;i<=h;i++)\n\t\t\tfor(int j=1;j<=w;j++){\n\t\t\t\tdp[i][j]=(g[i][j]==1)?0:min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1;\n\t\t\t\tmaxwidth=max(maxwidth,dp[i][j]);\n\t\t\t}\n\t\tcout<<maxwidth*maxwidth<<endl;\n}", "accuracy": 0.925, "time_ms": 100, "memory_kb": 17764, "score_of_the_acc": -0.5533, "final_rank": 16 }, { "submission_id": "aoj_DPL_3_A_10694634", "code_snippet": "#include <iostream>\n#include<algorithm>\n#include<cstdio>\nusing namespace std;\n#define MAX 1400\nint dp[MAX][MAX],G[MAX][MAX];\nint getLargestSquare(int H,int W)\n{\n int maxWidth=0;\n for(int i=0;i<H;i++){\n for(int j=0;j<W;j++){\n dp[i][j]=(G[i][j]+1)%2;\n maxWidth=dp[i][j];\n }\n }\n for(int i=1;i<H;i++){\n for(int j=1;j<W;j++){\n if(G[i][j]){\n dp[i][j]=0;\n }else{\n dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;\n maxWidth=max(maxWidth,dp[i][j]);\n }\n }\n }\n return maxWidth*maxWidth;\n}\nint main()\n{\n int H,W;\n scanf(\"%d %d\",&H,&W);\n for(int i=0;i<H;i++){\n for(int j=0;j<W;j++){\n scanf(\"%d\",&G[i][j]);\n }\n }\n printf(\"%d\\n\",getLargestSquare(H,W));\n return 0;\n}", "accuracy": 0.775, "time_ms": 20, "memory_kb": 13796, "score_of_the_acc": -0.3144, "final_rank": 20 }, { "submission_id": "aoj_DPL_3_A_10694630", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAXN = 1400 + 10;\n\nint row, column;\nint maze[MAXN][MAXN], pre[MAXN][MAXN], dp[MAXN][MAXN];\nint ans;\n\nbool isVaild(int r0, int c0, int r1, int c1){\n\treturn !(pre[r1][c1] - pre[r0 - 1][c1] - pre[r1][c0 - 1] + pre[r0 - 1][c0 - 1]);\n}\n\nint main(void)\n{\n\tscanf(\"%d%d\", &row, &column);\n\tfor(int r = 1; r <= row; r++)\tfor(int c = 1; c <= column; c++)\n\t\tscanf(\"%d\", &maze[r][c]), pre[r][c] = pre[r][c - 1] + pre[r - 1][c] + maze[r][c] - pre[r - 1][c - 1];\n\tfor(int r = 1; r <= row; r++)\tfor(int c = 1; c <= column; c++)\tfor(int i = 0; i < min(r, c); i++){\n\t\tif(!isVaild(r - i, c - i, r, c))\tcontinue;\n\t\tans = max(ans, dp[r][c] = (i + 1) * (i + 1));\n\t\t//printf(\"dp[%d][%d] = %d\\n\", r, c, dp[r][c]);\n\t}printf(\"%d\\n\", ans);\n\treturn 0;\n}", "accuracy": 1, "time_ms": 790, "memory_kb": 25748, "score_of_the_acc": -1.7123, "final_rank": 15 }, { "submission_id": "aoj_DPL_3_A_10638318", "code_snippet": "#include <cstdio>\n#include <algorithm>\n\nconstexpr int MAX = 1'400;\n\nint dp[MAX][MAX], G[MAX][MAX];\n\nint get_largest_square(int H, int W) {\n int max_width = 0;\n for (int i = 0; i < H; ++i) {\n for (int j = 0; j < W; ++j) {\n dp[i][j] = (G[i][j] + 1) % 2; // dp初期化 汚れたタイル(1):0 きれいなタイル(0):1 となるような計算\n max_width |= dp[i][j];\n }\n }\n\n for (int i = 1; i < H; ++i) {\n for (int j = 1; j < W; ++j) {\n if (G[i][j]) {\n // 汚れたタイル\n dp[i][j] = 0;\n } else {\n // きれいなタイル\n dp[i][j] = std::min(dp[i - 1][j - 1], std::min(dp[i - 1][j], dp[i][j - 1])) + 1;\n max_width = std::max(max_width, dp[i][j]);\n }\n }\n }\n\n return max_width * max_width;\n}\n\nint main() {\n int H, W;\n\n scanf(\"%d %d\", &H, &W);\n\n for (int i = 0; i < H; ++i) {\n for (int j = 0; j < W; ++j) {\n scanf(\"%d\", &G[i][j]);\n }\n }\n\n printf(\"%d\\n\", get_largest_square(H, W));\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 18356, "score_of_the_acc": -0.5224, "final_rank": 6 }, { "submission_id": "aoj_DPL_3_A_10595993", "code_snippet": "#include <iostream>\n#include <string>\n#include <map>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <limits.h>\nusing namespace std;\n\n\nint main() {\n int H;\n int W;\n cin >> H >> W;\n //int c[1400][1400];\n //int dp[1400][1400];\n vector<vector<int>> c(1400, vector<int>(1400, 0));\n vector<vector<int>> dp(1400, vector<int>(1400, 0));\n\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n cin >> c[i][j];\n }\n }\n\n int maxWidth = 0;\n // dpの初期化\n // きれいなタイルは1, 汚いタイルは0\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n if (c[i][j]) { // 汚いタイル\n dp[i][j] = 0;\n }\n else { // きれいなタイル\n dp[i][j] = 1;\n maxWidth |= dp[i][j];\n }\n }\n }\n\n // 動的計画法で正方形の最大の辺の長さを求める\n // i,jどちらも1からスタート\n // 左上に向かって正方形を大きくしていく想定\n // dpの左上, 上, 左に注目し、最小値に+1したものをdp[i][j]に入れる\n for (int i = 1; i < H; i++) {\n for (int j = 1; j < W; j++) {\n if (dp[i][j] != 0) { // dp = 0の時は無視(汚いタイルなため)\n int tmpMin = INT_MAX;\n // 左上\n if (tmpMin >= dp[i - 1][j - 1]) {\n tmpMin = dp[i - 1][j - 1];\n }\n // 左\n if (tmpMin >= dp[i][j - 1]) {\n tmpMin = dp[i][j - 1];\n }\n // 上\n if (tmpMin >= dp[i - 1][j]) {\n tmpMin = dp[i - 1][j];\n }\n\n dp[i][j] = tmpMin + 1;\n\n if (maxWidth <= dp[i][j]) {\n maxWidth = dp[i][j];\n }\n }\n }\n }\n\n cout << maxWidth * maxWidth << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 18428, "score_of_the_acc": -0.6402, "final_rank": 12 }, { "submission_id": "aoj_DPL_3_A_10525908", "code_snippet": "#include<cstdio>\n#include<algorithm>\nusing namespace std;\n#define MAX 1400\n\nint dp[MAX][MAX];\nint G[MAX][MAX];\n\nint getLargestSquare(int H, int W) {\n int maxWidth = 0;\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n dp[i][j] = (G[i][j]) & 2;\n maxWidth |= dp[i][j];\n }\n }\n\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n if (G[i][j] == 1) {\n dp[i][j] = 0;\n } else {\n dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;\n maxWidth = max(maxWidth, dp[i][j]);\n }\n }\n }\n \n return maxWidth * maxWidth;\n}\n\nint main (void) {\n int H;\n int W;\n\n scanf(\"%d %d\", &H, &W);\n\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n scanf(\"%d\", &G[i][j]);\n }\n }\n\n printf(\"%d\\n\", getLargestSquare(H, W));\n\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 18264, "score_of_the_acc": -0.532, "final_rank": 7 }, { "submission_id": "aoj_DPL_3_A_10442740", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\nint main()\n{\n int h;\n int w;\n int i;\n int j;\n int c;\n int maxp;\n int minp;\n\n cin >> h >> w;\n vector<vector<int>> DP(h, vector<int>(w, 0));\n maxp = 0;\n rep(i, h)\n {\n rep(j, w)\n {\n cin >> c;\n if (c == 0)\n {\n DP.at(i).at(j) = 1;\n maxp = 1;\n }\n }\n }\n for (i = 1; i < h; i++)\n {\n for (j = 1; j < w; j++)\n {\n if (DP.at(i).at(j) == 0)\n {\n continue;\n }\n DP.at(i).at(j) = min(DP.at(i - 1).at(j), min(DP.at(i).at(j - 1), DP.at(i - 1).at(j - 1))) + 1;\n maxp = max(maxp, DP.at(i).at(j));\n }\n }\n cout << maxp * maxp << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 10684, "score_of_the_acc": -0.3741, "final_rank": 3 }, { "submission_id": "aoj_DPL_3_A_10442737", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\nint main()\n{\n int h;\n int w;\n int i;\n int j;\n int c;\n int maxp;\n int minp;\n\n cin >> h >> w;\n vector<vector<int>> DP(h, vector<int>(w, 0));\n maxp = 0;\n rep(i, h)\n {\n rep(j, w)\n {\n cin >> c;\n if (c == 0)\n {\n DP.at(i).at(j) = 1;\n maxp = 1;\n }\n }\n }\n for (i = 1; i < h; i++)\n {\n for (j = 1; j < w; j++)\n {\n if (DP.at(i).at(j) == 0)\n {\n continue;\n }\n minp = min(DP.at(i - 1).at(j), min(DP.at(i).at(j - 1), DP.at(i - 1).at(j - 1)));\n DP.at(i).at(j) = minp + 1;\n maxp = max(maxp, DP.at(i).at(j));\n }\n }\n cout << maxp * maxp << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 10760, "score_of_the_acc": -0.3639, "final_rank": 2 }, { "submission_id": "aoj_DPL_3_A_10442726", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\nint main()\n{\n int h;\n int w;\n int i;\n int j;\n int c;\n int maxp;\n int minp;\n\n cin >> h >> w;\n vector<vector<int>> DP(h, vector<int>(w, 0));\n maxp = 0;\n rep(i, h)\n {\n rep(j, w)\n {\n cin >> c;\n if (c == 0)\n {\n DP.at(i).at(j) = 1;\n maxp = 1;\n }\n }\n }\n for (i = 1; i < h; i++)\n {\n for (j = 1; j < w; j++)\n {\n if (DP.at(i).at(j) == 0)\n {\n continue;\n }\n minp = min(DP.at(i - 1).at(j), DP.at(i).at(j - 1));\n if (DP.at(i - minp).at(j - minp) != 0)\n {\n DP.at(i).at(j) = minp + 1;\n maxp = max(maxp, DP.at(i).at(j));\n }\n else\n {\n DP.at(i).at(j) = minp;\n }\n }\n }\n cout << maxp * maxp << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 10736, "score_of_the_acc": -0.3631, "final_rank": 1 }, { "submission_id": "aoj_DPL_3_A_10442718", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\nint main()\n{\n int h;\n int w;\n int i;\n int j;\n int c;\n int maxp;\n int minp;\n\n cin >> h >> w;\n vector<vector<int>> DP(h, vector<int>(w, 0));\n rep(i, h)\n {\n rep(j, w)\n {\n cin >> c;\n if (c == 0)\n {\n DP.at(i).at(j) = 1;\n }\n }\n }\n maxp = DP.at(0).at(0);\n for (i = 1; i < h; i++)\n {\n for (j = 1; j < w; j++)\n {\n if (DP.at(i).at(j) == 0)\n {\n continue;\n }\n minp = min(DP.at(i - 1).at(j), DP.at(i).at(j - 1));\n if (DP.at(i - minp).at(j - minp) != 0)\n {\n DP.at(i).at(j) = minp + 1;\n maxp = max(maxp, DP.at(i).at(j));\n }\n else\n {\n DP.at(i).at(j) = minp;\n }\n }\n }\n cout << maxp * maxp << endl;\n\n return 0;\n}", "accuracy": 0.775, "time_ms": 30, "memory_kb": 5020, "score_of_the_acc": -0.0256, "final_rank": 18 }, { "submission_id": "aoj_DPL_3_A_10397680", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX = 1400;\n\nint M[MAX][MAX], dp[MAX][MAX];\n\nint getLargestSquare(int H, int W) {\n\tint maxWidth = 0;\n\t\n\tfor (int i = 0; i < H; ++i) {\n\t\tfor (int j = 0; j < W; ++j) {\n\t\t\tif (M[i][j]) dp[i][j] = 0;\n\t\t\telse if (i == 0 || j == 0) {\n\t\t\t\tdp[i][j] = 1;\n\t\t\t\tmaxWidth = max(maxWidth, dp[i][j]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdp[i][j] = min({dp[i-1][j-1], dp[i-1][j], dp[i][j-1]}) + 1;\n\t\t\t\tmaxWidth = max(maxWidth, dp[i][j]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn maxWidth * maxWidth;\n}\n\nint main() {\n\tint H, W; cin >> H >> W;\n\tfor (int i = 0; i < H; ++i) {\n\t\tfor (int j = 0; j < W; ++j) {\n\t\t\tcin >> M[i][j];\n\t\t}\n\t}\n\t\n\tcout << getLargestSquare(H, W) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 18632, "score_of_the_acc": -0.6344, "final_rank": 9 }, { "submission_id": "aoj_DPL_3_A_10397664", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX = 1400;\n\nint M[MAX][MAX], dp[MAX][MAX];\n\nint getLargestSquare(int H, int W) {\n\tint maxWidth = 0;\n\tfor (int i = 0; i < H; ++i) {\n\t\tfor (int j = 0; j < W; ++j) {\n\t\t\tdp[i][j] = M[i][j] ? 0 : 1;\n\t\t\tif (dp[i][j]) maxWidth = 1;\n\t\t}\n\t}\n\t\n\tfor (int i = 1; i < H; ++i) {\n\t\tfor (int j = 1; j < W; ++j) {\n\t\t\tif (!dp[i][j]) continue;\n\t\t\tdp[i][j] = min({dp[i-1][j-1], dp[i-1][j], dp[i][j-1]}) + 1;\n\t\t\tmaxWidth = max(maxWidth, dp[i][j]);\n\t\t}\n\t}\n\t\n\treturn maxWidth * maxWidth;\n}\n\nint main() {\n\tint H, W; cin >> H >> W;\n\tfor (int i = 0; i < H; ++i) {\n\t\tfor (int j = 0; j < W; ++j) {\n\t\t\tcin >> M[i][j];\n\t\t}\n\t}\n\t\n\tcout << getLargestSquare(H, W) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 18652, "score_of_the_acc": -0.6351, "final_rank": 11 } ]
aoj_DPL_2_C_cpp
Bitonic Traveling Salesman Problem (Bitonic TSP) For given $N$ points in the 2D Euclidean plane, find the distance of the shortest tour that meets the following criteria: Visit the points according to the following steps: It starts from the leftmost point (starting point), goes strictly from left to right, and then visits the rightmost point (turn-around point). Then it starts from the turn-around point, goes strictly from right to left, and then back to the starting point. Through the processes 1. 2., the tour must visit each point at least once. Input The input data is given in the following format: $N$ $x_1$ $y_1$ $x_2$ $y_2$ ... $x_N$ $y_N$ Constraints $2 \leq N \leq 1000$ $-1000 \leq x_i, y_i \leq 1000$ $x_i$ differ from each other The given points are already sorted by x-coordinates Output Print the distance of the shortest tour in a line. The output should not have an error greater than 0.0001. Sample Input 1 3 0 0 1 1 2 0 Sample Output 1 4.82842712 Sample Input 2 4 0 1 1 2 2 0 3 1 Sample Output 2 7.30056308 Sample Input 3 5 0 0 1 2 2 1 3 2 4 0 Sample Output 3 10.94427191
[ { "submission_id": "aoj_DPL_2_C_10868658", "code_snippet": "#include <bits/stdc++.h>\n#define reb(i,n) for (int i = 0; i < (n); i++)\n#define rep(i, n0, n) for (int i = (n0); i < (n); i++)\n#define repp(i, n0, n) for (int i = (n0); i <= (n); i++)\n#define rrep(i, n0, n) for (int i = (n0); i >= (n); i--) \n#define bit(n,k) ((n>>k)&1)\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\nusing pl = pair<ll,ll>;\nusing pi = pair<int,int>;\ntemplate<class T> inline bool chmax(T& a, T b) { if(a<b) { a = b; return true;} return false; }\ntemplate<class T> inline bool chmin(T& a, T b) { if(a>b) { a = b; return true;} return false; }\n\nvoid solve() {\n int N; cin >> N;\n vector<int> x(N), y(N);\n reb(i,N) cin >> x[i] >> y[i];\n vector<pi> xy(N);\n reb(i,N) xy[i] = make_pair(x[i],y[i]);\n sort(all(xy));\n auto dist = [&](int i, int j) -> double {\n return hypot(x[i]-x[j], y[i]-y[j]);\n };\n if (N == 2) {\n cout << 2 * dist(0,1) << endl;\n return;\n }\n\n vector<vector<double>> dp(N,vector<double>(N));\n reb(j,N-2) {\n dp[N-2][j] = dist(N-2,N-1) + dist(j,N-1);\n }\n\n auto findTour = [&](auto findTour, int i, int j) -> double {\n if (dp[i][j] > 0) return dp[i][j];\n dp[i][j] = min(findTour(findTour,i+1,j) + dist(i,i+1), findTour(findTour,i+1,i) + dist(j,i+1)); \n return dp[i][j];\n };\n cout << fixed << setprecision(15);\n cout << findTour(findTour,0,0) << endl;\n}\n\nint main() {\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10924, "score_of_the_acc": -0.0395, "final_rank": 2 }, { "submission_id": "aoj_DPL_2_C_9572689", "code_snippet": "#include<iostream>\n#include<cmath>\n\nusing namespace std;\nconst int N = 1010;\n\nint n;\npair<int, int> a[N];\nlong double dp[N][N];\n\nlong double dist(int i, int j) {\n return sqrtl((a[i].first - a[j].first) * (a[i].first - a[j].first) + (a[i].second - a[j].second) * (a[i].second - a[j].second));\n}\n\nvoid calc(int i, int j) {\n if(dp[i][j] != -1) return;\n if(max(i, j) == n) {\n dp[i][j] = dist(min(i, j), n);\n return;\n }\n int k = max(i, j) + 1;\n calc(k, j);\n calc(i, k);\n dp[i][j] = min(dp[i][k] + dist(j, k), dp[k][j] + dist(i, k));\n}\n\nint main() {\n cin >> n;\n for(int i = 1; i <= n; ++i) cin >> a[i].first >> a[i].second;\n for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j) dp[i][j] = -1;\n calc(1, 1);\n cout.precision(8);\n cout << fixed << dp[1][1] << '\\n';\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 19184, "score_of_the_acc": -1.6667, "final_rank": 19 }, { "submission_id": "aoj_DPL_2_C_8798803", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = int64_t;\n\ndouble caldst(vector<vector<double>> &dst,vector<vector<double>> &xy,int a,int b){\n if(dst[a][b]!=0) return dst[a][b];\n return dst[a][b]=sqrt(pow(xy[a][0]-xy[b][0],2)+pow(xy[a][1]-xy[b][1],2));\n}\n\nint main(){\n int n;\n cin >> n;\n vector xy(n,vector<double>(2));\n for(int i=0;i<n;i++) cin >> xy[i][0] >> xy[i][1];\n \n vector dst(n,vector<double>(n,0));\n \n vector dp(n,vector<double>(n,1e9));\n dp[0][0]=0;\n for(int i=1;i<n;i++){\n for(int j=0;j<i;j++){\n if((j==0)||(i-j>1)) dp[i][j]=dp[i-1][j]+caldst(dst,xy,i-1,i);\n else{\n for(int k=0;k<j;k++){\n dp[i][j]=min(dp[i][j],dp[j][k]+caldst(dst,xy,k,i));\n } \n }\n // cout << i << j << \" \" << dp[i][j] << endl;\n }\n }\n for(int i=0;i<n-1;i++){\n dp[n-1][n-1]=min(dp[n-1][n-1],dp[n-1][i]+caldst(dst,xy,i,n-1));\n }\n printf(\"%.8lf\\n\",dp[n-1][n-1]);\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18972, "score_of_the_acc": -0.9753, "final_rank": 17 }, { "submission_id": "aoj_DPL_2_C_8204890", "code_snippet": "#include <bits/stdc++.h>\n\n\nstruct Point {\n int x, y;\n double dist(Point pt) { return std::hypot((double)pt.x - x, (double)pt.y - y); }\n};\n\n\nint main() {\n const int INF = 1e9;\n\n int N;\n std::cin >> N;\n\n std::vector<Point> points(N);\n for (int i = 0; i < N; i++) {\n std::cin >> points[i].x >> points[i].y;\n }\n\n std::vector<std::vector<double>> dp(N, std::vector<double>(N, 0.0));\n\n for (int j = 1; j < N; j++) {\n for (int i = 0; i < j; i++) {\n if (i == 0 && j == 1) {\n dp[i][j] = points[0].dist(points[1]);\n } else if (i < j - 1) {\n dp[i][j] = dp[i][j - 1] + points[j - 1].dist(points[j]);\n } else {\n dp[i][j] = std::numeric_limits<double>::infinity();\n for (int k = 0; k < i; k++) {\n dp[i][j] = std::min(dp[i][j], dp[k][i] + points[k].dist(points[j]));\n }\n }\n }\n }\n double min_dist = std::numeric_limits<double>::infinity();\n for (int k = 0; k < N - 1; k++) {\n min_dist = std::min(min_dist, dp[k][N - 1] + points[k].dist(points[N - 1]));\n }\n\n std::cout << std::fixed << std::setprecision(10) << min_dist << std::endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11004, "score_of_the_acc": -0.0488, "final_rank": 5 }, { "submission_id": "aoj_DPL_2_C_7671271", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n// https://www.geeksforgeeks.org/bitonic-traveling-salesman-problem/ より\nconst int MAX_N = 1005;\n// 頂点の数\nint N;\n// 二次元座標\nstruct Point {\n\tdouble x, y;\n};\nPoint A[MAX_N];\n// 2つの点の距離\ndouble distance(const Point& a, const Point& b)\n{\n\treturn hypot(a.x - b.x, a.y - b.y);\n}\n// 二次元DP\ndouble dp[MAX_N][MAX_N];\n// バイトニックツアーの距離を求めるための下請け\ndouble findTourDistance(int i, int j)\n{\n\t// メモ化\n\tif (dp[i][j] > 0)\n\t\treturn dp[i][j];\n\t\n\t// dp[i][j]を更新\n\tdp[i][j] = min(\n\t\tfindTourDistance(i + 1, j) + distance(A[i], A[i + 1]),\n\t\tfindTourDistance(i + 1, i) + distance(A[j], A[i + 1])\n\t);\n\n\treturn dp[i][j];\n}\n// バイトニックツアーの距離を求める\nvoid bitonicTSP(int N)\n{\n\t// dpの配列を初期化\n\tfor (int i = 0; i <= N; i++)\n\t\tfill(dp[i], dp[i] + N + 1, 0.0);\n\n\tfor (int j = 1; j < N - 1; j++)\n\t\tdp[N - 1][j] = distance(A[N - 1], A[N]) + distance(A[j], A[N]);\n\t// 答えの表示\n\tprintf(\"%.8f\\n\", findTourDistance(1, 1));\n}\n\nint main()\n{\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tcin >> N;\n\tfor (int i = 1; i <= N; i++)\n\t\tcin >> A[i].x >> A[i].y;\n\tif (N == 2) {\n\t\tprintf(\"%.8f\\n\", 2.0 * distance(A[1], A[2]));\n\t} else {\n\t\tbitonicTSP(N);\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11540, "score_of_the_acc": -0.1112, "final_rank": 11 }, { "submission_id": "aoj_DPL_2_C_7096412", "code_snippet": "#line 1 \"/home/maspy/compro/library/my_template.hpp\"\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"unroll-loops\")\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing pi = pair<ll, ll>;\nusing vi = vector<ll>;\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nusing i128 = __int128;\n\ntemplate <class T>\nusing vc = vector<T>;\ntemplate <class T>\nusing vvc = vector<vc<T>>;\ntemplate <class T>\nusing vvvc = vector<vvc<T>>;\ntemplate <class T>\nusing vvvvc = vector<vvvc<T>>;\ntemplate <class T>\nusing vvvvvc = vector<vvvvc<T>>;\ntemplate <class T>\nusing pq = priority_queue<T>;\ntemplate <class T>\nusing pqg = priority_queue<T, vector<T>, greater<T>>;\n\n#define vec(type, name, ...) vector<type> name(__VA_ARGS__)\n#define vv(type, name, h, ...) \\\n vector<vector<type>> name(h, vector<type>(__VA_ARGS__))\n#define vvv(type, name, h, w, ...) \\\n vector<vector<vector<type>>> name( \\\n h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))\n#define vvvv(type, name, a, b, c, ...) \\\n vector<vector<vector<vector<type>>>> name( \\\n a, vector<vector<vector<type>>>( \\\n b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))\n\n// https://trap.jp/post/1224/\n#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)\n#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)\n#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)\n#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))\n#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)\n#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)\n#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)\n#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))\n#define overload4(a, b, c, d, e, ...) e\n#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)\n#define FOR_R(...) \\\n overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)\n\n#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))\n#define all(x) x.begin(), x.end()\n#define len(x) ll(x.size())\n#define elif else if\n\n#define eb emplace_back\n#define mp make_pair\n#define mt make_tuple\n#define fi first\n#define se second\n\n#define stoi stoll\n\ntemplate <typename T, typename U>\nT SUM(const vector<U> &A) {\n T sum = 0;\n for (auto &&a: A) sum += a;\n return sum;\n}\n\n#define MIN(v) *min_element(all(v))\n#define MAX(v) *max_element(all(v))\n#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))\n#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))\n#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())\n\nint popcnt(int x) { return __builtin_popcount(x); }\nint popcnt(u32 x) { return __builtin_popcount(x); }\nint popcnt(ll x) { return __builtin_popcountll(x); }\nint popcnt(u64 x) { return __builtin_popcountll(x); }\n// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)\nint topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }\nint topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }\nint topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }\nint topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }\n// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)\nint lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }\nint lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }\nint lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }\nint lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }\n\ntemplate <typename T>\nT pick(deque<T> &que) {\n T a = que.front();\n que.pop_front();\n return a;\n}\n\ntemplate <typename T>\nT pick(pq<T> &que) {\n T a = que.top();\n que.pop();\n return a;\n}\n\ntemplate <typename T>\nT pick(pqg<T> &que) {\n assert(que.size());\n T a = que.top();\n que.pop();\n return a;\n}\n\ntemplate <typename T>\nT pick(vc<T> &que) {\n assert(que.size());\n T a = que.back();\n que.pop_back();\n return a;\n}\n\ntemplate <typename T, typename U>\nT ceil(T x, U y) {\n return (x > 0 ? (x + y - 1) / y : x / y);\n}\n\ntemplate <typename T, typename U>\nT floor(T x, U y) {\n return (x > 0 ? x / y : (x - y + 1) / y);\n}\n\ntemplate <typename T, typename U>\npair<T, T> divmod(T x, U y) {\n T q = floor(x, y);\n return {q, x - q * y};\n}\n\ntemplate <typename F>\nll binary_search(F check, ll ok, ll ng) {\n assert(check(ok));\n while (abs(ok - ng) > 1) {\n auto x = (ng + ok) / 2;\n tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));\n }\n return ok;\n}\n\ntemplate <typename F>\ndouble binary_search_real(F check, double ok, double ng, int iter = 100) {\n FOR(iter) {\n double x = (ok + ng) / 2;\n tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));\n }\n return (ok + ng) / 2;\n}\n\ntemplate <class T, class S>\ninline bool chmax(T &a, const S &b) {\n return (a < b ? a = b, 1 : 0);\n}\ntemplate <class T, class S>\ninline bool chmin(T &a, const S &b) {\n return (a > b ? a = b, 1 : 0);\n}\n\nvc<int> s_to_vi(const string &S, char first_char) {\n vc<int> A(S.size());\n FOR(i, S.size()) { A[i] = S[i] - first_char; }\n return A;\n}\n\ntemplate <typename T, typename U>\nvector<T> cumsum(vector<U> &A, int off = 1) {\n int N = A.size();\n vector<T> B(N + 1);\n FOR(i, N) { B[i + 1] = B[i] + A[i]; }\n if (off == 0) B.erase(B.begin());\n return B;\n}\n\ntemplate <typename CNT, typename T>\nvc<CNT> bincount(const vc<T> &A, int size) {\n vc<CNT> C(size);\n for (auto &&x: A) { ++C[x]; }\n return C;\n}\n\n// stable\ntemplate <typename T>\nvector<int> argsort(const vector<T> &A) {\n vector<int> ids(A.size());\n iota(all(ids), 0);\n sort(all(ids),\n [&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });\n return ids;\n}\n\n// A[I[0]], A[I[1]], ...\ntemplate <typename T>\nvc<T> rearrange(const vc<T> &A, const vc<int> &I) {\n int n = len(I);\n vc<T> B(n);\n FOR(i, n) B[i] = A[I[i]];\n return B;\n}\n#line 1 \"/home/maspy/compro/library/other/io.hpp\"\n// based on yosupo's fastio\n#include <unistd.h>\n\nnamespace detail {\ntemplate <typename T, decltype(&T::is_modint) = &T::is_modint>\nstd::true_type check_value(int);\ntemplate <typename T>\nstd::false_type check_value(long);\n} // namespace detail\n\ntemplate <typename T>\nstruct is_modint : decltype(detail::check_value<T>(0)) {};\ntemplate <typename T>\nusing is_modint_t = enable_if_t<is_modint<T>::value>;\ntemplate <typename T>\nusing is_not_modint_t = enable_if_t<!is_modint<T>::value>;\n\nstruct Scanner {\n FILE *fp;\n char line[(1 << 15) + 1];\n size_t st = 0, ed = 0;\n void reread() {\n memmove(line, line + st, ed - st);\n ed -= st;\n st = 0;\n ed += fread(line + ed, 1, (1 << 15) - ed, fp);\n line[ed] = '\\0';\n }\n bool succ() {\n while (true) {\n if (st == ed) {\n reread();\n if (st == ed) return false;\n }\n while (st != ed && isspace(line[st])) st++;\n if (st != ed) break;\n }\n if (ed - st <= 50) {\n bool sep = false;\n for (size_t i = st; i < ed; i++) {\n if (isspace(line[i])) {\n sep = true;\n break;\n }\n }\n if (!sep) reread();\n }\n return true;\n }\n template <class T, enable_if_t<is_same<T, string>::value, int> = 0>\n bool read_single(T &ref) {\n if (!succ()) return false;\n while (true) {\n size_t sz = 0;\n while (st + sz < ed && !isspace(line[st + sz])) sz++;\n ref.append(line + st, sz);\n st += sz;\n if (!sz || st != ed) break;\n reread();\n }\n return true;\n }\n template <class T, enable_if_t<is_integral<T>::value, int> = 0>\n bool read_single(T &ref) {\n if (!succ()) return false;\n bool neg = false;\n if (line[st] == '-') {\n neg = true;\n st++;\n }\n ref = T(0);\n while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }\n if (neg) ref = -ref;\n return true;\n }\n template <class T, is_modint_t<T> * = nullptr>\n bool read_single(T &ref) {\n long long val = 0;\n bool f = read_single(val);\n ref = T(val);\n return f;\n }\n bool read_single(double &ref) {\n string s;\n if (!read_single(s)) return false;\n ref = std::stod(s);\n return true;\n }\n bool read_single(char &ref) {\n string s;\n if (!read_single(s) || s.size() != 1) return false;\n ref = s[0];\n return true;\n }\n template <class T>\n bool read_single(vector<T> &ref) {\n for (auto &d: ref) {\n if (!read_single(d)) return false;\n }\n return true;\n }\n template <class T, class U>\n bool read_single(pair<T, U> &p) {\n return (read_single(p.first) && read_single(p.second));\n }\n template <class A, class B, class C>\n bool read_single(tuple<A, B, C> &p) {\n return (read_single(get<0>(p)) && read_single(get<1>(p))\n && read_single(get<2>(p)));\n }\n template <class A, class B, class C, class D>\n bool read_single(tuple<A, B, C, D> &p) {\n return (read_single(get<0>(p)) && read_single(get<1>(p))\n && read_single(get<2>(p)) && read_single(get<3>(p)));\n }\n void read() {}\n template <class H, class... T>\n void read(H &h, T &... t) {\n bool f = read_single(h);\n assert(f);\n read(t...);\n }\n Scanner(FILE *fp) : fp(fp) {}\n};\n\nstruct Printer {\n Printer(FILE *_fp) : fp(_fp) {}\n ~Printer() { flush(); }\n\n static constexpr size_t SIZE = 1 << 15;\n FILE *fp;\n char line[SIZE], small[50];\n size_t pos = 0;\n void flush() {\n fwrite(line, 1, pos, fp);\n pos = 0;\n }\n void write(const char &val) {\n if (pos == SIZE) flush();\n line[pos++] = val;\n }\n template <class T, enable_if_t<is_integral<T>::value, int> = 0>\n void write(T val) {\n if (pos > (1 << 15) - 50) flush();\n if (val == 0) {\n write('0');\n return;\n }\n if (val < 0) {\n write('-');\n val = -val; // todo min\n }\n size_t len = 0;\n while (val) {\n small[len++] = char(0x30 | (val % 10));\n val /= 10;\n }\n for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }\n pos += len;\n }\n void write(const string &s) {\n for (char c: s) write(c);\n }\n void write(const char *s) {\n size_t len = strlen(s);\n for (size_t i = 0; i < len; i++) write(s[i]);\n }\n void write(const double &x) {\n ostringstream oss;\n oss << fixed << setprecision(15) << x;\n string s = oss.str();\n write(s);\n }\n void write(const long double &x) {\n ostringstream oss;\n oss << fixed << setprecision(15) << x;\n string s = oss.str();\n write(s);\n }\n template <class T, is_modint_t<T> * = nullptr>\n void write(T &ref) {\n write(ref.val);\n }\n template <class T>\n void write(const vector<T> &val) {\n auto n = val.size();\n for (size_t i = 0; i < n; i++) {\n if (i) write(' ');\n write(val[i]);\n }\n }\n template <class T, class U>\n void write(const pair<T, U> &val) {\n write(val.first);\n write(' ');\n write(val.second);\n }\n template <class A, class B, class C>\n void write(const tuple<A, B, C> &val) {\n auto &[a, b, c] = val;\n write(a), write(' '), write(b), write(' '), write(c);\n }\n template <class A, class B, class C, class D>\n void write(const tuple<A, B, C, D> &val) {\n auto &[a, b, c, d] = val;\n write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d);\n }\n template <class A, class B, class C, class D, class E>\n void write(const tuple<A, B, C, D, E> &val) {\n auto &[a, b, c, d, e] = val;\n write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d), write(' '), write(e);\n }\n template <class A, class B, class C, class D, class E, class F>\n void write(const tuple<A, B, C, D, E, F> &val) {\n auto &[a, b, c, d, e, f] = val;\n write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d), write(' '), write(e), write(' '), write(f);\n }\n template <class T, size_t S>\n void write(const array<T, S> &val) {\n auto n = val.size();\n for (size_t i = 0; i < n; i++) {\n if (i) write(' ');\n write(val[i]);\n }\n }\n void write(i128 val) {\n string s;\n bool negative = 0;\n if(val < 0){\n negative = 1;\n val = -val;\n }\n while (val) {\n s += '0' + int(val % 10);\n val /= 10;\n }\n if(negative) s += \"-\";\n reverse(all(s));\n if (len(s) == 0) s = \"0\";\n write(s);\n }\n};\n\nScanner scanner = Scanner(stdin);\nPrinter printer = Printer(stdout);\n\nvoid flush() { printer.flush(); }\nvoid print() { printer.write('\\n'); }\ntemplate <class Head, class... Tail>\nvoid print(Head &&head, Tail &&... tail) {\n printer.write(head);\n if (sizeof...(Tail)) printer.write(' ');\n print(forward<Tail>(tail)...);\n}\n\nvoid read() {}\ntemplate <class Head, class... Tail>\nvoid read(Head &head, Tail &... tail) {\n scanner.read(head);\n read(tail...);\n}\n\n#define INT(...) \\\n int __VA_ARGS__; \\\n read(__VA_ARGS__)\n#define LL(...) \\\n ll __VA_ARGS__; \\\n read(__VA_ARGS__)\n#define STR(...) \\\n string __VA_ARGS__; \\\n read(__VA_ARGS__)\n#define CHAR(...) \\\n char __VA_ARGS__; \\\n read(__VA_ARGS__)\n#define DBL(...) \\\n double __VA_ARGS__; \\\n read(__VA_ARGS__)\n\n#define VEC(type, name, size) \\\n vector<type> name(size); \\\n read(name)\n#define VV(type, name, h, w) \\\n vector<vector<type>> name(h, vector<type>(w)); \\\n read(name)\n\nvoid YES(bool t = 1) { print(t ? \"YES\" : \"NO\"); }\nvoid NO(bool t = 1) { YES(!t); }\nvoid Yes(bool t = 1) { print(t ? \"Yes\" : \"No\"); }\nvoid No(bool t = 1) { Yes(!t); }\nvoid yes(bool t = 1) { print(t ? \"yes\" : \"no\"); }\nvoid no(bool t = 1) { yes(!t); }\n#line 3 \"main.cpp\"\n\nvoid solve() {\n LL(N);\n VEC(pi, XY, N);\n const ll INF = 1LL << 60;\n using Re = double;\n\n auto dist = [&](int i, int j) -> Re {\n auto [xi, yi] = XY[i];\n auto [xj, yj] = XY[j];\n Re dx = xi - xj;\n Re dy = yi - yj;\n return sqrt(dx * dx + dy * dy);\n };\n\n vv(Re, dp, N, N, INF);\n dp[0][0] = 0;\n FOR(i, N) FOR(j, N) {\n int k = max<int>(i, j);\n chmin(dp[i][k], dp[i][j] + dist(j, k));\n chmin(dp[k][j], dp[i][j] + dist(i, k));\n ++k;\n if (k == N) continue;\n chmin(dp[i][k], dp[i][j] + dist(j, k));\n chmin(dp[k][j], dp[i][j] + dist(i, k));\n }\n\n Re ANS = dp[N - 1][N - 1];\n print(ANS);\n}\n\nsigned main() {\n cout << fixed << setprecision(15);\n\n ll T = 1;\n // LL(T);\n FOR(T) solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10960, "score_of_the_acc": -0.0437, "final_rank": 3 }, { "submission_id": "aoj_DPL_2_C_6789927", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define EPS (1e-10)\n#define int long long\n//#define lson (rt<<1)\n//#define rson (rt<<1|1)\n//#define mid ((l+r)>>1)\n#define mst(a) memset(a,0,sizeof(a))\n#define cf int Tcodeforces, Tcodeforce;cin>>Tcodeforces;for(Tcodeforce = 1; Tcodeforce <= Tcodeforces; Tcodeforce++)\nconst int maxn = 1e3 +7;\nconst int maxm = 2e5 +7;\nconst int inf = 0x3f3f3f3f;\nconst int mod = 1e9 +7;\n\nint n;\ndouble x[maxn], y[maxn];\ndouble d[maxn][maxn];\ndouble f[maxn][maxn];\n\ndouble getf(int p1, int p2) { // p1 <= p2\n if(p1==p2&&p1==1) return 0;\n if(f[p1][p2]) return f[p1][p2];\n double res = inf;\n if(p1==p2) {\n for(int i = 1; i < p2- 1 || i == 1; i++) {\n res = min(res, getf(i,p2)+d[i][p2]);\n }\n }\n else if(p1==p2-1) {\n for(int i = 1; i < p2 - 1; i++) {\n res = min(res, getf(i,p1)+d[i][p2]);\n }\n }\n else {\n res = getf(p1,p2-1) + d[p2-1][p2];\n }\n return f[p1][p2] = res;\n}\n\nsigned main() {\n #ifdef moyi_qwq\n freopen(\"D:/source file/intxt/in.txt\",\"r\",stdin);\n #endif\n \n cin>>n;\n for(int i = 1; i <= n; i++) {cin>>x[i]>>y[i];}\n for(int i = 1; i <= n; i++) {\n for(int j = 1; j <= n; j++) {\n double dx = x[i]-x[j], dy = y[i] - y[j];\n d[i][j] = sqrt(dx*dx+dy*dy);\n }\n }\n f[1][1] = 0;\n f[1][2] = d[1][2];\n //f[2][2] = d[1][2] * 2;\n printf(\"%.10lf\",getf(n,n));\n //cout<<getf(n,n)<<endl;\n\n\n //cerr<<\"Time : \"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\";\n return (0);\n}\n\n/*\n\ndp[i][j] 两条路到i和j 之间的点最多走一条 都走 i<=j\nfor i 1-(j-1):\n dp[i][j] = min(dp[i][j-1] + e[j-1][j],\n dp[x][j-1] + e[x][j])\n\n\n*/", "accuracy": 1, "time_ms": 10, "memory_kb": 18132, "score_of_the_acc": -0.8777, "final_rank": 14 }, { "submission_id": "aoj_DPL_2_C_6367310", "code_snippet": "#include <bits/stdc++.h>\n\n#define pb push_back\n#define mp make_pair\n#define X first\n#define Y second\nusing namespace std;\n\ntypedef long long int ll;\ntypedef vector <int> vi;\ntypedef pair <int,int> pii;\nconst int Size=1e3+10;\nconst int INF=0x3f3f3f3f;\n\ninline int read()\n{\n int x=0, f=1; char ch=getchar();\n while(ch<'0' || ch>'9') {if(ch=='-') f=-1; ch=getchar();}\n while(ch>='0' && ch<='9') {x=x*10+ch-'0'; ch=getchar();}\n return x*f;\n}\n\nstruct point{\n double x,y;\n void init(){scanf(\"%lf%lf\",&x,&y);}\n};\n\npoint p[Size];\ndouble dis[Size][Size];\ndouble dp[Size][Size];\n/*\ndp[i][j]表示从点1连两条路径到点i、j的最短距离\n(两条路径除去起点、终点可以相同,中间节点不同)\n不妨设i>=j\n答案为dp[n][n]\n若j<i-1,点i的前一个点必然是点i-1,dp[i][j]=dp[i-1][j]+dis(i-1,i)\n若j>=i-1,点i的前一个点是1~i-2,dp[i][j]=min{dp[i-1][k]+dis(k,i)+dis(i-1,j)}\n*/\n\ndouble get_dis(int i,int j){return hypot(p[i].x-p[j].x,p[i].y-p[j].y);}\nint main()\n{\n int n=read();\n for (int i=1;i<=n;++i) p[i].init();\n for (int i=1;i<=n;++i)\n for (int j=i;j<=n;++j) dis[i][j]=dis[j][i]=get_dis(i,j);\n\n dp[1][1]=0;\n for (int i=2;i<=n;++i) dp[i][1]=dp[i-1][1]+dis[i-1][i];\n for (int i=2;i<=n;++i)\n for (int j=1;j<=i;++j)\n {\n if (j<i-1) {dp[i][j]=dp[i-1][j]+dis[i-1][i]; continue;}\n dp[i][j]=INF;\n for (int k=1;k<=max(i-2,1);++k)\n dp[i][j]=min(dp[i][j],dp[i-1][k]+dis[k][i]+dis[i-1][j]);\n }\n\n double res=dp[n][n];\n printf(\"%.10lf\\n\",res);\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18752, "score_of_the_acc": -0.9498, "final_rank": 15 }, { "submission_id": "aoj_DPL_2_C_6318888", "code_snippet": "#include<bits/stdc++.h>\ntypedef long long int ll;\ntypedef unsigned long long int ull;\n//double max:0x7f,0x43 min:0xfe 0x c2 int:0x3f \n//运算符 priority 后缀 前缀 */+- 位移 比较 &^| && || 赋值\nusing namespace std;\ndouble f[1005][1005];\nint k,n,m;\nstruct Node{\n\tdouble x;\n\tdouble y;\n\tNode(double x,double y):x(x),y(y){}\n\tNode(){\t}\n}a[1005];\ndouble dist(int x,int y){\n\treturn hypot((a[x].x-a[y].x),(a[x].y-a[y].y));\n}\nvoid solve(){\n\tcin>>n;\n\tfor(int i=1;i<=n;i++) cin>>a[i].x>>a[i].y;\n\tmemset(f,0x7f,sizeof f);\n\tf[1][1]=0; \n\tfor(int i=2;i<=n;i++)\n\t\tfor(int j=1;j<i;j++){\n\t\t\tif(i==2&&j==1) f[i][j]=dist(1,2);\n\t\t\telse if(i==j+1){\n\t\t\t\tfor(int k=1;k<j;k++) f[i][j]=min(f[i][j],f[j][k]+dist(k,i)); \t\t\t\t\n\t\t\t}else{\n\t\t\t\tf[i][j]=f[i-1][j]+dist(i-1,i);\n\t\t\t}\n\t\t}\n\tdouble res=f[0][0];\n\tfor(int i=1;i<=n;i++){\n\t\tres=min(res,f[n][i]+dist(i,n));\n\t}\n\n\tcout<<fixed<<setprecision(8)<<res<<endl;\n}\nint main()\n{\t\n\t//cout.setf(ios::fixed);\n\t//cout<<fixed<<setprecision(4)<<x<<endl;\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t#if 0\n\tfreopen(\"in.txt\",\"r\",stdin);\n\tfreopen(\"out.txt\",\"w\",stdout);\n\t#endif \n solve();\n\t#if 0\n\tint T;\n\tcin>>T;\n\twhile(T--){\n\t\tsolve();\n\t}\n\t#endif\n\t\n\t#if 0\n\tfclose(stdin);\n\tfclose(stdout);\n\t#endif \n return 0;\n}\n//so upset dp was wrong \n/*\n\tbecause,in fact, the local optimum isn't f[j], it's f[j]+dist(a[g[j]],a[j+1]);\nBut we can't denote this by linear array. So we need f[i][j] to denote the first path was end with i and second path was end with j\n\n\n*/", "accuracy": 1, "time_ms": 10, "memory_kb": 11540, "score_of_the_acc": -0.1112, "final_rank": 11 }, { "submission_id": "aoj_DPL_2_C_6148671", "code_snippet": "#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <set>\n#include <stack>\n#include <queue>\n#include <cmath>\n#include <iomanip>\nusing namespace std;\nusing ll = long long;\ntemplate<class T> inline bool chmax(T& a, T b){ if (a < b){ a = b; return true; } return false; }\ntemplate<class T> inline bool chmin(T& a, T b){ if (a > b){ a = b; return true; } return false; }\nconst double inf = 1e9;\n\ndouble dist(double x, double y, double xx, double yy) {\n return sqrt((x - xx)*(x - xx) + (y - yy)*(y - yy)) ;\n}\n\nint main() {\n int n; cin >> n;\n vector<double> x(n), y(n); \n for(int i=0; i<n; ++i) {\n cin >> x[i] >> y[i];\n }\n vector<vector<double>> dp(n, vector<double>(n, inf));\n dp[0][0] = 0.0;\n for(int i=0; i<n; ++i) {\n for(int j=0; j<n; ++j) {\n if (i + 1 < n) {\n chmin(dp[i+1][j], dp[i][j] + dist(x[i], y[i], x[i+1], y[i+1]));\n chmin(dp[i][i+1], dp[i][j] + dist(x[j], y[j], x[i+1], y[i+1]));\n }\n if (j + 1 < n) {\n chmin(dp[j+1][j], dp[i][j] + dist(x[i], y[i], x[j+1], y[j+1]));\n chmin(dp[i][j+1], dp[i][j] + dist(x[j], y[j], x[j+1], y[j+1]));\n }\n }\n }\n printf(\"%.12f\\n\", dp[n-1][n-1]);\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11096, "score_of_the_acc": -0.0595, "final_rank": 10 }, { "submission_id": "aoj_DPL_2_C_6061576", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nnamespace geometry{\n constexpr double eps = 1e-10;\n bool eq(double a, double b){ return fabs(a - b) < eps; }\n template<typename T> bool eq(T a, T b){ return a == b; }\n bool is_zero(double a){ return fabs(a) < eps; }\n template<typename T> bool is_zero(T a){ return a == 0; }\n bool le(double a, double b){ return a <= b + eps; }\n template<typename T> bool le(T a, T b){ return a <= b; }\n bool lt(double a, double b){ return a < b - eps; }\n template<typename T> bool lt(T a, T b){ return a < b; }\n int sgn(double a){ return is_zero(a) ? 0 : ((a < 0) ? -1 : 1); }\n template<typename T> int sgn(T a){ return (a<0) ? -1 : ((a > 0) ? 1 : 0); }\n template<typename T> double psqrt(T a){ return sqrt(max(T(0), a)); }\n};\n\n\ntemplate<class T> struct Point{\n T x,y;\n Point(){}\n Point(T x, T y) : x(x), y(y) {}\n Point(const pair<T,T> &p) : x(p.first), y(p.second) {}\n\n Point operator*(const T b) const { return Point(x * b, y * b); }\n Point operator/(const T b) const { return Point(x / b, y / b); }\n Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }\n Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }\n Point operator*(const Point &b) const { return Point(x*b.x - y*b.y, x*b.y + y*b.x); }\n Point operator/(const Point &b) const { return Point(x*b.x + y*b.y, y*b.x - x*b.y)/(b.x*b.x + b.y*b.y); }\n\n Point &operator*=(const T b){ return (*this) = (*this) * b; }\n Point &operator/=(const T b){ return (*this) = (*this) / b; }\n Point &operator+=(const Point &b){ return (*this) = (*this) + b; }\n Point &operator-=(const Point &b){ return (*this) = (*this) - b; }\n Point &operator*=(const Point &b){ return (*this) = (*this) * b; }\n Point &operator/=(const Point &b){ return (*this) = (*this) / b; }\n \n bool operator==(const Point &b) const {\n return geometry::eq(x, b.x) && geometry::eq(y, b.y);\n }\n bool operator<(const Point &b) const { \n if(geometry::eq(x, b.x)) return y < b.y;\n return x < b.x;\n }\n T Norm() const { return x * x + y * y; }\n double Abs() const { return hypot<double>(x, y); }\n double dist(const Point &b) const { return hypot<double>(x - b.x, y - b.y); }\n double arg() const { return atan2<double>(y, x); }\n \n Point ArgVec() const {\n if((*this) == Point(0, 0)) return (*this);\n if(geometry::is_zero(x)) return Point(0, -1);\n return (*this) / gcd(x, y) * (x < 0 ? -1 : 1);\n }\n\n int ort() const {\n if(geometry::is_zero(x) && geometry::is_zero(y)) return 0;\n if(geometry::is_zero(y)) return x > 0 ? 1 : 3;\n if(geometry::is_zero(x)) return y > 0 ? 2 : 4;\n if (y > 0) return x > 0 ? 1 : 2;\n else return x > 0 ? 4 : 3;\n }\n Point rotate90() const { return Point(-y, x);}\n Point rotate180() const { return Point(-x, -y);}\n Point rotate270() const { return Point(y, -x);}\n\n Point flip_x(T p = 0) const { return Point(p*2 - x, y);}\n Point flip_y(T p = 0) const { return Point(x, p*2 - y);}\n\n Point rotate(double theta) const {\n return Point(cos(theta)*x - sin(theta)*y, sin(theta)*x + cos(theta)*y);\n }\n\n Point flip(double theta) const {\n return (*this).rotate(-theta).flip_y().rotate(theta);\n }\n\n friend ostream &operator<<(ostream &os, const Point &p) {\n return os << p.x << \" \" << p.y;\n }\n friend istream &operator>>(istream &is, Point &p) {\n T a, b; is >> a >> b;\n p = Point<T>(a, b);\n return (is);\n }\n};\n\ntemplate<typename T> Point<T> Polar(const T& rho, const T& theta = 0){\n return Point<T>(rho * cos(theta), rho * sin(theta));\n}\n\ntemplate<typename T> using Polygon = vector<Point<T>>;\n\ntemplate<class T> T Cross(const Point<T> &a, const Point<T> &b) { return a.x * b.y - a.y * b.x; }\n\ntemplate<class T> T Dot(const Point<T> &a, const Point<T> &b) { return a.x * b.x + a.y * b.y; }\n\ntemplate<class T> int iSP(const Point<T> &a, const Point<T> &b, const Point<T> &c){\n T fl = Cross(b-a, c-a);\n if(geometry::lt(T(0), fl)) return 1; // CCW\n if(geometry::lt(fl, T(0))) return -1; // CW\n if(geometry::lt(T(0), Dot(b-a, c-b))) return 2; //abc\n if(geometry::lt(T(0), Dot(a-b, c-a))) return -2; //bac\n return 0; // acb\n}\n\ntemplate<class T> bool Intersect(const Point<T> &a, const Point<T> &b, const Point<T> &c, const Point<T> &d) {\n return (iSP(a, b, c)*iSP(a, b, d) <= 0) && (iSP(c, d, a)*iSP(c, d, b) <= 0);\n}\n\ntemplate<class T> int angletype(const Point<T> &a, const Point<T> &b, const Point<T> &c){\n T v = Dot(a-b, c-a);\n if(geometry::is_zero(v)) return 0; // right angle\n if(v > 0) return 1; // acute angle\n return -1; // obtuse angle\n}\n\ntemplate<typename T>\nbool cmp_y(const Point<T>& p1, const Point<T> &p2){\n if(p1.y == p2.y) return p1.x < p2.x;\n return p1.y < p2.y;\n}\n\ntemplate<typename T>\nbool cmp_arg(const Point<T>& p1, const Point<T> &p2){\n if(p1.ort() != p2.ort()) return p1.ort() < p2.ort();\n return iSP(Point<T>(0,0), p1, p2) > 0;\n}\n\ntemplate<typename T>\nvoid ArgSort(Polygon<T> &ps){\n sort(begin(ps), end(ps), cmp_arg<T>);\n}\n\ntemplate<typename T>\ndouble bitonicTSP(const Polygon<T> &ps){\n int n = int(ps.size());\n vector dp(n, vector(n, 0.0));\n for(int j = 1; j < n; ++j){\n for(int i = 0; i < j; ++i){\n if(i == 0 && j == 1) dp[i][j] = ps[i].dist(ps[j]);\n else if(i < j-1) dp[i][j] = dp[i][j-1] + ps[j-1].dist(ps[j]);\n else{\n dp[i][j] = numeric_limits<double>::infinity();\n for(int k = 0; k < i; ++k) dp[i][j] = min(dp[i][j], dp[k][i] + ps[j].dist(ps[k]));\n }\n }\n }\n double ans = numeric_limits<double>::infinity();\n for(int k = 0; k < n-1; ++k) ans = min(ans, dp[k][n-1] + ps[k].dist(ps[n-1]));\n return ans;\n}\n\nint main() {\n int n; cin >> n;\n Polygon<double> ps(n);\n for(auto&p : ps) cin >> p;\n cout << fixed << setprecision(12);\n cout << bitonicTSP(ps) << \"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11092, "score_of_the_acc": -0.0591, "final_rank": 9 }, { "submission_id": "aoj_DPL_2_C_5884660", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long \n#define vi vector<int>\n#define pii pair<int,int>\n\n\nint n;\nvector<pii> A;\n\ndouble distance(int i, int j){\n return hypot(A[i].first-A[j].first,A[i].second-A[j].second);\n}\ndouble dp[1000][1000];\ndouble solve(int i,int j){\n int k = max(i,j)+1;\n if(k==n-1){\n return distance(i,k)+distance(j,k);\n }\n if(dp[i][j]!=-1) return dp[i][j];\n //k goes top \n double a = solve(k,j)+distance(i,k);\n //k goes bottom \n double b = solve(i,k)+distance(j,k);\n return dp[i][j] = min(a,b);\n}\n\nint main()\n{\n cin>>n;\n for(int i=0;i<n;i++){\n int x, y;\n cin>>x>>y;\n A.push_back(make_pair(x,y));\n }\n sort(A.begin(),A.end());\n for(int i=0;i<n;i++) for(int j=0;j<n;j++)\n dp[i][j] = -1;\n printf(\"%.8f\\n\",solve(0,0));\n\n\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 11440, "score_of_the_acc": -0.4329, "final_rank": 13 }, { "submission_id": "aoj_DPL_2_C_5819998", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int N;\n cin >> N;\n vector<int> x(N), y(N);\n for(int i = 0; i < N; i++) cin >> x[i] >> y[i];\n vector<vector<double>> d(N, vector<double>(N));\n for(int i = 0; i < N; i++){\n for(int j = 0; j < N; j++){\n d[i][j] = sqrt((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]));\n }\n }\n vector<vector<double>> dp(N, vector<double>(N, numeric_limits<double>::infinity()));\n dp[0][0] = 0;\n for(int i = 1; i < N; i++){\n for(int j = 0; j < i; j++){\n if(j == 0 && i == 1){\n dp[j][i] = d[j][i];\n }\n else if(j < i - 1){\n dp[j][i] = min(dp[j][i], dp[j][i - 1] + d[i - 1][i]);\n }\n else{\n for(int k = 0; k < i; k++){\n dp[j][i] = min(dp[j][i], dp[k][j] + d[k][i]);\n }\n }\n }\n }\n double ans = numeric_limits<double>::infinity();\n for(int i = 0; i < N - 1; i++){\n ans = min(ans, dp[i][N - 1] + d[i][N - 1]);\n }\n printf(\"%.10lf\\n\", ans);\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18952, "score_of_the_acc": -0.973, "final_rank": 16 }, { "submission_id": "aoj_DPL_2_C_5651887", "code_snippet": "#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n#include <algorithm>\n#include <cmath>\nusing namespace std;\nconst int max_n = 1000;\nconst int Inf = 0x3fffffff;\nint x[max_n+1];\nint y[max_n+1];\ndouble OPT[max_n+1][max_n+1];\n\ndouble Eu_dis(int i,int j){\n return(sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])));\n}\n\nint main(){\n int n;\n //n = 3;\n scanf(\"%d\",&n);\n for(int i=1;i<=n;i++){\n scanf(\"%d%d\",x+i,y+i);\n }\n for(int i=1;i<=n;i++){\n for(int j=1;j<=n;j++){\n OPT[i][j] = Inf;\n }\n }\n OPT[1][1] = 0;\n for(int i=1;i<=n;i++){\n for(int j=i;j<=n;j++){\n if(j+1<=n){\n //i -> j+1\n OPT[j][j+1] = min(OPT[j][j+1],OPT[i][j]+Eu_dis(i,j+1));\n //j -> j+1\n OPT[i][j+1] = min(OPT[i][j+1],OPT[i][j]+Eu_dis(j,j+1));\n }\n //i -> j\n OPT[j][j] = min(OPT[j][j],OPT[i][j]+Eu_dis(i,j));\n }\n }\n printf(\"%.8lf\\n\",OPT[n][n]);\n //system(\"Pause\");\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11044, "score_of_the_acc": -0.0535, "final_rank": 8 }, { "submission_id": "aoj_DPL_2_C_5462095", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\nusing namespace std;\nconst int MAX_N = 1000;\nconst int INF = 0x3f3f3f3f;\ndouble OPT[MAX_N+1][MAX_N+1];\nint x[MAX_N+1], y[MAX_N+1];\ndouble dist(int i,int j){\n\tint dx = x[i]-x[j];\n\tint dy = y[i]-y[j];\n\treturn sqrt(dx*dx+dy*dy);\n}\n\ndouble solve(int N){\n\tfor (int i = 0; i <= N; ++i)\n\t\tfor (int j = 0; j <= N; ++j)\n\t\t\tOPT[i][j] = INF;\n\tOPT[1][1] = 0;\n\n\tfor (int i = 1; i <= N; ++i)\n\t\tfor (int j = i; j <= N; ++j){\n\t\t\tif(j+1 <= N)\n\t\t\t\tOPT[j][j+1] = min(OPT[j][j+1],OPT[i][j]+dist(i,j+1));\n\t\t\tif(j+1 <= N)\n\t\t\t\tOPT[i][j+1] = min(OPT[i][j+1],OPT[i][j]+dist(j,j+1));\n\t\t\tOPT[j][j] = min(OPT[j][j],OPT[i][j]+dist(i,j));\n\t\t}\n\n\treturn OPT[N][N];\n}\n\nint main(){\n\tint N;\tscanf(\"%d\",&N);\n\tfor (int i = 1; i <= N; ++i)\n\t\tscanf(\"%d%d\",x+i,y+i);\n\tdouble ans = solve(N);\n\tprintf(\"%.20lf\\n\",ans);\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10584, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DPL_2_C_5223574", "code_snippet": "#include <bits/stdc++.h>\n\n\nstruct Point {\n int x, y;\n double dist(Point pt) { return std::hypot((double)pt.x - x, (double)pt.y - y); }\n};\n\n\nint main() {\n const int INF = 1e9;\n\n int N;\n std::cin >> N;\n\n std::vector<Point> points(N);\n for (int i = 0; i < N; i++) {\n std::cin >> points[i].x >> points[i].y;\n }\n\n std::vector<std::vector<double>> dp(N, std::vector<double>(N, 0.0));\n\n for (int j = 1; j < N; j++) {\n for (int i = 0; i < j; i++) {\n if (i == 0 && j == 1) {\n dp[i][j] = points[0].dist(points[1]);\n } else if (i < j - 1) {\n dp[i][j] = dp[i][j - 1] + points[j - 1].dist(points[j]);\n } else {\n dp[i][j] = std::numeric_limits<double>::infinity();\n for (int k = 0; k < i; k++) {\n dp[i][j] = std::min(dp[i][j], dp[k][i] + points[k].dist(points[j]));\n }\n }\n }\n }\n double min_dist = std::numeric_limits<double>::infinity();\n for (int k = 0; k < N - 1; k++) {\n min_dist = std::min(min_dist, dp[k][N - 1] + points[k].dist(points[N - 1]));\n }\n\n std::cout << std::fixed << std::setprecision(10) << min_dist << std::endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10964, "score_of_the_acc": -0.0442, "final_rank": 4 }, { "submission_id": "aoj_DPL_2_C_5081292", "code_snippet": "#line 2 \"/home/yuruhiya/programming/library/template/template.cpp\"\n#include <bits/stdc++.h>\n#line 6 \"/home/yuruhiya/programming/library/template/constants.cpp\"\n\n#define rep(i, n) for (int i = 0; i < (n); ++i)\n#define FOR(i, m, n) for (int i = (m); i < (n); ++i)\n#define rrep(i, n) for (int i = (n)-1; i >= 0; --i)\n#define rfor(i, m, n) for (int i = (m); i >= (n); --i)\n#define unless(c) if (!(c))\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define range_it(a, l, r) (a).begin() + (l), (a).begin() + (r)\n\nusing namespace std;\nusing ll = long long;\nusing LD = long double;\nusing VB = vector<bool>;\nusing VVB = vector<VB>;\nusing VI = vector<int>;\nusing VVI = vector<VI>;\nusing VL = vector<ll>;\nusing VVL = vector<VL>;\nusing VS = vector<string>;\nusing VD = vector<LD>;\nusing PII = pair<int, int>;\nusing VP = vector<PII>;\nusing PLL = pair<ll, ll>;\nusing VPL = vector<PLL>;\ntemplate <class T> using PQ = priority_queue<T>;\ntemplate <class T> using PQS = priority_queue<T, vector<T>, greater<T>>;\nconstexpr int inf = 1000000000;\nconstexpr long long inf_ll = 1000000000000000000ll, MOD = 1000000007;\nconstexpr long double PI = 3.14159265358979323846, EPS = 1e-12;\n#line 7 \"/home/yuruhiya/programming/library/template/Input.cpp\"\nusing namespace std;\n\n#ifdef _WIN32\n#define getchar_unlocked _getchar_nolock\n#define putchar_unlocked _putchar_nolock\n#define fwrite_unlocked fwrite\n#define fflush_unlocked fflush\n#endif\nclass Scanner {\n\tstatic int gc() {\n\t\treturn getchar_unlocked();\n\t}\n\tstatic char next_char() {\n\t\tchar c;\n\t\tread(c);\n\t\treturn c;\n\t}\n\ttemplate <class T> static void read(T& v) {\n\t\tcin >> v;\n\t}\n\tstatic void read(char& v) {\n\t\twhile (isspace(v = gc()))\n\t\t\t;\n\t}\n\tstatic void read(bool& v) {\n\t\tv = next_char() != '0';\n\t}\n\tstatic void read(string& v) {\n\t\tv.clear();\n\t\tfor (char c = next_char(); !isspace(c); c = gc()) v += c;\n\t}\n\tstatic void read(int& v) {\n\t\tv = 0;\n\t\tbool neg = false;\n\t\tchar c = next_char();\n\t\tif (c == '-') {\n\t\t\tneg = true;\n\t\t\tc = gc();\n\t\t}\n\t\tfor (; isdigit(c); c = gc()) v = v * 10 + (c - '0');\n\t\tif (neg) v = -v;\n\t}\n\tstatic void read(long long& v) {\n\t\tv = 0;\n\t\tbool neg = false;\n\t\tchar c = next_char();\n\t\tif (c == '-') {\n\t\t\tneg = true;\n\t\t\tc = gc();\n\t\t}\n\t\tfor (; isdigit(c); c = gc()) v = v * 10 + (c - '0');\n\t\tif (neg) v = -v;\n\t}\n\tstatic void read(double& v) {\n\t\tv = 0;\n\t\tdouble dp = 1;\n\t\tbool neg = false, after_dp = false;\n\t\tchar c = next_char();\n\t\tif (c == '-') {\n\t\t\tneg = true;\n\t\t\tc = gc();\n\t\t}\n\t\tfor (; isdigit(c) || c == '.'; c = gc()) {\n\t\t\tif (c == '.') {\n\t\t\t\tafter_dp = true;\n\t\t\t} else if (after_dp) {\n\t\t\t\tv += (c - '0') * (dp *= 0.1);\n\t\t\t} else {\n\t\t\t\tv = v * 10 + (c - '0');\n\t\t\t}\n\t\t}\n\t\tif (neg) v = -v;\n\t}\n\tstatic void read(long double& v) {\n\t\tv = 0;\n\t\tlong double dp = 1;\n\t\tbool neg = false, after_dp = false;\n\t\tchar c = next_char();\n\t\tif (c == '-') {\n\t\t\tneg = true;\n\t\t\tc = gc();\n\t\t}\n\t\tfor (; isdigit(c) || c == '.'; c = gc()) {\n\t\t\tif (c == '.') {\n\t\t\t\tafter_dp = true;\n\t\t\t} else if (after_dp) {\n\t\t\t\tv += (c - '0') * (dp *= 0.1);\n\t\t\t} else {\n\t\t\t\tv = v * 10 + (c - '0');\n\t\t\t}\n\t\t}\n\t\tif (neg) v = -v;\n\t}\n\ttemplate <class T, class U> static void read(pair<T, U>& v) {\n\t\tread(v.first);\n\t\tread(v.second);\n\t}\n\ttemplate <class T> static void read(vector<T>& v) {\n\t\tfor (auto& e : v) read(e);\n\t}\n\ttemplate <size_t N = 0, class T> static void read_tuple_impl(T& v) {\n\t\tif constexpr (N < tuple_size_v<T>) {\n\t\t\tread(get<N>(v));\n\t\t\tread_tuple_impl<N + 1>(v);\n\t\t}\n\t}\n\ttemplate <class... T> static void read(tuple<T...>& v) {\n\t\tread_tuple_impl(v);\n\t}\n\tstruct ReadVectorHelper {\n\t\tsize_t n;\n\t\tReadVectorHelper(size_t _n) : n(_n) {}\n\t\ttemplate <class T> operator vector<T>() {\n\t\t\tvector<T> v(n);\n\t\t\tread(v);\n\t\t\treturn v;\n\t\t}\n\t};\n\tstruct Read2DVectorHelper {\n\t\tsize_t n, m;\n\t\tRead2DVectorHelper(const pair<size_t, size_t>& nm) : n(nm.first), m(nm.second) {}\n\t\ttemplate <class T> operator vector<vector<T>>() {\n\t\t\tvector<vector<T>> v(n, vector<T>(m));\n\t\t\tread(v);\n\t\t\treturn v;\n\t\t}\n\t};\n\npublic:\n\tstring read_line() const {\n\t\tstring v;\n\t\tfor (char c = gc(); c != '\\n' && c != '\\0'; c = gc()) v += c;\n\t\treturn v;\n\t}\n\ttemplate <class T> T read() const {\n\t\tT v;\n\t\tread(v);\n\t\treturn v;\n\t}\n\ttemplate <class T> vector<T> read_vector(size_t n) const {\n\t\tvector<T> a(n);\n\t\tread(a);\n\t\treturn a;\n\t}\n\ttemplate <class T> operator T() const {\n\t\treturn read<T>();\n\t}\n\tint operator--(int) const {\n\t\treturn read<int>() - 1;\n\t}\n\tReadVectorHelper operator[](size_t n) const {\n\t\treturn ReadVectorHelper(n);\n\t}\n\tRead2DVectorHelper operator[](const pair<size_t, size_t>& nm) const {\n\t\treturn Read2DVectorHelper(nm);\n\t}\n\tvoid operator()() const {}\n\ttemplate <class H, class... T> void operator()(H&& h, T&&... t) const {\n\t\tread(h);\n\t\toperator()(forward<T>(t)...);\n\t}\n\nprivate:\n\ttemplate <template <class...> class, class...> struct Multiple;\n\ttemplate <template <class...> class V, class Head, class... Tail>\n\tstruct Multiple<V, Head, Tail...> {\n\t\ttemplate <class... Args> using vec = V<vector<Head>, Args...>;\n\t\tusing type = typename Multiple<vec, Tail...>::type;\n\t};\n\ttemplate <template <class...> class V> struct Multiple<V> { using type = V<>; };\n\ttemplate <class... T> using multiple_t = typename Multiple<tuple, T...>::type;\n\ttemplate <size_t N = 0, class T> void multiple_impl(T& t) const {\n\t\tif constexpr (N < tuple_size_v<T>) {\n\t\t\tauto& vec = get<N>(t);\n\t\t\tusing V = typename remove_reference_t<decltype(vec)>::value_type;\n\t\t\tvec.push_back(read<V>());\n\t\t\tmultiple_impl<N + 1>(t);\n\t\t}\n\t}\n\npublic:\n\ttemplate <class... T> auto multiple(size_t h) const {\n\t\tmultiple_t<T...> result;\n\t\twhile (h--) multiple_impl(result);\n\t\treturn result;\n\t}\n} in;\n#define inputs(T, ...) \\\n\tT __VA_ARGS__; \\\n\tin(__VA_ARGS__)\n#define ini(...) inputs(int, __VA_ARGS__)\n#define inl(...) inputs(long long, __VA_ARGS__)\n#define ins(...) inputs(string, __VA_ARGS__)\n#line 7 \"/home/yuruhiya/programming/library/template/Output.cpp\"\n#include <charconv>\n#line 10 \"/home/yuruhiya/programming/library/template/Output.cpp\"\nusing namespace std;\n\nstruct BoolStr {\n\tconst char *t, *f;\n\tBoolStr(const char* _t, const char* _f) : t(_t), f(_f) {}\n} Yes(\"Yes\", \"No\"), yes(\"yes\", \"no\"), YES(\"YES\", \"NO\"), Int(\"1\", \"0\");\nstruct DivStr {\n\tconst char *d, *l;\n\tDivStr(const char* _d, const char* _l) : d(_d), l(_l) {}\n} spc(\" \", \"\\n\"), no_spc(\"\", \"\\n\"), end_line(\"\\n\", \"\\n\"), comma(\",\", \"\\n\"),\n no_endl(\" \", \"\");\nclass Printer {\n\tBoolStr B{Yes};\n\tDivStr D{spc};\n\npublic:\n\tvoid print(int v) const {\n\t\tchar buf[12]{};\n\t\tif (auto [ptr, e] = to_chars(begin(buf), end(buf), v); e == errc{}) {\n\t\t\tfwrite(buf, sizeof(char), ptr - buf, stdout);\n\t\t} else {\n\t\t\tassert(false);\n\t\t}\n\t}\n\tvoid print(long long v) const {\n\t\tchar buf[21]{};\n\t\tif (auto [ptr, e] = to_chars(begin(buf), end(buf), v); e == errc{}) {\n\t\t\tfwrite(buf, sizeof(char), ptr - buf, stdout);\n\t\t} else {\n\t\t\tassert(false);\n\t\t}\n\t}\n\tvoid print(bool v) const {\n\t\tprint(v ? B.t : B.f);\n\t}\n\tvoid print(vector<bool>::reference v) const {\n\t\tprint(v ? B.t : B.f);\n\t}\n\tvoid print(char v) const {\n\t\tputchar_unlocked(v);\n\t}\n\tvoid print(const char* v) const {\n\t\tfwrite_unlocked(v, 1, strlen(v), stdout);\n\t}\n\tvoid print(double v) const {\n\t\tprintf(\"%.20f\", v);\n\t}\n\tvoid print(long double v) const {\n\t\tprintf(\"%.20Lf\", v);\n\t}\n\ttemplate <class T> void print(const T& v) const {\n\t\tcout << v;\n\t}\n\ttemplate <class T, class U> void print(const pair<T, U>& v) const {\n\t\tprint(v.first);\n\t\tprint(D.d);\n\t\tprint(v.second);\n\t}\n\ttemplate <class InputIterater>\n\tvoid print_range(const InputIterater& begin, const InputIterater& end) const {\n\t\tfor (InputIterater i = begin; i != end; ++i) {\n\t\t\tif (i != begin) print(D.d);\n\t\t\tprint(*i);\n\t\t}\n\t}\n\ttemplate <class T> void print(const vector<T>& v) const {\n\t\tprint_range(v.begin(), v.end());\n\t}\n\ttemplate <class T, size_t N> void print(const array<T, N>& v) const {\n\t\tprint_range(v.begin(), v.end());\n\t}\n\ttemplate <class T> void print(const vector<vector<T>>& v) const {\n\t\tfor (size_t i = 0; i < v.size(); ++i) {\n\t\t\tif (i) print(D.l);\n\t\t\tprint(v[i]);\n\t\t}\n\t}\n\n\tPrinter() = default;\n\tPrinter(const BoolStr& _boolstr, const DivStr& _divstr) : B(_boolstr), D(_divstr) {}\n\tPrinter& operator()() {\n\t\tprint(D.l);\n\t\treturn *this;\n\t}\n\ttemplate <class H> Printer& operator()(H&& h) {\n\t\tprint(h);\n\t\tprint(D.l);\n\t\treturn *this;\n\t}\n\ttemplate <class H, class... T> Printer& operator()(H&& h, T&&... t) {\n\t\tprint(h);\n\t\tprint(D.d);\n\t\treturn operator()(forward<T>(t)...);\n\t}\n\ttemplate <class InputIterator>\n\tPrinter& range(const InputIterator& begin, const InputIterator& end) {\n\t\tprint_range(begin, end);\n\t\tprint(D.l);\n\t\treturn *this;\n\t}\n\ttemplate <class T> Printer& range(const T& a) {\n\t\trange(a.begin(), a.end());\n\t\treturn *this;\n\t}\n\ttemplate <class... T> void exit(T&&... t) {\n\t\toperator()(forward<T>(t)...);\n\t\tstd::exit(EXIT_SUCCESS);\n\t}\n\tPrinter& flush() {\n\t\tfflush_unlocked(stdout);\n\t\treturn *this;\n\t}\n\tPrinter& set(const BoolStr& b) {\n\t\tB = b;\n\t\treturn *this;\n\t}\n\tPrinter& set(const DivStr& d) {\n\t\tD = d;\n\t\treturn *this;\n\t}\n\tPrinter& set(const char* t, const char* f) {\n\t\tB = BoolStr(t, f);\n\t\treturn *this;\n\t}\n} out;\n#line 3 \"/home/yuruhiya/programming/library/template/Step.cpp\"\nusing namespace std;\n\ntemplate <class T> struct Step {\n\tusing value_type = T;\n\n\tclass iterator {\n\t\tvalue_type a, b, c;\n\n\tpublic:\n\t\tconstexpr iterator() : a(value_type()), b(value_type()), c(value_type()) {}\n\t\tconstexpr iterator(value_type _b, value_type _c, value_type _s)\n\t\t : a(_b), b(_c), c(_s) {}\n\t\tconstexpr iterator& operator++() {\n\t\t\t--b;\n\t\t\ta += c;\n\t\t\treturn *this;\n\t\t}\n\t\tconstexpr iterator operator++(int) {\n\t\t\titerator tmp = *this;\n\t\t\t--b;\n\t\t\ta += c;\n\t\t\treturn tmp;\n\t\t}\n\t\tconstexpr const value_type& operator*() const {\n\t\t\treturn a;\n\t\t}\n\t\tconstexpr const value_type* operator->() const {\n\t\t\treturn &a;\n\t\t}\n\t\tconstexpr bool operator==(const iterator& i) const {\n\t\t\treturn b == i.b;\n\t\t}\n\t\tconstexpr bool operator!=(const iterator& i) const {\n\t\t\treturn !(b == i.b);\n\t\t}\n\t\tconstexpr value_type start() const {\n\t\t\treturn a;\n\t\t}\n\t\tconstexpr value_type size() const {\n\t\t\treturn b;\n\t\t}\n\t\tconstexpr value_type step() const {\n\t\t\treturn c;\n\t\t}\n\t};\n\tconstexpr Step(value_type b, value_type c, value_type s) : be(b, c, s) {}\n\tconstexpr iterator begin() const {\n\t\treturn be;\n\t}\n\tconstexpr iterator end() const {\n\t\treturn en;\n\t}\n\tconstexpr value_type start() const {\n\t\treturn be.start();\n\t}\n\tconstexpr value_type size() const {\n\t\treturn be.size();\n\t}\n\tconstexpr value_type step() const {\n\t\treturn be.step();\n\t}\n\tconstexpr value_type sum() const {\n\t\treturn start() * size() + step() * (size() * (size() - 1) / 2);\n\t}\n\toperator vector<value_type>() const {\n\t\treturn to_a();\n\t}\n\tauto to_a() const {\n\t\tvector<value_type> result;\n\t\tresult.reserve(size());\n\t\tfor (auto i : *this) {\n\t\t\tresult.push_back(i);\n\t\t}\n\t\treturn result;\n\t}\n\nprivate:\n\titerator be, en;\n};\ntemplate <class T> constexpr auto step(T a) {\n\treturn Step<T>(0, a, 1);\n}\ntemplate <class T> constexpr auto step(T a, T b) {\n\treturn Step<T>(a, b - a, 1);\n}\ntemplate <class T> constexpr auto step(T a, T b, T c) {\n\treturn Step<T>(a, a < b ? (b - a - 1) / c + 1 : 0, c);\n}\n#line 8 \"/home/yuruhiya/programming/library/template/Ruby.cpp\"\nusing namespace std;\n\ntemplate <class F> struct Callable {\n\tF func;\n\tCallable(const F& f) : func(f) {}\n};\ntemplate <class T, class F> auto operator|(const T& v, const Callable<F>& c) {\n\treturn c.func(v);\n}\n\nstruct Sort_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tsort(begin(v), end(v), f);\n\t\t\treturn v;\n\t\t});\n\t}\n\ttemplate <class T> friend auto operator|(T v, [[maybe_unused]] const Sort_impl& c) {\n\t\tsort(begin(v), end(v));\n\t\treturn v;\n\t}\n} Sort;\nstruct SortBy_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tsort(begin(v), end(v),\n\t\t\t [&](const auto& i, const auto& j) { return f(i) < f(j); });\n\t\t\treturn v;\n\t\t});\n\t}\n} SortBy;\nstruct RSort_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tsort(rbegin(v), rend(v), f);\n\t\t\treturn v;\n\t\t});\n\t}\n\ttemplate <class T> friend auto operator|(T v, [[maybe_unused]] const RSort_impl& c) {\n\t\tsort(rbegin(v), rend(v));\n\t\treturn v;\n\t}\n} RSort;\nstruct RSortBy_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tsort(begin(v), end(v),\n\t\t\t [&](const auto& i, const auto& j) { return f(i) > f(j); });\n\t\t\treturn v;\n\t\t});\n\t}\n} RSortBy;\nstruct Reverse_impl {\n\ttemplate <class T> friend auto operator|(T v, const Reverse_impl& c) {\n\t\treverse(begin(v), end(v));\n\t\treturn v;\n\t}\n} Reverse;\nstruct Unique_impl {\n\ttemplate <class T> friend auto operator|(T v, const Unique_impl& c) {\n\t\tv.erase(unique(begin(v), end(v), end(v)));\n\t\treturn v;\n\t}\n} Unique;\nstruct Uniq_impl {\n\ttemplate <class T> friend auto operator|(T v, const Uniq_impl& c) {\n\t\tsort(begin(v), end(v));\n\t\tv.erase(unique(begin(v), end(v)), end(v));\n\t\treturn v;\n\t}\n} Uniq;\nstruct Rotate_impl {\n\tauto operator()(int&& left) {\n\t\treturn Callable([&](auto v) {\n\t\t\tint s = static_cast<int>(size(v));\n\t\t\tassert(-s <= left && left <= s);\n\t\t\tif (0 <= left) {\n\t\t\t\trotate(begin(v), begin(v) + left, end(v));\n\t\t\t} else {\n\t\t\t\trotate(begin(v), end(v) + left, end(v));\n\t\t\t}\n\t\t\treturn v;\n\t\t});\n\t}\n} Rotate;\nstruct Max_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) { return *max_element(begin(v), end(v), f); });\n\t}\n\ttemplate <class T> friend auto operator|(T v, const Max_impl& c) {\n\t\treturn *max_element(begin(v), end(v));\n\t}\n} Max;\nstruct Min_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) { return *min_element(begin(v), end(v), f); });\n\t}\n\ttemplate <class T> friend auto operator|(T v, const Min_impl& c) {\n\t\treturn *min_element(begin(v), end(v));\n\t}\n} Min;\nstruct MaxPos_impl {\n\ttemplate <class T> friend auto operator|(T v, const MaxPos_impl& c) {\n\t\treturn max_element(begin(v), end(v)) - begin(v);\n\t}\n} MaxPos;\nstruct MinPos_impl {\n\ttemplate <class T> friend auto operator|(T v, const MinPos_impl& c) {\n\t\treturn min_element(begin(v), end(v)) - begin(v);\n\t}\n} MinPos;\nstruct MaxBy_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tauto max_it = begin(v);\n\t\t\tauto max_val = f(*max_it);\n\t\t\tfor (auto it = next(begin(v)); it != end(v); ++it) {\n\t\t\t\tif (auto val = f(*it); max_val < val) {\n\t\t\t\t\tmax_it = it;\n\t\t\t\t\tmax_val = val;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *max_it;\n\t\t});\n\t}\n} MaxBy;\nstruct MinBy_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tauto min_it = begin(v);\n\t\t\tauto min_val = f(*min_it);\n\t\t\tfor (auto it = next(begin(v)); it != end(v); ++it) {\n\t\t\t\tif (auto val = f(*it); min_val > val) {\n\t\t\t\t\tmin_it = it;\n\t\t\t\t\tmin_val = val;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *min_it;\n\t\t});\n\t}\n} MinBy;\nstruct MaxOf_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tauto max_val = f(*begin(v));\n\t\t\tfor (auto it = next(begin(v)); it != end(v); ++it) {\n\t\t\t\tif (auto val = f(*it); max_val < val) {\n\t\t\t\t\tmax_val = val;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn max_val;\n\t\t});\n\t}\n} MaxOf;\nstruct MinOf_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tauto min_val = f(*begin(v));\n\t\t\tfor (auto it = next(begin(v)); it != end(v); ++it) {\n\t\t\t\tif (auto val = f(*it); min_val > val) {\n\t\t\t\t\tmin_val = val;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn min_val;\n\t\t});\n\t}\n} MinOf;\nstruct Count_impl {\n\ttemplate <class V> auto operator()(const V& val) {\n\t\treturn Callable([&](auto v) { return count(begin(v), end(v), val); });\n\t}\n} Count;\nstruct CountIf_impl {\n\ttemplate <class F> auto operator()(const F& f) {\n\t\treturn Callable([&](auto v) { return count_if(begin(v), end(v), f); });\n\t}\n} CountIf;\nstruct Index_impl {\n\ttemplate <class V> auto operator()(const V& val) {\n\t\treturn Callable([&](auto v) -> optional<int> {\n\t\t\tauto result = find(begin(v), end(v), val);\n\t\t\treturn result != end(v) ? optional(result - begin(v)) : nullopt;\n\t\t});\n\t}\n\ttemplate <class V> auto operator()(const V& val, size_t i) {\n\t\treturn Callable([&](auto v) -> optional<int> {\n\t\t\tauto result = find(next(begin(v), i), end(v), val);\n\t\t\treturn result != end(v) ? optional(result - begin(v)) : nullopt;\n\t\t});\n\t}\n} Index;\nstruct IndexIf_impl {\n\ttemplate <class F> auto operator()(const F& f) {\n\t\treturn Callable([&](auto v) -> optional<int> {\n\t\t\tauto result = find_if(begin(v), end(v), f);\n\t\t\treturn result != end(v) ? optional(result - begin(v)) : nullopt;\n\t\t});\n\t}\n} IndexIf;\nstruct FindIf_impl {\n\ttemplate <class F> auto operator()(const F& f) {\n\t\treturn Callable([&](auto v) -> optional<typename decltype(v)::value_type> {\n\t\t\tauto result = find_if(begin(v), end(v), f);\n\t\t\treturn result != end(v) ? optional(*result) : nullopt;\n\t\t});\n\t}\n} FindIf;\nstruct Sum_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\treturn accumulate(next(begin(v)), end(v), f(*begin(v)),\n\t\t\t [&](const auto& a, const auto& b) { return a + f(b); });\n\t\t});\n\t}\n\ttemplate <class T> friend auto operator|(T v, const Sum_impl& c) {\n\t\treturn accumulate(begin(v), end(v), typename T::value_type{});\n\t}\n} Sum;\nstruct Includes {\n\ttemplate <class V> auto operator()(const V& val) {\n\t\treturn Callable([&](auto v) { return find(begin(v), end(v), val) != end(v); });\n\t}\n} Includes;\nstruct IncludesIf_impl {\n\ttemplate <class F> auto operator()(const F& f) {\n\t\treturn Callable([&](auto v) { return find_if(begin(v), end(v), f) != end(v); });\n\t}\n} IncludesIf;\nstruct RemoveIf_impl {\n\ttemplate <class F> auto operator()(const F& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tv.erase(remove_if(begin(v), end(v), f), end(v));\n\t\t\treturn v;\n\t\t});\n\t}\n} RemoveIf;\nstruct Each_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tfor (const auto& i : v) {\n\t\t\t\tf(i);\n\t\t\t}\n\t\t});\n\t}\n} Each;\nstruct EachConsPair_impl {\n\ttemplate <class T, class value_type = typename T::value_type>\n\tfriend auto operator|(const T& v, EachConsPair_impl& c) {\n\t\tvector<pair<value_type, value_type>> result;\n\t\tif (size(v) >= 2) {\n\t\t\tresult.reserve(size(v) - 1);\n\t\t\tfor (size_t i = 0; i < size(v) - 1; ++i) {\n\t\t\t\tresult.emplace_back(v[i], v[i + 1]);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n} EachConsPair;\nstruct Select_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tusing value_type = typename decltype(v)::value_type;\n\t\t\tvector<value_type> result;\n\t\t\tfor (const auto& i : v) {\n\t\t\t\tif (f(i)) result.push_back(i);\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t}\n} Select;\nstruct Map_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tusing result_type = invoke_result_t<F, typename decltype(v)::value_type>;\n\t\t\tvector<result_type> result;\n\t\t\tresult.reserve(size(v));\n\t\t\tfor (const auto& i : v) {\n\t\t\t\tresult.push_back(f(i));\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t}\n} Map;\nstruct Indexed_impl {\n\ttemplate <class T> friend auto operator|(const T& v, Indexed_impl& c) {\n\t\tusing value_type = typename T::value_type;\n\t\tvector<pair<value_type, int>> result;\n\t\tresult.reserve(size(v));\n\t\tint index = 0;\n\t\tfor (const auto& i : v) {\n\t\t\tresult.emplace_back(i, index++);\n\t\t}\n\t\treturn result;\n\t}\n} Indexed;\nstruct AllOf_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tfor (const auto& i : v) {\n\t\t\t\tif (!f(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t}\n} AllOf;\nstruct AnyOf_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tfor (const auto& i : v) {\n\t\t\t\tif (f(i)) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n\t}\n} AnyOf;\nstruct NoneOf_impl {\n\ttemplate <class F> auto operator()(F&& f) {\n\t\treturn Callable([&](auto v) {\n\t\t\tfor (const auto& i : v) {\n\t\t\t\tif (f(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t}\n} NoneOf;\n\nstruct Tally_impl {\n\ttemplate <class F> auto operator()(size_t max_val) {\n\t\treturn Callable([&](auto v) {\n\t\t\tvector<size_t> result(max_val);\n\t\t\tfor (const auto& i : v) {\n\t\t\t\tresult[static_cast<size_t>(i)]++;\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t}\n\ttemplate <class T, class value_type = typename T::value_type>\n\tfriend auto operator|(const T& v, Tally_impl& c) {\n\t\tmap<value_type, size_t> result;\n\t\tfor (const auto& i : v) {\n\t\t\tresult[i]++;\n\t\t}\n\t\treturn result;\n\t}\n} Tally;\n\ntemplate <class T> auto operator*(const vector<T>& a, size_t n) {\n\tT result;\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tresult.insert(result.end(), a.begin(), a.end());\n\t}\n\treturn result;\n}\nauto operator*(string a, size_t n) {\n\tstring result;\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tresult += a;\n\t}\n\treturn result;\n}\ntemplate <class T, class U> auto& operator<<(vector<T>& a, const U& b) {\n\ta.insert(a.end(), all(b));\n\treturn a;\n}\ntemplate <class T> auto& operator<<(string& a, const T& b) {\n\ta.insert(a.end(), all(b));\n\treturn a;\n}\ntemplate <class T, class U> auto operator+(vector<T> a, const U& b) {\n\ta << b;\n\treturn a;\n}\ntemplate <class T> auto operator+(string a, const T& b) {\n\ta << b;\n\treturn a;\n}\n#line 7 \"/home/yuruhiya/programming/library/template/functions.cpp\"\nusing namespace std;\n\ntemplate <class T = long long> constexpr T TEN(size_t n) {\n\tT result = 1;\n\tfor (size_t i = 0; i < n; ++i) result *= 10;\n\treturn result;\n}\ntemplate <class T, class U,\n enable_if_t<is_integral_v<T> && is_integral_v<U>, nullptr_t> = nullptr>\nconstexpr auto div_ceil(T n, U m) {\n\treturn (n + m - 1) / m;\n}\ntemplate <class T, class U> constexpr auto div_ceil2(T n, U m) {\n\treturn div_ceil(n, m) * m;\n}\ntemplate <class T> constexpr T triangle(T n) {\n\treturn (n & 1) ? (n + 1) / 2 * n : n / 2 * (n + 1);\n}\ntemplate <class T> constexpr T nC2(T n) {\n\treturn (n & 1) ? (n - 1) / 2 * n : n / 2 * (n - 1);\n}\ntemplate <class T, class U> constexpr auto middle(const T& l, const U& r) {\n\treturn l + (r - l) / 2;\n}\ntemplate <class T, class U, class V>\nconstexpr bool in_range(const T& v, const U& lower, const V& upper) {\n\treturn lower <= v && v < upper;\n}\ntemplate <class T, enable_if_t<is_integral_v<T>, nullptr_t> = nullptr>\nconstexpr bool is_square(T n) {\n\tT s = sqrt(n);\n\treturn s * s == n || (s + 1) * (s + 1) == n;\n}\ntemplate <class T = long long> constexpr T BIT(int b) {\n\treturn T(1) << b;\n}\ntemplate <class T> constexpr int BIT(T x, int i) {\n\treturn (x & (T(1) << i)) ? 1 : 0;\n}\ntemplate <class T> constexpr int Sgn(T x) {\n\treturn (0 < x) - (0 > x);\n}\ntemplate <class T, class U, enable_if_t<is_integral_v<U>, nullptr_t> = nullptr>\nconstexpr T Pow(T a, U n) {\n\tassert(n >= 0);\n\tT result = 1;\n\twhile (n > 0) {\n\t\tif (n & 1) {\n\t\t\tresult *= a;\n\t\t\tn--;\n\t\t} else {\n\t\t\ta *= a;\n\t\t\tn >>= 1;\n\t\t}\n\t}\n\treturn result;\n}\ntemplate <class T, class U, enable_if_t<is_integral_v<U>, nullptr_t> = nullptr>\nconstexpr T Powmod(T a, U n, T mod) {\n\tassert(n >= 0);\n\tif (a > mod) a %= mod;\n\tT result = 1;\n\twhile (n > 0) {\n\t\tif (n & 1) {\n\t\t\tresult = result * a % mod;\n\t\t\tn--;\n\t\t} else {\n\t\t\ta = a * a % mod;\n\t\t\tn >>= 1;\n\t\t}\n\t}\n\treturn result;\n}\ntemplate <class T> bool chmax(T& a, const T& b) {\n\tif (a < b) {\n\t\ta = b;\n\t\treturn true;\n\t}\n\treturn false;\n}\ntemplate <class T> bool chmin(T& a, const T& b) {\n\tif (a > b) {\n\t\ta = b;\n\t\treturn true;\n\t}\n\treturn false;\n}\ntemplate <class T> int sz(const T& v) {\n\treturn v.size();\n}\ntemplate <class T, class U> int lower_index(const T& a, const U& v) {\n\treturn lower_bound(all(a), v) - a.begin();\n}\ntemplate <class T, class U> int upper_index(const T& a, const U& v) {\n\treturn upper_bound(all(a), v) - a.begin();\n}\ntemplate <class T> auto Slice(const T& v, size_t i, size_t len) {\n\treturn i < v.size() ? T(v.begin() + i, v.begin() + min(i + len, v.size())) : T();\n}\ntemplate <class T, class U = typename T::value_type> U Gcdv(const T& v) {\n\treturn accumulate(next(v.begin()), v.end(), U(*v.begin()), gcd<U, U>);\n}\ntemplate <class T, class U = typename T::value_type> U Lcmv(const T& v) {\n\treturn accumulate(next(v.begin()), v.end(), U(*v.begin()), lcm<U, U>);\n}\nnamespace internal {\n\ttemplate <class T, size_t N> auto make_vector(vector<int>& sizes, const T& init) {\n\t\tif constexpr (N == 1) {\n\t\t\treturn vector(sizes[0], init);\n\t\t} else {\n\t\t\tint size = sizes[N - 1];\n\t\t\tsizes.pop_back();\n\t\t\treturn vector(size, make_vector<T, N - 1>(sizes, init));\n\t\t}\n\t}\n} // namespace internal\ntemplate <class T, size_t N>\nauto make_vector(const int (&sizes)[N], const T& init = T()) {\n\tvector s(rbegin(sizes), rend(sizes));\n\treturn internal::make_vector<T, N>(s, init);\n}\n#line 9 \"/home/yuruhiya/programming/library/template/template.cpp\"\n#if __has_include(<library/dump.hpp>)\n#include <library/dump.hpp>\n#define LOCAL\n#else\n#define dump(...) ((void)0)\n#endif\n\ntemplate <class T> constexpr T oj_local(const T& oj, const T& local) {\n#ifndef LOCAL\n\treturn oj;\n#else\n\treturn local;\n#endif\n}\n#line 2 \"a.cpp\"\n\nint main() {\n\tini(n);\n\tauto [x, y] = in.multiple<LD, LD>(n);\n\n\tauto dist = [&](int i, int j) {\n\t\treturn hypot(x[i] - x[j], y[i] - y[j]);\n\t};\n\n\tauto dp = make_vector<LD>({n, n}, -1);\n\tauto rec = [&](auto&& f, int i, int j) -> LD {\n\t\tLD& res = dp[i][j];\n\t\tif (res != -1) {\n\t\t\treturn res;\n\t\t} else if (i == 0 && j == 1) {\n\t\t\treturn res = dist(i, j);\n\t\t} else if (i < j - 1) {\n\t\t\treturn res = f(f, i, j - 1) + dist(j - 1, j);\n\t\t} else {\n\t\t\tres = 1e18;\n\t\t\trep(k, j - 1) chmin(res, f(f, k, j - 1) + dist(k, j));\n\t\t\treturn res;\n\t\t}\n\t};\n\n\tLD ans = 1e18;\n\trep(i, n - 1) {\n\t\tdump(i, n - 1, rec(rec, i, n - 1));\n\t\tchmin(ans, rec(rec, i, n - 1) + dist(i, n - 1));\n\t}\n\tout(ans);\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 18880, "score_of_the_acc": -1.9647, "final_rank": 20 }, { "submission_id": "aoj_DPL_2_C_5079077", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n__attribute__((constructor))\nvoid fast_io() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n}\n\nint main() {\n int n;\n cin >> n;\n vector<int> x(n), y(n);\n for (int i = 0; i < n; ++i) cin >> x[i] >> y[i];\n auto dist = [&](int i, int j) { return hypot(x[i] - x[j], y[i] - y[j]); };\n vector dp(n, vector(n, DBL_MAX));\n dp[0][1] = dist(0, 1);\n for (int j = 2; j < n; ++j) {\n for (int i = 0; i < j - 1; ++i) {\n dp[i][j] = min(dp[i][j], dp[i][j - 1] + dist(j - 1, j));\n dp[j - 1][j] = min(dp[j - 1][j], dp[i][j - 1] + dist(i, j));\n }\n }\n double ans = DBL_MAX;\n for (int i = 0; i < n; ++i) ans = min(ans, dp[i][n-1] + dist(i, n - 1));\n cout << fixed << setprecision(8) << ans << '\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11032, "score_of_the_acc": -0.0521, "final_rank": 6 }, { "submission_id": "aoj_DPL_2_C_5079076", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n__attribute__((constructor))\nvoid fast_io() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n}\n\nint main() {\n int n;\n cin >> n;\n vector<int> x(n), y(n);\n for (int i = 0; i < n; ++i) cin >> x[i] >> y[i];\n auto dist = [&](int i, int j) { return hypot(x[i] - x[j], y[i] - y[j]); };\n vector dp(n, vector(n, DBL_MAX));\n dp[0][1] = dist(0, 1);\n for (int j = 2; j < n; ++j) {\n for (int i = 0; i < j - 1; ++i) {\n dp[i][j] = min(dp[i][j], dp[i][j - 1] + dist(j - 1, j));\n dp[j - 1][j] = min(dp[j - 1][j], dp[i][j - 1] + dist(i, j));\n }\n }\n double ans = DBL_MAX;\n for (int i = 0; i < n; ++i) ans = min(ans, dp[i][n-1] + dist(i, n - 1));\n cout << fixed << setprecision(8) << ans << '\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11032, "score_of_the_acc": -0.0521, "final_rank": 6 }, { "submission_id": "aoj_DPL_2_C_5079070", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n vector<int> x(n), y(n);\n for (int i = 0; i < n; ++i) cin >> x[i] >> y[i];\n\n vector dist(n, vector<double>(n));\n for (int i = 0; i < n; ++i) for (int j = i; j < n; ++j)\n dist[i][j] = dist[j][i] = hypot(x[i] - x[j], y[i] - y[j]);\n\n vector dp(n, vector(n, DBL_MAX));\n dp[0][1] = dist[0][1];\n for (int j = 2; j < n; ++j) {\n for (int i = 0; i < j - 1; ++i) {\n dp[i][j] = min(dp[i][j], dp[i][j - 1] + dist[j - 1][j]);\n dp[j - 1][j] = min(dp[j - 1][j], dp[i][j - 1] + dist[i][j]);\n }\n }\n double ans = DBL_MAX;\n for (int i = 0; i < n; ++i) ans = min(ans, dp[i][n-1] + dist[i][n-1]);\n cout << fixed << setprecision(8) << ans << '\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18988, "score_of_the_acc": -0.9772, "final_rank": 18 } ]
aoj_DPL_3_B_cpp
Largest Rectangle Given a matrix ( H × W ) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s. Input H W c 1,1 c 1,2 ... c 1,W c 2,1 c 2,2 ... c 2,W : c H,1 c H,2 ... c H,W In the first line, two integers H and W separated by a space character are given. In the following H lines, c i , j , elements of the H × W matrix, are given. Output Print the area (the number of 0s) of the largest rectangle. Constraints 1 ≤ H , W ≤ 1,400 Sample Input 4 5 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 Sample Output 6
[ { "submission_id": "aoj_DPL_3_B_10988570", "code_snippet": "#include <cstdio>\n#include <stack>\nusing namespace std;\nconst int maxv=1401;\nint C[maxv][maxv];\nint D[maxv][maxv];\nint H,W;\nint maxsquare(){\n int largest=0;\n for(int i=0;i<H;i++){\n stack<pair<int,int>> rect;\n for(int j=0;j<=W;j++){\n if(rect.empty()){\n rect.push(make_pair(j,D[i][j]));\n }else if(D[i][j]>rect.top().second){\n rect.push(make_pair(j,D[i][j]));\n }else if(D[i][j]<rect.top().second){\n int c;\n while(!rect.empty()&&D[i][j]<rect.top().second){\n c=rect.top().first;\n int d=rect.top().second;\n int m=(j-c)*d;\n largest=max(largest,m);\n rect.pop();\n }\n rect.push(make_pair(c,D[i][j]));\n }\n }\n }\n return largest;\n}\nint main(){\n scanf(\"%d %d\",&H,&W);\n for(int i=0;i<H;i++){\n for(int j=0;j<W;j++){\n scanf(\"%d\",&C[i][j]);\n }\n }\n for(int i=0;i<W;i++){\n for(int j=0;j<H;j++){\n if(C[j][i]){\n D[j][i]=0;\n }else{\n if(j!=0){\n D[j][i]=1+D[j-1][i];\n }else D[j][i]=1; \n }\n }\n }\n for(int i=0;i<H;i++){\n D[i][W]=0;\n }\n int u=maxsquare();\n printf(\"%d\\n\",u);\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 18316, "score_of_the_acc": -0.6374, "final_rank": 9 }, { "submission_id": "aoj_DPL_3_B_10932502", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n#include <chrono>\n#include <complex>\n#include <cmath>\n#include <unistd.h>\n#define pc_u putchar\n#pragma GCC target (\"avx\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n#define rep(i,a,b) for(it i=(it)(a);i<(it)b;i++)\n#define rep2(i,a,b,c) for(it i=(it)(a);i<(it)b;i+=(it)c)\n#define repp(i,a,b) for(it i=(it)(a);i<=(it)b;i++)\n#define repp2(i,a,b,c) for(it i=(it)(a);i<=(it)b;i+=(it)c)\n#define irep(i,a,b) for(int i=(int)(a);i<(int)b;i++)\n#define irep2(i,a,b,c) for(int i=(int)(a);i<(int)b;i+=c)\n#define irepp(i,a,b) for(int i=(int)(a);i<=(int)b;i++)\n#define irepp2(i,a,b,c) for(int i=(int)(a);i<=(int)b;i+=c)\n#define nrep(i,a,b) for(it i=(it)(a)-1;i>=(it)b;i--)\n#define nrepp(i,a,b) for(it i=(it)(a);i>=(it)b;i--)\n#define inrep(i,a,b) for(int i=(int)(a)-1;i>=(int)b;i--)\n#define inrepp(i,a,b) for(int i=(int)(a);i>=(int)b;i--)\n#define inrep2(i,a,b,c) for(int i=(int)(a)-1;i>=(int)b;i-=c)\n#define inrepp2(i,a,b,c) for(int i=(int)(a);i>=(int)b;i-=c)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define Min(x) *min_element(all(x))\n#define Max(x) *max_element(all(x))\n#define popcount(x) __builtin_popcountll(x)\n#define moda 998244353LL\n#define modb 1000000007LL\n#define modc 968244353LL\n#define dai 2502502502502502502LL\n#define sho -dai\n#define aoi 1e18+1e6\n#define giri 1010000000\n#define en 3.14159265358979\n#define eps 1e-14\n#define fi first\n#define se second\n#define elif else if\ntemplate<typename T> using pq=priority_queue<T>;\ntemplate<typename T> using pqg=priority_queue<T,vector<T>,greater<T>>;\n#define uni(a) a.erase(unique(all(a)),a.end())\nusing it=long long;\nusing itn=int;\nusing un=unsigned long long;\nusing idb=double;\nusing db=long double;\nusing st=string;\nusing ch=char;\nusing bo=bool;\nusing P=pair<it,it>;\nusing ip=pair<int,int>;\nusing vi=vector<it>;\nusing ivi=vector<int>;\nusing ivd=vector<idb>;\nusing vd=vector<db>;\nusing vs=vector<st>;\nusing vc=vector<ch>;\nusing vb=vector<bo>;\nusing vp=vector<P>;\nusing ivp=vector<ip>;\nusing sp=set<P>;\nusing isp=set<ip>;\nusing ss=set<st>;\nusing sca=set<ch>;\nusing si=set<it>;\nusing isi=set<int>;\nusing svi=set<vi>;\nusing svb=set<vb>;\nusing vvi=vector<vi>;\nusing ivvi=vector<ivi>;\nusing ivvd=vector<ivd>;\nusing vvd=vector<vd>;\nusing vvs=vector<vs>;\nusing vvb=vector<vb>;\nusing vvc=vector<vc>;\nusing vvp=vector<vp>;\nusing ivvp=vector<ivp>;\nusing vsi=vector<si>;\nusing ivsi=vector<isi>;\nusing isvi=set<ivi>;\nusing vsc=vector<sca>;\nusing vsp=vector<sp>;\nusing ivsp=vector<isp>;\nusing vvsi=vector<vsi>;\nusing ivvsi=vector<ivsi>;\nusing vvsp=vector<vsp>;\nusing ivvsp=vector<ivsp>;\nusing svvb=set<vvb>;\nusing vvvi=vector<vvi>;\nusing ivvvi=vector<ivvi>;\nusing ivvvd=vector<ivvd>;\nusing vvvd=vector<vvd>;\nusing vvvb=vector<vvb>;\nusing ivvvp=vector<ivvp>;\nusing vvvp=vector<vvp>;\nusing vvvvi=vector<vvvi>;\nusing ivvvvi=vector<ivvvi>;\nusing vvvvd=vector<vvvd>;\nusing vvvvb=vector<vvvb>;\nusing ivvvvp=vector<ivvvp>;\nusing vvvvp=vector<vvvp>;\nusing ivvvvvi=vector<ivvvvi>;\nusing vvvvvi=vector<vvvvi>;\nusing ivvvvvvi=vector<ivvvvvi>;\nusing vvvvvvi=vector<vvvvvi>;\nusing ivvvvvvvi=vector<ivvvvvvi>;\nusing vvvvvvvi=vector<vvvvvvi>;\nusing vvvvvvvvi=vector<vvvvvvvi>;\nconst int dx[8]={0,1,0,-1,1,1,-1,-1};\nconst int dy[8]={1,0,-1,0,1,-1,1,-1};\nst abc=\"abcdefghijklmnopqrstuvwxyz\";\nst ABC=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nst num=\"0123456789\";\nst mb=\"xo\";\nst MB=\"XO\";\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\ntemplate<class T> using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\nnamespace {\n\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const pair<T, U> &p) {\n os << p.first << \" \" << p.second;\n return os;\n}\ntemplate <typename T, typename U>\nistream &operator>>(istream &is, pair<T, U> &p) {\n is >> p.first >> p.second;\n return is;\n}\n\ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v) {\n int s = (int)v.size();\n for (int i = 0; i < s; i++) os << (i ? \" \" : \"\") << v[i];\n return os;\n}\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v) {\n for (auto &x : v) is >> x;\n return is;\n}\n\nistream &operator>>(istream &is, __int128_t &x) {\n string S;\n is >> S;\n x = 0;\n int flag = 0;\n for (auto &c : S) {\n if (c == '-') {\n flag = true;\n continue;\n }\n x *= 10;\n x += c - '0';\n }\n if (flag) x = -x;\n return is;\n}\n\nistream &operator>>(istream &is, __uint128_t &x) {\n string S;\n is >> S;\n x = 0;\n for (auto &c : S) {\n x *= 10;\n x += c - '0';\n }\n return is;\n}\n\nostream &operator<<(ostream &os, __int128_t x) {\n if (x == 0) return os << 0;\n if (x < 0) os << '-', x = -x;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\nostream &operator<<(ostream &os, __uint128_t x) {\n if (x == 0) return os << 0;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\n\nvoid input() {}\ntemplate <typename T, class... U>\nvoid input(T &t, U &...u) {\n cin >> t;\n input(u...);\n}\ntemplate <typename T, class... U>\nvoid input1(T &t, U &...u) {\n input(u...);\n}\nvoid print() { cout << \"\\n\"; }\ntemplate <typename T, class... U, char sep = ' '>\nvoid print(const T &t, const U &...u) {\n cout << t;\n if (sizeof...(u)) cout << sep;\n print(u...);\n}\ntemplate <typename T, class... U, char sep = ' '>\nvoid print1(const T &t, const U &...u) {\n print(u...);\n}\n\nstruct IoSetupNya {\n IoSetupNya() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n cerr << fixed << setprecision(7);\n }\n} iosetupnya;\n\n} //namespace Nyaan\n\ntemplate<typename T>\nT Sum(vector<T> &a){\n T s=0;\n for(auto i:a)s+=i;\n return s;\n}\n\ntemplate<typename T>\nT Sum(vector<T> &a,int l,int r){\n T s=0;\n irep(i,l,r)s+=a[i];\n return s;\n}\n\ntemplate <typename T>\nvoid dec(vector<T> &t,T k=1){\n for(auto &i:t)i-=k;\n}\n\ntemplate <typename T>\nvoid inc(vector<T> &t,T k=1){\n for(auto &i:t)i+=k;\n}\n\ntemplate <typename T>\nvector<T> make_vec(int n,T t){\n vector<T> g(n);\n for(auto &i:g)i=t;\n return g;\n}\n\ntemplate <typename T>\nvector<T> subvec(vector<T> a,int f,int l){\n vector<T> g(l);\n irep(i,f,f+l)g[i-f]=a[i];\n return g;\n}\n\ntemplate<typename T>\nT gcda(T a,T b){\n if(!a||!b)return max(a,b);\n while(a%b&&b%a){\n if(a>b)a%=b;\n else b%=a;\n }\n return min(a,b);\n}\n\nit lcma(it a,it b){\n return a/gcda(a,b)*b;\n}\n\ndb distance(db a,db b,db c,db d){return sqrt((a-c)*(a-c)+(b-d)*(b-d));}\n\ndb getAngle(db xa, db ya, db xb, db yb, db xc, db yc) {\n //角BACを求める\n //E8さんの記事コピペ\n db VectorAB = sqrt((xb - xa) * (xb - xa) + (yb - ya) * (yb - ya));\n db VectorAC = sqrt((xc - xa) * (xc - xa) + (yc - ya) * (yc - ya));\n db Naiseki = (xb - xa) * (xc - xa) + (yb - ya) * (yc - ya);\n db cosTheta = Naiseki / (VectorAB * VectorAC);\n return acos(cosTheta) * 180.0 / 3.14159265358979;\n}\n\nlong double segment_origin_dist(long double A, long double B, long double C, long double D) {\n // P = (A,B), Q = (C,D)\n long double vx = C - A, vy = D - B; // ベクトルPQ\n long double wx = -A, wy = -B; // ベクトルPO (O-P)\n\n long double vv = vx * vx + vy * vy; // |PQ|^2\n if (vv == 0) {\n // P == Q の場合、点と原点の距離\n return sqrt(A * A + B * B);\n }\n\n long double t = (wx * vx + wy * vy) / vv; // 射影パラメータ\n\n long double nx, ny; // 最近点\n if (t <= 0) {\n nx = A; ny = B;\n } else if (t >= 1) {\n nx = C; ny = D;\n } else {\n nx = A + t * vx;\n ny = B + t * vy;\n }\n\n return sqrt(nx * nx + ny * ny);\n}\n\nbo outc(int h,int w,int x,int y){\n return (x<0||x>=h||y<0||y>=w);\n}\n\ntemplate<typename T>\nvector<vector<T>> nep(vector<T> a){\n vector<vector<T>> e;\n sort(all(a));\n do{\n e.emplace_back(a);\n }while(next_permutation(all(a)));\n return e;\n}\n\ntemplate<typename T>\nvoid chmin(T &a,T b){a=min(a,b);}\ntemplate<typename T>\nvoid chmax(T &a,T b){a=max(a,b);}\n\nvoid yn(bo a){print(a?string(\"Yes\"):string(\"No\"));}\nvoid YN(bo a){print(a?string(\"YES\"):string(\"NO\"));}\n\nstruct dsu1{\n ivi par,siz;\n dsu1(int n){\n init(n);\n }\n void init(int n){\n irep(i,0,n){\n par.emplace_back(i);\n }\n siz.resize(n,1);\n }\n int leader(int u){\n if(par[u]==u)return u;\n return par[u]=leader(par[u]);\n }\n void merge(int u,int v){\n int ru=leader(u),rv=leader(v);\n if(ru==rv)return;\n if(size(ru)<size(rv))swap(ru,rv);\n siz[ru]+=siz[rv];\n par[rv]=ru;\n }\n bool same(int u,int v){\n return leader(u)==leader(v);\n }\n int size(int u){\n return siz[leader(u)];\n }\n};\n\nstruct edge{\n int f;\n int t;\n it l;\n};\nvoid input(edge &a){input(a.f,a.t,a.l);}\nbo comppppp(edge &a,edge &b){return a.l<b.l;}\n\nit minspantree(vector<edge> &e,int n){\n /*\n 与えられた辺を持つグラフの最小全域木を求める\n 存在する場合はその答えを 存在しないならinf\n 計算量はO(MlogM+N)くらい\n */\n vector<edge> g=e;sort(all(g),comppppp);\n it ans=0;\n dsu1 uf(n);\n for(auto i:g){\n if(!uf.same(i.f,i.t)){\n uf.merge(i.f,i.t);\n ans+=i.l;\n }\n }\n if(uf.size(0)==n)return ans;\n return dai;\n}\n\n/*#include <atcoder/all>\nusing namespace atcoder;\nusing mints=modint998244353;\nusing mint=modint;\nusing minto=modint1000000007;\nusing vm=vector<mint>;\nusing vms=vector<mints>;\nusing vmo=vector<minto>;\nusing vvm=vector<vm>;\nusing vvms=vector<vms>;\nusing vvmo=vector<vmo>;\nusing vvvm=vector<vvm>;\nusing vvvms=vector<vvms>;\nusing vvvmo=vector<vvmo>;\nusing vvvvm=vector<vvvm>;\nusing vvvvms=vector<vvvms>;\nusing vvvvmo=vector<vvvmo>;\nusing vvvvvm=vector<vvvvm>;\nusing vvvvvms=vector<vvvvms>;\nusing vvvvvmo=vector<vvvvmo>;\nusing vvvvvvm=vector<vvvvvm>;\nusing vvvvvvms=vector<vvvvvms>;\nusing vvvvvvmo=vector<vvvvvmo>;\nusing vvvvvvvms=vector<vvvvvvms>;\nusing vvvvvvvmo=vector<vvvvvvmo>;*/\n\n/*総和をもとめるセグ木\nstruct nod{\n it val;\n nod(it v=0):val(v){}\n};\n\nnod op(nod a,nod b){return nod(a.val+b.val);}\nnod e(){return nod(0);}\n\nstruct act{\n it a;\n act(it e=0):a(e){}\n};\n\nnod mapping(act f,nod x){return nod(f.a+x.val);}\nact comp(act f,act g){return act(f.a+g.a);}\nact id(){return act(0);}*/\n//#define endl '\\n'\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n\nvoid solve(){\n int h,w;input(h,w);\n ivvi a(h,ivi(w));input(a);\n ivi u(h,-1);int ans=0;\n irep(j,0,w){\n irep(i,0,h)\n if(u[i]<j){\n u[i]=j;\n while(u[i]<w&&!a[i][u[i]])u[i]++;\n }\n //print(j,u);\n ivvi c(w+1);\n irep(i,0,h)c[u[i]-j].emplace_back(i);\n dsu1 uf(h);vb s(h);\n inrep(p,w+1,0)\n for(int i:c[p]){\n if(i&&s[i-1])uf.merge(i-1,i);\n if(i!=h-1&&s[i+1])uf.merge(i+1,i);\n chmax(ans,p*uf.size(i));\n s[i]=1;\n }\n }\n print(ans);\n}\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int t=1;//input(t);\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 11172, "score_of_the_acc": -0.4559, "final_rank": 2 }, { "submission_id": "aoj_DPL_3_B_10874919", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntemplate<typename T, typename F>\nclass CartesianTree {\n private:\n int N;\n F op;\n vector<int> left, right;\n vector<T> A;\n public:\n int root;\n vector<vector<int>> E;//2分木を構築\n vector<int> par;\n CartesianTree() {}\n CartesianTree(F _op, const vector<T> _A) \n : A(_A), op(_op), N(_A.size()), left(_A.size()), right(_A.size()), E(_A.size()) {\n vector<int> st;\n par.resize(N, -1);\n for (int i = 0; i < N; i++) {\n int pre = -1;\n while (!st.empty() && op(A[st.back()], A[i])) {\n pre = st.back();\n st.pop_back();\n }\n if (pre != -1) {\n par[pre] = i;\n }\n if (!st.empty()) {\n par[i] = st.back();\n } else {\n root = i;\n }\n st.push_back(i);\n }\n for (int i = 0; i < N; i++) {\n if (par[i] != -1) {\n E[par[i]].push_back(i);\n }\n }\n calc();\n } \n void calc() {\n for (int i = 0; i < N; i++) {\n left[i] = i;\n right[i] = i + 1;\n }\n auto dfs = [&] (auto &&self, int v) -> void {\n for (int w : E[v]) {\n self(self, w);\n left[v] = min(left[v], left[w]);\n right[v] = max(right[v], right[w]);\n }\n };\n dfs(dfs, root);\n }\n //A[v]が最大値または最小値(opによる)を取る区間を[l ,r)で返す\n pair<int, int> get_range(int v) {\n return make_pair(left[v], right[v]);\n }\n};\nbool op(int a, int b) {\n return a > b;\n}\nint main() {\n int H, W;\n cin >> H >> W;\n vector c(H, vector<int>(W));\n vector<int> h(W);\n int ans = 0;\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n cin >> c[i][j];\n if (c[i][j] == 1) {\n h[j] = 0;\n } else {\n h[j]++;\n }\n }\n CartesianTree CT(op, h);\n CT.calc();\n for (int i = 0; i < W; i++) {\n auto [l, r] = CT.get_range(i);\n int width = \n ans = max(ans, (r - l) * h[i]);\n }\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 240, "memory_kb": 11264, "score_of_the_acc": -1.2484, "final_rank": 19 }, { "submission_id": "aoj_DPL_3_B_10862260", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct rect\n{\n int h, i;\n rect(int h, int i) : h(h), i(i) {}\n};\n\nint main()\n{\n int h, w;\n cin >> h >> w;\n int grid[h][w];\n for (int i = 0; i < h; i++)\n {\n for (int j = 0; j < w; j++)\n {\n cin >> grid[i][j];\n }\n }\n\n int dp[h][w];\n\n for (int j = 0; j < w; j++)\n dp[0][j] = grid[0][j] == 1 ? 0 : 1;\n\n for (int i = 1; i < h; i++)\n {\n for (int j = 0; j < w; j++)\n {\n dp[i][j] = grid[i][j] == 1 ? 0 : dp[i-1][j] + 1;\n }\n }\n\n int ans = 0;\n\n for (int i = 0; i < h; i++)\n {\n stack<rect> s;\n for (int j = 0; j < w; j++)\n {\n if (s.empty() || s.top().h < dp[i][j])\n {\n s.push( rect(dp[i][j], j) );\n }\n else if (s.top().h > dp[i][j])\n {\n int lasti = 0;\n while (!s.empty() && s.top().h > dp[i][j])\n {\n ans = max( ans, s.top().h * (j - s.top().i) );\n lasti = s.top().i;\n s.pop();\n }\n s.push( rect(dp[i][j], lasti) );\n }\n }\n\n while (!s.empty())\n {\n ans = max( ans, s.top().h * (w - s.top().i) );\n s.pop();\n }\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 140, "memory_kb": 18628, "score_of_the_acc": -0.9635, "final_rank": 14 }, { "submission_id": "aoj_DPL_3_B_10833554", "code_snippet": "#include <bits/stdc++.h>\n#include <cmath>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < n; i++)\nusing ll = long long;\nusing P = pair<int, int>;\nusing Pll = pair<ll, ll>;\nvoid chmin(int& a, int b) { a = min(a, b); }\nvoid chminll(ll& a, ll b) { a = min(a, b); }\nvoid chminD(double& a, double b) { a = min(a, b); }\nvoid chmax(int& a, int b) { a = max(a, b); }\nvoid chmaxll(ll& a, ll b) { a = max(a, b); }\nvoid chmaxD(double& a, double b) { a = max(a, b); }\nint ceil(int a, int b) { return (a+b-1)/b; };\nll ceil_ll(ll a, ll b) { return (a+b-1)/b; }; \n// define DEBUG\n\nvoid printVector(vector<vector<int>> a) {\n for (int i = 0; i < a.size(); i++) {\n for (int j = 0; j < a[0].size(); j++) {\n cout << a[i][j] << \" \";\n }\n cout << endl;\n }\n}\n\nint main() {\n int h, w;\n cin >> h >> w;\n vector c(h,vector<int>(w));\n rep(i,h)rep(j,w) cin >> c[i][j];\n vector upper(h,vector<int>(w));\n rep(i,h)rep(j,w) {\n if (c[i][j]) continue;\n upper[i][j] = 1;\n if (i) upper[i][j] += upper[i-1][j];\n } \n int ans = 0;\n rep(i,h) {\n vector<P> stack;\n vector<int> l(w), r(w,w);\n stack.emplace_back(-1,-1);\n rep(j,w) {\n while (stack.size()) {\n auto [hi,pj] = stack.back();\n if (hi <= upper[i][j]) break;\n r[pj] = j;\n stack.pop_back();\n }\n l[j] = stack.back().second+1;\n stack.emplace_back(upper[i][j],j);\n }\n rep(j,w) chmax(ans,upper[i][j]*(r[j]-l[j]));\n }\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 19072, "score_of_the_acc": -0.8727, "final_rank": 13 }, { "submission_id": "aoj_DPL_3_B_10830895", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nusing pii=pair<int,int>;\n#define rep(a,b,c) for(int a=b;a<c;a++)\n#define rep1(a,b,c) for(int a=b;a>=c;a--)\n#define vc vector\n#define pbk push_back\n#define ebk emplace_back\n#define fst first\n#define snd second\n#define sz(a) (int)a.size()\n#define out(a,b,c,d,e) cout << a << \" \" << b << \" \" << c << \" \" << d << \" \" << e << endl\n\n\nsigned main() {\n\tint h,w;cin >> h >> w;\n\tvc g(h+1,vc<int>(w,0));\n\tint c;\n\trep(i,1,h+1)rep(j,0,w){\n\t\tcin >> c;\n\t\tif(c==0) g[i][j]=g[i-1][j]+1;\n\t\telse g[i][j]=0;\n\t}\n\t/*rep(i,h,h+1){\n\t\trep(j,0,w){\n\t\t\tcout << g[i][j] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}*/\n\n\tint ans=0;\n\trep(i,1,h+1){\n\t\tstack<pii> st;\n\t\trep(j,0,w+1){\n\t\t\tint ch=0;\n\t\t\tif(j<w) ch=g[i][j];\n\t\t\twhile(!st.empty() && st.top().fst>ch){\n\t\t\t\tauto [ph,it]=st.top();\n\t\t\t\tst.pop();\n\t\t\t\tint lft=-1;\n\t\t\t\tif(!st.empty()) lft=st.top().snd;\n\n\t\t\t\tint tmp=ph*(j-(lft+1));\n\t\t\t\t//out(i,ls,a[ls].fst,j,a[ls].snd);\n\t\t\t\t//cout << tmp << endl;\n\t\t\t\tans=max(ans,tmp);\n\t\t\t}\n\t\t\tst.push({ch,j});\n\n\t\t}\n\t\t//cout << i << \" \" << ans << endl;\n\t}\n\tcout << ans << endl;\n\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 11264, "score_of_the_acc": -0.6168, "final_rank": 8 }, { "submission_id": "aoj_DPL_3_B_10801115", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define ld long double\n#define INF 1e18\nll r,c,n,cnt=-1;\nint main(){\n \n ll h,w,ans=0,f,sub;cin>>h>>w;\n vector<vector<bool>> ma(h,vector<bool>(w,false));\n vector<ll> a(w+1,0);\n stack<ll> s;\n for(ll i=0;i<h;i++)for(ll j=0;j<w;j++){\n cin>>f;\n if(f)ma[i][j]=true;\n }\n for(ll i=0;i<h;i++){\n for(ll j=0;j<w;j++){\n if(ma[i][j]==false)a[j]++;\n else a[j]=0;\n }\n for(ll j=0;j<=w;j++){\n while(s.size()&&a[s.top()]>=a[j]){\n f=a[s.top()];s.pop();\n sub=(s.empty()?-1:s.top());\n ans=max(ans,f*(j-sub-1));\n }\n s.push(j);\n }\n while(s.size())s.pop();\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 3684, "score_of_the_acc": -0.5263, "final_rank": 4 }, { "submission_id": "aoj_DPL_3_B_10798691", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint c[1405][1405],dp[1405][1405],l[1405][1405],r[1405][1405];\nstack<int>sl;\nstack<int>sr;\nint main(){\n\tint h,w;\n\tcin>>h>>w;\n\tint i,j;\n\tfor(i=1;i<=h;i++){\n\t\tfor(j=1;j<=w;j++){\n\t\t\tcin>>c[i][j];\n\t\t}\n\t}\n\tfor(j=1;j<=w;j++){\n\t\tfor(i=1;i<=h;i++){\n\t\t\tif(c[i][j]==1){\n\t\t\t\tdp[i][j]=0;\n\t\t\t}else{\n\t\t\t\tdp[i][j]=dp[i-1][j]+1;\n\t\t\t}\n\t\t}\n\t}\n\tfor(i=1;i<=h;i++){\n\t\tfor(j=1;j<=w;j++){\n\t\t\twhile(!sl.empty()&&dp[i][sl.top()]>=dp[i][j]){\n\t\t\t\tsl.pop();\n\t\t\t}\n\t\t\tif(sl.empty()){\n\t\t\t\tl[i][j]=0;\n\t\t\t}else{\n\t\t\t\tl[i][j]=sl.top();\n\t\t\t}\n\t\t\tsl.push(j);\n\t\t}\n\t\twhile(!sl.empty()){\n\t\t\tsl.pop();\n\t\t}\n\t}\n\tfor(i=1;i<=h;i++){\n\t\tfor(j=w;j>=1;j--){\n\t\t\twhile(!sr.empty()&&dp[i][sr.top()]>=dp[i][j]){\n\t\t\t\tsr.pop();\n\t\t\t}\n\t\t\tif(sr.empty()){\n\t\t\t\tr[i][j]=w+1;\n\t\t\t}else{\n\t\t\t\tr[i][j]=sr.top();\n\t\t\t}\n\t\t\tsr.push(j);\n\t\t}\n\t\twhile(!sr.empty()){\n\t\t\tsr.pop();\n\t\t}\n\t}\n\tint ans=0;\n\tfor(i=1;i<=h;i++){\n\t\tfor(j=1;j<=w;j++){\n\t\t\tans=max(ans,dp[i][j]*(r[i][j]-l[i][j]-1));\n\t\t}\n\t}\n\tcout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 34196, "score_of_the_acc": -1.5263, "final_rank": 20 }, { "submission_id": "aoj_DPL_3_B_10726461", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long \n#define endl '\\n'\ntypedef pair<int,int> PII;\nint getans(int a[],int m){\n\tvector<PII>p;\n\tp.push_back({-1,0});\n\tint mx=0;\n\tfor(int i=1;i<=m;i++){\n\t\twhile(p.back().first>=a[i]){\n\t\t\tint num=p.back().first;\n\t\t\tp.pop_back();\n\t\t\tint d=i-p.back().second-1;\n\t\t\t//mx=max(mx,d*a[i]);\n\t\t\tmx=max(mx,d*num);\n\t\t}\n\t\tint d=i-p.back().second;\n\t\tmx=max(mx,d*a[i]);\n\t\tp.push_back({a[i],i});\n \t}\n \twhile(p.size()>1){\n \t\tint num=p.back().first;\n \t\tp.pop_back();\n \t\tint d=m-p.back().second;\n \t \tmx=max(mx,d*num);\n \t}\n \treturn mx;\n}\nvoid solve(){\n int n,m;cin>>n>>m;\n int c[n+1][m+1];\n for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) cin>>c[i][j];\n int a[m+1];\n for(int i=0;i<=m;i++) a[i]=0;\n int ans=0;\n for(int i=1;i<=n;i++){\n \tfor(int j=1;j<=m;j++){\n \t \tif(c[i][j]) a[j]=0;\n \t \telse a[j]++;\n \t}\n\t\tans=max(ans,getans(a,m));\n }\n cout<<ans<<endl;\n}\nsigned main(){\n \tios::sync_with_stdio(false);\n \tcin.tie(0),cout.tie(0);\n \tint t=1;\n \t//cin>>t;\n \twhile(t--){\n \t\tsolve();\n \t}\n \treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 18724, "score_of_the_acc": -0.5456, "final_rank": 5 }, { "submission_id": "aoj_DPL_3_B_10638681", "code_snippet": "#include <cstdio>\n#include <iostream>\n#include <stack>\n#include <algorithm>\n\nconstexpr int MAX = 1'400;\n\nstruct Rectangle {\n int height;\n int pos;\n};\n\n// ひとつの行について求解\nint get_largest_rectangle(int size, int buffer[]) {\n std::stack<Rectangle> S;\n int maxv = 0;\n buffer[size] = 0;\n\n for (int i = 0; i <= size; ++i) {\n Rectangle rect;\n rect.height = buffer[i];\n rect.pos = i;\n if (S.empty()) {\n S.push(rect);\n } else {\n if (S.top().height < rect.height) {\n S.push(rect);\n } else if (S.top().height > rect.height) {\n int target = i;\n while (!S.empty() && S.top().height >= rect.height) {\n Rectangle pre = S.top();\n S.pop();\n int area = pre.height * (i - pre.pos);\n maxv = std::max(maxv, area);\n target = pre.pos;\n }\n rect.pos = target;\n S.push(rect);\n }\n }\n }\n\n return maxv;\n}\n\nint H, W;\nint buffer[MAX][MAX];\nint T[MAX][MAX];\n\n// 前処理+求解\nint get_largest_rectangle() {\n // 前処理\n for (int j = 0; j < W; ++j) {\n for (int i = 0; i < H; ++i) {\n if (buffer[i][j]) {\n // 汚れたタイル\n T[i][j] = 0;\n } else {\n // きれいなタイル\n T[i][j] = (i > 0) ? T[i - 1][j] + 1 : 1;\n }\n }\n }\n\n // 求解\n int maxv = 0;\n for (int i = 0; i < H; ++i) {\n maxv = std::max(maxv, get_largest_rectangle(W, T[i]));\n }\n\n return maxv;\n}\n\nint main() {\n scanf(\"%d %d\", &H, &W);\n for (int i = 0; i < H; ++i) {\n for (int j = 0; j < W; ++j) {\n scanf(\"%d\", &buffer[i][j]);\n }\n }\n\n std::cout << get_largest_rectangle() << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 18936, "score_of_the_acc": -0.5525, "final_rank": 6 }, { "submission_id": "aoj_DPL_3_B_10598395", "code_snippet": "#include <iostream>\n#include <string>\n#include <map>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <stack>\n#include <limits.h>\nusing namespace std;\n\nstruct rect {\n int pos;\n int height;\n};\n\n\nint main() {\n int H, W;\n cin >> H >> W;\n\n vector<vector<int>> c(1410, vector<int>(1410, 0));\n vector<vector<int>> rectHeight(1410, vector<int>(1410, 0));\n\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n cin >> c[i][j];\n }\n }\n\n\n // 動的計画法を用いて解く\n // まず、長方形の高さを格納するための配列作成を行う(これも動的計画法)\n // 長方形の高さを格納するための配列 : 二次元の配列で、上に向かってきれいなタイルをカウントしていき、長方形の高さをヒストグラムに格納していく\n\n // 長方形の高さを格納するための配列を用いて長方形の最大の面積を求める この時、スタックを活用する\n // H,Wのループでやるが、Wのループ毎にスタックを用意する\n // Hのループの中にWのループがあり、Hのループが回る度にWのループで長方形の最大値が求まり。最終的にHのループが終わるころには、全体での長方形の最大面積が求まっているイメージ\n // 各Wループの処理は以下のイメージ\n // 0<= i <Wでループ(※1)\n // 以下の条件でスタックへの追加・取り出しを行いつつ処理を行う\n // スタックに何もないとき→(i,recHeight(i,j))を格納 ※j : H方向のループカウンタ\n // スタックにあるとき\n // - スタックのトップのrecHeightが、追加しようとしている情報のrecHeightよりも小さいとき : そのままスタックに追加\n // - スタックのトップのrecHeightが、追加しようとしている情報のrecHeightと同じとき : 何もしない\n // - スタックのトップのrecHeightが、追加しようとしている情報のrecHeightよりも大きいとき : 長方形が出来上がるため、以下の処理を実行したうえでスタックに追加\n // スタックのトップを取り出し、長方形の面積を求める→現在のインデックスiと、スタックから取り出したインデックスiと、recHeightを用いれば長方形の面積が求まる (長方形の最大値も適宜記録しておく)\n // ※スタックの中に情報が残っていて、長方形の面積の求め漏れが起きるのを防ぐために、rectHeightの、x座標がWの箇所には、0を格納しておき、※1のループも、 0<= i <=Wで行う必要があるので注意\n\n // 長方形の高さを格納するための配列作成\n for (int i = 0; i < H; i++) {\n for (int j = 0; j < W; j++) {\n // 汚いタイル\n if (c[i][j]) {\n rectHeight[i][j] = 0; // 高さは0\n }\n else { // きれいなタイル\n if (i == 0) {\n rectHeight[i][j] = 1; // y座標が0できれいなタイルの場合、高さ1\n }\n else {\n rectHeight[i][j] = rectHeight[i - 1][j] + 1; // 1つ前のy座標に格納されている高さ+1\n }\n }\n }\n }\n\n // 最大長方形を求める\n int maxRecArea = 0;\n for (int i = 0; i < H; i++) {\n stack<rect> s;\n for (int j = 0; j <= W; j++) {\n // j==Wの時はHeightに0を入れる\n if (j == W) {\n rectHeight[i][j] = 0;\n }\n\n rect tmpRect = { j, rectHeight[i][j] }; // 追加しようとしているrect\n\n // スタックに何もない\n if (s.empty()) {\n s.push(tmpRect);\n }\n // スタックにある\n else {\n\n //スタックのトップのrecHeightが、追加しようとしている情報のrecHeightよりも小さいとき\n if (s.top().height < tmpRect.height) {\n s.push(tmpRect);\n }\n // スタックのトップのrecHeightが、追加しようとしている情報のrecHeightと同じときは何もしない\n // スタックのトップのrecHeightが、追加しようとしている情報のrecHeightよりも大きいとき\n if (s.top().height > tmpRect.height) {\n // ひたすらにスタックから取り出す処理がない\n\n // スタックが空でないかつ、スタックのトップのheightが、tmpRect.heightよりも大きいときはひたすらスタックから取り出し続ける\n while (!s.empty() && s.top().height >= tmpRect.height) {\n rect tmpTop = s.top();\n s.pop(); // スタックのトップを取り出す\n\n // 長方形の面積\n int recArea = (j - tmpTop.pos) * tmpTop.height;\n if (maxRecArea <= recArea) {\n maxRecArea = recArea;\n }\n\n // スタックから取り出した後、新たにスタックに追加する場合は、rect構造体のposに注意\n tmpRect.pos = tmpTop.pos;\n }\n\n // 長方形の面積算出後にスタックに追加\n s.push(tmpRect);\n }\n }\n }\n }\n\n cout << maxRecArea << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 18692, "score_of_the_acc": -1.0182, "final_rank": 16 }, { "submission_id": "aoj_DPL_3_B_10442946", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\nstruct Rectangle\n{\n int height;\n int pos;\n};\n\nint main()\n{\n int h;\n int w;\n int i;\n int j;\n int c;\n int maxv;\n Rectangle cur;\n Rectangle prev;\n stack<Rectangle> S;\n int tgt;\n\n cin >> h >> w;\n vector<vector<int>> DP(h, vector<int>(w, 0));\n rep(i, h)\n {\n rep(j, w)\n {\n cin >> c;\n if (c == 0)\n {\n if (i == 0)\n {\n DP.at(i).at(j) = 1;\n }\n else\n {\n DP.at(i).at(j) = DP.at(i - 1).at(j) + 1;\n }\n }\n }\n }\n maxv = 0;\n rep(i, h)\n {\n rep(j, w)\n {\n cur.height = DP.at(i).at(j);\n cur.pos = j;\n if (S.empty())\n {\n S.push(cur);\n }\n else\n {\n if (S.top().height < cur.height)\n {\n S.push(cur);\n }\n else\n {\n tgt = j;\n while (!S.empty() && S.top().height >= cur.height)\n {\n prev = S.top();\n S.pop();\n maxv = max(maxv, prev.height * (j - prev.pos));\n tgt = prev.pos;\n }\n cur.pos = tgt;\n S.push(cur);\n }\n }\n }\n tgt = w;\n while (!S.empty())\n {\n prev = S.top();\n S.pop();\n maxv = max(maxv, prev.height * (w - prev.pos));\n }\n }\n cout << maxv << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 11008, "score_of_the_acc": -0.6085, "final_rank": 7 }, { "submission_id": "aoj_DPL_3_B_10398035", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX = 1400;\n\nint H, W;\nint buffer[MAX][MAX];\nint T[MAX][MAX];\n\nstruct Rectangle {\n\tint height, pos;\n};\n\nint getLargestRectangle(int size, int buffer[]) {\n\tstack<Rectangle> S;\n\tint maxv = 0;\n\tbuffer[size] = 0;\n\t\n\tfor (int i = 0; i <= size; ++i) {\n\t\tRectangle rect;\n\t\trect.height = buffer[i];\n\t\trect.pos = i;\n\t\tif (S.empty()) {\n\t\t\tS.push(rect);\n\t\t} else if (S.top().height < rect.height) {\n\t\t\tS.push(rect);\n\t\t} else if (S.top().height > rect.height) {\n\t\t\tint target = i;\n\t\t\twhile (!S.empty() && S.top().height >= rect.height) {\n\t\t\t\tRectangle pre = S.top(); S.pop();\n\t\t\t\tint area = pre.height * (i - pre.pos);\n\t\t\t\tmaxv = max(maxv, area);\n\t\t\t\ttarget = pre.pos;\n\t\t\t}\n\t\t\trect.pos = target;\n\t\t\tS.push(rect);\n\t\t}\n\t}\n\treturn maxv;\n}\n\nint getLargestRectangle() {\n\tfor (int i = 0; i < H; ++i) {\n\t\tfor (int j = 0; j < W; ++j) {\n\t\t\tif (buffer[i][j]) {\n\t\t\t\tT[i][j] = 0;\n\t\t\t} else {\n\t\t\t\tT[i][j] = (i > 0) ? T[i-1][j] + 1 : 1;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint maxv = 0;\n\tfor (int i = 0; i < H; ++i) {\n\t\tmaxv = max(maxv, getLargestRectangle(W, T[i]));\n\t}\n\t\n\treturn maxv;\n}\n\nint main() {\n\tcin >> H >> W;\n\tfor (int i = 0; i < H; ++i) {\n\t\tfor (int j = 0; j < W; ++j) {\n\t\t\tcin >> buffer[i][j];\n\t\t}\n\t}\n\t\n\tcout << getLargestRectangle() << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 18692, "score_of_the_acc": -1.0182, "final_rank": 16 }, { "submission_id": "aoj_DPL_3_B_10398029", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX = 1400;\n\nint H, W;\nint buffer[MAX][MAX];\nint T[MAX][MAX];\n\nstruct Rectangle {\n\tint height, pos;\n};\n\nint getLargestRectangle(int size, int buffer[]) {\n\tstack<Rectangle> S;\n\tint maxv = 0;\n\tbuffer[size] = 0;\n\t\n\tfor (int i = 0; i <= size; ++i) {\n\t\tRectangle rect;\n\t\trect.height = buffer[i];\n\t\trect.pos = i;\n\t\tif (S.empty()) {\n\t\t\tS.push(rect);\n\t\t} else if (S.top().height < rect.height) {\n\t\t\tS.push(rect);\n\t\t} else if (S.top().height > rect.height) {\n\t\t\tint target = i;\n\t\t\twhile (!S.empty() && S.top().height >= rect.height) {\n\t\t\t\tRectangle pre = S.top(); S.pop();\n\t\t\t\tint area = pre.height * (i - pre.pos);\n\t\t\t\tmaxv = max(maxv, area);\n\t\t\t\ttarget = pre.pos;\n\t\t\t}\n\t\t\trect.pos = target;\n\t\t\tS.push(rect);\n\t\t}\n\t}\n\treturn maxv;\n}\n\nint getLargestRectangle() {\n\tfor (int j = 0; j < W; ++j) {\n\t\tfor (int i = 0; i < H; ++i) {\n\t\t\tif (buffer[i][j]) {\n\t\t\t\tT[i][j] = 0;\n\t\t\t} else {\n\t\t\t\tT[i][j] = (i > 0) ? T[i-1][j] + 1 : 1;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint maxv = 0;\n\tfor (int i = 0; i < H; ++i) {\n\t\tmaxv = max(maxv, getLargestRectangle(W, T[i]));\n\t}\n\t\n\treturn maxv;\n}\n\nint main() {\n\tcin >> H >> W;\n\tfor (int i = 0; i < H; ++i) {\n\t\tfor (int j = 0; j < W; ++j) {\n\t\t\tcin >> buffer[i][j];\n\t\t}\n\t}\n\t\n\tcout << getLargestRectangle() << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 18756, "score_of_the_acc": -1.0203, "final_rank": 18 }, { "submission_id": "aoj_DPL_3_B_10392348", "code_snippet": "/******************************************************************************\n\n Online C++ Compiler.\n Code, Compile, Run and Debug C++ program online.\nWrite your code in this editor and press \"Run\" button to compile and execute it.\n\n*******************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <queue>\n#include <stack>\n#include <set>\n#include <limits.h>\n\nusing namespace std;\n\nint main()\n{\n int h, w;\n cin >> h >> w;\n \n vector<vector<int> > mat(h, vector<int>(w)), heights(h, vector<int>(w));\n \n for (int i = 0; i < h; i++) {\n for (int j = 0; j < w; j++) {\n cin >> mat[i][j];\n }\n }\n \n for (int i = 0; i < h; i++) {\n for (int j = 0; j < w; j++) {\n if(mat[i][j] == 0) {\n if (i > 0) {\n heights[i][j] = heights[i - 1][j] + 1;\n }\n else {\n heights[i][j] = 1;\n }\n }\n else {\n heights[i][j] = 0;\n }\n // cout << heights[i][j] << \" \";\n }\n // cout << endl;\n }\n \n int ans = 0;\n \n for (int i = 0; i < h; i++) {\n stack<pair<int, int> > st;\n \n for (int j = 0; j <= w; j++) {\n int curH = 0;\n if (j < w) {\n curH = heights[i][j];\n }\n \n while (!st.empty() && st.top().first >= curH) {\n auto [prevH, _] = st.top();\n st.pop();\n \n int left = -1;\n \n if (!st.empty()) {\n left = st.top().second;\n }\n \n ans = max(ans, prevH * ((j - 1) - (left + 1) + 1));\n }\n \n st.push({curH, j});\n }\n }\n \n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 18816, "score_of_the_acc": -0.8644, "final_rank": 12 }, { "submission_id": "aoj_DPL_3_B_10062387", "code_snippet": "#include <bits/stdc++.h>\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> ii;\ntypedef vector<int> vi;\ntypedef tuple<int, int, int> iii;\ntypedef pair<ll, ll> pll;\ntypedef vector<ii> vii;\ntypedef vector<ll> vll;\n\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define LSOne(S) ((S) & -(S))\n\ntemplate <class T>\nusing ordered_set = tree<T, null_type, greater<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\ntemplate <class T>\nbool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }\ntemplate <class T>\nbool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }\n\nusing a2 = array<int, 2>;\nvoid solve() {\n int n, m;\n cin >> n >> m;\n vector<vi> dp(n, vi(m));\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n int b;\n cin >> b;\n if (b == 1)\n dp[i][j] = 0;\n else\n dp[i][j] = (i ? dp[i - 1][j] : 0) + 1;\n }\n }\n\n auto largest_rect = [&](vi& A) {\n vector<a2> bounds(m);\n\n stack<a2> stk;\n stk.push({INT_MIN, -1});\n for (int i = 0; i < m; i++) {\n while (stk.top()[0] >= A[i]) stk.pop();\n bounds[i][0] = stk.top()[1];\n stk.push({A[i], i});\n }\n\n stk = stack<a2>();\n stk.push({INT_MIN, m});\n for (int i = m - 1; i >= 0; i--) {\n while (stk.top()[0] >= A[i]) stk.pop();\n bounds[i][1] = stk.top()[1];\n stk.push({A[i], i});\n }\n\n int ans = 0;\n for (int i = 0; i < m; i++) {\n auto [l, r] = bounds[i];\n ans = max(ans, (r - l - 1) * A[i]);\n }\n\n return ans;\n };\n\n int ans = 0;\n for (int i = 0; i < n; i++) {\n ans = max(ans, largest_rect(dp[i]));\n }\n\n cout << ans << '\\n';\n}\n\nint main() {\n ios_base::sync_with_stdio(0), cin.tie(0);\n\n int tc = 1;\n // cin >> tc;\n\n while (tc--) {\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 10744, "score_of_the_acc": -0.3893, "final_rank": 1 }, { "submission_id": "aoj_DPL_3_B_10058223", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\n// const int M = 1e9 + 7;\nconst int M = 998244353;\n\nll bin(ll a, ll b){\n ll ans = 1;\n while(b){\n if(b%2) ans = (a * ans)%M;\n a = (a*a)%M;\n b/=2;\n }\n return ans;\n}\n\nvoid solve(){\n int n, m; cin >> n >> m;\n vector<vector<int>> arr(n, vector<int>(m));\n vector<vector<int>> c(n, vector<int>(m));\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n cin >> arr[i][j];\n if(arr[i][j] == 1) c[i][j] = 0;\n else if(i == 0) c[i][j] = 1;\n else c[i][j] = c[i - 1][j] + 1;\n }\n }\n int ans = 0;\n for(int kk = 0; kk < n; kk++){\n vector<int> &arr = c[kk];\n stack<int> sl, sr;\n vector<int> right(m), left(m);\n for(int i = 0; i < m; i++){\n while(sl.size() && arr[i] <= arr[sl.top()]){\n sl.pop();\n }\n left[i] = (sl.empty() ? 0 : sl.top() + 1);\n sl.push(i);\n }\n for(int i = m - 1; i >= 0; i--){\n while(sr.size() && arr[i] <= arr[sr.top()]){\n sr.pop();\n }\n right[i] = (sr.empty() ? m - 1 : sr.top() - 1);\n sr.push(i);\n }\n for(int i = 0; i < m; i++){\n ans = max(ans, (right[i] - left[i] + 1) * arr[i]);\n }\n }\n cout << ans << '\\n';\n}\n\nint32_t main(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int _ = 1;\n // cin >> _;\n while(_--){\n solve();\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 18520, "score_of_the_acc": -0.6441, "final_rank": 11 }, { "submission_id": "aoj_DPL_3_B_10054847", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\nvoid solve(){\n int n, m; cin >> n >> m;\n vector<vector<int>> arr(n, vector<int>(m));\n vector<vector<int>> c(n, vector<int>(m));\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n cin >> arr[i][j];\n if(arr[i][j] == 1) c[i][j] = 0;\n else if(i == 0) c[i][j] = 1;\n else c[i][j] = c[i - 1][j] + 1;\n }\n }\n int ans = 0;\n for(int kk = 0; kk < n; kk++){\n vector<int> &arr = c[kk];\n stack<int> sl, sr;\n vector<int> right(m), left(m);\n for(int i = 0; i < m; i++){\n while(sl.size() && arr[i] <= arr[sl.top()]){\n sl.pop();\n }\n left[i] = (sl.empty() ? 0 : sl.top() + 1);\n sl.push(i);\n }\n for(int i = m - 1; i >= 0; i--){\n while(sr.size() && arr[i] <= arr[sr.top()]){\n sr.pop();\n }\n right[i] = (sr.empty() ? m - 1 : sr.top() - 1);\n sr.push(i);\n }\n for(int i = 0; i < m; i++){\n ans = max(ans, (right[i] - left[i] + 1) * arr[i]);\n }\n }\n cout << ans << '\\n';\n}\n\nint32_t main(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int _ = 1;\n // cin >> _;\n while(_--){\n solve();\n }\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 18492, "score_of_the_acc": -0.6432, "final_rank": 10 }, { "submission_id": "aoj_DPL_3_B_10054845", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\nvoid solve(){\n int n, m; cin >> n >> m;\n vector<vector<int>> arr(n, vector<int>(m));\n vector<vector<int>> c(n, vector<int>(m));\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n cin >> arr[i][j];\n if(arr[i][j] == 1) c[i][j] = 0;\n else if(i == 0) c[i][j] = 1;\n else c[i][j] = c[i - 1][j] + 1;\n }\n }\n int ans = 0;\n for(int kk = 0; kk < n; kk++){\n vector<int> &arr = c[kk];\n stack<int> sl, sr;\n vector<int> right(m), left(m);\n for(int i = 0; i < m; i++){\n while(sl.size() && arr[i] <= arr[sl.top()]){\n sl.pop();\n }\n left[i] = (sl.empty() ? 0 : sl.top() + 1);\n sl.push(i);\n }\n for(int i = m - 1; i >= 0; i--){\n while(sr.size() && arr[i] <= arr[sr.top()]){\n sr.pop();\n }\n right[i] = (sr.empty() ? m - 1 : sr.top() - 1);\n sr.push(i);\n }\n for(int i = 0; i < m; i++){\n ans = max(ans, (right[i] - left[i] + 1) * arr[i]);\n }\n }\n cout << ans << '\\n';\n return;\n}\n\nint32_t main(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int _ = 1;\n // cin >> _;\n while(_--){\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 18816, "score_of_the_acc": -0.4959, "final_rank": 3 }, { "submission_id": "aoj_DPL_3_B_9964675", "code_snippet": "#include <iostream>\n#include <stdio.h>\n#include <string>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <set>\n#include <cmath>\n#include <algorithm>\nusing namespace std;\n\nint main () {\n int h, w;\n cin >> h >> w;\n\n int c[h][w];\n\n for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) cin >> c[i][j];\n\n int heights[h][w];\n\n for (int i = 0; i < h; i++) {\n for (int j = 0; j < w; j++) {\n if (c[i][j]) {\n heights[i][j] = 0;\n }\n else {\n if (i == 0) {\n heights[i][j] = 1;\n }\n else {\n heights[i][j] = heights[i - 1][j] + 1;\n }\n }\n }\n }\n\n int ans = 0;\n\n for (int i = 0; i < h; i++) {\n stack<pair<int, int> > st;\n for (int j = 0; j < w; j++) {\n int l = j;\n\n while (1) {\n if (st.empty()) {\n st.push(make_pair(heights[i][j], l));\n break;\n }\n else {\n pair<int, int> top = st.top();\n\n if (top.first < heights[i][j]) {\n st.push(make_pair(heights[i][j], l));\n break;\n }\n else if (top.first == heights[i][j]) {\n break;\n }\n else if (top.first > heights[i][j]) {\n ans = max(ans, top.first * (j - top.second));\n }\n\n l = top.second;\n st.pop();\n }\n }\n }\n\n while (!st.empty()) {\n pair<int, int> top = st.top();\n st.pop();\n ans = max(ans, top.first * (w - top.second));\n }\n }\n\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 150, "memory_kb": 18640, "score_of_the_acc": -1.0165, "final_rank": 15 } ]
aoj_DPL_5_A_cpp
Balls and Boxes 1 Balls Boxes Any way At most one ball At least one ball Distinguishable Distinguishable 1 2 3 Indistinguishable Distinguishable 4 5 6 Distinguishable Indistinguishable 7 8 9 Indistinguishable Indistinguishable 10 11 12 Problem You have $n$ balls and $k$ boxes. You want to put these balls into the boxes. Find the number of ways to put the balls under the following conditions: Each ball is distinguished from the other. Each box is distinguished from the other. Each ball can go into only one box and no one remains outside of the boxes. Each box can contain an arbitrary number of balls (including zero). Note that you must print this count modulo $10^9+7$. Input $n$ $k$ The first line will contain two integers $n$ and $k$. Output Print the number of ways modulo $10^9+7$ in a line. Constraints $1 \le n \le 1000$ $1 \le k \le 1000$ Sample Input 1 2 3 Sample Output 1 9 Sample Input 2 10 5 Sample Output 2 9765625 Sample Input 3 100 100 Sample Output 3 424090053
[ { "submission_id": "aoj_DPL_5_A_9527776", "code_snippet": "/*\n Created by Pujx on 2024/8/4.\n*/\n#pragma GCC optimize(2, 3, \"Ofast\", \"inline\")\n#include <bits/stdc++.h>\nusing namespace std;\n#define endl '\\n'\n//#define int long long\n//#define double long double\nusing i64 = long long;\nusing ui64 = unsigned long long;\n//using i128 = __int128;\n#define inf (int)0x3f3f3f3f3f3f3f3f\n#define INF 0x3f3f3f3f3f3f3f3f\n#define yn(x) cout << (x ? \"yes\" : \"no\") << endl\n#define Yn(x) cout << (x ? \"Yes\" : \"No\") << endl\n#define YN(x) cout << (x ? \"YES\" : \"NO\") << endl\n#define mem(x, i) memset(x, i, sizeof(x))\n#define cinarr(a, n) for (int _ = 1; _ <= n; _++) cin >> a[_]\n#define cinstl(a) for (auto& _ : a) cin >> _\n#define coutarr(a, n) for (int _ = 1; _ <= n; _++) cout << a[_] << \" \\n\"[_ == n]\n#define coutstl(a) for (const auto& _ : a) cout << _ << ' '; cout << endl\n#define all(x) (x).begin(), (x).end()\n#define ls (s << 1)\n#define rs (s << 1 | 1)\n#define ft first\n#define se second\n#define pii pair<int, int>\n#ifdef DEBUG\n #include \"debug.h\"\n#else\n #define dbg(...) void(0)\n#endif\n\nconst int N = 2000 + 5;\n//const int M = 1e5 + 5;\n//const int mod = 998244353;\nconst int mod = 1e9 + 7;\n//template <typename T> T ksm(T a, i64 b) { T ans = 1; for (; b; a = 1ll * a * a, b >>= 1) if (b & 1) ans = 1ll * ans * a; return ans; }\n//template <typename T> T ksm(T a, i64 b, T m = mod) { T ans = 1; for (; b; a = 1ll * a * a % m, b >>= 1) if (b & 1) ans = 1ll * ans * a % m; return ans; }\n\nint a[N];\nint n, m, t, k, q;\n\ntemplate <int P> struct MInt {\n int x;\n MInt() : x(0) {}\n MInt(const signed& x) : x(norm(x % getMod())) {}\n MInt(const long long& x) : x(norm(x % getMod())) {}\n\n static int Mod;\n static int getMod() { return P > 0 ? P : Mod; }\n static void setMod(int _Mod) { Mod = _Mod; }\n int norm(const int& x) const { return x < 0 ? x + getMod() : (x >= getMod() ? x - getMod() : x); }\n int val() const { return x; }\n explicit operator int() const { return x; }\n MInt operator - () const { MInt res; res.x = norm(getMod() - x); return res; }\n MInt ksm(const long long& x) const {\n MInt a = *this, ans = 1;\n for (long long pw = x; pw; a *= a, pw >>= 1) if (pw & 1) ans *= a;\n return ans;\n }\n MInt inv() const { assert(x != 0); return ksm(getMod() - 2); }\n MInt& operator += (const MInt& b) & { x = norm(x + b.x); return *this; }\n MInt& operator -= (const MInt& b) & { x = norm(x - b.x); return *this; }\n MInt& operator *= (const MInt& b) & { x = norm(1ll * x * b.x % getMod()); return *this; }\n MInt& operator /= (const MInt& b) & { return *this *= b.inv(); }\n MInt& operator ++ () & { return *this += 1; }\n MInt& operator -- () & { return *this -= 1; }\n const MInt operator ++ (signed) { MInt old = *this; ++(*this); return old; }\n const MInt operator -- (signed) { MInt old = *this; --(*this); return old; }\n friend MInt operator + (const MInt& a, const MInt& b) { MInt res = a; res += b; return res; }\n friend MInt operator - (const MInt& a, const MInt& b) { MInt res = a; res -= b; return res; }\n friend MInt operator * (const MInt& a, const MInt& b) { MInt res = a; res *= b; return res; }\n friend MInt operator / (const MInt& a, const MInt& b) { MInt res = a; res /= b; return res; }\n friend istream& operator >> (istream& in, MInt& a) { long long v; in >> v; a = MInt(v); return in; }\n friend ostream& operator << (ostream& out, const MInt& a) { return out << a.val(); }\n friend bool operator == (const MInt& a, const MInt& b) { return a.val() == b.val(); }\n friend bool operator != (const MInt& a, const MInt& b) { return a.val() != b.val(); }\n friend bool operator < (const MInt& a, const MInt& b) { return a.val() < b.val(); }\n friend bool operator > (const MInt& a, const MInt& b) { return a.val() > b.val(); }\n friend bool operator <= (const MInt& a, const MInt& b) { return a.val() <= b.val(); }\n friend bool operator >= (const MInt& a, const MInt& b) { return a.val() >= b.val(); }\n};\nusing Mint = MInt<mod>;\ntemplate<> int MInt<0>::Mod = 1;\n\nMint fac[N], c[N][N], s[N][N], p[N][N];\n\nvoid init() {\n fac[0] = 1, c[0][0] = s[0][0] = p[0][0] = 1;\n for (int i = 1; i <= 2000; i++) {\n fac[i] = fac[i - 1] * i;\n c[i][0] = 1, s[i][0] = p[i][0] = 0;\n for (int j = 1; j <= i; j++) {\n c[i][j] = c[i - 1][j - 1] + c[i - 1][j];\n s[i][j] = s[i - 1][j - 1] + j * s[i - 1][j];\n p[i][j] = p[i - 1][j - 1] + p[i - j][j];\n }\n }\n}\n\nvoid work() {\n cin >> n >> k;\n t = 1;\n if (t == 1) {\n cout << Mint(k).ksm(n) << endl;\n }\n else if (t == 2) {\n cout << (n < m ? 0 : fac[n] / fac[n - m]) << endl;\n }\n else if (t == 3) {\n cout << fac[k] * s[n][k] << endl;\n }\n else if (t == 4) {\n cout << c[n + k - 1][k - 1] << endl;\n }\n else if (t == 5) {\n cout << c[k][n] << endl;\n }\n else if (t == 6) {\n cout << c[n - 1][k - 1] << endl;\n }\n else if (t == 7) {\n Mint ans = 0;\n for (int i = 1; i <= k; i++)\n ans += s[n][i];\n cout << ans << endl;\n }\n else if (t == 8) {\n cout << (k >= n) << endl;\n }\n else if (t == 9) {\n cout << s[n][k] << endl;\n }\n else if (t == 10) {\n cout << p[n + k][k] << endl;\n }\n else if (t == 11) {\n cout << (k >= n) << endl;\n }\n else {\n cout << p[n][k] << endl;\n }\n}\n\nsigned main() {\n#ifdef LOCAL\n freopen(\"C:\\\\Users\\\\admin\\\\CLionProjects\\\\Practice\\\\data.in\", \"r\", stdin);\n freopen(\"C:\\\\Users\\\\admin\\\\CLionProjects\\\\Practice\\\\data.out\", \"w\", stdout);\n#endif\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n init();\n int Case = 1;\n //cin >> Case;\n while (Case--) work();\n return 0;\n}\n/*\n _____ _ _ _ __ __\n | _ \\ | | | | | | \\ \\ / /\n | |_| | | | | | | | \\ \\/ /\n | ___/ | | | | _ | | } {\n | | | |_| | | |_| | / /\\ \\\n |_| \\_____/ \\_____/ /_/ \\_\\\n*/", "accuracy": 1, "time_ms": 20, "memory_kb": 50580, "score_of_the_acc": -0.6434, "final_rank": 5 }, { "submission_id": "aoj_DPL_5_A_6950878", "code_snippet": "#include <bits/stdc++.h>\n#include <stdio.h>\nusing namespace std;\nusing ll = long long;\n\nll mod_pow(ll x, ll n, ll mod) {\n if (n == 0) {\n return 1;\n }\n ll\n res = mod_pow(x * x % mod, n / 2, mod);\n if (n & 1) res = res * x % mod;\n return res;\n}\n\nconst ll MOD = 1e9 + 7;\nconst ll MAX = 1100000;\n\nvector<ll> fact(MAX), inv(MAX), inv_fact(MAX);\n\nvoid init() {\n fact.at(0) = fact.at(1) = 1;\n inv.at(0) = inv.at(1) = 1;\n inv_fact.at(0) = inv_fact.at(1) = 1;\n \n for (int i = 2; i < MAX; i++) {\n fact.at(i) = fact.at(i - 1) * i % MOD;\n inv.at(i) = MOD - inv.at(MOD % i) * (MOD / i) % MOD;\n inv_fact.at(i) = inv_fact.at(i - 1) * inv.at(i) % MOD;\n }\n}\n\nll nCk(ll n, ll k) {\n ll x = fact.at(n);\n ll y = inv_fact.at(n - k);\n ll z = inv_fact.at(k);\n\n if (n < k) {\n return 0;\n }\n if (n < 0 || k < 0) {\n return 0;\n }\n\n return (x * ((y * z) % MOD)) % MOD;\n}\n\nint main() {\n\tinit();\n\tll n, k;\n\tcin >> n >> k;\n\n\tcout << mod_pow(k, n, MOD) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 28688, "score_of_the_acc": -0.2354, "final_rank": 4 }, { "submission_id": "aoj_DPL_5_A_4784497", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct countcase {\n\tvector<long long> fac, finv, inv;\n\tint mod;\n\n\tcountcase(int _mod = 1000000007, int n = 3100000) : mod(_mod), fac(n), finv(n), inv(n) {\n\t\tfac.resize(n);\n\t\tfinv.resize(n);\n\t\tinv.resize(n);\n\t\tfac[0] = fac[1] = 1;\n\t\tfinv[0] = finv[1] = 1;\n\t\tinv[1] = 1;\n\t\tfor(int i = 2; i < n; i++) {\n\t\t\tfac[i] = fac[i - 1] * i % _mod;\n\t\t\tinv[i] = _mod - inv[_mod % i] * (_mod / i) % _mod;\n\t\t\tfinv[i] = finv[i - 1] * inv[i] % _mod;\n\t\t}\n\t}\n\n\tlong long c(int n, int k) {\t // 二項係数計算\n\t\tif(n < k) return 0;\n\t\tif(n < 0 || k < 0) return 0;\n\t\treturn fac[n] * (finv[k] * finv[n - k] % mod) % mod;\n\t}\n\n\tlong long p(int n, int k) {\t //順列計算\n\t\tif(n < k) return 0;\n\t\tif(n < 0 || k < 0) return 0;\n\t\treturn fac[n] * finv[n - k] % mod;\n\t}\n\n\t// nHk計算\n\t// n個の区別しないoを区別するk個の箱に入れる方法の総数\n\t//(n+k-1)C(k-1)と等しい\n\tlong long h(int n, int k) { return c(n + k - 1, n); }\n\n\tlong long pow(long long a, long long n) {\n\t\ta %= mod;\n\t\tif(a == 0) return 0LL;\n\t\tn %= mod - 1;\n\t\tlong long ret = 1;\n\t\twhile(n) {\n\t\t\tif(n & 1) (ret *= a) %= mod;\n\t\t\t(a *= a) %= mod;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn ret;\n\t}\n};\n\nint main() {\n\tlong long n, k;\n\tcin >> n >> k;\n\tcountcase kazu(1000000007);\n\tcout << kazu.pow(k, n)<<endl;\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 75444, "score_of_the_acc": -2, "final_rank": 6 }, { "submission_id": "aoj_DPL_5_A_4769808", "code_snippet": "#include \"bits/stdc++.h\"\n#pragma GCC optimize(\"Ofast\")\n\n// Begin Header {{{\nusing namespace std;\n\n#ifndef DEBUG\n#define dump(...)\n#endif\n\n#define all(x) x.begin(), x.end()\n#define rep(i, b, e) for (intmax_t i = (b), i##_limit = (e); i < i##_limit; ++i)\n#define reps(i, b, e) for (intmax_t i = (b), i##_limit = (e); i <= i##_limit; ++i)\n#define repr(i, b, e) for (intmax_t i = (b), i##_limit = (e); i >= i##_limit; --i)\n#define var(Type, ...) Type __VA_ARGS__; input(__VA_ARGS__)\n\nconstexpr size_t operator\"\"_zu(unsigned long long value) { return value; };\nconstexpr intmax_t operator\"\"_jd(unsigned long long value) { return value; };\nconstexpr uintmax_t operator\"\"_ju(unsigned long long value) { return value; };\n\nconstexpr int INF = 0x3f3f3f3f;\nconstexpr intmax_t LINF = 0x3f3f3f3f3f3f3f3f_jd;\n\ntemplate <class T, class Compare = less<>>\nusing MaxHeap = priority_queue<T, vector<T>, Compare>;\ntemplate <class T, class Compare = greater<>>\nusing MinHeap = priority_queue<T, vector<T>, Compare>;\n\ninline void input() {}\ntemplate <class Head, class... Tail>\ninline void input(Head&& head, Tail&&... tail) {\n cin >> head;\n input(forward<Tail>(tail)...);\n}\n\ntemplate <class T>\ninline istream& operator>>(istream &is, vector<T> &vec) {\n for (auto &e: vec) {\n is >> e;\n }\n return is;\n}\n\ninline void output() { cout << \"\\n\"; }\ntemplate <class Head, class... Tail>\ninline void output(Head&& head, Tail&&... tail) {\n cout << head;\n if (sizeof...(tail)) {\n cout << \" \";\n }\n output(forward<Tail>(tail)...);\n}\n\ntemplate <class T>\ninline ostream& operator<<(ostream &os, const vector<T> &vec) {\n static constexpr const char *delim[] = {\" \", \"\"};\n for (const auto &e: vec) {\n os << e << delim[&e == &vec.back()];\n }\n return os;\n}\n\ntemplate <class T>\ninline vector<T> makeVector(const T &initValue, size_t sz) {\n return vector<T>(sz, initValue);\n}\n\ntemplate <class T, class... Args>\ninline auto makeVector(const T &initValue, size_t sz, Args... args) {\n return vector<decltype(makeVector<T>(initValue, args...))>(sz, makeVector<T>(initValue, args...));\n}\n\ntemplate <class Func>\nclass FixPoint : Func {\npublic:\n explicit constexpr FixPoint(Func&& f) noexcept : Func(forward<Func>(f)) {}\n\n template <class... Args>\n constexpr decltype(auto) operator()(Args&&... args) const {\n return Func::operator()(*this, std::forward<Args>(args)...);\n }\n};\n\ntemplate <class Func>\nstatic inline constexpr decltype(auto) makeFixPoint(Func&& f) noexcept {\n return FixPoint<Func>{forward<Func>(f)};\n}\n\ntemplate <class Container>\nstruct reverse_t {\n Container &c;\n reverse_t(Container &c) : c(c) {}\n auto begin() { return c.rbegin(); }\n auto end() { return c.rend(); }\n};\n\ntemplate <class Container>\nauto reversed(Container &c) {\n return reverse_t<Container>(c);\n}\n\ntemplate <class T>\ninline bool chmax(T &a, const T &b) noexcept {\n return b > a && (a = b, true);\n}\n\ntemplate <class T>\ninline bool chmin(T &a, const T &b) noexcept {\n return b < a && (a = b, true);\n}\n\ntemplate <class T>\ninline T diff(const T &a, const T &b) noexcept {\n return a < b ? b - a : a - b;\n}\n// End Header }}}\n\nconst intmax_t MOD = intmax_t(1e9) + 7;\n// ModInt {{{\ntemplate <intmax_t MOD>\nclass ModInt {\n intmax_t value;\n\npublic:\n inline ModInt(const ModInt& other) :\n value(other.value)\n {}\n\n inline ModInt(intmax_t value = 0) {\n if (value >= MOD) {\n this->value = value % MOD;\n } else if (value < 0) {\n this->value = (value + MOD) % MOD;\n } else {\n this->value = value;\n }\n }\n\n template <class T>\n explicit inline operator T() const {\n return static_cast<T>(value);\n }\n\n inline ModInt inverse() const {\n return ModInt::pow(value, MOD - 2);\n }\n\n inline ModInt& operator+=(const ModInt other) {\n value = (value + other.value) % MOD;\n return *this;\n }\n\n inline ModInt& operator-=(const ModInt other) {\n value = (MOD + value - other.value) % MOD;\n return *this;\n }\n\n inline ModInt& operator*=(const ModInt other) {\n value = (value * other.value) % MOD;\n return *this;\n }\n\n inline ModInt& operator/=(const ModInt other) {\n value = (value * other.inverse().value) % MOD;\n return *this;\n }\n\n inline ModInt operator+(const ModInt other) {\n return ModInt(*this) += other;\n }\n\n inline ModInt operator-(const ModInt other) {\n return ModInt(*this) -= other;\n }\n\n inline ModInt operator*(const ModInt other) {\n return ModInt(*this) *= other;\n }\n\n inline ModInt operator/(const ModInt other) {\n return ModInt(*this) /= other;\n }\n\n inline bool operator==(const ModInt other) {\n return value == other.value;\n }\n\n inline bool operator!=(const ModInt other) {\n return value != other.value;\n }\n\n friend ostream& operator<<(ostream &os, const ModInt other) {\n os << other.value;\n return os;\n }\n\n friend istream& operator>>(istream &is, ModInt& other) {\n is >> other.value;\n return is;\n }\n\n static constexpr inline ModInt pow(intmax_t n, intmax_t p) {\n intmax_t ret = 1;\n for (; p > 0; p >>= 1) {\n if (p & 1) ret = (ret * n) % MOD;\n n = (n * n) % MOD;\n }\n return ret;\n }\n};\n\nusing Mint = ModInt<MOD>;\n// }}}\n\n// Factorial {{{\n#ifdef DEBUG\n#define constexpr\n#endif\n\ntemplate <size_t N, size_t MOD>\nstruct Factorial {\n vector<uint_fast64_t> fact_;\n\n constexpr inline Factorial() : fact_(N + 1) {\n fact_[0] = 1;\n for (intmax_t i = 1; i <= N; ++i) {\n fact_[i] = (fact_[i - 1] * i) % MOD;\n }\n }\n\n constexpr inline Mint operator[](size_t pos) const {\n return fact_[pos];\n }\n};\n\ntemplate <size_t N, size_t MOD>\nstruct InvFact {\n vector<uint_fast64_t> inv_;\n vector<uint_fast64_t> finv_;\n\n constexpr inline InvFact() : inv_(N + 1), finv_(N + 1) {\n inv_[1] = 1;\n finv_[0] = finv_[1] = 1;\n for (intmax_t i = 2; i <= N; ++i) {\n inv_[i] = (MOD - MOD / i) * inv_[MOD % i] % MOD;\n finv_[i] = finv_[i - 1] * inv_[i] % MOD;\n }\n }\n\n constexpr inline Mint operator[](size_t pos) const {\n return finv_[pos];\n }\n};\n\n#ifdef constexpr\n#undef constexpr\n#endif\n\nFactorial<510000, MOD> fact;\nInvFact<510000, MOD> finv;\n\ninline Mint nCr(int n, int r) {\n if (r < 0 || n < r) {\n return 0;\n }\n return fact[n] * (finv[r] * finv[n - r]);\n}\n\ninline Mint nPr(int n, int r) {\n if (r < 0 || n < r) {\n return 0;\n }\n return fact[n] * finv[n - r];\n}\n\ninline Mint nHr(int n, int r) {\n return nCr(n + r - 1, r);\n}\n// }}}\n\nsigned main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.setf(ios_base::fixed);\n cout.precision(10);\n\n var(intmax_t, n, k);\n output(Mint::pow(k, n));\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 14536, "score_of_the_acc": -0.004, "final_rank": 2 }, { "submission_id": "aoj_DPL_5_A_4131630", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,int> Pii;\ntypedef pair<ll,ll> Pll;\n#define rep(i,n) for (ll i=0;i<(n);++i)\n#define rep2(i,a,b) for (ll i=(a);i<(b);++i)\n#define debug(x) cout << #x << '=' << x << endl\n#define all(v) (v).begin(),(v).end()\nconst ll MOD=1e9+7;\n//const ll MOD=998244353;\nconst ll INF=1e9;\nconst ll IINF=1e18;\nconst double EPS=1e-8;\nconst double pi=acos(-1);\n\ntemplate<class T> inline bool chmin(T &a,T b){\n if (a>b){a=b; return true;} return false;\n}\ntemplate<class T> inline bool chmax(T &a,T b){\n if (a<b){a=b; return true;} return false;\n}\n\ntemplate<uint_fast64_t Modulus> class modint{\n using u64=uint_fast64_t;\n public:\n u64 a;\n constexpr modint(const u64 x=0) noexcept:a(((x%Modulus)+Modulus)%Modulus){}\n constexpr u64 &value() noexcept{return a;}\n constexpr const u64 &value() const noexcept{return a;}\n constexpr modint &operator+=(const modint &rhs) noexcept{\n a+=rhs.a;\n if (a>=Modulus) a-=Modulus;\n return *this;\n }\n constexpr modint operator+(const modint &rhs) const noexcept{\n return modint(*this)+=rhs;\n }\n constexpr modint &operator++() noexcept{\n return ++a,*this;\n }\n constexpr modint operator++(int) noexcept{\n modint t=*this; return ++a,t;\n }\n constexpr modint &operator-=(const modint &rhs) noexcept{\n if (a<rhs.a) a+=Modulus;\n a-=rhs.a;\n return *this;\n }\n constexpr modint operator-(const modint &rhs) const noexcept{\n return modint(*this)-=rhs;\n }\n constexpr modint &operator--() noexcept{\n return --a,*this;\n }\n constexpr modint operator--(int) noexcept{\n modint t=*this; return --a,t;\n }\n constexpr modint &operator*=(const modint &rhs) noexcept{\n a=a*rhs.a%Modulus;\n return *this;\n }\n constexpr modint operator*(const modint &rhs) const noexcept{\n return modint(*this)*=rhs;\n }\n constexpr modint &operator/=(modint rhs) noexcept{\n u64 exp=Modulus-2;\n while(exp){\n if (exp&1) *this*=rhs;\n rhs*=rhs; exp>>=1;\n }\n return *this;\n }\n constexpr modint operator/(const modint &rhs) const noexcept{\n return modint(*this)/=rhs;\n }\n constexpr modint operator-() const noexcept{\n return modint(Modulus-a);\n }\n constexpr bool operator==(const modint &rhs) const noexcept{\n return a==rhs.a;\n }\n constexpr bool operator!=(const modint &rhs) const noexcept{\n return a!=rhs.a;\n }\n constexpr bool operator!() const noexcept{return !a;}\n friend constexpr modint pow(modint &rhs,long long exp) noexcept{\n modint res{1};\n while(exp){\n if (exp&1) res*=rhs;\n rhs*=rhs; exp>>=1;\n }\n return res;\n }\n friend ostream &operator<<(ostream &s,const modint &rhs) noexcept {\n return s << rhs.a;\n }\n friend istream &operator>>(istream &s,modint &rhs) noexcept {\n u64 a; rhs=modint{(s >> a,a)}; return s;\n }\n};\n\nusing mint=modint<MOD>;\n\nconst int MAX=5e5+10;\nvector<mint> fac(MAX),finv(MAX),inv(MAX);\nvoid COMinit(){\n fac[0]=fac[1]=1;\n finv[0]=finv[1]=1;\n inv[1]=1;\n rep2(i,2,MAX){\n fac[i]=fac[i-1]*i;\n inv[i]=-inv[MOD%i]*(MOD/i);\n finv[i]=finv[i-1]*inv[i];\n }\n}\nmint COM(int n,int k){\n if (n<k||n<0||k<0) return 0;\n return fac[n]*finv[k]*finv[n-k];\n}\n\nint main(){\n cin.tie(0);\n ios::sync_with_stdio(false);\n COMinit();\n ll n; mint k; cin >> n >> k;\n cout << pow(k,n) << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 14292, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DPL_5_A_3199691", "code_snippet": "// DPL_5_A: Count the number of ways to put\n// n distinguishable balls in\n// k distinguishable boxes\n//\n// -> Sum over 1 <= j <= K of j! * S(n,j) * C(k, j)\n\n#include <iostream>\nusing ll = long long;\nll S[1001][1001];\nll C[1001][1001];\nll M = 1e9 + 7;\n\nint main() {\n int N, K;\n std::cin >> N >> K;\n\n S[0][0] = 1;\n for (int k = 1; k <= K; ++k)\n for (int n = k; n <= N; ++n)\n S[n][k] = (S[n - 1][k - 1] + k * S[n - 1][k]) % M;\n\n for (int n = 0; n <= K; ++n)\n C[n][0] = 1;\n for (int k = 1; k <= K; ++k)\n for (int n = k; n <= K; ++n)\n C[n][k] = (C[n - 1][k - 1] + C[n - 1][k]) % M;\n\n ll res = 0;\n ll F = 1;\n for (int j = 1; j <= K; ++j) {\n F = (F * j) % M;\n res = (res + ((((F * S[N][j]) % M) * C[K][j]) % M)) % M;\n }\n std::cout << res << \"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 16852, "score_of_the_acc": -0.0419, "final_rank": 3 } ]
aoj_DPL_4_B_cpp
Coin Combination Problem II You have N coins each of which has a value a i . Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R . Constraints 1 ≤ K ≤ N ≤ 40 1 ≤ a i ≤ 10 16 1 ≤ L ≤ R ≤ 10 16 All input values are given in integers Input The input is given in the following format. N K L R a 1 a 2 ... a N Output Print the number of combinations in a line. Sample Input 1 2 2 1 9 5 1 Sample Output 1 1 Sample Input 2 5 2 7 19 3 5 4 2 2 Sample Output 2 5
[ { "submission_id": "aoj_DPL_4_B_11055869", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> \ninline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> \ninline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> \npair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> \nvector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> \nvector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> \nstruct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> \nstd::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> \nstd::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> \nT pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> \nT fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> \nT perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> \nT comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> \nvoid fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> \nvoid fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> \nvector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> \nvector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> \nvector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\ntemplate<typename T> \nvector<T> compress(vector<T> &A) {\n vector<T> vals = A;\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n\n for(int i = 0; i < (int)A.size(); i++) {\n A[i] = lower_bound(vals.begin(), vals.end(), A[i]) - vals.begin();\n }\n return vals;\n}\ntemplate<typename T>\nvector<T> compress2(vector<T> &A1, vector<T> &A2) {\n vector<T> vals;\n int N = A1.size();\n for(int i = 0; i < N; i++) {\n for(T d = 0; d < 2; d++) {\n T a1 = A1[i] + d;\n T a2 = A2[i] + d;\n vals.push_back(a1);\n vals.push_back(a2);\n }\n }\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n \n for(int i = 0; i < N; i++) {\n A1[i] = lower_bound(vals.begin(), vals.end(), A1[i]) - vals.begin();\n A2[i] = lower_bound(vals.begin(), vals.end(), A2[i]) - vals.begin();\n }\n return vals;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//最小全域木\nll Kruskal(const WeightedGraph &G) {\n int N = G.size();\n return 0;\n}\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n, sz;\n vector<long long> node;\n function<ll(ll, ll)> op = [](ll a, ll b) {return max(a,b);}; //セグ木上の積\n ll e = 0; //セグ木上の積の単位元\n\n SegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, e);\n }\n SegTree(vector<long long> a) {\n sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, e);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = op(node[2*i+1], node[2*i+2]);\n }\n\n //a_iを取得\n long long get(int i) {\n return node[n-1+i];\n }\n //[a,b)における積\n long long prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return e;\n if(a <= l and r <= b) return node[k];\n long long vl = prod(a, b, 2*k+1, l, (l+r)/2);\n long long vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return op(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = op(node[2*i+1], node[2*i+2]);\n }\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n const ll ex = 0, //セグ木上の積の単位元\n em = 0; //遅延評価木上の積の単位元\n function<ll(ll, ll)> fx = [](ll x, ll y) {return x+y;}, //セグ木上の積\n fa = [](ll x, ll a) {return x+a;}, //遅延評価木からセグ木への作用\n fm = [](ll a, ll b) {return a+b;}, //遅延評価木上の積\n fp = [](ll a, ll n) {return a*n;}; //区間長の作用への影響\n\n LazySegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n }\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = fx(node[2*i+1], node[2*i+2]);\n }\n\n void eval(int k, int len) {\n if(lazy[k] == em) return;\n\n node[k] = fa(node[k], fp(lazy[k], len));\n if(k < n-1) {\n lazy[2*k+1] = fm(lazy[2*k+1], lazy[k]);\n lazy[2*k+2] = fm(lazy[2*k+2], lazy[k]);\n }\n lazy[k] = em;\n }\n //区間[a,b)を値xに更新\n void update(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] = fm(lazy[k], x);\n eval(k, r - l);\n }else {\n update(a, b, x, 2*k+1, l, (l+r)/2);\n update(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = fx(node[2*k+1], node[2*k+2]);\n }\n }\n //区間[a,b)の積を取得\n ll prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return ex;\n if(a <= l and r <= b) return node[k];\n \n ll vl = prod(a, b, 2*k+1, l, (l+r)/2);\n ll vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return fx(vl, vr);\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//平方分割\nstruct Backet {\n vector<ll> array;\n vector<ll> backet;\n int N, M;\n\n Backet(vector<ll> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n void add(int i, ll x) {\n array[i] += x;\n backet[i/M] += x;\n }\n //区間[i,j)の和\n ll getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n ll s = 0;\n if(l > r) {\n rep(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n rep(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n//最小共通祖先\nstruct LCA {\n Graph G;\n int N, LOG_N;\n vector<int> depth;\n vector<vector<int>> par;\n\n function<void(int)> dfs = [&](int v) {\n for(auto next_v : G[v]) {\n if(depth[next_v] != inf) continue;\n depth[next_v] = depth[v] + 1;\n par[0][next_v] = v;\n dfs(next_v);\n }\n return;\n };\n\n LCA(Graph &g) {\n G = g;\n N = G.size();\n depth.resize(N, inf);\n depth[0] = 0;\n LOG_N = 0;\n while((1<<LOG_N) < N) LOG_N++;\n par.resize(LOG_N+1, vector<int>(N));\n dfs(0);\n rep(i,1,LOG_N) {\n rep(j,0,N) {\n if(par[i-1][j] == -1) par[i][j] = -1;\n else par[i][j] = par[i-1][par[i-1][j]];\n }\n }\n }\n\n //頂点uのk代目の祖先\n int ancestor(int u, int k) {\n int g = 0;\n while(k > 0) {\n if(k % 2 == 1) u = par[g][u];\n k /= 2;\n g++;\n }\n return u;\n }\n //頂点u,vの最小共通祖先\n int lca(int u, int v) {\n int d1 = depth[u], d2 = depth[v];\n if(d1 < d2) v = ancestor(v, d2-d1);\n if(d1 > d2) u = ancestor(u, d1-d2);\n\n if(u == v) return u;\n for(int k = LOG_N; k >= 0; k--) {\n if(par[k][u] != par[k][v]) {\n u = par[k][u];\n v = par[k][v];\n }\n }\n return par[0][u];\n }\n //頂点u,vの距離\n int dist(int u, int v) {\n return depth[u] + depth[v] - 2*depth[lca(u, v)];\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, K; ll L, R; cin >> N >> K >> L >> R;\n vll A(N);\n vvll lefthalf(N+1), righthalf(N+1);\n rep(i,0,N) {\n cin >> A[i];\n }\n\n rep(tmp,0,(1<<(N/2))) {\n bitset<20> s(tmp);\n int k = 0;\n ll sum = 0;\n rep(i,0,20) {\n if(s.test(i)) {\n sum += A[i];\n k++;\n }\n }\n lefthalf[k].push_back(sum);\n }\n rep(i,0,N) sort(all(lefthalf[i]));\n rep(tmp,0,(1<<((N+1)/2))) {\n bitset<20> s(tmp);\n int k = 0;\n ll sum = 0;\n rep(i,0,20) {\n if(s.test(i)) {\n sum += A[i+N/2];\n k++;\n }\n }\n righthalf[k].push_back(sum);\n }\n rep(i,0,N) sort(all(righthalf[i]));\n\n ll ans = 0;\n REP(k,0,K) {\n for(auto x : lefthalf[k]) {\n auto p = lower_bound(all(righthalf[K-k]), L-x), q = upper_bound(all(righthalf[K-k]), R-x);\n ans += ll(q-p);\n }\n }\n cout << ans << \"\\n\";\n\n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 23464, "score_of_the_acc": -0.8881, "final_rank": 6 }, { "submission_id": "aoj_DPL_4_B_11055866", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing vi = vector<int>;\nusing vvi = vector<vector<int>>;\nusing vvvi = vector<vector<vector<int>>>;\nusing vll = vector<ll>;\nusing vvll = vector<vector<ll>>;\nusing vvvll = vector<vector<vector<ll>>>;\nusing vd = vector<double>;\nusing vvd = vector<vector<double>>;\nusing vstr = vector<string>;\nusing vchar = vector<char>;\nusing vvchar = vector<vector<char>>;\nusing vb = vector<bool>;\nusing vvb = vector<vector<bool>>;\nusing vvvb = vector<vector<vector<bool>>>;\nusing pii = pair<int,int>;\nusing pll = pair<long long, long long>;\nusing Graph = vector<vector<int>>;\nusing WeightedGraph = vector<vector<pair<int,ll>>>;\nconst int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\nconst int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};\n\n#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)\n#define REP(i, a, b) for (ll i = (ll)a; i <= (ll)b; i++)\n#define rrep(i, a, b) for(ll i = (ll)b-1; i >= (ll)a; i--)\n#define RREP(i, a, b) for(ll i = (ll)b; i >= (ll)a; i--)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define YESNO(flag) cout << (flag ? \"Yes\" : \"No\") << \"\\n\"\n#define spa \" \"\n#define mint modint<MOD>\n\nconst int inf = 1070000000;\nconst long long INF = 4500000000000000000;\n//const long long MOD = 998244353;\nconst long long MOD = 1000000007;\nconst double pi = 3.141592653589793238;\nconst double eps = (1e-10);\nconst string ABC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst string abc = \"abcdefghijklmnopqrstuvwxyz\";\n\ntemplate<typename T> \ninline bool chmin(T& a, T b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename T> \ninline bool chmax(T& a, T b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate<typename S, typename T> \npair<S, T> operator+(pair<S, T> a, pair<S, T> b) {\n pair<S, T> ans;\n ans.first = a.first + b.first;\n ans.second = a.second + b.second;\n return ans;\n} \ntemplate<typename T> \nvector<T> operator+(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size());\n vector<T> c(N);\n for(int i = 0; i < N; i++) {\n if(i >= a.size()) c[i] = b[i];\n else if(i >= b.size()) c[i] = a[i];\n else c[i] = a[i] + b[i];\n }\n return c;\n}\ntemplate<typename T> \nvector<T> operator*(vector<T> a, vector<T> b) {\n int N = max(a.size(), b.size()), n = min(a.size(), b.size());\n vector<T> c(N, 0);\n for(int i = 0; i < n; i++) {\n c[i] = a[i] * b[i];\n }\n return c;\n}\n\n//拡張ユークリッド\nll ext_gcd(ll a, ll b, ll &x, ll &y) {\n if(b == 0) {\n x = 1, y = 0;\n return a;\n }\n\n ll q = a/b;\n ll g = ext_gcd(b, a-q*b, x, y);\n ll z = x-q*y;\n x = y, y = z;\n return g;\n}\n//mod mにおけるaの逆元. aとmは互いに素.\nll inverse(ll a, ll m) {\n ll x, y;\n ext_gcd(a, m, x, y);\n x = (x+m) % m;\n return x;\n}\n//modint\ntemplate<std::uint_fast64_t mod> \nstruct modint {\n using u64 = std::uint_fast64_t;\n u64 val;\n\n modint(u64 v = 0) : val(v % mod) {}\n\n bool operator==(modint other) {\n return val == other.val;\n }\n bool operator<(const modint& other) const {\n return val < other.val;\n }\n // operator> (大なり)\n bool operator>(const modint& other) const {\n return val > other.val;\n }\n modint operator+(modint other) {\n modint<mod> ans;\n ans.val = val + other.val;\n if(ans.val >= mod) ans.val -= mod;\n return ans;\n }\n modint operator-(modint other) {\n modint<mod> ans;\n if(val < other.val) val += mod;\n ans.val = val - other.val;\n return ans;\n }\n modint operator*(modint other) {\n modint<mod> ans;\n ans.val = (val * other.val) % mod;\n return ans;\n }\n modint operator/(modint other) {\n modint<mod> ans;\n ans.val = (val * inverse(other.val, mod)) % mod;\n return ans;\n }\n modint &operator+=(modint other) {\n *this = *this + other;\n return *this;\n }\n modint &operator-=(modint other) {\n *this = *this - other;\n return *this;\n }\n modint &operator*=(modint other) {\n *this = *this * other;\n return *this;\n }\n modint &operator/=(modint other) {\n *this = *this / other;\n return *this;\n }\n modint &operator++() {\n *this += 1;\n return *this;\n }\n modint &operator++(int) {\n ++(*this);\n return *this;\n }\n modint &operator--() {\n *this -= 1;\n return *this;\n }\n modint &operator--(int) {\n --(*this);\n return *this;\n }\n};\n//modintの入出力\ntemplate<std::uint_fast64_t mod> \nstd::ostream& operator<<(std::ostream &os, const modint<mod> &x) {\n // modint の 'val' メンバを出力ストリーム(os)に渡す\n os << x.val;\n return os; // ストリームを返す (チェーンのため)\n}\ntemplate<std::uint_fast64_t mod> \nstd::istream& operator>>(std::istream& is, modint<mod> &x) {\n // modintが内部で使っているu64型を取得\n using u64 = typename modint<mod>::u64; \n \n u64 input_value;\n is >> input_value; // (1) istream(cin) から一時変数に値を読み込む\n \n // (2) 読み込んだ値を使って modint を再構築する\n // modintのコンストラクタが (input_value % mod) を処理してくれる\n x = modint<mod>(input_value); \n \n return is; // (3) ストリームを返す (チェーンのため)\n}\n//累乗, x^n\ntemplate<typename T> \nT pow(T x, int n) {\n T ans = 1;\n while(n > 0) {\n if(n & 1) ans *= x;\n x *= x;\n n >>= 1; \n }\n return ans;\n}\n//階乗, n!\ntemplate<typename T> \nT fact(T n) {\n if(n == 0) return 1;\n return n * fact(n-1);\n}\n//nPk\ntemplate<typename T> \nT perm(T n, T k) {\n if(k == 0) return 1;\n return n * perm(n-1, k-1);\n}\n//nCk\ntemplate<typename T> \nT comb(T n, T k) {\n if(k > n) return 0;\n return perm(n, min(k, n-k))/fact(min(k, n-k));\n}\n//ord(n)\nll ord(ll n, ll p) {\n int ans = 0;\n while(n % p == 0) {\n n /= p;\n ans++;\n }\n return ans;\n}\n//ルジャンドルの公式ord(n!)\nll factord(ll n, ll p) {\n ll ans = 0;\n ll q = p, tmp = n;\n while(tmp > 0) {\n tmp = n/q;\n ans += tmp;\n q *= p;\n }\n return ans;\n}\n//素因数分解, O(√N)\nvector<pair<ll,ll>> factorize(ll N) {\n vector<pair<ll,ll>> ans;\n for(ll p = 2; p*p <= N; p++) {\n int ex = 0;\n while(N % p == 0) {\n N /= p;\n ex++;\n }\n if(ex != 0) ans.push_back({p,ex});\n }\n if(N != 1) ans.push_back({N,1});\n return ans;\n}\n//素数判定\nbool isprime(long long x) {\n if(x == 1) return false;\n \n for(long long i = 2; i*i <= x; i++) {\n if(x % i == 0) return false;\n }\n return true;\n}\n//エラトステネスの篩\nstruct Eratosthenes {\n vector<bool> prime;\n vector<int> minfactor;\n vector<int> mobius;\n vector<ll> euler;\n\n //コンストラクタ O(NloglogN)\n Eratosthenes(int N) : prime(N+1, true),\n minfactor(N+1, -1),\n mobius(N+1, 1),\n euler(N+1, 1) {\n prime[0] = false;\n prime[1] = false;\n minfactor[1] = 1;\n REP(i,1,N) euler[i] = i;\n\n for(int p = 2; p <= N; p++) {\n if(!prime[p]) continue;\n\n minfactor[p] = p;\n mobius[p] = -1;\n euler[p] = p-1;\n\n for(int q = 2; p*q <= N; q++) {\n prime[p*q] = false;\n if(minfactor[p*q] == -1) minfactor[p*q] = p;\n if(q % p == 0) mobius[p*q] = 0;\n else mobius[p*q] *= -1;\n euler[p*q] = euler[p*q]*(p-1)/p;\n }\n }\n }\n\n //素因数分解 O(logn)\n vector<pair<int,int>> factorize(int n) {\n vector<pair<int,int>> ans;\n while(n > 1) {\n int p = minfactor[n], exp = 0;\n while(n % p == 0) {\n n /= p;\n exp++;\n }\n ans.push_back({p, exp});\n }\n return ans;\n }\n //約数列挙 O(σ(n))\n vector<int> divisors(int n) {\n vector<int> ans = {1};\n while(n > 1) {\n int p = minfactor[n], d = 1, s = ans.size();\n while(n % p == 0) {\n d *= p;\n for(int i = 0; i < s; i++) {\n ans.push_back(ans[i]*d);\n }\n n /= p;\n }\n }\n return ans;\n }\n //素数関数 O(n)\n int count(int n) {\n int ans = 0;\n REP(i,2,n) if(prime[i]) ans++;\n return ans;\n }\n};\n//高速ゼータ変換\ntemplate<typename T> \nvoid fast_zeta(vector<T> &f) {\n int N = f.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n \n for(int k = N/p; k >= 1; k--) {\n f[k] += f[k*p];\n }\n }\n}\n//高速メビウス変換\ntemplate<typename T> \nvoid fast_mobius(vector<T> &F) {\n int N = F.size()-1;\n Eratosthenes sieve(N);\n for(int p = 2; p < N; p++) {\n if(!sieve.prime[p]) continue;\n\n for(int k = 1; k*p <= N; k++) {\n F[k] -= F[k*p];\n }\n }\n}\n//添字GCD畳み込み\ntemplate<typename T> \nvector<T> gcd_conv(vector<T> &f, vector<T> &g) {\n int N = max(f.size(), g.size());\n vector<T> F(N, 0), G(N, 0), H(N);\n for(int i = 0; i < f.size(); i++) F[i] = f[i];\n for(int i = 0; i < g.size(); i++) G[i] = g[i];\n fast_zeta(F);\n fast_zeta(G);\n \n for(int i = 0; i < N; i++) H[i] = F[i]*G[i];\n fast_mobius(H);\n \n return H;\n}\n\n//行列積\ntemplate<typename T> \nvector<vector<T>> matrix_product(vector<vector<T>> A, vector<vector<T>> B) {\n int H = A.size(), W = A[0].size(), P = B.size(), Q = B[0].size();\n if(W != P) {\n cout << \"matrix_size_error\" << \"\\n\";\n return vector<vector<T>>(0);\n }\n\n vector<vector<T>> C(H, vector<T>(Q, 0));\n rep(i,0,H) rep(j,0,Q) {\n rep(k,0,W) {\n C[i][j] += A[i][k]*B[k][j];\n }\n }\n return C;\n}\n//行列累乗\ntemplate<typename T> \nvector<vector<T>> matrix_pow(vector<vector<T>> A, ll n) {\n int N = A.size();\n vector<vector<T>> ans(N, vector<T>(N, 0));\n rep(i,0,N) ans[i][i] = 1;\n \n while(n > 0) {\n if(n & 1) ans = matrix_product(ans, A);\n A = matrix_product(A, A);\n n >>= 1; \n }\n return ans;\n}\n\n//1+2+...+n = n(n+1)/2\nll tri(ll n) {\n ll x = n*(n+1);\n return x/2;\n}\n\n//座標圧縮\ntemplate<typename T> \nvector<T> compress(vector<T> &A) {\n vector<T> vals = A;\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n\n for(int i = 0; i < (int)A.size(); i++) {\n A[i] = lower_bound(vals.begin(), vals.end(), A[i]) - vals.begin();\n }\n return vals;\n}\ntemplate<typename T>\nvector<T> compress2(vector<T> &A1, vector<T> &A2) {\n vector<T> vals;\n int N = A1.size();\n for(int i = 0; i < N; i++) {\n for(T d = 0; d < 2; d++) {\n T a1 = A1[i] + d;\n T a2 = A2[i] + d;\n vals.push_back(a1);\n vals.push_back(a2);\n }\n }\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n \n for(int i = 0; i < N; i++) {\n A1[i] = lower_bound(vals.begin(), vals.end(), A1[i]) - vals.begin();\n A2[i] = lower_bound(vals.begin(), vals.end(), A2[i]) - vals.begin();\n }\n return vals;\n}\n\n//正方形グリッドの右回転, 左回転\nvoid rotate_right(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[N-1-j][i];\n }\n S = T;\n}\nvoid rotate_left(vector<vector<char>> &S) {\n int N = S.size();\n auto T = S;\n rep(i,0,N) rep(j,0,N) {\n T[i][j] = S[j][N-1-i];\n }\n S = T;\n}\n\n//2点(a,b)と(x,y)の距離\nlong double dist(pair<long double, long double> a, pair<long double, long double> b) {\n return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second));\n}\nlong double man(pair<long double, long double> a, pair<long double, long double> b) {\n return abs(a.first-b.first) + abs(a.second-b.second);\n}\n//内分点\npair<long double, long double> internal_division(pair<long double, long double> a, pair<long double, long double> b, long double p) {\n long double x = a.first + (b.first - a.first) * p;\n long double y = a.second + (b.second - a.second) * p;\n return {x, y};\n}\n\n//桁数\nint digit(ll N) {\n if(N <= 9) return 1;\n\n return 1 + digit(N / 10);\n}\n//A進数文字列NをB進数に変換. A,Bは10以下\nstring base_change(string N, ll A, ll B) {\n ll X = stoll(N), Y = 0;\n\n ll i = 1;\n while(X != 0) {\n Y += (X % 10) * i;\n i *= A;\n X /= 10;\n }\n\n X = Y, Y = 0;\n i = 1;\n while(X != 0) {\n Y += (X % B) * i;\n i *= 10;\n X /= B;\n }\n\n return to_string(Y);\n}\n//回文判定\nbool palin(string S) {\n rep(i,0,S.size()) {\n if(S[i] != S[S.size()-1-i]) return false;\n }\n return true;\n}\n\n//hh:mm:ss to second\nint convert_to_time(string S) {\n ll h = 10*(S[0]-'0') + (S[1]-'0');\n ll m = 10*(S[3]-'0') + (S[4]-'0');\n ll s = 10*(S[6]-'0') + (S[7]-'0');\n \n return h*3600+m*60+s;\n}\n\n//DFS\nvoid dfs(const Graph &G, int v, vector<bool> &seen) { \n seen[v] = true;\n \n for (auto next_v : G[v]) { \n if (!seen[next_v]) {\n dfs(G, next_v, seen);\n }\n }\n}\nvoid griddfs(const vector<vector<char>> &G, int x, int y, vector<vector<bool>> &seen) {\n int H = G.size(), W = G[0].size();\n seen[x][y] = true;\n \n for (int i = 0; i < 8; i++) { \n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if (!seen[nx][ny] and G[nx][ny] != '#') griddfs(G, nx, ny, seen);\n }\n}\n//BFS\nvoid bfs(const Graph &G, int v, vector<int> &dist) {\n rep(i,0,dist.size()) dist[i] = inf;\n dist[v] = 0;\n queue<int> q;\n q.push(v);\n while(!q.empty()) {\n int u = q.front();\n q.pop();\n for(auto next_u : G[u]) {\n if(dist[next_u] == inf) {\n dist[next_u] = dist[u] + 1;\n q.push(next_u);\n }\n }\n }\n}\nvoid gridbfs(const vector<vector<char>> &G, int x, int y, vector<vector<int>> &dist) {\n int H = G.size(), W = G[0].size();\n dist[x][y] = 0;\n queue<pair<int, int>> q;\n q.push(make_pair(x, y));\n while(!q.empty()) {\n int x = q.front().first, y = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n if(nx < 0 or nx >= H or ny < 0 or ny >= W) continue;\n if(dist[nx][ny] == inf and G[nx][ny] != '#') {\n dist[nx][ny] = dist[x][y] + 1;\n q.push(make_pair(nx, ny));\n }\n }\n }\n}\n//ワーシャル・フロイド\nvector<vector<ll>> floyd(vector<vector<ll>> G) {\n int N = G.size();\n auto dp = G;\n for (int k = 0; k < N; k++){\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if(dp[i][j] > dp[i][k] + dp[k][j] and dp[i][k] != INF and dp[k][j] != INF) {\n dp[i][j] = dp[i][k] + dp[k][j];\n }\n }\n }\n }\n return dp;\n}\n//サイクルがあるか判定\nbool cycle(const Graph &G, int v, vector<bool> &seen, vector<bool> &finished) {\n seen[v] = true; // 行きがけ時に true になる\n for (auto v2 : G[v]) {\n //if (v2 が逆戻りの場合) continue; // 無向グラフの場合は必要\n\n // 頂点 v2 がすでに探索済みの場合はスキップ \n if (finished[v2]) continue;\n\n // サイクル検出\n if (seen[v2] && !finished[v2]) return true;\n\n // 頂点 v2 を再帰的に探索\n if (cycle(G, v2, seen, finished)) return true;\n }\n finished[v] = true; // 帰りがけ時に true になる\n return false;\n}\n\n//Union-Find\nstruct UnionFind {\n vector<int> par; // par[i]:iの親の番号 (例) par[3] = 2 : 3の親が2\n vector<ll> cnt;\n \n UnionFind(int N) : par(N),\n cnt(N, 1) { //最初は全てが根であるとして初期化\n for(int i = 0; i < N; i++) par[i] = i;\n }\n \n int root(int x) { // データxが属する木の根を再帰で得る:root(x) = {xの木の根}\n if (par[x] == x) return x;\n return par[x] = root(par[x]);\n }\n \n void unite(int x, int y) { // xとyの木を併合\n int rx = root(x); //xの根をrx\n int ry = root(y); //yの根をry\n if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま\n par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時:xの根rxをyの根ryにつける\n cnt[ry] += cnt[rx];\n }\n \n bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す\n int rx = root(x);\n int ry = root(y);\n return rx == ry;\n }\n\n ll num(int x) { //データxと同じ木に属するデータの数を得る\n return cnt[x] = cnt[root(x)];\n }\n};\n//最小全域木\nll Kruskal(const WeightedGraph &G) {\n int N = G.size();\n return 0;\n}\n//BIT\nstruct BIT {\n vector<long long> array;\n const int n;\n\n BIT(int _n) : array(_n, 0), n(_n) {}\n\n //a_0 + ... + a_i\n long long sum(int i) {\n long long s = 0;\n while(i >= 0) {\n s += array[i];\n i -= (i+1) & -(i+1);\n }\n return s;\n }\n //a_i + ... + a_j\n long long sum(int i, int j) {\n long long ans_i = sum(i-1);\n long long ans_j = sum(j);\n return ans_j - ans_i;\n }\n //a_i += x\n void add(int i, long long x) {\n while(i < n) {\n array[i] += x;\n i += (i+1) & -(i+1);\n }\n }\n};\n//セグ木\nstruct SegTree {\n int n, sz;\n vector<long long> node;\n function<ll(ll, ll)> op = [](ll a, ll b) {return max(a,b);}; //セグ木上の積\n ll e = 0; //セグ木上の積の単位元\n\n SegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, e);\n }\n SegTree(vector<long long> a) {\n sz = a.size();\n\n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, e);\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = op(node[2*i+1], node[2*i+2]);\n }\n\n //a_iを取得\n long long get(int i) {\n return node[n-1+i];\n }\n //[a,b)における積\n long long prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n if(r <= a or b <= l) return e;\n if(a <= l and r <= b) return node[k];\n long long vl = prod(a, b, 2*k+1, l, (l+r)/2);\n long long vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return op(vl, vr);\n }\n void update(int i, long long x) {\n i = n-1+i;\n node[i] = x;\n while(i > 0) {\n i = (i-1)/2;\n node[i] = op(node[2*i+1], node[2*i+2]);\n }\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//遅延セグ木\nstruct LazySegTree {\n int n;\n vector<ll> node, lazy;\n const ll ex = 0, //セグ木上の積の単位元\n em = 0; //遅延評価木上の積の単位元\n function<ll(ll, ll)> fx = [](ll x, ll y) {return x+y;}, //セグ木上の積\n fa = [](ll x, ll a) {return x+a;}, //遅延評価木からセグ木への作用\n fm = [](ll a, ll b) {return a+b;}, //遅延評価木上の積\n fp = [](ll a, ll n) {return a*n;}; //区間長の作用への影響\n\n LazySegTree(int n_) {\n n = 1;\n while(n < n_) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n }\n LazySegTree(vector<ll> a) {\n int sz = a.size();\n \n n = 1;\n while(n < sz) n *= 2;\n node.resize(2*n-1, ex);\n lazy.resize(2*n-1, em);\n\n for(int i = 0; i < sz; i++) node[n-1+i] = a[i];\n for(int i = n-2; i >= 0; i--) node[i] = fx(node[2*i+1], node[2*i+2]);\n }\n\n void eval(int k, int len) {\n if(lazy[k] == em) return;\n\n node[k] = fa(node[k], fp(lazy[k], len));\n if(k < n-1) {\n lazy[2*k+1] = fm(lazy[2*k+1], lazy[k]);\n lazy[2*k+2] = fm(lazy[2*k+2], lazy[k]);\n }\n lazy[k] = em;\n }\n //区間[a,b)を値xに更新\n void update(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return;\n if(a <= l and r <= b) {\n lazy[k] = fm(lazy[k], x);\n eval(k, r - l);\n }else {\n update(a, b, x, 2*k+1, l, (l+r)/2);\n update(a, b, x, 2*k+2, (l+r)/2, r);\n node[k] = fx(node[2*k+1], node[2*k+2]);\n }\n }\n //区間[a,b)の積を取得\n ll prod(int a, int b, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(r <= a or b <= l) return ex;\n if(a <= l and r <= b) return node[k];\n \n ll vl = prod(a, b, 2*k+1, l, (l+r)/2);\n ll vr = prod(a, b, 2*k+2, (l+r)/2, r);\n return fx(vl, vr);\n }\n //[a,b)でa_i >= xなる最大のiを求める\n int maxindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return a-1;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vr = maxindex(a, b, x, 2*k+2, (l+r)/2, r);\n if(vr != a-1) return vr;\n else return maxindex(a, b, x, 2*k+1, l, (l+r)/2);\n }\n }\n //[a,b)でa_i >= xなる最小のiを求める\n int minindex(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {\n if(r < 0) r = n;\n\n eval(k, r - l);\n if(node[k] < x or r <= a or b <= l) return b;\n else if(k >= n-1) return (k - (n-1));\n else {\n int vl = minindex(a, b, x, 2*k+1, l, (l+r)/2);\n if(vl != b) return vl;\n else return minindex(a, b, x, 2*k+2, (l+r)/2, r);\n }\n }\n};\n//平方分割\nstruct Backet {\n vector<ll> array;\n vector<ll> backet;\n int N, M;\n\n Backet(vector<ll> a) {\n array = a;\n N = a.size(), M = ceil(sqrt(N));\n \n backet.resize((N+M-1)/M);\n for(int i = 0; i < N; i++) {\n backet[i/M] += a[i];\n }\n }\n void add(int i, ll x) {\n array[i] += x;\n backet[i/M] += x;\n }\n //区間[i,j)の和\n ll getsum(int i, int j) {\n int l = i/M + 1, r = j/M;\n ll s = 0;\n if(l > r) {\n rep(k,i,j) s += array[k];\n }else {\n rep(k,i,l*M) s += array[k];\n rep(k,l,r) s += backet[k];\n rep(k,r*M,j) s += array[k];\n }\n return s;\n }\n};\n//最小共通祖先\nstruct LCA {\n Graph G;\n int N, LOG_N;\n vector<int> depth;\n vector<vector<int>> par;\n\n function<void(int)> dfs = [&](int v) {\n for(auto next_v : G[v]) {\n if(depth[next_v] != inf) continue;\n depth[next_v] = depth[v] + 1;\n par[0][next_v] = v;\n dfs(next_v);\n }\n return;\n };\n\n LCA(Graph &g) {\n G = g;\n N = G.size();\n depth.resize(N, inf);\n depth[0] = 0;\n LOG_N = 0;\n while((1<<LOG_N) < N) LOG_N++;\n par.resize(LOG_N+1, vector<int>(N));\n dfs(0);\n rep(i,1,LOG_N) {\n rep(j,0,N) {\n if(par[i-1][j] == -1) par[i][j] = -1;\n else par[i][j] = par[i-1][par[i-1][j]];\n }\n }\n }\n\n //頂点uのk代目の祖先\n int ancestor(int u, int k) {\n int g = 0;\n while(k > 0) {\n if(k % 2 == 1) u = par[g][u];\n k /= 2;\n g++;\n }\n return u;\n }\n //頂点u,vの最小共通祖先\n int lca(int u, int v) {\n int d1 = depth[u], d2 = depth[v];\n if(d1 < d2) v = ancestor(v, d2-d1);\n if(d1 > d2) u = ancestor(u, d1-d2);\n\n if(u == v) return u;\n for(int k = LOG_N; k >= 0; k--) {\n if(par[k][u] != par[k][v]) {\n u = par[k][u];\n v = par[k][v];\n }\n }\n return par[0][u];\n }\n //頂点u,vの距離\n int dist(int u, int v) {\n return depth[u] + depth[v] - 2*depth[lca(u, v)];\n }\n};\n\nvoid solve() {\n}\n\nint main() {\n int N, K; ll L, R; cin >> N >> K >> L >> R;\n vll A(N);\n vvll lefthalf(N+1), righthalf(N+1);\n rep(i,0,N) {\n cin >> A[i];\n }\n\n rep(tmp,0,(1<<(N/2))) {\n bitset<20> s(tmp);\n int k = 0;\n ll sum = 0;\n rep(i,0,20) {\n if(s.test(i)) {\n sum += A[i];\n k++;\n }\n }\n lefthalf[k].push_back(sum);\n }\n rep(i,0,N) sort(all(lefthalf[i]));\n rep(tmp,0,(1<<((N+1)/2))) {\n bitset<20> s(tmp);\n int k = 0;\n ll sum = 0;\n rep(i,0,20) {\n if(s.test(i)) {\n sum += A[i+N/2];\n k++;\n }\n }\n righthalf[k].push_back(sum);\n }\n rep(i,0,N) sort(all(righthalf[i]));\n\n int ans = 0;\n REP(k,0,K) {\n for(auto x : lefthalf[k]) {\n auto p = lower_bound(all(righthalf[K-k]), L-x), q = upper_bound(all(righthalf[K-k]), R-x);\n ans += q-p;\n }\n }\n cout << ans << \"\\n\";\n\n return 0;\n}", "accuracy": 0.5, "time_ms": 30, "memory_kb": 6796, "score_of_the_acc": -0.002, "final_rank": 20 }, { "submission_id": "aoj_DPL_4_B_11037918", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n#define rep(i, n) for (int i = 0; i < (n); ++i)\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n ll N, K, L, R;\n cin >> N >> K >> L >> R;\n vector<ll> A(N);\n rep(i, N) cin >> A[i];\n\n int M = N / 2;\n vector<vector<ll>> sum1(M + 1);\n rep(i, (1 << M)) {\n ll sum = 0;\n int cnt = 0;\n rep(j, M) {\n if ((i >> j) & 1) {\n sum += A[j];\n cnt++;\n }\n }\n sum1[cnt].push_back(sum);\n }\n\n vector<vector<ll>> sum2(N - M + 1);\n rep(i, (1 << (N - M))) {\n ll sum = 0;\n int cnt = 0;\n rep(j, N - M) {\n if ((i >> j) & 1) {\n sum += A[j + M];\n cnt++;\n }\n }\n sum2[cnt].push_back(sum);\n }\n\n rep(i, sum2.size()) { sort(sum2[i].begin(), sum2[i].end()); }\n\n ll res = 0;\n rep(i, sum1.size()) {\n int remain_cnt = K - i;\n if (remain_cnt >= sum2.size()) continue;\n for (ll s1 : sum1[i]) {\n auto& vec = sum2[remain_cnt];\n auto r = upper_bound(vec.begin(), vec.end(), R - s1);\n auto l = lower_bound(vec.begin(), vec.end(), L - s1);\n ll cnt = r - l;\n res += cnt;\n }\n }\n\n cout << res << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 23044, "score_of_the_acc": -0.9398, "final_rank": 8 }, { "submission_id": "aoj_DPL_4_B_10881243", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nint main(){\n ll N,K,L,R; cin>>N>>K>>L>>R;\n vector<ll> A(N);\n for(ll i=0;i<N;i++) cin>>A[i];\n\n ll N1=N/2,N2=N-N1;\n vector<vector<ll>> A1(N1+1),A2(N2+1);\n for(int i=0;i<(1<<N1);i++){\n ll popcount=0,value=0;\n for(int j=0;j<N1;j++){\n if((i&1<<j)!=0){\n popcount++;\n value+=A[j];\n }\n }\n A1[popcount].push_back(value);\n }\n for(int i=0;i<(1<<N2);i++){\n ll popcount=0,value=0;\n for(int j=0;j<N2;j++){\n if((i&1<<j)!=0){\n popcount++;\n value+=A[N1+j];\n }\n }\n A2[popcount].push_back(value);\n }\n for(int i=0;i<=N2;i++) sort(A2[i].begin(),A2[i].end());\n\n ll ans=0;\n for(int i=0;i<=N1;i++){\n if(K-i<0||N2<K-i) continue;\n for(int j=0;j<A1[i].size();j++){\n ans+=upper_bound(A2[K-i].begin(),A2[K-i].end(),R-A1[i][j])-lower_bound(A2[K-i].begin(),A2[K-i].end(),L-A1[i][j]);\n }\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 270, "memory_kb": 23808, "score_of_the_acc": -0.9386, "final_rank": 7 }, { "submission_id": "aoj_DPL_4_B_10879941", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid generate_sums_bitmask(int s, int e, const vector<long long> &a, vector<vector<long long>> &sums) {\n //sからe-1まで。\n int n = e - s;\n for (int i = 0; i < (1 << n); ++i) {\n long long curr_sum = 0;\n int count = 0;\n for (int j = 0; j < n; ++j) {\n if ((i >> j) & 1) {\n curr_sum += a[s + j];\n count++;\n }\n }\n sums[count].push_back(curr_sum);\n }\n}\n\nint main() {\n int N, K;\n long long L, R;\n cin >> N >> K >> L >> R;\n\n // N枚のコインの値段 a_i を入力\n vector<long long> a(N);\n for (int i = 0; i < N; ++i) {\n cin >> a[i];\n }\n\n int n1 = N / 2;\n int n2 = N - n1;\n vector<vector<long long>> sum1(n1 + 1);\n generate_sums_bitmask(0, n1, a, sum1);\n vector<vector<long long>> sum2(n2 + 1);\n generate_sums_bitmask(n1, N, a, sum2);\n\n for (auto & v: sum2) {\n sort(v.begin(), v.end());\n }\n long long ans = 0;\n for (int i = 0; i <= n1; ++i) {\n int j = K - i;\n if (j < 0 || j > n2) continue;\n for (long long s1: sum1[i]) {\n long long l = L - s1;\n long long r = R - s1;\n auto it_l = lower_bound(sum2[j].begin(), sum2[j].end(), l);\n auto it_r = upper_bound(sum2[j].begin(), sum2[j].end(), r);\n ans += it_r - it_l;\n }\n }\n\n cout << ans << endl;\n return 0;\n\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 23432, "score_of_the_acc": -0.9498, "final_rank": 11 }, { "submission_id": "aoj_DPL_4_B_10879939", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid generate_sums_bitmask(int s, int e, const vector<long long> &a, vector<vector<long long>> &sums) {\n //sからe-1まで。\n int n = e - s;\n for (int i = 0; i < (1 << n); ++i) {\n long long curr_sum = 0;\n int count = 0;\n for (int j = 0; j < n; ++j) {\n if ((i >> j) & 1) {\n curr_sum += a[s + j];\n count++;\n }\n }\n sums[count].push_back(curr_sum);\n }\n}\n\nint main() {\n int N, K;\n long long L, R;\n cin >> N >> K >> L >> R;\n\n // N枚のコインの値段 a_i を入力\n vector<long long> a(N);\n for (int i = 0; i < N; ++i) {\n cin >> a[i];\n }\n\n int n1 = N / 2;\n int n2 = N - n1;\n vector<vector<long long>> sum1(n1 + 1);\n generate_sums_bitmask(0, n1, a, sum1);\n vector<vector<long long>> sum2(n2 + 1);\n generate_sums_bitmask(n1, N, a, sum2);\n\n for (auto & v: sum2) {\n sort(v.begin(), v.end());\n }\n long long ans = 0;\n for (int i = 0; i <= n1; ++i) {\n int j = K - i;\n if (j < 0 || j > n2) continue;\n for (long long s1: sum1[i]) {\n long long l = L - s1;\n long long r = R - s1;\n auto it_l = lower_bound(sum2[j].begin(), sum2[j].end(), l);\n auto it_r = upper_bound(sum2[j].begin(), sum2[j].end(), r);\n ans += distance(it_l, it_r);\n }\n }\n\n cout << ans << endl;\n return 0;\n\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 23432, "score_of_the_acc": -0.9498, "final_rank": 11 }, { "submission_id": "aoj_DPL_4_B_10848461", "code_snippet": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint N,K;\nll a[50];\nll L,R;\n\nvector<pair<int,ll> >x,y;\n\nvoid func(int l,int r ,vector<pair<int,ll> >&t){\n int w=r-l;\n for(int i=0;i<(1<<w);i++){\n ll sum=0;\n int cnt=0;\n for(int j=0;j<w;j++){\n if((i>>j)&1){\n sum+=a[l+j];\n cnt++;\n }\n }\n t.push_back(make_pair(cnt,sum));\n }\n}\n\nint main(){\n cin>>N>>K>>L>>R;\n for(int i=0;i<N;i++)\n cin>>a[i];\n func(0,N/2,x);\n func(N/2,N,y);\n sort(y.begin(),y.end());\n ll ans=0;\n for(int i=0;i<x.size();i++){\n vector<pair<int,ll> >::iterator it1,it2;\n it1=lower_bound(y.begin(),y.end(),pair<int,ll>(K-x[i].first,L-x[i].second));\n it2=upper_bound(y.begin(),y.end(),pair<int,ll>(K-x[i].first,R-x[i].second));\n ans+=(it2-it1);\n }\n cout<<ans<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 510, "memory_kb": 45680, "score_of_the_acc": -2, "final_rank": 16 }, { "submission_id": "aoj_DPL_4_B_10830037", "code_snippet": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\nint n,k;\nll l,r;\nll a[44];\nvector<ll> b[41];// 选i个硬币有哪些不同结果 \nvector<ll> c[41];\nvoid dfs1(int i,ll v,int cnt){\n\tif(i==n/2){b[cnt].push_back(v);return;}\n\tdfs1(i+1,v+a[i],cnt+1);\n\tdfs1(i+1,v,cnt);\n}\nvoid dfs2(int i,ll v,int cnt){\n\tif(i==n){c[cnt].push_back(v);return;}\n\tdfs2(i+1,v+a[i],cnt+1);\n\tdfs2(i+1,v,cnt);\n}\nvoid solve(){\n\tif(n==1){cout<<(k==1&&a[0]>=l&&a[0]<=r)<<\"\\n\";return;}\n\tdfs1(0,0,0);\n\tdfs2(n/2,0,0);\n\tll res=0;\n\tfor(int i=0;i<=40;i++)sort(b[i].begin(),b[i].end()),sort(c[i].begin(),c[i].end());\n\tfor(int i=0;i<=k;i++){\n\t\tint j=k-i;\n\t\tfor(int t=0;t<b[i].size();t++){\n\t\t\tll v=b[i][t];\n\t\t\tres+=upper_bound(c[j].begin(),c[j].end(),r-v)-lower_bound(c[j].begin(),c[j].end(),l-v);\n\t\t}\n\t}cout<<res<<\"\\n\";\n}\nint main(){\n\tcin>>n>>k>>l>>r;\n\tfor(int i=0;i<n;i++)cin>>a[i];\n\tsolve();\n\treturn 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 23308, "score_of_the_acc": -0.6966, "final_rank": 2 }, { "submission_id": "aoj_DPL_4_B_10803195", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nint main(){\n\n int K, N;\n ll a, L, R, res = 0;\n vector<ll> la, ra;\n vector<vector<ll>> lax, rax;\n\n cin >> N >> K >> L >> R;\n for( int i = 0 ; i < N / 2 ; i++ ){\n cin >> a;\n la.push_back( a );\n vector<ll> v;\n lax.push_back( v );\n }\n for( int i = N / 2 ; i < N ; i++ ){\n cin >> a;\n ra.push_back( a );\n vector<ll> v;\n rax.push_back( v );\n }\n vector<ll> tmp;\n lax.push_back( tmp );\n rax.push_back( tmp );\n for( ll i = 0 ; i < ( 1 << la.size() ) ; i++ ){\n int id = 0;\n ll _i = i, val = 0;\n for( int j = 0 ; j < la.size() ; j++ ){\n if( _i & 1LL ){\n id++;\n val += la[j];\n }\n _i >>= 1;\n }\n lax[id].push_back( val );\n }\n for( ll i = 0 ; i < ( 1 << ra.size() ) ; i++ ){\n int id = 0;\n ll _i = i, val = 0;\n for( int j = 0 ; j < ra.size() ; j++ ){\n if( _i & 1LL ){\n id++;\n val += ra[j];\n }\n _i >>= 1;\n }\n rax[id].push_back( val );\n }\n for( int i = 0 ; i < ra.size() ; i++ )\n sort( rax[i].begin(), rax[i].end() );\n for( int i = 0 ; i <= la.size() ; i++ ){\n for( int j = 0 ; j < lax[i].size() ; j++ ){\n if( K - i >= 0 && K - i <= ra.size() )\n res += upper_bound( rax[K-i].begin(), rax[K-i].end(), R - lax[i][j] ) - lower_bound( rax[K-i].begin(), rax[K-i].end(), L - lax[i][j] );\n }\n }\n cout << res << endl;\n \n}", "accuracy": 1, "time_ms": 280, "memory_kb": 23428, "score_of_the_acc": -0.9497, "final_rank": 10 }, { "submission_id": "aoj_DPL_4_B_10769747", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\nint N,K;\nusing ll=long long;\nll L,R,a[40];\nvector<ll>sum[2][20+1];\nsigned main(){\n cin.tie(0)->sync_with_stdio(0);\n cin>>N>>K>>L>>R;\n rep(i,N)cin>>a[i];\n vector<vector<ll>>p(2);\n rep(i,N)p[i%2].emplace_back(a[i]);\n rep(i,2){\n rep(bit,1<<p[i].size()){\n int pc=0;\n ll s=0;\n rep(j,p[i].size()){\n if(bit&(1<<j)){\n ++pc;\n s+=p[i][j];\n }\n }\n sum[i][pc].emplace_back(s);\n }\n }\n rep(i,20+1)sort(sum[1][i].begin(),sum[1][i].end());\n ll ans=0;\n rep(c,20+1){\n int d=K-c;\n if(d<0||20<d)continue;\n for(const auto&s:sum[0][c]){\n ans+=distance(lower_bound(sum[1][d].begin(),sum[1][d].end(),L-s),upper_bound(sum[1][d].begin(),sum[1][d].end(),R-s));\n }\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 270, "memory_kb": 25708, "score_of_the_acc": -0.9874, "final_rank": 13 }, { "submission_id": "aoj_DPL_4_B_10769744", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\nint N,K;\nusing ll=long long;\nll L,R,a[40];\nvector<ll>sum[2][20+1];\nsigned main(){\n cin.tie(0)->sync_with_stdio(0);\n cin>>N>>K>>L>>R;\n rep(i,N)cin>>a[i];\n vector<vector<ll>>p(2);\n rep(i,N)p[i%2].emplace_back(a[i]);\n rep(i,2){\n rep(bit,1<<p[i].size()){\n int pc=0;\n ll s=0;\n rep(j,p[i].size()){\n if(bit&(1<<j)){\n ++pc;\n s+=p[i][j];\n }\n }\n sum[i][pc].emplace_back(s);\n }\n }\n rep(i,20+1)sort(sum[1][i].begin(),sum[1][i].end());\n ll ans=0;\n rep(c,20+1){\n int d=K-c;\n if(d<0||20<d)break;\n for(const auto&s:sum[0][c]){\n ans+=distance(lower_bound(sum[1][d].begin(),sum[1][d].end(),L-s),upper_bound(sum[1][d].begin(),sum[1][d].end(),R-s));\n }\n }\n cout<<ans<<endl;\n}", "accuracy": 0.5625, "time_ms": 30, "memory_kb": 7108, "score_of_the_acc": -0.01, "final_rank": 19 }, { "submission_id": "aoj_DPL_4_B_10769741", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\nint N,K;\nusing ll=long long;\nll L,R,a[40];\nvector<ll>sum[2][20+1];\nsigned main(){\n cin.tie(0)->sync_with_stdio(0);\n cin>>N>>K>>L>>R;\n rep(i,N)cin>>a[i];\n vector<vector<ll>>p(2);\n rep(i,N)p[i%2].emplace_back(a[i]);\n rep(i,2){\n rep(bit,1<<p[i].size()){\n int pc=0;\n ll s=0;\n rep(j,p[i].size()){\n if(bit&(1<<j)){\n ++pc;\n s+=p[i][j];\n }\n }\n sum[i][pc].emplace_back(s);\n }\n }\n rep(i,20+1)sort(sum[1][i].begin(),sum[1][i].end());\n ll ans=0;\n rep(c,20+1){\n int d=K-c;\n if(d<0)break;\n for(const auto&s:sum[0][c]){\n ans+=distance(lower_bound(sum[1][d].begin(),sum[1][d].end(),L-s),upper_bound(sum[1][d].begin(),sum[1][d].end(),R-s));\n }\n }\n cout<<ans<<endl;\n}", "accuracy": 0.59375, "time_ms": 30, "memory_kb": 7108, "score_of_the_acc": -0.01, "final_rank": 17 }, { "submission_id": "aoj_DPL_4_B_10766678", "code_snippet": "#include <bits/stdc++.h>\n\n\nusing namespace std;\n\n\nusing ll = long long;\nusing v_int = vector<int>;\nusing v_ll = vector<long long>;\nusing vv_int = vector<vector<int>>;\nusing vv_ll = vector<vector<long long>>;\nusing vvv_ll =vector<vv_ll>;\nusing p_ii = pair<int,int>;\nusing p_ll = pair<long long,long long>;\nusing v_string = vector<string>;\n\n#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)\n#define sorted(X) sort(X.begin(),X.end())\n#define ALL(a) (a).begin(), (a).end()\n\ntemplate<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }\nlong long INF = 1LL<<60;\n\n\n\nint main(){\n ll t;\n cin >> t;\n\n ll N = t/2;\n ll M = t-N;\n\n ll K,L,R;\n cin >> K >> L>>R;\n\n v_ll A(N);\n v_ll B(M);\n rep(i,N){\n cin >> A[i];\n }\n rep(i,M){\n cin >> B[i];\n }\n\n vv_ll A_com(max(N+1,K+1));\n vv_ll B_com(max(M+1,K+1));\n\n for(ll bit=0;bit<(1LL<<N);bit++){\n ll pop_cnt=0;\n ll sum=0;\n for(ll i=0;i<N;i++){\n if(bit&(1LL<<i)){\n sum += A[i];\n pop_cnt++;\n }\n }\n\n A_com[pop_cnt].push_back(sum);\n }\n for(ll bit=0;bit<(1LL<<M);bit++){\n ll pop_cnt=0;\n ll sum=0;\n for(ll i=0;i<M;i++){\n if(bit&(1LL<<i)){\n sum += B[i];\n pop_cnt++;\n }\n }\n\n B_com[pop_cnt].push_back(sum);\n }\n\n ll ans = 0;\n for(ll i=0;i<=K;i++){\n sort(ALL(B_com[i]));\n }\n\n for(ll i=0;i<=K;i++){\n for(ll j=0;j<A_com[i].size();j++){\n if(R-A_com[i][j] < 0) continue;\n ll Lp = max(L- A_com[i][j],0LL);\n ll Rp = R-A_com[i][j];\n\n auto L_it = lower_bound(ALL(B_com[K-i]),Lp);\n auto R_it= upper_bound(ALL(B_com[K-i]),Rp);\n\n ans += R_it-L_it;\n }\n }\n\n cout << ans << endl;\n\n\n\n\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 23420, "score_of_the_acc": -0.9495, "final_rank": 9 }, { "submission_id": "aoj_DPL_4_B_10750308", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n#define all(a) a.begin(),a.end()\nusing ll = long long;\n\nint main() {\n int N, K; ll L, R;\n cin >> N >> K >> L >> R;\n vector<ll> V(N);\n rep(i,N) cin >> V[i];\n\n int a = N/2, b = N-a;\n vector<pair<int,ll>> A;\n vector<vector<ll>> B(b+1);\n\n for (int bit=0; bit<(1<<a); bit++) {\n int cnt = 0;\n ll price = 0;\n rep(i,a) {\n if ((bit>>i) & 1) {\n cnt++;\n price += V[i];\n }\n }\n A.emplace_back(make_pair(cnt, price));\n }\n for (int bit=0; bit<(1<<b); bit++) {\n int cnt = 0;\n ll price = 0;\n rep(i,b) {\n if ((bit>>i) & 1) {\n cnt++;\n price += V[a+i];\n }\n }\n B[cnt].emplace_back(price);\n }\n\n rep(i,b+1) {\n sort(all(B[i]));\n }\n\n ll ans = 0;\n rep(i, A.size()) {\n int cnt = K - A[i].first;\n ll l = L - A[i].second, r = R - A[i].second;\n if (0 <= cnt && cnt <= b) {\n ans += upper_bound(all(B[cnt]), r) - lower_bound(all(B[cnt]), l);\n }\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 33020, "score_of_the_acc": -1.2792, "final_rank": 15 }, { "submission_id": "aoj_DPL_4_B_10731414", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nconst ll INF = LLONG_MAX / 4;\nconst ll mod1 = 1000000007;\nconst ll mod9 = 998244353;\nconst ll Hash = 10000000000000061;\n#define all(a) (a).begin(),(a).end()\n#define rep(i, n) for (ll i = 0; (i) < (n); ++(i))\n#define reps(i, l, r) for(ll i = (l); (i) < (r); ++(i))\nll dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nll dy[8] = {0, -1, -1, -1, 0, 1, 1, 1};\ntemplate <typename T>\nbool chmax(T &a, const T& b) {\n if (a < b) { a = b; return true; }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T& b) {\n if (a > b) { a = b; return true; }\n return false;\n}\n\n#define EPS (1e-10)\n#define equals(a, b) (fabs((a) - (b)) < EPS)\nclass Point {\npublic:\n ld x;\n ld y;\n Point(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}\n Point operator+(Point p) { return Point(x + p.x, y + p.y); }\n Point operator-(Point p) { return Point(x - p.x, y - p.y); }\n Point operator*(ld a) { return Point(a * x, a * y); }\n Point operator/(ld a) { return Point(x / a, y / a); }\n\n ld abs() { return sqrt(norm()); }\nld norm() { return x * x + y * y; }\n\n bool operator<(const Point& p) const {\n return !equals(x, p.x) ? x < p.x : y < p.y;\n }\n bool operator==(const Point& p) const {\n return fabs(x - p.x) < (1e-10) && fabs(y - p.y) < (1e-10);\n }\n};\ntypedef Point Vector;\nstruct Segment {\n Point A;\n Point B;\n};\ntypedef Segment Line;\nclass Circle {\npublic:\n Point C;\n ld r;\n Circle(Point C = Point(), ld r = 0.0) : C(C), r(r) {}\n};\ntypedef vector<Point> Polygon;\n\nvoid solve(){\n ll N, K, L, R; cin >> N >> K >> L >> R; R++;\n vector<ll> a(N); rep(i, N) cin >> a[i];\n vector<ll> b;\n rep(i, N/2){\n b.push_back(a.back());\n a.pop_back();\n }\n sort(all(a)); sort(all(b));\n ll A = a.size(), B = b.size();\n vector<vector<ll>> c(A+1), d(B+1);\n rep(bit, (1<<A)){\n ll pp = __builtin_popcount(bit);\n ll x = 0;\n rep(i, A){\n if((bit>>i) & 1){\n x += a[i];\n }\n }\n c[pp].push_back(x);\n }\n rep(i, A+1) sort(all(c[i]));\n rep(bit, (1<<B)){\n ll pp = __builtin_popcount(bit);\n ll x = 0;\n rep(i, B){\n if((bit>>i) & 1){\n x += b[i];\n }\n }\n d[pp].push_back(x);\n }\n rep(i, B+1) sort(all(d[i]));\n ll ans = 0;\n rep(i, A+1){\n rep(k, B+1){\n if(i+k != K) continue;\n for(ll x : c[i]){\n ans += (lower_bound(all(d[k]), R - x) - lower_bound(all(d[k]), L-x));\n }\n }\n }\n cout << ans << endl;\n}\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n cout << fixed << setprecision(20);\n \n solve();\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 23084, "score_of_the_acc": -0.795, "final_rank": 5 }, { "submission_id": "aoj_DPL_4_B_10716489", "code_snippet": "// #ifndef ONLINE_JUDGE\n// #define _GLIBCXX_DEBUG//[]で配列外参照をするとエラーにしてくれる。上下のやつがないとTLEになるので注意 ABC311Eのサンプル4みたいなデバック中のTLEは防げないので注意\n// #endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n// #include <atcoder/all>\n// using namespace atcoder;\n\n\ntemplate<typename T> using vc = vector<T>;//prioriy_queueに必要なのでここにこれ書いてます\ntemplate<typename T> using vv = vc<vc<T>>;\n\n//-------------1.型系---------------\nusing ll = long long;\nll INF = 2e18;\n\n// #include <boost/multiprecision/cpp_int.hpp>//インストール的なのをしてないとできないので注意\n// namespace multip = boost::multiprecision;\n// //using lll = multip::cpp_int;//無制限を使いたいときはこっちを使う\n// using lll = multip::int128_t;\n\nusing ld = long double;\nusing bl = bool;\n// using mint = modint998244353;\n//using mint = modint1000000007;\n//using mint = modint;//使うときはコメントアウトを外す\n//mint::set_mod(m);//使うときはコメントアウトを外す\n\ntemplate<class T> using pq = priority_queue<T, vc<T>>;//大きい順\ntemplate<class T> using pq_g = priority_queue<T, vc<T>, greater<T>>;//小さい順\n//-----------------------------------\n\n\n\n//-------------2.配列系--------------\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\nusing vb = vc<bl>; using vvb = vv<bl>; using vvvb = vv<vb>;\nusing vld = vc<ld>; using vvld = vv<ld>; using vvvld = vv<vld>;\nusing pii = pair<int, int>;\nusing pll = pair<ll, ll>;\n// using vmint = vc<mint>; using vvmint = vv<mint>; using vvvmint = vv<vmint>;\n\n//配列外参照対策のやつは一番上の行にあります\n\n#define rep(i,n) for(ll i = 0; i < (n); ++i)//↓でrepを使うので書いてます\ntemplate<class T>istream& operator>>(istream& i, vc<T>& v) { rep(j, size(v))i >> v[j]; return i; }\n\nusing ar2 = array<ll, 2>;\n\n//----------------------------------\n\n\n\n//--------3.コード短縮化とか---------\n#define rep(i,n) for(ll i = 0; i < (n); ++i)\n#define rrep(i,n) for(ll i = 1; i <= (n); ++i)\n#define drep(i,n) for(ll i = (n)-1; i >= 0; --i)\n#define nfor(i,s,n) for(ll i=s;i<n;i++)//i=s,s+1...n-1 ノーマルfor\n#define dfor(i,s,n) for(ll i = (s)-1; i>=n;i--)//s-1スタートでnまで落ちる\n\n#define nall(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n\n#define chmax(x,y) x = max(x,y)\n#define chmin(x,y) x = min(x,y)\n\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n\n\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\n#define YN {cout<<\"Yes\"<<endl;}else{cout<<\"No\"<<endl;}// if(a==b)YN;\n#define dame cout<<-1<<endl\n\n\n#define vc_unique(v) v.erase( unique(v.begin(), v.end()), v.end() );\n#define vc_rotate(v) rotate(v.begin(),v.begin()+1,v.end());\n\n#define pop_cnt(s) ll(popcount(uint64_t(s)))\n\n#define next_p(v) next_permutation(v.begin(),v.end())\n\n//if (regex_match(s, regex(\"\")))YN;//文字列sの判定を行う。コメントアウトを外して「\"\"」の中に判定する内容を入れる\n\n//-------------------------------\n\n\n\n\n//---------4.グリッド系----------\nvl di = { 0,1,0,-1 };//vl di={0,1,1,1,0,-1,-1,-1};\nvl dj = { 1,0,-1,0 };//vl dj={1,1,0,-1,-1,-1,0,1};\n\nbool out_grid(ll i, ll j, ll h, ll w) {//trueならcontinue\n return (!(0 <= i && i < h && 0 <= j && j < w));\n}\n\n#define vvl_kaiten_r(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//時計回りに90°回転\n#define vvl_kaiten_l(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//反時計周りに90°回転\n\n#define vs_kaiten_r(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//文字列版 時計回りに90°回転\n#define vs_kaiten_l(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//文字列版 反時計周りに90°回転\n\n\n#define vvl_tenti(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][i]=v[i][j];swap(nx,v);}\n#define vs_tenti(v) {ll n = size(v); vs nx(n, string(n,'.')); rep(i, n)rep(j, n)nx[j][i] = v[i][j]; swap(nx, v);}\n\n//--------------------------------\n\n\n\n\n//-----------5.数学系--------------\n#define yu_qurid(x,y) ((x)*(x)+(y)*(y))//ユークリッド距離 sqrtはしてないなので注意\n#define mannhattan(x1,x2,y1,y2) (abs(x1-x2)+abs(y1-y2)) // マンハッタン距離 = |x1-x2|+|y1-y2|\n\ntemplate<class T>T tousa_sum1(T l, T d, T r) {//初項,公差,末項 で総和を求める\n T wide = (r - l) / d + 1;\n return (l + r) * wide / 2;\n}\ntemplate<class T>T tousa_sum2(T a, T d, T n) {//初項,交差,項数 で総和を求める\n return (a * 2 + d * (n - 1)) * n / 2;\n}\nll kousa_kousuu(ll l, ll r, ll d) {//初項,末項,交差 で等差数列の項数を求める\n return (r - l) / d + 1;\n}\n// mint touhi_sum(mint a, mint r, ll n) {//初項,公比,項数で等比数列の総和を求める\n// if (r == 1) {\n// return a * n;\n// }\n// mint bunsi = a * (r.pow(n) - mint(1));\n// mint bunbo = r - 1;\n// return bunsi / bunbo;\n// }\n\nll nc2(ll x) { return x * (x - 1) / 2; }\nll nc3(ll x) { return x * (x - 1) * (x - 2) / 6; }\n\n//----------------------------------------------\n\n\n\n\n//-----------6.デバックや出力系------------------\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\nvoid mukou_debug(vvl to, bool yukou) {//GRAPH × GRAPH用の無向グラフを出力する\n ll n = size(to); ll cnt = 0;//辺の本数\n vc<pair<ll, ll>>v; rep(i, n)for (ll t : to[i]) if (i < t || yukou)cnt++, v.eb(i + 1, t + 1);//有向グラフなら全部OK、違うなら無向なのでf<tのみ見る、using Pのやつを別のにしたいときのためにPを使わずにpair<ll,ll>にしてる\n cout << n << ' ' << cnt << endl; for (auto [f, t] : v)cout << f << ' ' << t << endl;\n}\n\n#define vc_cout(v){ll n = size(v);rep(i,n)cout<<v[i]<<endl;}//一次元配列を出力する\n#define vv_cout(v){ll n = size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<' ';}cout<<endl;}}//二次元配列を出力する\n\nint main(){\n ll n, k, l, r;\n cin >> n >> k >> l >> r;\n vl a(n);\n rep(i, n) cin >> a[i];\n\n vvl list1(21, vl()), list2(21, vl());\n ll n1 = n/2, n2 = n - n/2;\n\n for(ll bit = 0; bit < (1 << n1); bit++){\n ll cnt = 0, sum = 0;\n rep(i, n1){\n ll mask = (1ll << i);\n if(bit & mask){\n cnt++;\n sum += a[i];\n }\n }\n list1[cnt].pb(sum);\n }\n\n for(ll bit = 0; bit < (1 << n2); bit++){\n ll cnt = 0, sum = 0;\n rep(i, n2){\n ll mask = (1ll << i);\n if(bit & mask){\n cnt++;\n sum += a[i + n1];\n }\n }\n list2[cnt].pb(sum);\n }\n\n for(ll i = 0; i <= n2; i++) sort(nall(list2[i]));\n\n ll ans = 0;\n rep(i, n1+1){\n if(k - i < 0 || i + n2 < k) continue;\n\n for(ll a : list1[i]){\n auto it1 = upper_bound(nall(list2[k-i]), r-a);\n auto it2 = lower_bound(nall(list2[k-i]), l-a);\n\n ans += it1 - it2;\n }\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 23392, "score_of_the_acc": -0.9904, "final_rank": 14 }, { "submission_id": "aoj_DPL_4_B_10716487", "code_snippet": "// #ifndef ONLINE_JUDGE\n// #define _GLIBCXX_DEBUG//[]で配列外参照をするとエラーにしてくれる。上下のやつがないとTLEになるので注意 ABC311Eのサンプル4みたいなデバック中のTLEは防げないので注意\n// #endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n// #include <atcoder/all>\n// using namespace atcoder;\n\n\ntemplate<typename T> using vc = vector<T>;//prioriy_queueに必要なのでここにこれ書いてます\ntemplate<typename T> using vv = vc<vc<T>>;\n\n//-------------1.型系---------------\nusing ll = long long;\nll INF = 2e18;\n\n// #include <boost/multiprecision/cpp_int.hpp>//インストール的なのをしてないとできないので注意\n// namespace multip = boost::multiprecision;\n// //using lll = multip::cpp_int;//無制限を使いたいときはこっちを使う\n// using lll = multip::int128_t;\n\nusing ld = long double;\nusing bl = bool;\n// using mint = modint998244353;\n//using mint = modint1000000007;\n//using mint = modint;//使うときはコメントアウトを外す\n//mint::set_mod(m);//使うときはコメントアウトを外す\n\ntemplate<class T> using pq = priority_queue<T, vc<T>>;//大きい順\ntemplate<class T> using pq_g = priority_queue<T, vc<T>, greater<T>>;//小さい順\n//-----------------------------------\n\n\n\n//-------------2.配列系--------------\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\nusing vb = vc<bl>; using vvb = vv<bl>; using vvvb = vv<vb>;\nusing vld = vc<ld>; using vvld = vv<ld>; using vvvld = vv<vld>;\nusing pii = pair<int, int>;\nusing pll = pair<ll, ll>;\n// using vmint = vc<mint>; using vvmint = vv<mint>; using vvvmint = vv<vmint>;\n\n//配列外参照対策のやつは一番上の行にあります\n\n#define rep(i,n) for(ll i = 0; i < (n); ++i)//↓でrepを使うので書いてます\ntemplate<class T>istream& operator>>(istream& i, vc<T>& v) { rep(j, size(v))i >> v[j]; return i; }\n\nusing ar2 = array<ll, 2>;\n\n//----------------------------------\n\n\n\n//--------3.コード短縮化とか---------\n#define rep(i,n) for(ll i = 0; i < (n); ++i)\n#define rrep(i,n) for(ll i = 1; i <= (n); ++i)\n#define drep(i,n) for(ll i = (n)-1; i >= 0; --i)\n#define nfor(i,s,n) for(ll i=s;i<n;i++)//i=s,s+1...n-1 ノーマルfor\n#define dfor(i,s,n) for(ll i = (s)-1; i>=n;i--)//s-1スタートでnまで落ちる\n\n#define nall(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n\n#define chmax(x,y) x = max(x,y)\n#define chmin(x,y) x = min(x,y)\n\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n\n\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\n#define YN {cout<<\"Yes\"<<endl;}else{cout<<\"No\"<<endl;}// if(a==b)YN;\n#define dame cout<<-1<<endl\n\n\n#define vc_unique(v) v.erase( unique(v.begin(), v.end()), v.end() );\n#define vc_rotate(v) rotate(v.begin(),v.begin()+1,v.end());\n\n#define pop_cnt(s) ll(popcount(uint64_t(s)))\n\n#define next_p(v) next_permutation(v.begin(),v.end())\n\n//if (regex_match(s, regex(\"\")))YN;//文字列sの判定を行う。コメントアウトを外して「\"\"」の中に判定する内容を入れる\n\n//-------------------------------\n\n\n\n\n//---------4.グリッド系----------\nvl di = { 0,1,0,-1 };//vl di={0,1,1,1,0,-1,-1,-1};\nvl dj = { 1,0,-1,0 };//vl dj={1,1,0,-1,-1,-1,0,1};\n\nbool out_grid(ll i, ll j, ll h, ll w) {//trueならcontinue\n return (!(0 <= i && i < h && 0 <= j && j < w));\n}\n\n#define vvl_kaiten_r(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//時計回りに90°回転\n#define vvl_kaiten_l(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//反時計周りに90°回転\n\n#define vs_kaiten_r(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//文字列版 時計回りに90°回転\n#define vs_kaiten_l(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//文字列版 反時計周りに90°回転\n\n\n#define vvl_tenti(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][i]=v[i][j];swap(nx,v);}\n#define vs_tenti(v) {ll n = size(v); vs nx(n, string(n,'.')); rep(i, n)rep(j, n)nx[j][i] = v[i][j]; swap(nx, v);}\n\n//--------------------------------\n\n\n\n\n//-----------5.数学系--------------\n#define yu_qurid(x,y) ((x)*(x)+(y)*(y))//ユークリッド距離 sqrtはしてないなので注意\n#define mannhattan(x1,x2,y1,y2) (abs(x1-x2)+abs(y1-y2)) // マンハッタン距離 = |x1-x2|+|y1-y2|\n\ntemplate<class T>T tousa_sum1(T l, T d, T r) {//初項,公差,末項 で総和を求める\n T wide = (r - l) / d + 1;\n return (l + r) * wide / 2;\n}\ntemplate<class T>T tousa_sum2(T a, T d, T n) {//初項,交差,項数 で総和を求める\n return (a * 2 + d * (n - 1)) * n / 2;\n}\nll kousa_kousuu(ll l, ll r, ll d) {//初項,末項,交差 で等差数列の項数を求める\n return (r - l) / d + 1;\n}\n// mint touhi_sum(mint a, mint r, ll n) {//初項,公比,項数で等比数列の総和を求める\n// if (r == 1) {\n// return a * n;\n// }\n// mint bunsi = a * (r.pow(n) - mint(1));\n// mint bunbo = r - 1;\n// return bunsi / bunbo;\n// }\n\nll nc2(ll x) { return x * (x - 1) / 2; }\nll nc3(ll x) { return x * (x - 1) * (x - 2) / 6; }\n\n//----------------------------------------------\n\n\n\n\n//-----------6.デバックや出力系------------------\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\nvoid mukou_debug(vvl to, bool yukou) {//GRAPH × GRAPH用の無向グラフを出力する\n ll n = size(to); ll cnt = 0;//辺の本数\n vc<pair<ll, ll>>v; rep(i, n)for (ll t : to[i]) if (i < t || yukou)cnt++, v.eb(i + 1, t + 1);//有向グラフなら全部OK、違うなら無向なのでf<tのみ見る、using Pのやつを別のにしたいときのためにPを使わずにpair<ll,ll>にしてる\n cout << n << ' ' << cnt << endl; for (auto [f, t] : v)cout << f << ' ' << t << endl;\n}\n\n#define vc_cout(v){ll n = size(v);rep(i,n)cout<<v[i]<<endl;}//一次元配列を出力する\n#define vv_cout(v){ll n = size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<' ';}cout<<endl;}}//二次元配列を出力する\n\nint main(){\n ll n, k, l, r;\n cin >> n >> k >> l >> r;\n vl a(n);\n rep(i, n) cin >> a[i];\n\n vvl list1(21, vl()), list2(21, vl());\n ll n1 = n/2, n2 = n - n/2;\n\n for(ll bit = 0; bit < (1 << n1); bit++){\n ll cnt = 0, sum = 0;\n rep(i, n1){\n ll mask = (1ll << i);\n if(bit & mask){\n cnt++;\n sum += a[i];\n }\n }\n list1[cnt].pb(sum);\n }\n for(ll bit = 0; bit < (1 << n2); bit++){\n ll cnt = 0, sum = 0;\n rep(i, n2){\n ll mask = (1ll << i);\n if(bit & mask){\n cnt++;\n sum += a[i + n1];\n }\n }\n list2[cnt].pb(sum);\n }\n\n for(ll i = 0; i <= n2; i++) sort(nall(list2[i]));\n\n ll ans = 0;\n rep(i, n1+1){\n for(ll a : list1[i]){\n auto it1 = upper_bound(nall(list2[k-i]), r-a);\n auto it2 = lower_bound(nall(list2[k-i]), l-a);\n\n ans += it1 - it2;\n }\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 0.5625, "time_ms": 30, "memory_kb": 6720, "score_of_the_acc": 0, "final_rank": 18 }, { "submission_id": "aoj_DPL_4_B_10699695", "code_snippet": "// #ifndef ONLINE_JUDGE\n// #define _GLIBCXX_DEBUG//[]で配列外参照をするとエラーにしてくれる。上下のやつがないとTLEになるので注意 ABC311Eのサンプル4みたいなデバック中のTLEは防げないので注意\n// #endif\n\n#include <bits/stdc++.h>\nusing namespace std;\n// #include <atcoder/all>\n// using namespace atcoder;\n\n\ntemplate<typename T> using vc = vector<T>;//prioriy_queueに必要なのでここにこれ書いてます\ntemplate<typename T> using vv = vc<vc<T>>;\n\n//-------------1.型系---------------\nusing ll = long long;\nll INF = 2e18;\n\n// #include <boost/multiprecision/cpp_int.hpp>//インストール的なのをしてないとできないので注意\n// namespace multip = boost::multiprecision;\n// //using lll = multip::cpp_int;//無制限を使いたいときはこっちを使う\n// using lll = multip::int128_t;\n\nusing ld = long double;\nusing bl = bool;\n// using mint = modint998244353;\n//using mint = modint1000000007;\n//using mint = modint;//使うときはコメントアウトを外す\n//mint::set_mod(m);//使うときはコメントアウトを外す\n\ntemplate<class T> using pq = priority_queue<T, vc<T>>;//大きい順\ntemplate<class T> using pq_g = priority_queue<T, vc<T>, greater<T>>;//小さい順\n//-----------------------------------\n\n\n\n//-------------2.配列系--------------\nusing vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>; using vvvvl = vv<vvl>;\nusing vs = vc<string>; using vvs = vv<string>;\nusing vb = vc<bl>; using vvb = vv<bl>; using vvvb = vv<vb>;\nusing vld = vc<ld>; using vvld = vv<ld>; using vvvld = vv<vld>;\nusing pii = pair<int, int>;\nusing pll = pair<ll, ll>;\n// using vmint = vc<mint>; using vvmint = vv<mint>; using vvvmint = vv<vmint>;\n\n//配列外参照対策のやつは一番上の行にあります\n\n#define rep(i,n) for(ll i = 0; i < (n); ++i)//↓でrepを使うので書いてます\ntemplate<class T>istream& operator>>(istream& i, vc<T>& v) { rep(j, size(v))i >> v[j]; return i; }\n\nusing ar2 = array<ll, 2>;\n\n//----------------------------------\n\n\n\n//--------3.コード短縮化とか---------\n#define rep(i,n) for(ll i = 0; i < (n); ++i)\n#define rrep(i,n) for(ll i = 1; i <= (n); ++i)\n#define drep(i,n) for(ll i = (n)-1; i >= 0; --i)\n#define nfor(i,s,n) for(ll i=s;i<n;i++)//i=s,s+1...n-1 ノーマルfor\n#define dfor(i,s,n) for(ll i = (s)-1; i>=n;i--)//s-1スタートでnまで落ちる\n\n#define nall(a) a.begin(),a.end()\n#define rall(a) a.rbegin(),a.rend()\n\n#define chmax(x,y) x = max(x,y)\n#define chmin(x,y) x = min(x,y)\n\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n\n\n#define YES cout<<\"Yes\"<<endl\n#define NO cout<<\"No\"<<endl\n#define YN {cout<<\"Yes\"<<endl;}else{cout<<\"No\"<<endl;}// if(a==b)YN;\n#define dame cout<<-1<<endl\n\n\n#define vc_unique(v) v.erase( unique(v.begin(), v.end()), v.end() );\n#define vc_rotate(v) rotate(v.begin(),v.begin()+1,v.end());\n\n#define pop_cnt(s) ll(popcount(uint64_t(s)))\n\n#define next_p(v) next_permutation(v.begin(),v.end())\n\n//if (regex_match(s, regex(\"\")))YN;//文字列sの判定を行う。コメントアウトを外して「\"\"」の中に判定する内容を入れる\n\n//-------------------------------\n\n\n\n\n//---------4.グリッド系----------\nvl di = { 0,1,0,-1 };//vl di={0,1,1,1,0,-1,-1,-1};\nvl dj = { 1,0,-1,0 };//vl dj={1,1,0,-1,-1,-1,0,1};\n\nbool out_grid(ll i, ll j, ll h, ll w) {//trueならcontinue\n return (!(0 <= i && i < h && 0 <= j && j < w));\n}\n\n#define vvl_kaiten_r(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//時計回りに90°回転\n#define vvl_kaiten_l(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//反時計周りに90°回転\n\n#define vs_kaiten_r(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[j][n-i-1]=v[i][j];swap(nx,v);}//文字列版 時計回りに90°回転\n#define vs_kaiten_l(v) {ll n = size(v);vs nx(n,string(n,'.'));rep(i,n)rep(j,n)nx[n-j-1][i]=v[i][j];swap(nx,v);}//文字列版 反時計周りに90°回転\n\n\n#define vvl_tenti(v) {ll n = size(v);vvl nx(n,vl(n));rep(i,n)rep(j,n)nx[j][i]=v[i][j];swap(nx,v);}\n#define vs_tenti(v) {ll n = size(v); vs nx(n, string(n,'.')); rep(i, n)rep(j, n)nx[j][i] = v[i][j]; swap(nx, v);}\n\n//--------------------------------\n\n\n\n\n//-----------5.数学系--------------\n#define yu_qurid(x,y) ((x)*(x)+(y)*(y))//ユークリッド距離 sqrtはしてないなので注意\n#define mannhattan(x1,x2,y1,y2) (abs(x1-x2)+abs(y1-y2)) // マンハッタン距離 = |x1-x2|+|y1-y2|\n\ntemplate<class T>T tousa_sum1(T l, T d, T r) {//初項,公差,末項 で総和を求める\n T wide = (r - l) / d + 1;\n return (l + r) * wide / 2;\n}\ntemplate<class T>T tousa_sum2(T a, T d, T n) {//初項,交差,項数 で総和を求める\n return (a * 2 + d * (n - 1)) * n / 2;\n}\nll kousa_kousuu(ll l, ll r, ll d) {//初項,末項,交差 で等差数列の項数を求める\n return (r - l) / d + 1;\n}\n// mint touhi_sum(mint a, mint r, ll n) {//初項,公比,項数で等比数列の総和を求める\n// if (r == 1) {\n// return a * n;\n// }\n// mint bunsi = a * (r.pow(n) - mint(1));\n// mint bunbo = r - 1;\n// return bunsi / bunbo;\n// }\n\nll nc2(ll x) { return x * (x - 1) / 2; }\nll nc3(ll x) { return x * (x - 1) * (x - 2) / 6; }\n\n//----------------------------------------------\n\n\n\n\n//-----------6.デバックや出力系------------------\nvoid print(ld x) { printf(\"%.20Lf\\n\", x); }\n\nvoid mukou_debug(vvl to, bool yukou) {//GRAPH × GRAPH用の無向グラフを出力する\n ll n = size(to); ll cnt = 0;//辺の本数\n vc<pair<ll, ll>>v; rep(i, n)for (ll t : to[i]) if (i < t || yukou)cnt++, v.eb(i + 1, t + 1);//有向グラフなら全部OK、違うなら無向なのでf<tのみ見る、using Pのやつを別のにしたいときのためにPを使わずにpair<ll,ll>にしてる\n cout << n << ' ' << cnt << endl; for (auto [f, t] : v)cout << f << ' ' << t << endl;\n}\n\n#define vc_cout(v){ll n = size(v);rep(i,n)cout<<v[i]<<endl;}//一次元配列を出力する\n#define vv_cout(v){ll n = size(v);rep(i,n){rep(j,size(v[i])){cout<<v[i][j]<<' ';}cout<<endl;}}//二次元配列を出力する\n\nvoid rec(vl &a, ll i, ll cnt, ll n, ll val, vl &res){\n if(cnt == n){\n res.pb(val);\n return;\n }\n\n for(ll j = i; j < a.size(); j++){\n if (a.size() - i < n - cnt) break;\n rec(a, j+1, cnt+1, n, val+a[j], res);\n }\n\n return;\n}\n\nint main(){\n ll n, k, l, r;\n cin >> n >> k >> l >> r;\n vl a(n);\n rep(i, n) cin >> a[i];\n\n vl b, c;\n rep(i, n/2){\n b.pb(a[i]);\n }\n nfor(i, n/2, n){\n c.pb(a[i]);\n }\n\n ll ans = 0;\n for(ll kk = 0; kk <= k; kk++){\n if(b.size() < kk || c.size() < k-kk) continue;\n\n vl bb, cc;\n\n if (kk == 0) bb.pb(0); else rec(b, 0, 0, kk, 0, bb);\n if (k - kk == 0) cc.pb(0); else rec(c, 0, 0, k - kk, 0, cc);\n\n sort(nall(cc));\n\n for(ll x : bb){\n ll i = lower_bound(nall(cc), l-x) - cc.begin();\n ll j = upper_bound(nall(cc), r-x) - cc.begin();\n\n ans += j - i;\n }\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 8096, "score_of_the_acc": -0.4312, "final_rank": 1 }, { "submission_id": "aoj_DPL_4_B_10468141", "code_snippet": "// #include <atcoder/all>\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconstexpr ll inf = (1LL << 61);\nll dx[4] = {0, 1, 0, -1};\nll dy[4] = {-1, 0, 1, 0};\n#define rep(i, n) for (ll i = 0; i < (ll)(n); ++i)\n#define REP(i, init, n) for (ll i = (ll)init; i < (ll)(n); ++i)\n// ll op(ll a, ll b) { return min(a, b); }\n// ll e() { return inf; }\n\nll a[200005];\nint main() {\n ll n, k, l, r;\n cin >> n >> k >> l >> r;\n rep(i, n) cin >> a[i];\n ll L = n / 2, R = n - L;\n vector<vector<ll>> left(L + 1);\n rep(i, 1 << L) {\n ll cnt = 0, sum = 0;\n rep(j, L) {\n if (i & (1 << j)) {\n sum += a[j];\n cnt++;\n }\n }\n left[cnt].push_back(sum);\n }\n for (auto& v : left) sort(v.begin(), v.end());\n ll ans = 0;\n rep(i, 1 << R) {\n ll cnt = 0, sum = 0;\n rep(j, R) {\n if (i & (1 << j)) {\n sum += a[L + j];\n cnt++;\n }\n }\n ll need = k - cnt;\n if (need < 0 || need > L) continue;\n auto it = lower_bound(left[need].begin(), left[need].end(), l - sum);\n auto it2 = upper_bound(left[need].begin(), left[need].end(), r - sum);\n ans += it2 - it;\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 330, "memory_kb": 12612, "score_of_the_acc": -0.7762, "final_rank": 4 }, { "submission_id": "aoj_DPL_4_B_10282958", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing lli=long long int;\nusing ld=long double;\nusing vi=vector<int>;\nusing vvi=vector<vi>;\nusing vvvi=vector<vvi>;\nusing vvvvi=vector<vvvi>;\nusing vl=vector<lli>;\nusing vvl=vector<vl>;\nusing vb=vector<bool>;\nusing vvb=vector<vb>;\n#define rep(i,s,e) for(int i=s;i<e;i++)\n#define repl(i,s,e) for(lli i=s;i<e;i++)\n#define rrep(i,s,e) for(int i=s-1;i>=e;i--)\n#define in(v,seq) for(auto v:seq)\n#define veci(v,s) vi v(s); rep(i,0,s) cin >> v.at(i);\n#define vecl(v,s) vl v(s); rep(i,0,s) cin >> v.at(i);\n#define all(s) s.begin(),s.end()\n#define rall(s) s.rbegin(),s.rend()\nusing pii=pair<int,int>;\nusing pll=pair<lli,lli>;\n#define mp(f,s) make_pair(f,s)\n#define fi first\n#define se second\nusing vpii=vector<pii>;\nusing vpll=vector<pll>;\n#define vecpii(v,s) vpii v(s); rep(i,0,s) cin >> v.at(i).fi >> v.at(i).se;\n#define vecpll(v,s) vpll v(s); rep(i,0,s) cin >> v.at(i).fi >> v.at(i).se;\n#define pub(x) push_back(x)\n#define puf(x) push_front(x)\n#define pob(x) pop_back(x)\n#define pof(x) pop_front(x)\n#define emb(x) emplace_back(x)\n#define print(s) cout << s << endl;\nconst int I_INF=1<<30;\nconst lli LL_INF=1ll<<60;\nconst string alp=\"abcdefghijklmnopqrstuvwxyz\";\nconst int let=alp.size(); // 26\n\nint main(){\n int n,k; lli l,r; //[l,r]\n cin >> n >> k >> l >> r;\n int x=n/2,y=n-x;\n vecl(a,x); vecl(b,y);\n vvl mitm(x+1);\n\n rep(i,0,(1<<x)){\n lli res=0; int pc=0;\n rep(j,0,x){\n if(i&(1<<j)){\n res+=a.at(j);\n pc++;\n }\n }\n mitm.at(pc).pub(res);\n }\n\n in(&v,mitm){\n sort(all(v));\n }\n\n lli ans=0;\n repl(i,0,(1<<y)){\n lli res=0; int pc=k;\n rep(j,0,y){\n if(i&(1<<j)){\n res+=b.at(j);\n pc--;\n }\n }\n if(pc<0 || x<pc) continue;\n int L=lower_bound(all(mitm.at(pc)),l-res)-mitm.at(pc).begin();\n int R=upper_bound(all(mitm.at(pc)),r-res)-mitm.at(pc).begin();\n ans+=(lli)(R-L);\n }\n\n print(ans);\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 12588, "score_of_the_acc": -0.7548, "final_rank": 3 } ]
aoj_CGL_3_C_cpp
Polygon-Point-Containment For a given polygon g and target points t , print "2" if g contains t , "1" if t is on a segment of g , "0" otherwise. g is represented by a sequence of points p 1 , p 2 ,..., p n where line segments connecting p i and p i+1 (1 ≤ i ≤ n-1 ) are sides of the polygon. The line segment connecting p n and p 1 is also a side of the polygon. Note that the polygon is not necessarily convex. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : q th query g is given by coordinates of the points p 1 ,..., p n in the following format: n x 1 y 1 x 2 y 2 : x n y n The first integer n is the number of points. The coordinate of a point p i is given by two integers x i and y i . The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t . The coordinate is given by two intgers x and y . Output For each query, print "2", "1" or "0". Constraints 3 ≤ n ≤ 100 1 ≤ q ≤ 1000 -10000 ≤ x i , y i ≤ 10000 No point of the polygon will occur more than once. Two sides of the polygon can intersect only at a common endpoint. Sample Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Sample Output 2 1 0
[ { "submission_id": "aoj_CGL_3_C_10650599", "code_snippet": "# 1 \"tmp.cpp\"\n#include <bits/stdc++.h>\nusing namespace std;\n#include <atcoder/all>\nusing namespace atcoder;\n#define ll long long\n#define ld long double\n#define out(x) cout<<x<<'\\n'\n#define all(v) v.begin(),v.end()\n#define rep(i,n) for(int i=0;i<(ll)(n);i++)\ntemplate<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};\ntemplate<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};\nconst ll INF=(1LL<<60);\nconst ll mod=998244353;\nusing Graph = vector<vector<ll>>;\nusing Network = vector<vector<pair<ll,ll>>>;\nusing Grid = vector<string>;\nconst vector<ll> dx = {0, 1, 0, -1};\nconst vector<ll> dy = {1, 0, -1, 0};\n# 27 \"tmp.cpp\"\n#ifndef M_PI\n#define M_PI 3.14159265358979323846L\n#endif\nnamespace geo {\ntemplate <typename T> struct Point;\ntemplate <typename T> struct Vector;\ntemplate <typename T> struct Line;\ntemplate <typename T> struct Segment;\ntemplate <typename T> struct Circle;\ntemplate <typename T> struct Polygon;\ntemplate <typename T> class ConvexPolygon;\ntemplate <typename T> constexpr T EPS = 0;\ntemplate <> constexpr long double EPS<long double> = 1e-9;\n# 55 \"tmp.cpp\"\ntemplate <typename T>\nint sgn(T d) {\n if (d > EPS<T>) return 1;\n if (d < -EPS<T>) return -1;\n return 0;\n}\nenum class CCW : int {\n COUNTER_CLOCKWISE = 1,\n CLOCKWISE = -1,\n ONLINE_BACK = 2,\n ONLINE_FRONT = -2,\n ON_SEGMENT = 0\n};\nenum class Containment {\n INSIDE = 0,\n OUTSIDE = 1,\n ON_BOUNDARY = 2\n};\nenum class CollinearHandling {\n INCLUDE,\n EXCLUDE\n};\ntemplate <typename T>\nstruct Point {\n T x, y;\n Point() : x(0), y(0) {}\n Point(T x, T y) : x(x), y(y) {}\n Point(const Vector<T>& v) : x(v.x), y(v.y) {}\n Point<T>& operator+=(const Vector<T>& v);\n Point<T>& operator-=(const Vector<T>& v);\n Point<T>& operator*=(T s);\n Point<T>& operator/=(T s);\n T norm() const { return x * x + y * y; }\n T dist2(const Point<T>& p) const { return (*this - p).norm(); }\n long double abs() const { if constexpr (std::is_floating_point_v<T>) { return std::sqrt(static_cast<long double>(norm())); } else { static_assert(!sizeof(T), \"abs() is only available for floating point types.\"); return 0; } }\n long double dist(const Point<T>& p) const { if constexpr (std::is_floating_point_v<T>) { return (*this - p).abs(); } else { static_assert(!sizeof(T), \"dist() is only available for floating point types.\"); return 0; } }\n long double angle() const { if constexpr (std::is_floating_point_v<T>) { return std::atan2(y, x); } else { static_assert(!sizeof(T), \"angle() is only available for floating point types.\"); return 0; } }\n Point<T> project(const Line<T>& l) const;\n Point<T> reflect(const Line<T>& l) const;\n Point<T> rotate(long double rad) const;\n};\ntemplate <typename T>\nstruct Vector {\n T x, y;\n Vector() : x(0), y(0) {}\n Vector(T x, T y) : x(x), y(y) {}\n Vector(const Point<T>& p) : x(p.x), y(p.y) {}\n Vector(const Point<T>& p1, const Point<T>& p2) : x(p2.x - p1.x), y(p2.y - p1.y) {}\n Vector<T>& operator+=(const Vector<T>& v);\n Vector<T>& operator-=(const Vector<T>& v);\n Vector<T>& operator*=(T s);\n Vector<T>& operator/=(T s);\n T norm() const { return x * x + y * y; }\n long double abs() const { if constexpr (std::is_floating_point_v<T>) { return std::sqrt(static_cast<long double>(norm())); } else { static_assert(!sizeof(T), \"abs() is only available for floating point types.\"); return 0; } }\n long double angle() const { if constexpr (std::is_floating_point_v<T>) { return std::atan2(y, x); } else { static_assert(!sizeof(T), \"angle() is only available for floating point types.\"); return 0; } }\n Vector<T> rotate(long double rad) const;\n Vector<T> unit() const { if constexpr (std::is_floating_point_v<T>) { return *this / static_cast<T>(abs()); } else { static_assert(!sizeof(T), \"unit() is only available for floating point types.\"); return *this; } }\n Vector<T> normal() const { if constexpr (std::is_floating_point_v<T>) { return perp().unit(); } else { static_assert(!sizeof(T), \"normal() is only available for floating point types.\"); return *this; } }\n Vector<T> perp() const { return Vector<T>(-y, x); }\n T dot(const Vector<T>& v) const { return x * v.x + y * v.y; }\n T cross(const Vector<T>& v) const { return x * v.y - y * v.x; }\n};\ntemplate <typename T> Point<T> operator+(Point<T> p, const Vector<T>& v) { return p += v; }\ntemplate <typename T> Point<T> operator-(Point<T> p, const Vector<T>& v) { return p -= v; }\ntemplate <typename T> Vector<T> operator-(const Point<T>& p1, const Point<T>& p2) { return Vector<T>(p1.x - p2.x, p1.y - p2.y); }\ntemplate <typename T> Vector<T> operator+(Vector<T> v1, const Vector<T>& v2) { return v1 += v2; }\ntemplate <typename T> Vector<T> operator-(Vector<T> v1, const Vector<T>& v2) { return v1 -= v2; }\ntemplate <typename T> Vector<T> operator*(const Vector<T>& v, T s) { auto t = v; return t *= s; }\ntemplate <typename T> Vector<T> operator*(T s, const Vector<T>& v) { return v * s; }\ntemplate <typename T> Vector<T> operator/(const Vector<T>& v, T s) { auto t = v; return t /= s; }\ntemplate <typename T> Point<T> operator+(const Point<T>& p1, const Point<T>& p2) { return Point<T>(p1.x + p2.x, p1.y + p2.y); }\ntemplate <typename T> Point<T> operator*(const Point<T>& p, T s) { return Point<T>(p.x * s, p.y * s); }\ntemplate <typename T> Point<T> operator*(T s, const Point<T>& p) { return p * s; }\ntemplate <typename T> Point<T> operator/(const Point<T>& p, T s) { return Point<T>(p.x / s, p.y / s); }\ntemplate <typename T> bool operator<(const Point<T>& p1, const Point<T>& p2) { if (p1.x != p2.x) return p1.x < p2.x; return p1.y < p2.y; }\ntemplate <typename T> bool operator==(const Point<T>& p1, const Point<T>& p2) { return p1.x == p2.x && p1.y == p2.y; }\ntemplate <typename T> bool operator!=(const Point<T>& p1, const Point<T>& p2) { return !(p1 == p2); }\ntemplate <typename T> bool operator>(const Point<T>& p1, const Point<T>& p2) { return p2 < p1; }\ntemplate <typename T> bool operator<=(const Point<T>& p1, const Point<T>& p2) { return !(p1 > p2); }\ntemplate <typename T> bool operator>=(const Point<T>& p1, const Point<T>& p2) { return !(p1 < p2); }\ntemplate <typename T> bool operator<(const Vector<T>& v1, const Vector<T>& v2) { if (v1.x != v2.x) return v1.x < v2.x; return v1.y < v2.y; }\ntemplate <typename T> bool operator==(const Vector<T>& v1, const Vector<T>& v2) { return v1.x == v2.x && v1.y == v2.y; }\ntemplate <typename T> bool operator!=(const Vector<T>& v1, const Vector<T>& v2) { return !(v1 == v2); }\ntemplate <typename T> std::istream& operator>>(std::istream& is, Point<T>& p) { is >> p.x >> p.y; return is; }\ntemplate <typename T> std::ostream& operator<<(std::ostream& os, const Point<T>& p) { os << std::fixed << std::setprecision(15) << p.x << \" \" << p.y; return os; }\ntemplate <typename T> std::ostream& operator<<(std::ostream& os, const Vector<T>& v) { os << std::fixed << std::setprecision(15) << v.x << \" \" << v.y; return os; }\ntemplate <typename T> std::string debug_format(const Point<T>& p) { std::stringstream ss; ss << std::fixed << std::setprecision(8) << \"Point(\" << p.x << \", \" << p.y << \")\"; return ss.str(); }\ntemplate <typename T> std::string debug_format(const Vector<T>& v) { std::stringstream ss; ss << std::fixed << std::setprecision(8) << \"Vector[\" << v.x << \", \" << v.y << \"]\"; return ss.str(); }\ntemplate <typename T> bool eq(T a, T b) { return sgn(a - b) == 0; }\ntemplate <typename T> bool lt(T a, T b) { return sgn(a - b) < 0; }\ntemplate <typename T> bool gt(T a, T b) { return sgn(a - b) > 0; }\ntemplate <typename T> bool le(T a, T b) { return sgn(a - b) <= 0; }\ntemplate <typename T> bool ge(T a, T b) { return sgn(a - b) >= 0; }\ntemplate <typename T> bool eq(const Point<T>& p1, const Point<T>& p2) { return eq(p1.x, p2.x) && eq(p1.y, p2.y); }\ntemplate <typename T> bool eq(const Vector<T>& v1, const Vector<T>& v2) { return eq(v1.x, v2.x) && eq(v1.y, v2.y); }\ntemplate <typename T> T dot(const Vector<T>& v1, const Vector<T>& v2) { return v1.x * v2.x + v1.y * v2.y; }\ntemplate <typename T> T dot(const Point<T>& p1, const Point<T>& p2) { return p1.x * p2.x + p1.y * p2.y; }\ntemplate <typename T> T cross(const Vector<T>& v1, const Vector<T>& v2) { return v1.x * v2.y - v1.y * v2.x; }\ntemplate <typename T> T cross(const Point<T>& p1, const Point<T>& p2) { return p1.x * p2.y - p1.y * p2.x; }\n# 215 \"tmp.cpp\"\ntemplate <typename T>\nCCW ccw(const Point<T>& p0, const Point<T>& p1, const Point<T>& p2) {\n Vector<T> a = p1 - p0;\n Vector<T> b = p2 - p0;\n if (gt(cross(a, b), (T)0)) return CCW::COUNTER_CLOCKWISE;\n if (lt(cross(a, b), (T)0)) return CCW::CLOCKWISE;\n if (lt(dot(a, b), (T)0)) return CCW::ONLINE_BACK;\n if (lt(a.norm(), b.norm())) return CCW::ONLINE_FRONT;\n return CCW::ON_SEGMENT;\n}\ntemplate<typename T> Point<T>& Point<T>::operator+=(const Vector<T>& v) { x += v.x; y += v.y; return *this; }\ntemplate<typename T> Point<T>& Point<T>::operator-=(const Vector<T>& v) { x -= v.x; y -= v.y; return *this; }\ntemplate<typename T> Point<T>& Point<T>::operator*=(T s) { x *= s; y *= s; return *this; }\ntemplate<typename T> Point<T>& Point<T>::operator/=(T s) { x /= s; y /= s; return *this; }\ntemplate <typename T> Point<T> Point<T>::rotate(long double rad) const { if constexpr (std::is_floating_point_v<T>) { long double cs = std::cos(rad), sn = std::sin(rad); return Point<T>(this->x * cs - this->y * sn, this->x * sn + this->y * cs); } else { static_assert(!sizeof(T), \"rotate() is only available for floating point types.\"); return *this; } }\ntemplate<typename T> Vector<T>& Vector<T>::operator+=(const Vector<T>& v) { x += v.x; y += v.y; return *this; }\ntemplate<typename T> Vector<T>& Vector<T>::operator-=(const Vector<T>& v) { x -= v.x; y -= v.y; return *this; }\ntemplate<typename T> Vector<T>& Vector<T>::operator*=(T s) { x *= s; y *= s; return *this; }\ntemplate<typename T> Vector<T>& Vector<T>::operator/=(T s) { x /= s; y /= s; return *this; }\ntemplate <typename T> Vector<T> Vector<T>::rotate(long double rad) const { if constexpr (std::is_floating_point_v<T>) { long double cs = std::cos(rad), sn = std::sin(rad); return Vector<T>(x * cs - y * sn, x * sn + y * cs); } else { static_assert(!sizeof(T), \"rotate() is only available for floating point types.\"); return *this; } }\n}\n#if defined(__GNUC__) || defined(__clang__)\nnamespace sub_rational {\nstd::ostream& operator<<(std::ostream& os, __int128_t val) {\n if (!os.good()) return os;\n if (val == 0) return os << \"0\";\n std::string s = \"\";\n bool neg = val < 0;\n if (neg) val = -val;\n while (val > 0) {\n s += (val % 10) + '0';\n val /= 10;\n }\n if (neg) s += '-';\n std::reverse(s.begin(), s.end());\n return os << s;\n}\nstd::istream& operator>>(std::istream& is, __int128_t& val) {\n if (!is.good()) return is;\n std::string s;\n is >> s;\n val = 0;\n bool neg = s.length() > 0 && s[0] == '-';\n for (size_t i = (neg ? 1 : 0); i < s.length(); ++i) {\n if (isdigit(s[i])) {\n val = val * 10 + (s[i] - '0');\n }\n }\n if (neg) val = -val;\n return is;\n}\nconstexpr __int128_t gcd_128(__int128_t a, __int128_t b) {\n a = a < 0 ? -a : a;\n b = b < 0 ? -b : b;\n while (b) {\n a %= b;\n std::swap(a, b);\n }\n return a;\n}\n}\n#endif\ntemplate <typename T = long long>\nclass Rational {\nprivate:\n T num;\n T den;\n using int128 = __int128_t;\n template <typename IntT>\n static constexpr IntT abs_for_rational(IntT val) {\n return val < 0 ? -val : val;\n }\n constexpr void normalize() {\n if (den == 0) {\n throw std::domain_error(\"Denominator is zero in Rational number\");\n }\n if (den < 0) {\n num = -num;\n den = -den;\n }\n if (num == 0) {\n den = 1;\n return;\n }\n T common = std::gcd(std::abs(num), den);\n num /= common;\n den /= common;\n }\npublic:\n constexpr Rational(T n = 0) : num(n), den(1) {}\n constexpr Rational(T n, T d) : num(n), den(d) { normalize(); }\n template <typename U,\n typename = std::enable_if_t<std::is_arithmetic_v<U> && !std::is_same_v<U, T>>>\n constexpr Rational(U val) : num(static_cast<T>(val)), den(1) {}\n#if defined(__GNUC__) || defined(__clang__)\n constexpr Rational(int128 n, int128 d) {\n if (d == 0) throw std::domain_error(\"Denominator is zero in Rational number\");\n if (d < 0) { n = -n; d = -d; }\n if (n == 0) {\n num = 0; den = 1;\n return;\n }\n int128 common = sub_rational::gcd_128(n, d);\n n /= common;\n d /= common;\n num = static_cast<T>(n);\n den = static_cast<T>(d);\n }\n#endif\n constexpr T numerator() const { return num; }\n constexpr T denominator() const { return den; }\n constexpr Rational operator+() const { return *this; }\n constexpr Rational operator-() const { return Rational(-num, den); }\n constexpr Rational& operator+=(const Rational& rhs) {\n int128 new_num = (int128)num * rhs.den + (int128)rhs.num * den;\n int128 new_den = (int128)den * rhs.den;\n *this = Rational(new_num, new_den);\n return *this;\n }\n constexpr Rational& operator-=(const Rational& rhs) {\n int128 new_num = (int128)num * rhs.den - (int128)rhs.num * den;\n int128 new_den = (int128)den * rhs.den;\n *this = Rational(new_num, new_den);\n return *this;\n }\n constexpr Rational& operator*=(const Rational& rhs) {\n Rational r1(num, rhs.den);\n Rational r2(rhs.num, den);\n int128 new_num = (int128)r1.num * r2.num;\n int128 new_den = (int128)r1.den * r2.den;\n *this = Rational(new_num, new_den);\n return *this;\n }\n constexpr Rational& operator/=(const Rational& rhs) {\n if (rhs.num == 0) throw std::domain_error(\"Division by zero in Rational number\");\n *this *= Rational(rhs.den, rhs.num);\n return *this;\n }\n explicit operator double() const {\n return static_cast<double>(num) / den;\n }\n explicit operator long double() const {\n return static_cast<long double>(num) / den;\n }\n};\ntemplate <typename T>\nconstexpr Rational<T> operator+(const Rational<T>& lhs, const Rational<T>& rhs) { return Rational<T>(lhs) += rhs; }\ntemplate <typename T>\nconstexpr Rational<T> operator-(const Rational<T>& lhs, const Rational<T>& rhs) { return Rational<T>(lhs) -= rhs; }\ntemplate <typename T>\nconstexpr Rational<T> operator*(const Rational<T>& lhs, const Rational<T>& rhs) { return Rational<T>(lhs) *= rhs; }\ntemplate <typename T>\nconstexpr Rational<T> operator/(const Rational<T>& lhs, const Rational<T>& rhs) { return Rational<T>(lhs) /= rhs; }\ntemplate <typename T>\nconstexpr bool operator==(const Rational<T>& lhs, const Rational<T>& rhs) {\n return lhs.numerator() == rhs.numerator() && lhs.denominator() == rhs.denominator();\n}\ntemplate <typename T>\nconstexpr bool operator!=(const Rational<T>& lhs, const Rational<T>& rhs) { return !(lhs == rhs); }\ntemplate <typename T>\nconstexpr bool operator<(const Rational<T>& lhs, const Rational<T>& rhs) {\n using int128 = __int128_t;\n return (int128)lhs.numerator() * rhs.denominator() < (int128)rhs.numerator() * lhs.denominator();\n}\ntemplate <typename T>\nconstexpr bool operator>(const Rational<T>& lhs, const Rational<T>& rhs) { return rhs < lhs; }\ntemplate <typename T>\nconstexpr bool operator<=(const Rational<T>& lhs, const Rational<T>& rhs) { return !(rhs < lhs); }\ntemplate <typename T>\nconstexpr bool operator>=(const Rational<T>& lhs, const Rational<T>& rhs) { return !(lhs < rhs); }\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const Rational<T>& r) {\n os << r.numerator();\n if (r.denominator() != 1) {\n os << \"/\" << r.denominator();\n }\n return os;\n}\ntemplate <typename T>\nstd::istream& operator>>(std::istream& is, Rational<T>& r) {\n T n, d = 1;\n is >> n;\n if (is.peek() == '/') {\n is.ignore();\n is >> d;\n }\n r = Rational<T>(n, d);\n return is;\n}\n#include <initializer_list>\nnamespace geo {\ntemplate <typename T>\nContainment contains(const Polygon<T>& poly, const Point<T>& p);\ntemplate <typename T>\nlong double area(const Polygon<T>& poly);\ntemplate <typename T>\nbool is_convex(const Polygon<T>& poly);\ntemplate <typename T> struct Polygon {\npublic:\n using value_type = Point<T>;\n using reference = value_type&;\n using const_reference = const value_type&;\n using iterator = typename std::vector<Point<T>>::iterator;\n using const_iterator = typename std::vector<Point<T>>::const_iterator;\n using size_type = typename std::vector<Point<T>>::size_type;\n std::vector<Point<T>> vertices;\n Polygon() = default;\n Polygon(size_type n) : vertices(n) {}\n Polygon(std::vector<Point<T>> v) : vertices(std::move(v)) {}\n Polygon(std::initializer_list<Point<T>> il) : vertices(il) {}\n iterator begin() { return vertices.begin(); }\n const_iterator begin() const { return vertices.begin(); }\n iterator end() { return vertices.end(); }\n const_iterator end() const { return vertices.end(); }\n reference operator[](size_type i) { return vertices[i]; }\n const_reference operator[](size_type i) const { return vertices[i]; }\n reference at(size_type i) { return vertices.at(i); }\n const_reference at(size_type i) const { return vertices.at(i); }\n reference front() { return vertices.front(); }\n const_reference front() const { return vertices.front(); }\n reference back() { return vertices.back(); }\n const_reference back() const { return vertices.back(); }\n size_type size() const { return vertices.size(); }\n bool empty() const { return vertices.empty(); }\n void reserve(size_type n) { vertices.reserve(n); }\n void clear() { vertices.clear(); }\n void push_back(const Point<T>& p) { vertices.push_back(p); }\n void pop_back() { vertices.pop_back(); }\n void resize(size_type count) { vertices.resize(count); }\n Containment contains(const Point<T>& p) const { return ::geo::contains(*this, p); }\n auto area() const { return ::geo::area(*this); }\n bool is_convex() const { return ::geo::is_convex(*this); }\n};\ntemplate <typename T> std::ostream& operator<<(std::ostream& os, const Polygon<T>& poly) { for (size_t i = 0; i < poly.vertices.size(); ++i) { os << poly.vertices[i] << (i == poly.vertices.size() - 1 ? \"\" : \"\\n\"); } return os; }\ntemplate <typename T> std::string debug_format(const Polygon<T>& poly) { std::stringstream ss; ss << \"Polygon[\"; for (size_t i = 0; i < poly.vertices.size(); ++i) { ss << debug_format(poly.vertices[i]) << (i == poly.vertices.size() - 1 ? \"\" : \", \"); } ss << \"]\"; return ss.str(); }\ntemplate <typename T>\nlong double area(const Polygon<T>& poly) {\n long double a = 0;\n for (size_t i = 0; i < poly.vertices.size(); ++i) {\n a += cross(poly.vertices[i], poly.vertices[(i + 1) % poly.vertices.size()]);\n }\n return std::abs(a / 2.0L);\n}\ntemplate <typename U>\nRational<U> area(const Polygon<Rational<U>>& poly) {\n Rational<U> a = 0;\n for (size_t i = 0; i < poly.vertices.size(); ++i) {\n a += cross(poly.vertices[i], poly.vertices[(i + 1) % poly.vertices.size()]);\n }\n a /= 2;\n return a < Rational<U>(0) ? -a : a;\n}\n# 564 \"tmp.cpp\"\ntemplate <typename T>\nContainment contains(const Polygon<T>& poly, const Point<T>& p) {\n bool in = false;\n for (size_t i = 0; i < poly.vertices.size(); ++i) {\n Point<T> cur = poly.vertices[i];\n Point<T> next = poly.vertices[(i + 1) % poly.vertices.size()];\n Vector<T> a = cur - p;\n Vector<T> b = next - p;\n if (a.y > b.y) std::swap(a, b);\n if (lt(a.y, (T)0) && ge(b.y, (T)0) && gt(cross(a, b), (T)0)) {\n in = !in;\n }\n if (eq(cross(a, b), (T)0) && le(dot(a, b), (T)0)) {\n return Containment::ON_BOUNDARY;\n }\n }\n return in ? Containment::INSIDE : Containment::OUTSIDE;\n}\ntemplate<typename T>\nbool is_convex(const Polygon<T>& poly) {\n const auto& vertices = poly.vertices;\n int n = vertices.size();\n if (n < 3) return true;\n int turn_dir = 0;\n for (int i = 0; i < n; ++i) {\n auto res = ccw(vertices[i], vertices[(i + 1) % n], vertices[(i + 2) % n]);\n if (res == CCW::COUNTER_CLOCKWISE) {\n if (turn_dir == -1) return false;\n turn_dir = 1;\n } else if (res == CCW::CLOCKWISE) {\n if (turn_dir == 1) return false;\n turn_dir = -1;\n }\n }\n return true;\n}\n}\nusing R = Rational<ll>;\nusing namespace geo;\n# 624 \"tmp.cpp\"\nint main() {\n ll g;cin>>g;\n Polygon<R> poly(g);\n rep(i, g) cin >> poly[i];\n ll q;cin>>q;\n rep(i, q){\n Point<R> p;cin>>p;\n auto res = poly.contains(p);\n if(res == Containment::INSIDE) out(2);\n else if(res == Containment::ON_BOUNDARY) out(1);\n else out(0);\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3584, "score_of_the_acc": -0.1066, "final_rank": 2 }, { "submission_id": "aoj_CGL_3_C_10006778", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nstruct Point2d;\nusing Vector2d = Point2d;\nstruct Line2d;\nstruct Segment2d;\nstruct Triangle2d;\nstruct Polygon2d;\n\nstruct Point2d{\n\n ld x, y;\n\n Point2d( ld _x = 0.0, ld _y = 0.0 );\n\n void normalize();\n void print();\n\n ld length();\n ld dot( const Vector2d &p );\n ld cross( const Vector2d &p );\n ld distance( Point2d p );\n ld distance( Segment2d s );\n\n Point2d projection( Line2d l );\n\n bool on_segment( Segment2d s );\n\n Point2d operator+( const Point2d &p );\n Point2d operator-( const Point2d &p );\n Point2d operator*( const ld &mul );\n Point2d operator/( const ld &div );\n void operator+=( const Point2d &p );\n void operator-=( const Point2d &p );\n void operator*=( const ld &mul );\n void operator/=( const ld &div );\n\n};\n\nstruct Line2d{\n\n Point2d from, to;\n\n Line2d( Point2d _from, Point2d _to );\n\n Vector2d vector();\n\n Point2d cross_point( Line2d l );\n\n bool parallel( Line2d l );\n bool orthogonal( Line2d l );\n\n};\n\nstruct Segment2d : Line2d{\n\n Segment2d( Point2d _from, Point2d _to ) : Line2d( _from, _to ){}\n\n bool intersection( Segment2d s );\n\n ld distance( Segment2d s );\n\n};\n\nstruct Triangle2d{\n\n vector<Point2d> vertice;\n\n Triangle2d( vector<Point2d> _vertice );\n\n ld signed_area();\n\n};\n\nstruct Polygon2d{\n\n int size;\n vector<Point2d> vertice;\n\n Polygon2d( int _size, vector<Point2d> _vertice );\n\n bool is_convex();\n bool on_line( Point2d p );\n\n ld area();\n\n void contain( Point2d p );\n\n};\n\nistream& operator>>( istream& is, Point2d& dat ){\n\n return is >> dat.x >> dat.y;\n\n}\n\nostream& operator<<( ostream& os, const Point2d& dat ){\n\n return os << fixed << setprecision( 20 ) << dat.x << \" \" << dat.y;\n\n}\n\nPoint2d::Point2d( ld _x, ld _y){\n\n x = _x;\n y = _y;\n\n}\n\nvoid Point2d::normalize(){\n\n ld len = length();\n if( abs( len ) < EPS ) return;\n x /= len;\n y /= len;\n\n}\n\nvoid Point2d::print(){\n\n cout << fixed << setprecision( 20 ) << x << \" \" << y << endl;\n\n}\n\nld Point2d::length(){\n\n return sqrt( x * x + y * y );\n\n}\n\nld Point2d::dot( const Vector2d &p ){\n\n return x * p.x + y * p.y;\n\n}\n\nld Point2d::cross( const Vector2d &p ){\n\n return x * p.y - y * p.x;\n\n}\n\nld Point2d::distance( Point2d p ){\n\n Vector2d v( x - p.x, y - p.y );\n return v.length();\n\n}\n\nld Point2d::distance( Segment2d s ){\n\n Point2d p = projection( s );\n if( p.on_segment( s ) )\n return distance( p );\n else\n return min( distance( s.from ), distance( s.to ) );\n\n}\n\nPoint2d Point2d::projection( Line2d l ){\n\n Vector2d v1( x - l.from.x, y - l.from.y );\n Vector2d v2 = l.to - l.from;\n v2.normalize();\n return l.from + v2 * v1.dot( v2 );\n\n}\n\nbool Point2d::on_segment( Segment2d s ){\n\n Vector2d v1( x - s.from.x, y - s.from.y ), v2( x - s.to.x, y - s.to.y );\n return abs( v1.cross( v2 ) ) < EPS && v1.dot( v2 ) < EPS;\n\n}\n\nPoint2d Point2d::operator+( const Point2d &p ){\n\n Point2d res( x + p.x, y + p.y );\n return res;\n\n}\n\nPoint2d Point2d::operator-( const Point2d &p ){\n\n Point2d res( x - p.x, y - p.y );\n return res;\n\n}\n\nPoint2d Point2d::operator*( const ld &mul ){\n\n Point2d res( x * mul, y * mul );\n return res;\n\n}\n\nPoint2d Point2d::operator/( const ld &div ){\n\n Point2d res( x / div, y / div );\n return res;\n\n}\n\nvoid Point2d::operator+=( const Point2d &p ){\n\n x += p.x;\n y += p.y;\n\n}\n\nvoid Point2d::operator-=( const Point2d &p ){\n\n x -= p.x;\n y -= p.y;\n\n}\n\nvoid Point2d::operator*=( const ld &mul ){\n\n x *= mul;\n y *= mul;\n\n}\n\nvoid Point2d::operator/=( const ld &div ){\n\n x *= div;\n y *= div;\n\n}\n\nLine2d::Line2d( Point2d _from, Point2d _to ){\n\n from = _from;\n to = _to;\n\n}\n\nVector2d Line2d::vector(){\n\n return Vector2d( to.x - from.x, to.y - from.y );\n\n}\n\nPoint2d Line2d::cross_point( Line2d l ){\n\n if( abs( to.x - from.x ) < EPS ){\n ld katamuki = ( l.to.y - l.from.y ) / ( l.to.x - l.from.x );\n ld seppen = l.to.y - katamuki * l.to.x;\n return Point2d( to.x, katamuki * to.x + seppen );\n }\n else if( abs( l.to.x - l.from.x ) < EPS ){\n ld katamuki = ( to.y - from.y ) / ( to.x - from.x );\n ld seppen = to.y - katamuki * to.x;\n return Point2d( l.to.x, katamuki * l.to.x + seppen );\n }\n else{\n ld katamuki0 = ( to.y - from.y ) / ( to.x - from.x );\n ld seppen0 = to.y - katamuki0 * to.x;\n ld katamuki1 = ( l.to.y - l.from.y ) / ( l.to.x - l.from.x );\n ld seppen1 = l.to.y - katamuki1 * l.to.x;\n return Point2d( ( seppen1 - seppen0 ) / ( katamuki0 - katamuki1 ), ( katamuki0 * seppen1 - katamuki1 * seppen0 ) / ( katamuki0 - katamuki1 ) );\n }\n\n}\n\nbool Line2d::parallel( Line2d l ){\n\n Vector2d v0 = vector(), v1 = l.vector();\n return abs( v0.cross( v1 ) ) < EPS;\n\n}\n\nbool Line2d::orthogonal( Line2d l ){\n\n Vector2d v0 = vector(), v1 = l.vector();\n return abs( v0.dot( v1 ) ) < EPS;\n \n}\n\nbool Segment2d::intersection( Segment2d s ){\n\n if( from.on_segment( s ) || to.on_segment( s ) || s.from.on_segment( *this ) || s.to.on_segment( *this ) )\n return true;\n Line2d l0( from, s.from ), l1( from, s.to ), l2( to, s.from ), l3( to, s.to );\n Vector2d v0 = l0.vector(), v1 = l1.vector(), v2 = l2.vector(), v3 = l3.vector();\n return ( v0.cross( v1 ) * v2.cross( v3 ) < -EPS ) && ( v0.cross( v2 ) * v1.cross( v3 ) < -EPS );\n}\n\nld Segment2d::distance( Segment2d s ){\n\n if( intersection( s ) )\n return 0.0;\n return min( min( from.distance( s ), to.distance( s ) ), min( s.from.distance( *this ), s.to.distance( *this ) ) );\n\n}\n\nTriangle2d::Triangle2d( vector<Point2d> _vertice ){\n\n vertice = _vertice;\n\n}\n\nld Triangle2d::signed_area(){\n\n Vector2d v1( vertice[1].x - vertice[0].x, vertice[1].y - vertice[0].y );\n Vector2d v2( vertice[2].x - vertice[0].x, vertice[2].y - vertice[0].y );\n return v1.cross( v2 ) / 2.0;\n\n}\n\nPolygon2d::Polygon2d( int _size, vector<Point2d> _vertice ){\n\n size = _size;\n vertice = _vertice;\n\n}\n\nbool Polygon2d::is_convex(){\n\n vector<Vector2d> edges;\n for( int i = 0 ; i < size ; i++ ){\n Vector2d edge( vertice[(i+1)%size].x - vertice[i].x, vertice[(i+1)%size].y - vertice[i].y );\n edges.push_back( edge );\n }\n for( int i = 0 ; i < size - 1 ; i++ ){\n if( edges[i].cross( edges[i+1] ) < -EPS )\n return false;\n }\n return true;\n\n}\n\nbool Polygon2d::on_line( Point2d p ){\n\n vector<Segment2d> edges;\n for( int i = 0 ; i < size ; i++ ){\n Segment2d edge( vertice[i], vertice[(i+1)%size] );\n edges.push_back( edge );\n }\n for( int i = 0 ; i < size ; i++ ){\n if( p.on_segment( edges[i] ) )\n return true;\n }\n return false;\n\n}\n\nld Polygon2d::area(){\n\n ld res = 0.0;\n for( int i = 1 ; i < size - 1 ; i++ ){\n vector<Point2d> v;\n v.push_back( vertice[0] );\n v.push_back( vertice[i] );\n v.push_back( vertice[i+1] );\n Triangle2d t( v );\n res += t.signed_area();\n }\n return res;\n\n}\n\nvoid Polygon2d::contain( Point2d p ){\n\n if( on_line( p ) ){\n cout << 1 << endl;\n return;\n }\n ld angle = 0.0;\n for( int i = 0 ; i < size ; i++ ){\n Vector2d v1( vertice[i].x - p.x, vertice[i].y - p.y );\n v1.normalize();\n Vector2d v2( vertice[(i+1)%size].x - p.x, vertice[(i+1)%size].y - p.y );\n v2.normalize();\n if( v1.cross( v2 ) > EPS )\n angle += acos( v1.dot( v2 ) );\n else if( v1.cross( v2 ) < -EPS )\n angle -= acos( v1.dot( v2 ) );\n }\n if( angle < EPS )\n cout << 0 << endl;\n else\n cout << 2 << endl;\n\n}\n\nvoid counter_clockwise( const Point2d &p0, const Point2d &p1, const Point2d &p2 ){\n\n Line2d l1( p0, p1 ), l2( p0, p2 );\n Vector2d v1 = l1.vector(), v2 = l2.vector();\n ld c = v1.cross( v2 );\n if( c > EPS )\n cout << \"COUNTER_CLOCKWISE\" << endl;\n else if( c < -EPS )\n cout << \"CLOCKWISE\" << endl;\n else{\n ld d = v1.dot( v2 );\n if( d > -EPS ){\n if( v1.length() < v2.length() )\n cout << \"ONLINE_FRONT\" << endl;\n else\n cout << \"ON_SEGMENT\" << endl;\n }\n else\n cout << \"ONLINE_BACK\" << endl;\n }\n\n}\n\nint main(){\n\n int n, q;\n Point2d tmp;\n vector<Point2d> v;\n\n cin >> n;\n for( int i = 0 ; i < n ; i++ ){\n cin >> tmp;\n v.push_back( tmp );\n }\n Polygon2d p( n, v );\n cin >> q;\n for( int i = 0 ; i < q ; i++ ){\n cin >> tmp;\n p.contain( tmp );\n }\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3588, "score_of_the_acc": -0.1148, "final_rank": 3 }, { "submission_id": "aoj_CGL_3_C_9758202", "code_snippet": "// #define _GLIBCXX_DEBUG\n#define EPSILON (1e-10)\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nll MOD = 998244353;\n// ==================copyここから=======================\n\nenum class CCW\n{\n COUNTER_CLOCKWISE, // 反時計周り\n CLOCKWISE, // 時計回りの位置\n ONLINE_BACK, // 逆向き延長線上\n ONLINE_FRONT, // 正向き延長線上\n ON_SEGMENT, // ベクトル上\n};\n\n/**\n * =======================\n * N次元ベクトルクラスVector\n * =======================\n */\nstruct Vector\n{\n ll dim;\n\nprivate:\n vector<double> coord;\n\npublic:\n Vector(ll n = 2)\n {\n this->coord = vector<double>(n, 0);\n this->dim = n;\n }\n Vector(vector<double> coord)\n {\n this->coord = coord;\n this->dim = coord.size();\n }\n\n double norm(double p = 2) const\n {\n double ret = 0;\n for (auto e : this->coord)\n {\n ret += pow(e, p);\n }\n return pow(ret, 1 / p);\n }\n\n Vector unit() const\n {\n vector<double> v(this->coord.size());\n for (ll i = 0; i < this->dim; i++)\n {\n v[i] = this->coord[i] / this->norm(2);\n }\n return Vector(v);\n }\n\n Vector normal_unit2D() const\n {\n if (this->dim != 2)\n {\n throw runtime_error(\"DimensionMustBe2\");\n }\n vector<double> v(this->coord.size());\n v[0] = -this->coord[1];\n v[1] = this->coord[0];\n return Vector(v).unit();\n }\n\n double operator*(const Vector &v) const\n {\n if (this->coord.size() != v.coord.size())\n {\n throw runtime_error(\"MismatchOfVectorSizeError\");\n }\n double inner_product = 0;\n rep(i, this->coord.size())\n {\n inner_product += this->coord[i] * v.coord[i];\n }\n return inner_product;\n }\n\n double cross2D(const Vector &v) const\n {\n ll DIM = 2;\n if (v.dim != DIM || this->dim != DIM)\n {\n throw runtime_error(\"Not2DimensionVector\");\n }\n return this->coord[0] * v.coord[1] - this->coord[1] * v.coord[0];\n }\n\n Vector cross3D(const Vector &v) const\n {\n ll DIM = 3;\n if (v.dim != DIM || this->dim != DIM)\n {\n throw runtime_error(\"Not3DimensionVector\");\n }\n return Vector(vector<double>{\n this->coord[1] * v.coord[2] - this->coord[2] * v.coord[1],\n this->coord[2] * v.coord[0] - this->coord[0] * v.coord[2],\n this->coord[0] * v.coord[1] - this->coord[1] * v.coord[0],\n });\n }\n void print(bool no_line = false) const\n {\n cout << \"(\";\n rep(i, this->dim)\n {\n cout << this->coord[i]\n << (i != this->dim - 1 ? \", \" : \")\");\n }\n if (!no_line)\n {\n cout << endl;\n }\n }\n\n /**\n * 位置関係判定メソッド\n */\n enum CCW ccw(const Vector &v) const\n {\n if (this->dim != 2 || v.dim != 2)\n {\n throw runtime_error(\"Not2DimensionVector\");\n }\n auto cross = this->cross2D(v);\n if (cross > 0)\n {\n return CCW::COUNTER_CLOCKWISE;\n }\n if (cross < 0)\n {\n return CCW::CLOCKWISE;\n }\n if ((*this) * v < 0)\n {\n return CCW::ONLINE_BACK;\n }\n if (this->norm() < v.norm())\n {\n return CCW::ONLINE_FRONT;\n }\n return CCW::ON_SEGMENT;\n }\n\n Vector operator+(const Vector &v) const\n {\n if (this->coord.size() != v.coord.size())\n {\n throw runtime_error(\"MismatchOfVectorSizeError\");\n }\n vector<double> sum_v;\n rep(i, v.coord.size())\n {\n sum_v.push_back(this->coord[i] + v.coord[i]);\n }\n return Vector(sum_v);\n }\n\n Vector operator-(const Vector &v) const\n {\n if (this->coord.size() != v.coord.size())\n {\n throw runtime_error(\"MismatchOfVectorSizeError\");\n }\n vector<double> sum_v;\n rep(i, v.coord.size())\n {\n sum_v.push_back(this->coord[i] - v.coord[i]);\n }\n return Vector(sum_v);\n }\n\n double operator[](size_t t)\n {\n return this->coord.at(t);\n }\n double operator[](size_t t) const\n {\n return this->coord.at(t);\n }\n\n bool operator==(const Vector &v) const\n {\n if (this->coord.size() != v.coord.size())\n {\n return false;\n }\n rep(i, this->coord.size())\n {\n if (EPSILON < abs(this->coord[i] - v.coord[i]))\n {\n return false;\n }\n }\n return true;\n }\n};\n\nVector operator*(const Vector left_v, const double k)\n{\n vector<double> kv(left_v.dim);\n rep(i, left_v.dim)\n {\n kv[i] = k * left_v[i];\n }\n return Vector(kv);\n}\n\nVector operator*(const double k, const Vector left_v)\n{\n vector<double> kv(left_v.dim);\n rep(i, left_v.dim)\n {\n kv[i] = k * left_v[i];\n }\n return Vector(kv);\n}\n\nbool operator<(const Vector &left_v, const Vector &right_v)\n{\n if (left_v.dim != right_v.dim)\n {\n throw runtime_error(\"MustBeSameDimension\");\n }\n rep(i, left_v.dim)\n {\n if (abs(left_v[i] - right_v[i]) < EPSILON)\n {\n continue;\n }\n return left_v[i] < right_v[i];\n }\n return true;\n}\n\nbool operator>(const Vector &left_v, const Vector &right_v)\n{\n return !(left_v < right_v);\n}\n\nbool operator<=(const Vector &left_v, const Vector &right_v)\n{\n if (left_v.dim != right_v.dim)\n {\n throw runtime_error(\"MustBeSameDimension\");\n }\n rep(i, left_v.dim)\n {\n if (abs(left_v[i] - right_v[i]) < EPSILON)\n {\n continue;\n }\n return left_v[i] <= right_v[i];\n }\n return true;\n}\n\nbool operator>=(const Vector &left_v, const Vector &right_v)\n{\n if (left_v.dim != right_v.dim)\n {\n throw runtime_error(\"MustBeSameDimension\");\n }\n rep(i, left_v.dim)\n {\n if (abs(left_v[i] - right_v[i]) < EPSILON)\n {\n continue;\n }\n return left_v[i] >= right_v[i];\n }\n return true;\n}\n\n/**\n * ==================\n * N次元直線クラスLine\n * ==================\n */\nstruct Line\n{\n Vector v1, v2;\n Line(const vector<double> &v1, const vector<double> &v2) : v1(v1), v2(v2)\n {\n if (this->v1 == this->v2)\n {\n throw runtime_error(\"ShouldBeDefferentPoint\");\n }\n if (this->v1.dim != this->v2.dim)\n {\n throw runtime_error(\"ShouldBeInSameDimension\");\n }\n }\n\n Line(const Vector &v1, const Vector &v2)\n {\n if (v1 == v2)\n {\n throw runtime_error(\"ShouldBeDefferentPoint\");\n }\n if (v1.dim != v2.dim)\n {\n throw runtime_error(\"ShouldBeInSameDimension\");\n }\n this->v1 = v1;\n this->v2 = v2;\n }\n /**\n * 平行判定メソッド\n */\n bool is_horizontal(const Line &l) const\n {\n auto direction1 = this->v1 - this->v2;\n auto direction2 = l.v1 - l.v2;\n if (direction1.dim != direction2.dim)\n {\n throw runtime_error(\"ShouldBeInSameDimension\");\n }\n return abs(abs(direction1.norm(2) * direction2.norm(2)) - abs(direction1 * direction2)) < EPSILON;\n }\n /**\n * 垂直判定メソッド\n */\n bool is_orthogonal(const Line &l) const\n {\n auto direction1 = this->v1 - this->v2;\n auto direction2 = l.v1 - l.v2;\n if (direction1.dim != direction2.dim)\n {\n throw runtime_error(\"ShouldBeInSameDimension\");\n }\n return abs(direction1 * direction2) < EPSILON;\n }\n /**\n * 交点計算メソッド\n */\n // Vector intersecting_point(Line l) {}\n\n /**\n * 点との距離計算メソッド\n */\n double distance2D(const Vector &p) const\n {\n if (this->v1.dim != 2 || this->v2.dim != 2 || p.dim != 2)\n {\n throw runtime_error(\"DimensionMustBe2\");\n }\n auto v1 = p - this->v1;\n auto v2 = this->v2 - this->v1;\n auto pj_len = v2.unit() * v1; // 射影ベクトルの長さ(逆向きの場合は負)\n return (pj_len * v2.unit() - v1).norm(2);\n }\n\n Vector dirction_unit_vector() const\n {\n return (this->v1 - this->v2).unit();\n }\n\n bool is_online(const Vector &p) const\n {\n return this->distance2D(p) < EPSILON;\n }\n};\n\n/**\n * =====================\n * N次元線分クラスSegment\n * =====================\n */\nstruct Segment : public Line\n{\n using Line::Line;\n void print() const\n {\n this->v1.print(true);\n cout << \", \";\n this->v1.print();\n }\n double len() const\n {\n return (this->v1 - this->v2).norm(2);\n }\n bool is_intersected2D(const Segment &s) const\n {\n if (this->v1.dim != 2 || this->v2.dim != 2 || s.v1.dim != 2 || s.v2.dim != 2)\n {\n throw runtime_error(\"DimensionMustBe2\");\n }\n auto a1 = this->v2 - this->v1;\n auto a2 = s.v1 - this->v1;\n auto a3 = s.v2 - this->v1;\n auto ccw11 = a1.ccw(a2);\n auto ccw12 = a1.ccw(a3);\n if (ccw11 == CCW::ON_SEGMENT || ccw12 == CCW::ON_SEGMENT)\n {\n return true;\n }\n if (\n (ccw11 == CCW::COUNTER_CLOCKWISE && ccw12 == CCW::CLOCKWISE) ||\n (ccw11 == CCW::CLOCKWISE && ccw12 == CCW::COUNTER_CLOCKWISE))\n {\n }\n else if (\n (ccw11 == CCW::ONLINE_BACK && ccw12 == CCW::ONLINE_FRONT) ||\n (ccw11 == CCW::ONLINE_FRONT && ccw12 == CCW::ONLINE_BACK))\n {\n return true;\n }\n else\n {\n return false;\n }\n\n auto b1 = s.v2 - s.v1;\n auto b2 = this->v1 - s.v1;\n auto b3 = this->v2 - s.v1;\n auto ccw21 = b1.ccw(b2);\n auto ccw22 = b1.ccw(b3);\n if (ccw21 == CCW::ON_SEGMENT || ccw22 == CCW::ON_SEGMENT)\n {\n return true;\n }\n if (\n (ccw21 == CCW::COUNTER_CLOCKWISE && ccw22 == CCW::CLOCKWISE) ||\n (ccw21 == CCW::CLOCKWISE && ccw22 == CCW::COUNTER_CLOCKWISE))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n\n double distance2D(const Vector &p) const\n {\n if (this->v1.dim != 2 || this->v2.dim != 2 || p.dim != 2)\n {\n throw runtime_error(\"DimensionMustBe2\");\n }\n auto v1 = p - this->v1;\n auto v2 = this->v2 - this->v1;\n auto pj_len = v2.unit() * v1; // 射影ベクトルの長さ(逆向きの場合は負)\n if (v2.norm(2) <= pj_len || pj_len <= 0)\n {\n return min((p - this->v1).norm(2), (p - this->v2).norm(2));\n }\n else\n {\n return (pj_len * v2.unit() - v1).norm(2);\n }\n }\n double distance2D(const Segment &s) const\n {\n if (this->is_intersected2D(s))\n {\n return 0;\n }\n return min(\n min(this->distance2D(s.v1), this->distance2D(s.v2)),\n min(s.distance2D(this->v1), s.distance2D(this->v2)));\n }\n\n Vector intersection_point2D(Segment s)\n {\n if (!this->is_intersected2D(s))\n {\n throw runtime_error(\"NotIntersected\");\n }\n Line l(this->v1, this->v2);\n auto t = (l.distance2D(s.v1)) / (l.distance2D(s.v1) + l.distance2D(s.v2));\n return s.v1 + (s.v2 - s.v1) * t;\n }\n\n bool is_online(const Vector &p) const\n {\n return this->distance2D(p) < EPSILON;\n }\n};\n\nstruct Circle\n{\n Vector center;\n double radius;\n Circle(vector<double> center, double radius) : center(center),\n radius(radius)\n {\n }\n\n vector<Vector> intersection_point2D(const Line &l) const\n {\n auto d = l.distance2D(this->center);\n auto a1 = this->center + (l.v1 - l.v2).normal_unit2D() * d;\n auto a2 = this->center - (l.v1 - l.v2).normal_unit2D() * d;\n Vector a;\n if (l.is_online(a1))\n {\n a = a1;\n }\n else\n {\n a = a2;\n }\n vector<Vector> intersection_points;\n if (abs(d - this->radius) < EPSILON)\n {\n intersection_points.push_back(a);\n }\n else\n {\n auto length = pow(pow(this->radius, 2) - pow(d, 2), 0.5);\n intersection_points.push_back(a + length * l.dirction_unit_vector());\n intersection_points.push_back(a - length * l.dirction_unit_vector());\n }\n sort(intersection_points.begin(), intersection_points.end());\n return intersection_points;\n }\n\n vector<Vector> intersection_point2D(const Circle &c) const\n {\n vector<Vector> intersection_points;\n auto c1c2 = c.center - this->center;\n auto d = c1c2.norm(2);\n if (this->radius + c.radius < d)\n {\n return intersection_points;\n }\n auto d1 = (pow(d, 2) + pow(this->radius, 2) - pow(c.radius, 2)) / (2 * d);\n auto m = this->center + c1c2.unit() * d1;\n auto h = pow(pow(this->radius, 2) - pow(d1, 2), 0.5);\n if (abs(this->radius + c.radius - d) < EPSILON)\n {\n intersection_points.push_back(this->center + c1c2.unit() * d1);\n }\n else\n {\n intersection_points.push_back(this->center + c1c2.unit() * d1 + c1c2.normal_unit2D() * h);\n intersection_points.push_back(this->center + c1c2.unit() * d1 - c1c2.normal_unit2D() * h);\n }\n\n sort(intersection_points.begin(), intersection_points.end());\n return intersection_points;\n }\n\n double area() const\n {\n return M_PI * this->radius * this->radius;\n }\n};\n\nenum class POLYGON2D_INCLUSION_STATUS\n{\n INCLUDED,\n ON_BOUNDARY,\n EXCLUDED,\n};\n\nstruct Polygon2D\n{\n vector<Vector> points;\n Polygon2D(const vector<vector<double>> &points)\n {\n for (auto p : points)\n {\n this->points.push_back(Vector(p));\n }\n }\n enum POLYGON2D_INCLUSION_STATUS get_inclusion_status(const Vector &v) const\n {\n bool flag = false;\n rep(i, this->points.size())\n {\n auto v1 = this->points[i];\n Vector v2;\n if (i == this->points.size() - 1)\n {\n v2 = this->points[0];\n }\n else\n {\n v2 = this->points[i + 1];\n }\n if (v2[1] < v1[1])\n {\n auto tmp = v1;\n v1 = v2;\n v2 = tmp;\n }\n Segment s(v1, v2);\n if (s.is_online(v))\n {\n return POLYGON2D_INCLUSION_STATUS::ON_BOUNDARY;\n }\n if (v2[1] <= v[1] || v[1] < v1[1])\n {\n continue;\n }\n auto cross = (v - v1).cross2D(v - v2);\n if (0 < cross)\n {\n flag = !flag;\n }\n }\n if (flag)\n {\n return POLYGON2D_INCLUSION_STATUS::INCLUDED;\n }\n else\n {\n return POLYGON2D_INCLUSION_STATUS::EXCLUDED;\n }\n }\n};\n\n// ==================copyここまで=======================\n\nint main()\n{\n // input\n ll n;\n double x, y;\n vector<vector<double>> poly;\n vector<vector<double>> points;\n cin >> n;\n rep(i, n)\n {\n cin >> x >> y;\n poly.push_back(vector<double>{x, y});\n }\n cin >> n;\n rep(i, n)\n {\n cin >> x >> y;\n points.push_back(vector<double>{x, y});\n }\n\n // solve\n Polygon2D polygon(poly);\n vector<int> answers;\n rep(i, n)\n {\n auto ans = polygon.get_inclusion_status(Vector(points[i]));\n switch (ans)\n {\n case POLYGON2D_INCLUSION_STATUS::INCLUDED:\n answers.push_back(2);\n break;\n case POLYGON2D_INCLUSION_STATUS::EXCLUDED:\n answers.push_back(0);\n break;\n case POLYGON2D_INCLUSION_STATUS::ON_BOUNDARY:\n answers.push_back(1);\n break;\n }\n }\n\n // output\n for (auto a : answers)\n {\n cout << a << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4020, "score_of_the_acc": -2, "final_rank": 5 }, { "submission_id": "aoj_CGL_3_C_8536434", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ld = long double;\nconst ld eps = 1e-6;\nint sign(ld x) { return fabs(x) < eps ? 0 : x < 0 ? -1 : 1; }\nusing vec = complex<ld>;\n#define x(z) real(z)\n#define y(z) imag(z)\nistream& operator >>(istream &in, vec &p) { ld x, y; cin >> x >> y; p = {x, y}; return in; }\n#define C(a, b) y(conj(a) * (b))\nbool onseg(vec a, vec p, vec q) { return !sign(C(q - p, a - p)) && x(a) > min(x(p), x(q)) - eps && x(a) < max(x(p), x(q)) + eps && y(a) > min(y(p), y(q)) - eps && y(a) < max(y(p), y(q)) + eps; }\nvec intersection(vec a, vec b, vec c, vec d) {\n\treturn a + (b - a) * (C(a - c, d - c) / C(d - c, b - a));\n}\nbool hasinter(vec a, vec b, vec c, vec d) {\n\tvec o = intersection(a, b, c, d);\n\treturn onseg(o, a, b) && onseg(o, c, d);\n}\nint inPoly(vec p, vector<vec> a) {\n\tstatic mt19937 eng(chrono::steady_clock::now().time_since_epoch().count());\n\tstatic uniform_real_distribution<ld> uni(1e5, 2e5);\n\tvec q(uni(eng), uni(eng));\n\tint cnt = 0;\n\tfor (int i = 0; i < a.size(); i++) {\n\t\tif (onseg(p, a[i], a[(i + 1) % a.size()])) return 0;\n\t\tcnt += hasinter(a[i], a[(i + 1) % a.size()], p, q);\n\t}\n\treturn cnt % 2 ? 1 : -1;\n}\nint main() {\n\tcin.tie(0)->sync_with_stdio(0);\n\tint n;\n\tcin >> n;\n\tvector<vec> g(n);\n\tfor (auto &i : g) {\n\t\tcin >> i;\n\t}\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tvec o;\n\t\tcin >> o;\n\t\tcout << inPoly(o, g) + 1 << \"\\n\";\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3532, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_CGL_3_C_8246886", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define pii pair<int, int>\n#define mp make_pair\n#define fi first\n#define se second\n#define deb(var) cerr << #var << '=' << (var) << \"; \"\n#define double long double\nconst double eps = 1e-8, inf = 1e20, pi = acos(-1.0);\nint sgn(double x) {\n\treturn fabs(x) < eps ? 0 : (x < 0 ? -1 : 1); \n} \ndouble sqr(double x) { return x * x; }\nstruct Point {\n\tdouble x, y;\n\tPoint() { x = y = 0; }\n\tPoint(double a, double b) { x = a, y = b; }\n\tvoid input() { cin >> x >> y; }\n\tvoid output(int k) const { cout << fixed << setprecision(k) << x << ' ' << y << '\\n'; }\n\tbool operator == (Point b) const { return sgn(x - b.x) == 0 && sgn(y - b.y) == 0; }\n\tbool operator < (Point b) const { return sgn(x - b.x) == 0 ? sgn(y - b.y) < 0 : x < b.x; }\n\tPoint operator + (Point b) const { return Point(x + b.x, y + b.y); }\n\tPoint operator - (Point b) const { return Point(x - b.x, y - b.y); } \n\tPoint operator * (double k) const { return Point(x * k, y * k); }\n\tPoint operator / (double k) const { return Point(x / k, y / k); }\n\tdouble operator * (Point b) const { return x * b.x + y * b.y; } // 向量点积\n\tdouble operator ^ (Point b) const { return x * b.y - y * b.x; } // 向量叉积 \n\tfriend double dis(Point a, Point b) { return sqrt(sqr(a.x - b.x) + sqr(a.y - b.y)); } // 两点距离 \n\tfriend double dis(Point a) { return dis(Point(), a); }\n\tfriend Point unit(Point a) { return Point() == a ? a : a / dis(a); } // 向量单位化\n\tfriend Point turn(Point a, double k) { return Point(a.x * cos(k) - a.y * sin(k), a.y * cos(k) + a.x * sin(k)); } // 逆时针旋转弧度 k\n\tfriend Point move(Point a, Point b) { return a + b; } // 移动向量 b \n\tfriend double angle(Point a, Point b) { return sgn(a ^ b) * acos(a * b / dis(a) / dis(b)); } // a 到 b 的夹角\n};\nstruct Line {\n\tPoint s, t;\n\tLine() { s = t = Point(); };\n\tLine(Point a, Point b) { s = a, t = b; }\n\tvoid input() { s.input(), t.input(); }\n\tbool operator == (Line b) const { return s == b.s && t == b.t; }\n\tfriend double len(Line a) { return dis(a.s, a.t); }\n\tfriend Point prog(Point a, Line b) { // 点到直线投影 \n\t\ta = a - b.s, b.t = b.t - b.s;\n\t\treturn b.s + unit(b.t) * (a * b.t / dis(b.t));\n\t}\n\tfriend double dis(Point a, Line b) { return dis(a, prog(a, b)); } // 点到直线距离\n\tfriend Point symm(Point a, Line b) { return prog(a, b) * 2 - a; } // 点关于直线的对称点\n\tfriend Line turn(Line a, double k) { return Line(turn(a.s, k), turn(a.t, k)); }\n\tfriend Line move(Line a, Point b) { return Line(move(a.s, b), move(a.t, b)); }\n\tfriend bool online(Line a, Point b) { return sgn((a.t - a.s) ^ (b - a.s)) == 0; } // 点在直线上 \n\tfriend bool onsegm(Line a, Point b) { // 点在线段上 \n\t\treturn online(a, b) && sgn((b - a.s) * (b - a.t)) <= 0;\n\t}\n\tfriend int rela(Line a, Line b) { // 两直线关系 共线 1;平行 2;相交 3 \n\t\tPoint del = Point() - a.s; a = move(a, del), b = move(b, del);\n\t\tdouble k = angle(a.t, Point(1, 0)); a = turn(a, k), b = turn(b, k);\n\t\tif (sgn(b.s.y) == 0 && sgn(b.t.y) == 0) return 1;\n\t\tif (sgn(b.s.y - b.t.y) == 0) return 2; return 3;\n\t} \n\tfriend Point sect(Line a, Line b) { // 直线交点 \n\t\tPoint del = Point() - a.s; a = move(a, del), b = move(b, del);\n\t\tdouble k = angle(a.t, Point(1, 0)); a = turn(a, k), b = turn(b, k);\n\t\tdouble t = -(b.t.x - b.s.x) * b.s.y, d = b.t.y - b.s.y; \n\t\tPoint ans = Point(t / d + b.s.x, 0); ans = move(turn(ans, -k), Point() - del); return ans;\n\t}\n\tfriend int rela_segline(Line a, Line b) { // 线段 a 和直线 b 的关系 相交:1;无交:0\n\t\treturn sgn((b.t - b.s) ^ (a.s - b.s)) * sgn((b.t - b.s) ^ (a.t - b.s)) <= 0;\n\t}\n\tfriend int rela_segseg(Line a, Line b) { // 线段 a 和线段 b 的关系 相交:1;无交:0\n\t\tif (rela(a, b) == 1) return onsegm(b, a.t) | onsegm(b, a.s) | onsegm(a, b.s);\n\t\tPoint p = sect(a, b);\n\t\treturn onsegm(a, p) && onsegm(b, p); \n\t} \n\tfriend Point sect_segseg(Line a, Line b) { // 线段 a,b 的交点 \n\t\tif (rela(a, b) == 1) return onsegm(b, a.t) ? a.t : onsegm(b, a.s) ? a.s : b.s; return sect(a, b); \n\t}\n\tfriend double dis_seg(Point a, Line b) { // 点到线段距离 \n\t\tif (onsegm(b, prog(a, b))) return dis(a, b); else return min(dis(a, b.s), dis(a, b.t));\n\t}\n\tfriend double dis_segseg(Line a, Line b) { // 线段 a,b 的距离\n\t if (rela_segseg(a, b)) return 0;\n\t\tdouble ans = inf; \n\t\tans = min(ans, dis_seg(b.s, a));\n\t\tans = min(ans, dis_seg(b.t, a));\n\t\tans = min(ans, dis_seg(a.s, b));\n\t\tans = min(ans, dis_seg(a.t, b)); return ans; \n\t}\n};\nstruct Polygon {\n\tvector<Point> p;\n\tPolygon() { p.clear(); }\n\tPolygon(vector<Point> q) { p = q; }\n\tvoid input(int n) {\n\t\tp.clear(); Point q; while (n--) q.input(), p.push_back(q);\n\t}\n\tvoid output(int k) {\n\t\tfor (int i = 0; i < p.size(); i++) p[i].output(k); \n\t}\n\tconst int size() const { return p.size(); }\n\tvoid pop_back() { p.pop_back(); }\n\tvoid push_back(Point x) { p.pb(x); }\n\tPoint& operator [](int k) { return p[k]; }\n\tvector<Point>::iterator begin() { return p.begin(); }\n\tvector<Point>::iterator end() { return p.end(); } \n\tfriend int rela(Polygon p, Point v) { // 0 v 在 g 外;1 v 在 g 上;2 v 在 g 内 \n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < p.size(); i++) {\n\t\t\tPoint s = p[i] - v, t = p[(i + 1) % (int)p.size()] - v; Line l = Line(s, t);\n\t\t\tif (onsegm(l, Point())) return 1;\n\t\t\tif (s.y > t.y) swap(s, t);\n\t\t\tint b = sgn(s.y) * sgn(t.y) <= 0 && sgn(t.y) != 0;\n\t\t\tPoint sct = sect(l, Line(Point(), Point(1, 0)));\n\t\t\tcnt += b && sgn(sct.y) == 0 && sgn(sct.x) >= 0;\n\t\t} return cnt % 2 ? 2 : 0;\n\t}\n\tstruct angle_cmp {\n\t\tPoint p;\n\t\tangle_cmp() {}\n\t\tangle_cmp(Point x) { p = x; } \n\t\tbool operator ()(Point a, Point b) const {\n\t\t\ta = a - p, b = b - p;\n\t\t\treturn sgn(atan2(a.y, a.x) - atan2(b.y, b.x)) == 0 ? dis(a) < dis(b) : atan2(a.y, a.x) < atan2(b.y, b.x);\n\t\t}\n\t};\n\tfriend bool isconvex(Polygon p) {\n\t\tbool bk[3] = {0, 0, 0};\n\t\tfor (int i = 0; i < p.size(); i++) {\n\t\t\tint j = (i + 1) % (int)p.size(), k = (j + 1) % (int)p.size();\n\t\t\tbk[sgn((p[j] - p[i]) ^ (p[k] - p[j])) + 1] = 1; if ((bk[0] && bk[2]) || bk[1]) return 0;\n\t\t}\n\t\treturn 1;\n\t} \n\tfriend Polygon getconvex(Polygon p) { // 求凸包(逆时针) \n\t\tif (p.size() <= 1) return p;\n\t\tfor (int i = 1; i < p.size(); i++)\n\t\t\tif (p[i].y < p[0].y) swap(p[i], p[0]);\n\t\tsort(p.begin() + 1, p.end(), angle_cmp(p[0]));\n\t\tvector<Point> st(0); st.pb(p[0]); int top = 0;\n\t\tfor (int i = 1; i < p.size(); i++) {\n\t\t\twhile (top > 0 && sgn((st[top] - st[top - 1]) ^ (p[i] - st[top - 1])) <= 0) top--, st.pop_back(); st.push_back(p[i]); top++;\n\t\t}\n\t\treturn Polygon(st);\n\t}\n\tdouble peri() const { // 周长 \n\t\tdouble ans = 0; for (int i = 0; i < p.size(); i++) ans += dis(p[i], p[(i + 1) % (int)p.size()]); return ans;\n\t}\n\tdouble area() const { // 面积 \n\t\tdouble ans = 0; for (int i = 0; i < p.size(); i++) ans += p[i] ^ p[(i + 1) % (int)p.size()]; return fabs(ans) / 2;\n\t}\n\tdouble diam() const { // 直径(逆时针) \n\t\tint n = p.size();\n\t\tdouble ans = 0;\n\t\tfor (int i = 0, k = 0; i < p.size(); i++) {\n\t\t\twhile (sgn(dis(p[i], Line(p[(k + 1) % n], p[(k + 2) % n])) - dis(p[i], Line(p[k], p[(k + 1) % n]))) > 0) k = (k + 1) % n; ans = max(ans, max(dis(p[i], p[k]), dis(p[i], p[(k + 1) % n]))); \n\t\t}\n\t\treturn ans;\n\t}\n//\tfriend Polygon minkow(Polygon a, Polygon b) { // 闵可夫斯基和 \n//\t\t\n//\t}\n}; \nPolygon g;\nsigned main() {\n\tint n; cin >> n; g.input(n); int q; cin >> q;\n\twhile (q--) {\n\t\tPoint p; p.input(); cout << rela(g, p) << \"\\n\";\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3576, "score_of_the_acc": -0.3402, "final_rank": 4 } ]
aoj_DPL_4_A_cpp
Coin Combination Problem You have 4 bags A, B, C and D each of which includes N coins (there are totally 4N coins). Values of the coins in each bag are a i , b i , c i and d i respectively. Find the number of combinations that result when you choose one coin from each bag (totally 4 coins) in such a way that the total value of the coins is V . You should distinguish the coins in a bag. Constraints 1 ≤ N ≤ 1000 1 ≤ a i , b i , c i , d i ≤ 10 16 1 ≤ V ≤ 10 16 All input values are given in integers Input The input is given in the following format. N V a 1 a 2 ... a N b 1 b 2 ... b N c 1 c 2 ... c N d 1 d 2 ... d N Output Print the number of combinations in a line. Sample Input 1 3 14 3 1 2 4 8 2 1 2 3 7 3 2 Sample Output 1 9 Sample Input 2 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Sample Output 2 625
[ { "submission_id": "aoj_DPL_4_A_10881124", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nint main(){\n ll N,V; cin>>N>>V;\n vector<ll> A(N),B(N),C(N),D(N);\n for(ll& a:A) cin>>a;\n for(ll& a:B) cin>>a;\n for(ll& a:C) cin>>a;\n for(ll& a:D) cin>>a;\n\n vector<ll> M1(N*N),M2(N*N);\n for(int i=0;i<N;i++){\n for(int j=0;j<N;j++){\n M1[N*i+j]=A[i]+B[j];\n M2[N*i+j]=C[i]+D[j];\n }\n }\n sort(M2.begin(),M2.end());\n\n ll ans=0;\n for(int i=0;i<N*N;i++){\n ans+=upper_bound(M2.begin(),M2.end(),V-M1[i])-lower_bound(M2.begin(),M2.end(),V-M1[i]);\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 18824, "score_of_the_acc": -0.2596, "final_rank": 5 }, { "submission_id": "aoj_DPL_4_A_10850456", "code_snippet": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nll a[1005],b[1005],c[1005],d[1005];\nmap<ll,ll> m;\nint main(){\n ll N,V;\n cin>>N>>V;\n for(int i=0;i<N;i++) cin>>a[i];\n for(int i=0;i<N;i++) cin>>b[i];\n for(int i=0;i<N;i++) cin>>c[i];\n for(int i=0;i<N;i++) cin>>d[i];\n for(int i=0;i<N;i++)\n for(int j=0;j<N;j++)\n m[a[i]+b[j]]++;\n ll ans=0;\n for(int i=0;i<N;i++)\n for(int j=0;j<N;j++)\n ans+=m[V-c[i]-d[j]];\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 1070, "memory_kb": 128372, "score_of_the_acc": -2, "final_rank": 11 }, { "submission_id": "aoj_DPL_4_A_10776208", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nint main(){\n\n int N;\n ll res = 0, tmp, V;\n vector<ll> A, B, C, D, AB, CD;\n \n cin >> N >> V;\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n A.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n B.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n C.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n D.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n for( int j = 0 ; j < N ; j++ ){\n AB.push_back( A[i] + B[j] );\n CD.push_back( C[i] + D[j] );\n }\n }\n sort( CD.begin(), CD.end() );\n for( int i = 0 ; i < N * N ; i++ ){\n auto r = upper_bound( CD.begin(), CD.end(), V - AB[i] );\n auto l = lower_bound( CD.begin(), CD.end(), V - AB[i] );\n res += ( r - l );\n }\n cout << res << endl;\n\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 19120, "score_of_the_acc": -0.262, "final_rank": 6 }, { "submission_id": "aoj_DPL_4_A_10776200", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() - 1 ; i++ )\n cout << v[i] << ' ';\n cout << v[v.size()-1] << endl;\n}\n\nint main(){\n\n int N, res = 0;\n ll tmp, V;\n vector<ll> A, B, C, D, AB, CD;\n \n cin >> N >> V;\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n A.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n B.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n C.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n cin >> tmp;\n D.push_back( tmp );\n }\n for( int i = 0 ; i < N ; i++ ){\n for( int j = 0 ; j < N ; j++ ){\n AB.push_back( A[i] + B[j] );\n CD.push_back( C[i] + D[j] );\n }\n }\n sort( CD.begin(), CD.end() );\n for( int i = 0 ; i < N * N ; i++ ){\n auto r = upper_bound( CD.begin(), CD.end(), V - AB[i] );\n auto l = lower_bound( CD.begin(), CD.end(), V - AB[i] );\n res += ( r - l );\n }\n cout << res << endl;\n\n}", "accuracy": 0.6, "time_ms": 40, "memory_kb": 18796, "score_of_the_acc": -0.1273, "final_rank": 20 }, { "submission_id": "aoj_DPL_4_A_10769732", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\nint N;\nusing ll=long long;\nll V,a[4][1<<10];\nvector<ll>sum[2];\nsigned main(){\n cin.tie(0)->sync_with_stdio(0);\n cin>>N>>V;\n rep(i,4)rep(j,N)cin>>a[i][j];\n rep(i,2){\n rep(x,N)rep(y,N)sum[i].emplace_back(a[2*i][x]+a[2*i+1][y]);\n }\n sort(sum[1].begin(),sum[1].end());\n ll ans=0;\n for(const auto&s:sum[0]){\n ll t=V-s;\n ans+=distance(lower_bound(sum[1].begin(),sum[1].end(),t),upper_bound(sum[1].begin(),sum[1].end(),t));\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 24732, "score_of_the_acc": -0.2987, "final_rank": 7 }, { "submission_id": "aoj_DPL_4_A_10769728", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\nint N;\nusing ll=long long;\nll V,a[4][1<<10];\nvector<int>sum[2];\nsigned main(){\n cin.tie(0)->sync_with_stdio(0);\n cin>>N>>V;\n rep(i,4)rep(j,N)cin>>a[i][j];\n rep(i,2){\n rep(x,N)rep(y,N)sum[i].emplace_back(a[2*i][x]+a[2*i+1][y]);\n }\n sort(sum[1].begin(),sum[1].end());\n ll ans=0;\n for(const auto&s:sum[0]){\n ll t=V-s;\n ans+=distance(lower_bound(sum[1].begin(),sum[1].end(),t),upper_bound(sum[1].begin(),sum[1].end(),t));\n }\n cout<<ans<<endl;\n}", "accuracy": 0.92, "time_ms": 150, "memory_kb": 14544, "score_of_the_acc": -0.1961, "final_rank": 16 }, { "submission_id": "aoj_DPL_4_A_10278822", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n#include <queue>\n#include <map>\nusing namespace std;\n\n\nlong long solve(vector<vector<long long> > coin, long long n, long long v) {\n vector<long long> CD(n*n);\n //CとDからの取り出し方を全列挙\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n CD[n*i+j] = coin[2][i] + coin[3][j];\n }\n }\n\n sort(CD.begin(), CD.end());\n\n long long ans = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n long long cd = v - (coin[0][i] + coin[1][j]);\n ans += upper_bound(CD.begin(), CD.end(), cd) - lower_bound(CD.begin(), CD.end(), cd);\n }\n }\n return ans;\n}\n\n\nint main(void) {\n //入力\n long long n, v;\n cin >> n >> v;\n vector<vector<long long> > coin(4, vector<long long>(n));\n for(int i = 0; i < 4; i++) {\n for(int j = 0; j < n; j++) {\n cin >> coin[i][j];\n }\n }\n\n //出力\n cout << solve(coin, n, v) << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 11020, "score_of_the_acc": -0.1765, "final_rank": 1 }, { "submission_id": "aoj_DPL_4_A_10278808", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n#include <queue>\n#include <map>\nusing namespace std;\n\n\nlong long solve(vector<vector<long long> > coin, long long n, long long v) {\n vector<long long> CD(n*n);\n //CとDからの取り出し方を全列挙\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n CD[n*i+j] = coin[2][i] + coin[3][j];\n }\n }\n\n sort(CD.begin(), CD.end());\n\n long long ans = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n int cd = v - (coin[0][i] + coin[1][j]);\n ans += upper_bound(CD.begin(), CD.end(), cd) - lower_bound(CD.begin(), CD.end(), cd);\n }\n }\n return ans;\n}\n\n\nint main(void) {\n //入力\n long long n, v;\n cin >> n >> v;\n vector<vector<long long> > coin(4, vector<long long>(n));\n for(int i = 0; i < 4; i++) {\n for(int j = 0; j < n; j++) {\n cin >> coin[i][j];\n }\n }\n\n //出力\n cout << solve(coin, n, v) << endl;\n\n return 0;\n}", "accuracy": 0.92, "time_ms": 170, "memory_kb": 11052, "score_of_the_acc": -0.1862, "final_rank": 14 }, { "submission_id": "aoj_DPL_4_A_10278804", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n#include <queue>\n#include <map>\nusing namespace std;\n\n\nlong long solve(vector<vector<long> > coin, long n, long v) {\n vector<long long> CD(n*n);\n //CとDからの取り出し方を全列挙\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n CD[n*i+j] = coin[2][i] + coin[3][j];\n }\n }\n\n sort(CD.begin(), CD.end());\n\n long long ans = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n int cd = v - (coin[0][i] + coin[1][j]);\n ans += upper_bound(CD.begin(), CD.end(), cd) - lower_bound(CD.begin(), CD.end(), cd);\n }\n }\n return ans;\n}\n\n\nint main(void) {\n //入力\n long n, v;\n cin >> n >> v;\n vector<vector<long> > coin(4, vector<long>(n));\n for(int i = 0; i < 4; i++) {\n for(int j = 0; j < n; j++) {\n cin >> coin[i][j];\n }\n }\n\n //出力\n cout << solve(coin, n, v) << endl;\n\n return 0;\n}", "accuracy": 0.92, "time_ms": 170, "memory_kb": 11084, "score_of_the_acc": -0.1865, "final_rank": 15 }, { "submission_id": "aoj_DPL_4_A_10278800", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n#include <queue>\n#include <map>\nusing namespace std;\n\n\nlong long solve(vector<vector<int> > coin, int n, int v) {\n vector<long long> CD(n*n);\n //CとDからの取り出し方を全列挙\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n CD[n*i+j] = coin[2][i] + coin[3][j];\n }\n }\n\n sort(CD.begin(), CD.end());\n\n long long ans = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n int cd = v - (coin[0][i] + coin[1][j]);\n ans += upper_bound(CD.begin(), CD.end(), cd) - lower_bound(CD.begin(), CD.end(), cd);\n }\n }\n return ans;\n}\n\n\nint main(void) {\n //入力\n int n, v;\n cin >> n >> v;\n vector<vector<int> > coin(4, vector<int>(n));\n for(int i = 0; i < 4; i++) {\n for(int j = 0; j < n; j++) {\n cin >> coin[i][j];\n }\n }\n\n //出力\n cout << solve(coin, n, v) << endl;\n\n return 0;\n}", "accuracy": 0.92, "time_ms": 160, "memory_kb": 11052, "score_of_the_acc": -0.1768, "final_rank": 13 }, { "submission_id": "aoj_DPL_4_A_10278798", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n#include <queue>\n#include <map>\nusing namespace std;\n\n\nlong long solve(vector<vector<int> > coin, int n, int v) {\n vector<int> CD(n*n);\n //CとDからの取り出し方を全列挙\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n CD[n*i+j] = coin[2][i] + coin[3][j];\n }\n }\n\n sort(CD.begin(), CD.end());\n\n long long ans = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n int cd = v - (coin[0][i] + coin[1][j]);\n ans += upper_bound(CD.begin(), CD.end(), cd) - lower_bound(CD.begin(), CD.end(), cd);\n }\n }\n return ans;\n}\n\n\nint main(void) {\n //入力\n int n, v;\n cin >> n >> v;\n vector<vector<int> > coin(4, vector<int>(n));\n for(int i = 0; i < 4; i++) {\n for(int j = 0; j < n; j++) {\n cin >> coin[i][j];\n }\n }\n\n //出力\n cout << solve(coin, n, v) << endl;\n\n return 0;\n}", "accuracy": 0.92, "time_ms": 160, "memory_kb": 6964, "score_of_the_acc": -0.1432, "final_rank": 12 }, { "submission_id": "aoj_DPL_4_A_10278791", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n#include <queue>\n#include <map>\nusing namespace std;\n\n\nint solve(vector<vector<int> > coin, int n, int v) {\n vector<int> CD(n*n);\n //CとDからの取り出し方を全列挙\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n CD[n*i+j] = coin[2][i] + coin[3][j];\n }\n }\n\n sort(CD.begin(), CD.end());\n\n long long ans = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) {\n int cd = v - (coin[0][i] + coin[1][j]);\n ans += upper_bound(CD.begin(), CD.end(), cd) - lower_bound(CD.begin(), CD.end(), cd);\n }\n }\n return ans;\n}\n\n\nint main(void) {\n //入力\n int n, v;\n cin >> n >> v;\n vector<vector<int> > coin(4, vector<int>(n));\n for(int i = 0; i < 4; i++) {\n for(int j = 0; j < n; j++) {\n cin >> coin[i][j];\n }\n }\n\n //出力\n cout << solve(coin, n, v) << endl;\n\n return 0;\n}", "accuracy": 0.6, "time_ms": 30, "memory_kb": 6760, "score_of_the_acc": -0.0189, "final_rank": 17 }, { "submission_id": "aoj_DPL_4_A_10007151", "code_snippet": "#include <algorithm>\n#include <array>\n#include <bit>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <clocale>\n#include <cmath>\n#include <complex>\n#include <concepts>\n#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <deque>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <list>\n#include <map>\n#include <numbers>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <ranges>\n#include <regex>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nconstexpr int MOD{1'000'000'007};\nconstexpr int MOD2{998'244'353};\nconstexpr int INF{1'000'000'000}; //1e9\nconstexpr int NIL{-1};\nconstexpr long long LINF{1'000'000'000'000'000'000}; // 1e18\nconstexpr long double EPS{1E-10L};\nusing namespace std::literals;\nnamespace ranges = std::ranges;\nnamespace views = ranges::views;\n\ntemplate<class T, class S> bool chmax(T &a, const S &b){\n if(a < b){a = b; return true;}\n return false;\n}\ntemplate<class T, class S> bool chmin(T &a, const S &b){\n if(b < a){a = b; return true;}\n return false;\n}\ntemplate<class T> bool inside(T x, T lx, T rx){ //semi-open\n return (ranges::clamp(x, lx, rx-1) == x);\n}\ntemplate<class T> bool inside(T x, T y, T lx, T rx, T ly, T ry){\n return inside(x, lx, rx) && inside(y, ly, ry);\n}\ntemplate<class T, class S> std::istream &operator>>(std::istream &is, std::pair<T, S> &p){\n return is >> p.first >> p.second;\n}\ntemplate<class T, class S> std::ostream &operator<<(std::ostream &os, const std::pair<T, S> &p){\n return os << p.first << \" \" << p.second;\n}\ntemplate<class T> std::istream &operator>>(std::istream &is, std::vector<T> &v){\n {for(auto &e: v) is >> e;} return is;\n}\ntemplate<class Container> void print_container(const Container &c, std::string sep = \" \"s, std::string end = \"\\n\"s){\n for(int i{int(std::size(c))}; auto e: c) std::cout << e << (--i ? sep : end);\n}\nstd::string yesno(bool x){return x ? \"Yes\"s : \"No\"s;}\n\n\n\nint main(){\n int N; long long V; std::cin >> N >> V;\n auto ans{0LL};\n std::vector<long long> a(N), b(N), c(N), d(N), s;\n std::cin >> a >> b >> c >> d;\n for(auto e: a) for(auto f: b) s.push_back(e + f);\n ranges::sort(s);\n for(auto e: c) for(auto f: d){\n auto t{e + f};\n if(t > V) continue;\n ans += (long long)std::distance(ranges::lower_bound(s, V-t), ranges::upper_bound(s, V-t));\n }\n std::cout << ans << std::endl;\n return 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 12800, "score_of_the_acc": -0.2006, "final_rank": 2 }, { "submission_id": "aoj_DPL_4_A_9951529", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nint main(){\n int n;\n long long v;\n cin>>n>>v;\n vector<long long>a(n),b(n),c(n),d(n);\n for(int i=0;i<n;i++)cin>>a[i];\n for(int i=0;i<n;i++)cin>>b[i];\n for(int i=0;i<n;i++)cin>>c[i];\n for(int i=0;i<n;i++)cin>>d[i];\n auto calc=[](const vector<long long>&lhs,const vector<long long>&rhs)->vector<long long> {\n vector<long long>res;\n res.reserve(lhs.size()*rhs.size());\n for(int i=0;i<lhs.size();i++)for(int j=0;j<rhs.size();j++)res.push_back(lhs[i]+rhs[j]);\n return res;\n };\n auto f=calc(a,b);\n auto g=calc(c,d);\n sort(g.begin(),g.end());\n long long ans=0;\n for(int i=0;i<f.size();i++){\n long long t=v-f[i];\n ans+=upper_bound(g.begin(),g.end(),t)-lower_bound(g.begin(),g.end(),t);\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 18948, "score_of_the_acc": -0.2512, "final_rank": 4 }, { "submission_id": "aoj_DPL_4_A_9851163", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nusing ull=unsigned long long;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define loop(n) for (int tjh = 0; tjh < (int)(n); tjh++)\ntemplate <typename T>\nbool chmax(T &a, const T& b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T& b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\nint N;ll V;vector<ll>a;vector<ll>b;vector<ll>c;vector<ll>d;\nunordered_map<ll,int>A;ll A0;\nll res;\nint main() {\n std::cin.tie(nullptr);\n std::ios_base::sync_with_stdio(false);\n cout<<fixed<<setprecision(16);\n cin>>N>>V;a.resize(N);b.resize(N);\n rep(i,N)cin>>a[i];\n rep(i,N)cin>>b[i];\n rep(i,N){\n rep(j,N){\n A0=a[i]+b[j];\n if(A0<=V-2)A[A0]++;\n }\n }\n c.resize(N);d.resize(N);\n rep(i,N)cin>>c[i];\n rep(i,N)cin>>d[i];\n rep(i,N){\n rep(j,N){\n A0=c[i]+d[j];\n if(A0<=V-2)res+=(int)A[V-A0];\n }\n }\n cout<<res<<'\\n';\n}", "accuracy": 1, "time_ms": 420, "memory_kb": 88800, "score_of_the_acc": -1.0614, "final_rank": 9 }, { "submission_id": "aoj_DPL_4_A_9632043", "code_snippet": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n\nint main() {\n int N;\n long long V;\n std::cin >> N >> V;\n\n std::vector<long long> A(N), B(N), C(N), D(N);\n for (int i = 0; i < N; i++) std::cin >> A[i];\n for (int i = 0; i < N; i++) std::cin >> B[i];\n for (int i = 0; i < N; i++) std::cin >> C[i];\n for (int i = 0; i < N; i++) std::cin >> D[i];\n\n std::unordered_map<long long, int> counts;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = A[i] + B[j];\n counts[total]++;\n }\n }\n\n long long combinations = 0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = C[i] + D[j];\n if (counts.find(V - total) != counts.end()) {\n combinations += counts[V - total];\n }\n }\n }\n\n std::cout << combinations << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 290, "memory_kb": 52620, "score_of_the_acc": -0.6413, "final_rank": 8 }, { "submission_id": "aoj_DPL_4_A_9631987", "code_snippet": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n\nint main() {\n int N;\n long long V;\n std::cin >> N >> V;\n\n std::vector<long long> A(N), B(N), C(N), D(N);\n for (int i = 0; i < N; i++) std::cin >> A[i];\n for (int i = 0; i < N; i++) std::cin >> B[i];\n for (int i = 0; i < N; i++) std::cin >> C[i];\n for (int i = 0; i < N; i++) std::cin >> D[i];\n\n std::unordered_map<long long, int> counts;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = A[i] + B[j];\n counts[total]++;\n }\n }\n\n int combinations = 0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = C[i] + D[j];\n if (counts.find(V - total) != counts.end()) {\n combinations += counts[V - total];\n }\n }\n }\n\n std::cout << combinations << std::endl;\n\n return 0;\n}", "accuracy": 0.6, "time_ms": 10, "memory_kb": 9876, "score_of_the_acc": -0.0256, "final_rank": 18 }, { "submission_id": "aoj_DPL_4_A_9631985", "code_snippet": "#include <iostream>\n#include <vector>\n#include <map>\n\nint main() {\n int N;\n long long V;\n std::cin >> N >> V;\n\n std::vector<long long> A(N), B(N), C(N), D(N);\n for (int i = 0; i < N; i++) std::cin >> A[i];\n for (int i = 0; i < N; i++) std::cin >> B[i];\n for (int i = 0; i < N; i++) std::cin >> C[i];\n for (int i = 0; i < N; i++) std::cin >> D[i];\n\n std::map<long long, int> counts;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = A[i] + B[j];\n counts[total]++;\n }\n }\n\n long long combinations = 0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = C[i] + D[j];\n if (counts.find(V - total) != counts.end()) {\n combinations += counts[V - total];\n }\n }\n }\n\n std::cout << combinations << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 65936, "score_of_the_acc": -1.1281, "final_rank": 10 }, { "submission_id": "aoj_DPL_4_A_9631978", "code_snippet": "#include <iostream>\n#include <vector>\n#include <map>\n\nint main() {\n int N;\n long long V;\n std::cin >> N >> V;\n\n std::vector<long long> A(N), B(N), C(N), D(N);\n for (int i = 0; i < N; i++) std::cin >> A[i];\n for (int i = 0; i < N; i++) std::cin >> B[i];\n for (int i = 0; i < N; i++) std::cin >> C[i];\n for (int i = 0; i < N; i++) std::cin >> D[i];\n\n std::map<long long, int> counts;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = A[i] + B[j];\n counts[total]++;\n }\n }\n\n int combinations = 0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n long long total = C[i] + D[j];\n if (counts.find(V - total) != counts.end()) {\n combinations += counts[V - total];\n }\n }\n }\n\n std::cout << combinations << std::endl;\n\n return 0;\n}", "accuracy": 0.6, "time_ms": 60, "memory_kb": 13272, "score_of_the_acc": -0.1007, "final_rank": 19 }, { "submission_id": "aoj_DPL_4_A_9525768", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n\tcin.tie(nullptr);\n\tios::sync_with_stdio(false);\n\n\tint N, i, j, count;\n\tlong long V, ans = 0;\n\tcin >> N >> V;\n\tvector<long long> a(N), b(N), c(N), d(N), ab(N * N), cd(N * N);\n\tfor (i = 0; i != N; ++i) cin >> a[i];\n\tfor (i = 0; i != N; ++i) cin >> b[i];\n\tfor (i = 0; i != N; ++i) cin >> c[i];\n\tfor (i = 0; i != N; ++i) cin >> d[i];\n\n\tfor (i = 0; i != N; ++i)\n\t\tfor (j = 0; j != N; ++j)\n\t\t\tab[i * N + j] = a[i] + b[j], cd[i * N + j] = c[i] + d[j];\n\n\tsort(cd.begin(), cd.end());\n\tfor (i = 0; i != N * N; ++i)\n\t\tans += upper_bound(cd.begin(), cd.end(), V - ab[i]) - lower_bound(cd.begin(), cd.end(), V - ab[i]);\n\n\tcout << ans << '\\n';\n\treturn 0;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 18848, "score_of_the_acc": -0.2503, "final_rank": 3 } ]
aoj_DPL_3_C_cpp
Largest Rectangle in a Histogram A histogram is made of a number of contiguous bars, which have same width. For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area. Constraints $1 \leq N \leq 10^5$ $0 \leq h_i \leq 10^9$ Input The input is given in the following format. $N$ $h_1$ $h_2$ ... $h_N$ Output Print the area of the largest rectangle. Sample Input 1 8 2 1 3 5 3 4 2 1 Sample Output 1 12 Sample Input 2 3 2 0 1 Sample Output 2 2
[ { "submission_id": "aoj_DPL_3_C_11004547", "code_snippet": "#include <iostream>\n#include <stack>\n#include <vector>\n#include <utility>\n#define ll long long\nusing namespace std;\n\n// 自身より左にあって自身より小さい要素が一番最後に出てくるインデックス\nvector<int> find_small_left(const vector<ll>& hist){\n stack<pair<ll,int>> s; // pair{height, index}\n vector<int> ret(hist.size());\n s.push(make_pair(-1,-1));\n for(int i=0; i<hist.size();i++){\n if(s.top().first < hist[i]){\n ret[i] = i-1;\n s.push(make_pair(hist[i],i));\n }else{\n while(s.top().first>=hist[i]){\n s.pop();\n }\n ret[i] = s.top().second;\n s.push(make_pair(hist[i],i));\n }\n }\n return ret;\n}\n\nvector<int> find_small_right(vector<ll> hist){\n stack<pair<ll,int>> s;\n vector<int> ret(hist.size());\n s.push(make_pair(-1,hist.size()));\n for(int i=hist.size()-1; i>=0;i--){\n if(s.top().first < hist[i]){\n ret[i] = i+1;\n s.push(make_pair(hist[i],i));\n }else{\n while(s.top().first>=hist[i]){\n s.pop();\n }\n ret[i] = s.top().second;\n s.push(make_pair(hist[i],i));\n }\n }\n return ret;\n}\n\nll solve(vector<ll> hist){\n vector<int> left = find_small_left(hist);\n vector<int> right = find_small_right(hist);\n ll ans = 0;\n for(int i=0; i<hist.size(); i++){\n ll tmp = (right[i]-left[i]-1)*hist[i];\n if(ans < tmp){\n ans = tmp;\n }\n }\n return ans;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<ll> hist(n);\n for(int i=0; i<n; i++){\n cin >> hist[i];\n }\n cout << solve(hist) << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7816, "score_of_the_acc": -1.2955, "final_rank": 14 }, { "submission_id": "aoj_DPL_3_C_11004545", "code_snippet": "#include <iostream>\n#include <stack>\n#include <vector>\n#include <utility>\n#define ll long long\nusing namespace std;\n\n// 自身より左にあって自身より小さい要素が一番最後に出てくるインデックス\nvector<int> find_small_left(const vector<ll>& hist){\n stack<pair<ll,int>> s; // pair{height, index}\n vector<int> ret(hist.size());\n s.push(make_pair(-1,-1));\n for(int i=0; i<hist.size();i++){\n if(s.top().first < hist[i]){\n ret[i] = i-1;\n s.push(make_pair(hist[i],i));\n }else{\n while(s.top().first>=hist[i]){\n s.pop();\n }\n ret[i] = s.top().second;\n s.push(make_pair(hist[i],i));\n }\n }\n return ret;\n}\n\nvector<int> find_small_right(vector<ll> hist){\n stack<pair<ll,int>> s;\n vector<int> ret(hist.size());\n s.push(make_pair(-1,hist.size()));\n for(int i=hist.size()-1; i>=0;i--){\n if(s.top().first < hist[i]){\n ret[i] = i+1;\n s.push(make_pair(hist[i],i));\n }else{\n while(s.top().first>=hist[i]){\n s.pop();\n }\n ret[i] = s.top().second;\n s.push(make_pair(hist[i],i));\n }\n }\n return ret;\n}\n\nint solve(vector<ll> hist){\n vector<int> left = find_small_left(hist);\n vector<int> right = find_small_right(hist);\n ll ans = 0;\n for(int i=0; i<hist.size(); i++){\n ll tmp = (right[i]-left[i]-1)*hist[i];\n if(ans < tmp){\n ans = tmp;\n }\n }\n return ans;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<ll> hist(n);\n for(int i=0; i<n; i++){\n cin >> hist[i];\n }\n cout << solve(hist) << endl;\n}", "accuracy": 0.6666666666666666, "time_ms": 10, "memory_kb": 6620, "score_of_the_acc": -0.2089, "final_rank": 20 }, { "submission_id": "aoj_DPL_3_C_11003717", "code_snippet": "#include <iostream>\n#include <stack>\n#include <vector>\n#include <utility>\nusing namespace std;\n\n// 自身より左にあって自身より小さい要素が一番最後に出てくるインデックス\nvector<int> find_small_left(const vector<int>& hist){\n stack<pair<int,int>> s; // pair{height, index}\n vector<int> ret(hist.size());\n s.push(make_pair(-1,-1));\n for(int i=0; i<hist.size();i++){\n if(s.top().first < hist[i]){\n ret[i] = i-1;\n s.push(make_pair(hist[i],i));\n }else{\n while(s.top().first>=hist[i]){\n s.pop();\n }\n ret[i] = s.top().second;\n s.push(make_pair(hist[i],i));\n }\n }\n return ret;\n}\n\nvector<int> find_small_right(vector<int> hist){\n stack<pair<int,int>> s;\n vector<int> ret(hist.size());\n s.push(make_pair(-1,hist.size()));\n for(int i=hist.size()-1; i>=0;i--){\n if(s.top().first < hist[i]){\n ret[i] = i+1;\n s.push(make_pair(hist[i],i));\n }else{\n while(s.top().first>=hist[i]){\n s.pop();\n }\n ret[i] = s.top().second;\n s.push(make_pair(hist[i],i));\n }\n }\n return ret;\n}\n\nint solve(vector<int> hist){\n vector<int> left = find_small_left(hist);\n vector<int> right = find_small_right(hist);\n int ans = 0;\n for(int i=0; i<hist.size(); i++){\n int tmp = (right[i]-left[i]-1)*hist[i];\n if(ans < tmp){\n ans = tmp;\n }\n }\n return ans;\n}\n\nint main(){\n int n;\n cin >> n;\n vector<int> hist(n);\n for(int i=0; i<n; i++){\n cin >> hist[i];\n }\n cout << solve(hist) << endl;\n}", "accuracy": 0.6666666666666666, "time_ms": 10, "memory_kb": 5020, "score_of_the_acc": -0.093, "final_rank": 19 }, { "submission_id": "aoj_DPL_3_C_10945994", "code_snippet": "// C++ program to find maximum rectangular area in linear time\n#include<iostream>\n#include<stack>\nusing namespace std;\n \n// The main function to find the maximum rectangular area under given\n// histogram with n bars\nlong long getMaxArea(long long hist[], int n)\n{\n // Create an empty stack. The stack holds indexes of hist[] array\n // The bars stored in stack are always in increasing order of their\n // heights.\n stack<long long> s;\n \n long long max_area = 0; // Initalize max area\n long long tp; // To store top of stack\n long long area_with_top; // To store area with top bar as the smallest bar\n \n // Run through all bars of given histogram\n int i = 0;\n while (i < n)\n {\n // If this bar is higher than the bar on top stack, push it to stack\n if (s.empty() || hist[s.top()] <= hist[i])\n s.push(i++);\n \n // If this bar is lower than top of stack, then calculate area of rectangle \n // with stack top as the smallest (or minimum height) bar. 'i' is \n // 'right index' for the top and element before top in stack is 'left index'\n else\n {\n tp = s.top(); // store the top index\n s.pop(); // pop the top\n \n // Calculate the area with hist[tp] stack as smallest bar\n area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);\n \n // update max area, if needed\n if (max_area < area_with_top)\n max_area = area_with_top;\n }\n }\n \n // Now pop the remaining bars from stack and calculate area with every\n // popped bar as the smallest bar\n while (s.empty() == false)\n {\n tp = s.top();\n s.pop();\n area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);\n \n if (max_area < area_with_top)\n max_area = area_with_top;\n }\n \n return max_area;\n}\n \n// Driver program to test above function\nint main()\n{\n long long hist[100000];\n int n;\n\t\n\tcin >> n;\n\t\n\tfor(int i = 0; i < n; i++){\n\t\tcin >> hist[i];\n\t}\n\t\n cout << getMaxArea(hist, n) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4804, "score_of_the_acc": -1.0773, "final_rank": 4 }, { "submission_id": "aoj_DPL_3_C_10886455", "code_snippet": "#include <bits/stdc++.h>\n//#include <atcoder/modint>\n\nusing namespace std;\n//using namespace atcoder;\nusing ll = long long;\n//using mint = modint998244353;\n\nint main(){\n cin.tie(nullptr);\n ios_base::sync_with_stdio(false);\n\n /*\n 最大長方形\n stackに(インデックス、高さ)を入れ、stackで広義単調増加になるように高さを管理する。\n 番兵として(-∞, 0)を入れておく。\n stackの末尾がA_iより低くなるまでpopする。popできなくなったらそれが高さA_iの長方形の左端となる。\n 逆から見てくと右端もわかる。\n [l_i, r_i]が高さA_i以上となる区間なので(r_i-l_i+1)*A_iの長方形が作れる。\n */\n\n ll N, ans=0;\n cin >> N;\n vector<ll> A(N+1), left(N+1), right(N+1);\n for (int i=1; i<=N; i++) cin >> A[i];\n vector<pair<ll, ll>> v; //どこまでA_i以上の高さが連続するかを管理するstack\n v.push_back({-1e9, 0});\n for (int i=1; i<=N; i++){\n while(v.back().first >= A[i]) v.pop_back();\n left[i] = v.back().second+1;\n v.push_back({A[i], i});\n }\n v.clear();\n v.push_back({-1e9, N+1});\n for (int i=N; i>=1; i--){\n while(v.back().first >= A[i]) v.pop_back();\n right[i] = v.back().second-1;\n v.push_back({A[i], i});\n }\n\n for (int i=1; i<=N; i++) ans = max(ans, A[i]*(right[i]-left[i]+1));\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 7544, "score_of_the_acc": -0.2758, "final_rank": 2 }, { "submission_id": "aoj_DPL_3_C_10875527", "code_snippet": "#include<iostream>\n#include<vector>\nusing namespace std;\nint main() {\n int N;\n cin >> N;\n vector<int> h(N);\n for (int i = 0; i < N; i++) {\n cin >> h[i];\n }\n vector<pair<long long, int>> st;\n //st(高さ, idx)idxは左端を入れる\n long long ans = 0;\n for (int i = 0; i < N; i++) {\n int last = i;\n //[h[i]より大きい値のidx, i)の区間の長方形を計算する。そしてその飛び出たやつは消す\n while (!st.empty() && st.back().first > h[i]) {\n ans = max(ans, st.back().first * (i - st.back().second));\n last = st.back().second;\n st.pop_back();\n }\n if (st.empty() || st.back().first <= h[i]) {\n //st.back().first == h[i]のときは,左端のみが分かればいいため入れない。\n //lastは左端になっている。\n st.push_back(make_pair(h[i], last));\n }\n } \n while (!st.empty()) {\n ans = max(ans, st.back().first * (N - st.back().second));\n st.pop_back();\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5460, "score_of_the_acc": -1.1249, "final_rank": 7 }, { "submission_id": "aoj_DPL_3_C_10874908", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntemplate<typename T, typename F>\nclass CartesianTree {\n private:\n int N;\n F op;\n vector<int> left, right;\n vector<T> A;\n public:\n int root;\n vector<vector<int>> E;//2分木を構築\n vector<int> par;\n CartesianTree() {}\n CartesianTree(F _op, const vector<T> _A) \n : A(_A), op(_op), N(_A.size()), left(_A.size()), right(_A.size()), E(_A.size()) {\n vector<int> st;\n par.resize(N, -1);\n for (int i = 0; i < N; i++) {\n int pre = -1;\n while (!st.empty() && op(A[st.back()], A[i])) {\n pre = st.back();\n st.pop_back();\n }\n if (pre != -1) {\n par[pre] = i;\n }\n if (!st.empty()) {\n par[i] = st.back();\n } else {\n root = i;\n }\n st.push_back(i);\n }\n for (int i = 0; i < N; i++) {\n if (par[i] != -1) {\n E[par[i]].push_back(i);\n }\n }\n calc();\n } \n void calc() {\n for (int i = 0; i < N; i++) {\n left[i] = i;\n right[i] = i + 1;\n }\n auto dfs = [&] (auto &&self, int v) -> void {\n for (int w : E[v]) {\n self(self, w);\n left[v] = min(left[v], left[w]);\n right[v] = max(right[v], right[w]);\n }\n };\n dfs(dfs, root);\n }\n //A[v]が最大値または最小値(opによる)を取る区間を[l ,r)で返す\n pair<int, int> get_range(int v) {\n return make_pair(left[v], right[v]);\n }\n};\nbool op(int a, int b) {\n return a > b;\n}\nint main() {\n int N;\n cin >> N;\n vector<int> h(N);\n for (int i = 0; i < N; i++) {\n cin >> h[i];\n }\n CartesianTree CT(op, h);\n long long ans = 0;\n for (int i = 0; i < N; i++) {\n auto [l, r] = CT.get_range(i);\n ans = max(ans, (long long)(r - l) * h[i]);\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 17544, "score_of_the_acc": -2, "final_rank": 15 }, { "submission_id": "aoj_DPL_3_C_10800623", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define ld long double\n#define INF 1e18\nint main(){\n \n ll n,f,ans=0,sub;\n cin>>n;\n vector<ll> h(n);\n stack<pair<ll,ll>> s;\n for(auto& i:h)cin>>i;\n for(ll i=0;i<n;i++){\n if(s.empty()||s.top().first<h[i]){\n s.push({h[i],1});\n ans=max(ans,s.top().first);\n }\n else{\n f=0,sub=INF;\n while(s.size()&&s.top().first>=h[i]){\n f+=s.top().second;\n sub=min(sub,s.top().first);\n ans=max(ans,sub*f);\n s.pop();\n }\n s.push({h[i],f+1});\n ans=max(ans,s.top().first*(f+1));\n }\n }f=0,sub=INF;\n while(s.size()){\n auto [i,j]=s.top();s.pop();\n f+=j;\n if(s.empty())break;\n if(s.top().first<=i){\n ans=max(ans,s.top().first*(s.top().second+f));\n }\n else break;\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5176, "score_of_the_acc": -1.1043, "final_rank": 5 }, { "submission_id": "aoj_DPL_3_C_10798581", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nlong long int h[100005],l[100005],r[100005];\nstack<int>sl;\nstack<int>sr;\nint main(){\n\tint n;\n\tcin>>n;\n\tint i;\n\tfor(i=1;i<=n;i++){\n\t\tcin>>h[i];\n\t}\n\tfor(i=1;i<=n;i++){\n\t\twhile(!sl.empty()&&h[sl.top()]>=h[i]){\n\t\t\tsl.pop();\n\t\t}\n\t\tif(sl.empty()){\n\t\t\tl[i]=0;\n\t\t}else{\n\t\t\tl[i]=sl.top();\n\t\t}\n\t\tsl.push(i);\n\t}\n\tfor(i=n;i>=1;i--){\n\t\twhile(!sr.empty()&&h[sr.top()]>=h[i]){\n\t\t\tsr.pop();\n\t\t}\n\t\tif(sr.empty()){\n\t\t\tr[i]=n+1;\n\t\t}else{\n\t\t\tr[i]=sr.top();\n\t\t}\n\t\tsr.push(i);\n\t}\n\tlong long int ans=0;\n\tfor(i=1;i<=n;i++){\n\t\tans=max(ans,h[i]*(r[i]-l[i]-1));\n\t}\n\tcout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6204, "score_of_the_acc": -1.1787, "final_rank": 11 }, { "submission_id": "aoj_DPL_3_C_10777251", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n#include <chrono>\n#include <complex>\n#include <cmath>\n//#define PI M_PI\n#include <unistd.h>\n#define pc_u putchar\n#pragma GCC target (\"avx\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n#define rep(i,a,b) for(it i=(it)(a);i<=(it)b;i++)\n#define rep2(i,a,b,c) for(it i=(it)(a);i<=(it)b;i+=(it)c)\n#define irep(i,a,b) for(int i=(int)(a);i<=(int)b;i++)\n#define irep2(i,a,b,c) for(int i=(int)(a);i<=(int)b;i+=c)\n#define nrep(i,a,b) for(it i=(it)(a);i>=(it)b;i--)\n#define inrep(i,a,b) for(int i=(int)(a);i>=(int)b;i--)\n#define inrep2(i,a,b,c) for(int i=(int)(a);i>=(int)b;i-=c)\n#define all(v) v.begin(), v.end()\n#define rall(v) v.rbegin(), v.rend()\n#define Min(x) *min_element(all(x))\n#define Max(x) *max_element(all(x))\n#define moda 998244353LL\n#define modb 1000000007LL\n#define modc 968244353LL\n#define dai 2502502502502502502LL\n#define sho -dai\n#define aoi 1e18+1e6\n#define giri 1010000000\n#define en 3.14159265358979\n#define eps 1e-14\n#define fi first\n#define se second\n#define elif else if\ntemplate<typename T> using pq=priority_queue<T>;\ntemplate<typename T> using pqg=priority_queue<T,vector<T>,greater<T>>;\n#define uni(a) a.erase(unique(all(a)),a.end())\nusing it=long long;\nusing itn=int;\nusing un=unsigned long long;\nusing idb=double;\nusing db=long double;\nusing st=string;\nusing ch=char;\nusing bo=bool;\nusing P=pair<it,it>;\nusing ip=pair<int,int>;\nusing vi=vector<it>;\nusing ivi=vector<int>;\nusing ivd=vector<idb>;\nusing vd=vector<db>;\nusing vs=vector<st>;\nusing vc=vector<ch>;\nusing vb=vector<bo>;\nusing vp=vector<P>;\nusing ivp=vector<ip>;\nusing sp=set<P>;\nusing isp=set<ip>;\nusing ss=set<st>;\nusing sca=set<ch>;\nusing si=set<it>;\nusing isi=set<int>;\nusing svi=set<vi>;\nusing vvi=vector<vi>;\nusing ivvi=vector<ivi>;\nusing ivvd=vector<ivd>;\nusing vvd=vector<vd>;\nusing vvs=vector<vs>;\nusing vvb=vector<vb>;\nusing vvc=vector<vc>;\nusing vvp=vector<vp>;\nusing ivvp=vector<ivp>;\nusing vsi=vector<si>;\nusing ivsi=vector<isi>;\nusing isvi=set<ivi>;\nusing vsp=vector<sp>;\nusing ivsp=vector<isp>;\nusing vvsi=vector<vsi>;\nusing ivvsi=vector<ivsi>;\nusing vvsp=vector<vsp>;\nusing ivvsp=vector<ivsp>;\nusing svvb=set<vvb>;\nusing vvvi=vector<vvi>;\nusing ivvvi=vector<ivvi>;\nusing ivvvd=vector<ivvd>;\nusing vvvd=vector<vvd>;\nusing vvvb=vector<vvb>;\nusing ivvvp=vector<ivvp>;\nusing vvvvi=vector<vvvi>;\nusing ivvvvi=vector<ivvvi>;\nusing vvvvd=vector<vvvd>;\nusing ivvvvvi=vector<ivvvvi>;\nusing ivvvvvvi=vector<ivvvvvi>;\nusing ivvvvvvvi=vector<ivvvvvvi>;\nconst int dx[8]={0,1,0,-1,1,1,-1,-1};\nconst int dy[8]={1,0,-1,0,1,-1,1,-1};\nst abc=\"abcdefghijklmnopqrstuvwxyz\";\nst ABC=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nst num=\"0123456789\";\nst mb=\"xo\";\nst MB=\"XO\";\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\ntemplate<class T> using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;\n \nnamespace {\n \ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const pair<T, U> &p) {\n os << p.first << \" \" << p.second;\n return os;\n}\ntemplate <typename T, typename U>\nistream &operator>>(istream &is, pair<T, U> &p) {\n is >> p.first >> p.second;\n return is;\n}\n \ntemplate <typename T>\nostream &operator<<(ostream &os, const vector<T> &v) {\n int s = (int)v.size();\n for (int i = 0; i < s; i++) os << (i ? \" \" : \"\") << v[i];\n return os;\n}\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v) {\n for (auto &x : v) is >> x;\n return is;\n}\n \nistream &operator>>(istream &is, __int128_t &x) {\n string S;\n is >> S;\n x = 0;\n int flag = 0;\n for (auto &c : S) {\n if (c == '-') {\n flag = true;\n continue;\n }\n x *= 10;\n x += c - '0';\n }\n if (flag) x = -x;\n return is;\n}\n \nistream &operator>>(istream &is, __uint128_t &x) {\n string S;\n is >> S;\n x = 0;\n for (auto &c : S) {\n x *= 10;\n x += c - '0';\n }\n return is;\n}\n \nostream &operator<<(ostream &os, __int128_t x) {\n if (x == 0) return os << 0;\n if (x < 0) os << '-', x = -x;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\nostream &operator<<(ostream &os, __uint128_t x) {\n if (x == 0) return os << 0;\n string S;\n while (x) S.push_back('0' + x % 10), x /= 10;\n reverse(begin(S), end(S));\n return os << S;\n}\n \nvoid input() {}\ntemplate <typename T, class... U>\nvoid input(T &t, U &...u) {\n cin >> t;\n input(u...);\n}\ntemplate <typename T, class... U>\nvoid input1(T &t, U &...u) {\n input(u...);\n}\nvoid print() { cout << \"\\n\"; }\ntemplate <typename T, class... U, char sep = ' '>\nvoid print(const T &t, const U &...u) {\n cout << t;\n if (sizeof...(u)) cout << sep;\n print(u...);\n}\ntemplate <typename T, class... U, char sep = ' '>\nvoid print1(const T &t, const U &...u) {\n if (sizeof...(u)) cout << sep;\n print(u...);\n}\n \nstruct IoSetupNya {\n IoSetupNya() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n cerr << fixed << setprecision(7);\n }\n} iosetupnya;\n \n} //namespace Nyaan\n\ntemplate<typename T>\nT Sum(vector<T> &a){\n T s=0;\n for(auto i:a)s+=i;\n return s;\n}\n\ntemplate<typename T>\nvoid dec(vector<T> &a){\n rep(i,0,a.size()-1)a[i]--;\n return;\n}\n\ntemplate<typename T>\nT gcda(T a,T b){\n if(!a||!b)return max(a,b);\n while(a%b&&b%a){\n if(a>b)a%=b;\n else b%=a;\n }\n return min(a,b);\n}\n\nit lcma(it a,it b){\n return a/gcda(a,b)*b;\n}\n\ndb distance(db a,db b,db c,db d){return sqrt((a-c)*(a-c)+(b-d)*(b-d));}\n\nbo outc(int h,int w,int x,int y){\n return (x<0||x>=h||y<0||y>=w);\n}\n\ntemplate<typename T>\nvector<vector<T>> nep(vector<T> a){\n vector<vector<T>> e;\n sort(all(a));\n do{\n e.emplace_back(a);\n }while(next_permutation(all(a)));\n return e;\n}\n\nvoid yn(bo a){print(a?string(\"Yes\"):string(\"No\"));}\nvoid YN(bo a){print(a?string(\"YES\"):string(\"NO\"));}\n\n/*総和をもとめるセグ木\nstruct nod{\n it val;\n nod(it v=0):val(v){}\n};\n \nnod op(nod a,nod b){return nod(a.val+b.val);}\nnod e(){return nod(0);}\n \nstruct act{\n it a;\n act(it e=0):a(e){}\n};\n \nnod mapping(act f,nod x){return nod(f.a+x.val);}\nact comp(act f,act g){return act(f.a+g.a);}\nact id(){return act(0);}*/\n//#define endl '\\n'\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n\nstruct dsu1{\n ivi par,siz,mi,ma;\n dsu1(int n){\n init(n);\n }\n void init(int n){\n rep(i,0,n-1){\n par.emplace_back(i);\n siz.emplace_back(1);\n }\n }\n int leader(int u){\n if(par[u]==u)return u;\n return par[u]=leader(par[u]);\n }\n void merge(int u,int v){\n int ru=leader(u),rv=leader(v);\n if(ru==rv)return;\n if(size(ru)<size(rv))swap(ru,rv);\n siz[ru]+=siz[rv];\n par[rv]=ru;\n }\n bool same(int u,int v){\n return leader(u)==leader(v);\n }\n int size(int u){\n return siz[leader(u)];\n }\n};\n\nvoid solve(){\n int n;input(n);\n pq<P> que;\n vi h(n);\n irep(i,0,n-1){\n input(h[i]);\n que.push({h[i],i});\n }\n it ans=0;\n dsu1 uf(n);\n while(que.size()){\n it w=que.top().first;int u=que.top().second;que.pop();\n if(u&&h[u-1]>=h[u])uf.merge(u-1,u);\n if(u!=n-1&&h[u+1]>=h[u])uf.merge(u+1,u);\n ans=max(ans,w*uf.size(u));\n }\n print(ans);\n}\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int t=1;//input(t);\n while(t--)solve();\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6776, "score_of_the_acc": -1.2202, "final_rank": 13 }, { "submission_id": "aoj_DPL_3_C_10433399", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define rep(i,l,r) for(int i=(l);i<(r);i++)\nusing ll=long long;\ntemplate<typename T1,typename T2>inline bool chmin(T1 &a,T2 b){ return (a>b?a=b,true:false); }\ntemplate<typename T1,typename T2>inline bool chmax(T1 &a,T2 b){ return (a<b?a=b,true:false); }\n\nint main(){\n cin.tie(nullptr)->ios::sync_with_stdio(false); \n int n;\n cin>>n;\n vector<int> a(n);\n for(auto &e:a) cin>>e;\n vector<int> L(n),R(n);\n stack<pair<int,int>> st;\n st.emplace(-1,-1);\n rep(i,0,n){\n while(st.top().first>=a[i]) st.pop();\n L[i]=i-st.top().second-1;\n st.emplace(a[i],i);\n }\n while(st.size()) st.pop();\n st.emplace(-1,n);\n for(int i=n-1;i>=0;i--){\n while(st.top().first>=a[i]){\n st.pop();\n }\n R[i]=st.top().second-i-1;\n st.emplace(a[i],i);\n }\n ll ans=0;\n rep(i,0,n){\n chmax(ans,(ll)a[i]*(L[i]+R[i]+1));\n }\n cout<<ans<<\"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5088, "score_of_the_acc": -0.0979, "final_rank": 1 }, { "submission_id": "aoj_DPL_3_C_10338894", "code_snippet": "#include <iostream>\n#include <stack>\n#include <vector>\nusing namespace std;\n\nlong long largest(const vector<int> &height)\n{\n int n = height.size();\n stack<int> s;\n long long max_area = 0;\n for (int i = 0; i < n; ++i)\n {\n int h = height[i];\n while (!s.empty() && height[s.top()] >= h)\n {\n long long h = height[s.top()];\n s.pop();\n long long w;\n if (s.empty())\n w = i;\n else\n w = i - s.top() - 1;\n max_area = max(max_area, h * w);\n }\n s.push(i);\n }\n return max_area;\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector<int> height(N+1);\n for (int i = 0; i < N; ++i)\n cin >> height[i];\n height[N] = 0;\n cout << largest(height) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3736, "score_of_the_acc": -1, "final_rank": 3 }, { "submission_id": "aoj_DPL_3_C_10338888", "code_snippet": "#include <iostream>\n#include <stack>\n#include <vector>\nusing namespace std;\n\nint largest(const vector<int> &height)\n{\n int n = height.size();\n stack<int> s;\n long long max_area = 0;\n for (int i = 0; i < n; ++i)\n {\n int h = height[i];\n while (!s.empty() && height[s.top()] >= h)\n {\n long long h = height[s.top()];\n s.pop();\n long long w;\n if (s.empty())\n w = i;\n else\n w = i - s.top() - 1;\n max_area = max(max_area, h * w);\n }\n s.push(i);\n }\n return max_area;\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector<int> height(N+1);\n for (int i = 0; i < N; ++i)\n cin >> height[i];\n height[N] = 0;\n cout << largest(height) << endl;\n return 0;\n}", "accuracy": 0.6666666666666666, "time_ms": 10, "memory_kb": 3820, "score_of_the_acc": -0.0061, "final_rank": 17 }, { "submission_id": "aoj_DPL_3_C_10338857", "code_snippet": "#include <iostream>\n#include <stack>\n#include <vector>\nusing namespace std;\n\nint largest(const vector<int> &height)\n{\n int n = height.size();\n stack<int> s;\n int max_area = 0;\n for (int i = 0; i < n; ++i)\n {\n int h = height[i];\n while (!s.empty() && height[s.top()] > h)\n {\n int h = height[s.top()];\n s.pop();\n int w;\n if (s.empty())\n w = i;\n else\n w = i - s.top() - 1;\n max_area = max(max_area, h * w);\n }\n s.push(i);\n }\n return max_area;\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector<int> height(N+1);\n for (int i = 0; i < N; ++i)\n cin >> height[i];\n height[N] = 0;\n cout << largest(height) << endl;\n return 0;\n}", "accuracy": 0.6666666666666666, "time_ms": 10, "memory_kb": 3752, "score_of_the_acc": -0.0012, "final_rank": 16 }, { "submission_id": "aoj_DPL_3_C_10338855", "code_snippet": "#include <iostream>\n#include <stack>\n#include <vector>\nusing namespace std;\n\nint largest(const vector<int> &height)\n{\n int n = height.size();\n stack<int> s;\n int max_area = 0;\n for (int i = 0; i <= n; ++i)\n {\n int h = height[i];\n while (!s.empty() && height[s.top()] > h)\n {\n int h = height[s.top()];\n s.pop();\n int w;\n if (s.empty())\n w = i;\n else\n w = i - s.top() - 1;\n max_area = max(max_area, h * w);\n }\n s.push(i);\n }\n return max_area;\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector<int> height(N+1);\n for (int i = 0; i < N; ++i)\n cin >> height[i];\n height[N] = 0;\n cout << largest(height) << endl;\n return 0;\n}", "accuracy": 0.6666666666666666, "time_ms": 10, "memory_kb": 3876, "score_of_the_acc": -0.0101, "final_rank": 18 }, { "submission_id": "aoj_DPL_3_C_10313734", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < (n); ++i)\n#define repp(i,n) for(int i = 1; i <= (n); ++i)\n#define drep(i,n) for(int i = (n)-1; i >= 0; --i)\n#define srep(i,s,t) for (int i = s; i < (t); ++i)\n#define rng(a) a.begin(),a.end()\n#define rrng(a) a.rbegin(),a.rend()\n#define fi first\n#define se second\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define pob pop_back\n#define sz(x) (int)(x).size()\n#define pcnt __builtin_popcountll\n#define koulet srand((unsigned)clock()+(unsigned)time(NULL));\n#define newline puts(\"\")\n#define vc vector\n#define stoi stoll \nusing namespace std;\ntemplate<class T> using vv = vc<vc<T>>;\ntemplate<class T> using PQ = priority_queue<T,vc<T>,greater<T>>;\nusing uint = unsigned; using ull = unsigned long long;\nusing vi = vc<int>; using vvi = vv<int>; using vvvi = vv<vi>;\nusing ll = long long; using vl = vc<ll>; using vvl = vv<ll>; using vvvl = vv<vl>;\nusing P = pair<int,int>; using vp = vc<P>; using vvp = vv<P>; using LP = pair<ll,ll>;\nusing vs = vc<string>; using vb=vc<bool> ; using vlp = vc<LP> ; \nint geti(){int x;scanf(\"%d\",&x);return x;}\nvi pm(int n, int s=0) { vi a(n); iota(rng(a),s); return a;}\ntemplate<class T1,class T2>istream& operator>>(istream&i,pair<T1,T2>&v){return i>>v.fi>>v.se;}\ntemplate<class T1,class T2>ostream& operator<<(ostream&o,const pair<T1,T2>&v){return o<<v.fi<<\",\"<<v.se;}\ntemplate<class T>istream& operator>>(istream&i,vc<T>&v){rep(j,sz(v))i>>v[j];return i;}\ntemplate<class T>string join(const T&v,const string&d=\"\"){stringstream s;rep(i,sz(v))(i?s<<d:s)<<v[i];return s.str();}\ntemplate<class T>ostream& operator<<(ostream&o,const vc<T>&v){if(sz(v))o<<join(v,\" \");return o;}\ntemplate<class T>void vin(vc<T>&a){int n;cin>>n;a=vc<T>(n);cin>>a;}\ntemplate<class T>void vin(vv<T>&a){int n,m;cin>>n>>m;a=vv<T>(n,vc<T>(m));cin>>a;}\ntemplate<class T1,class T2>void operator--(pair<T1,T2>&a,int){a.fi--;a.se--;}\ntemplate<class T1,class T2>void operator++(pair<T1,T2>&a,int){a.fi++;a.se++;}\ntemplate<class T>void operator--(vc<T>&a,int){for(T&x:a)x--;}\ntemplate<class T>void operator++(vc<T>&a,int){for(T&x:a)x++;}\ntemplate<class T>void operator+=(vc<T>&a,T b){for(T&x:a)x+=b;}\ntemplate<class T>void operator-=(vc<T>&a,T b){for(T&x:a)x-=b;}\ntemplate<class T>void operator*=(vc<T>&a,T b){for(T&x:a)x*=b;}\ntemplate<class T>void operator/=(vc<T>&a,T b){for(T&x:a)x/=b;}\ntemplate<class T>void operator+=(vc<T>&a,const vc<T>&b){a.insert(a.end(),rng(b));}\ntemplate<class T1,class T2>pair<T1,T2>operator+(const pair<T1,T2>&a,const pair<T1,T2>&b){return {a.fi+b.fi,a.se+b.se};}\ntemplate<class T1,class T2>pair<T1,T2>operator-(const pair<T1,T2>&a,const pair<T1,T2>&b){return {a.fi-b.fi,a.se-b.se};}\ntemplate<class T>pair<T,T>operator*(const pair<T,T>&a,T b){return {a.fi*b,a.se*b};}\ntemplate<class T1,class T2>bool mins(T1& x,const T2&y){if(y<x){x=y;return true;}else return false;}\ntemplate<class T1,class T2>bool maxs(T1& x,const T2&y){if(x<y){x=y;return true;}else return false;}\ntemplate<class T>T min(const vc<T>&a){return *min_element(rng(a));}\ntemplate<class T>T max(const vc<T>&a){return *max_element(rng(a));}\ntemplate<class Tx,class Ty>Tx dup(Tx x, Ty y){return (x+y-1)/y;}\ntemplate<class T>ll suma(const vc<T>&a){ll s=0;for(auto&&x:a)s+=x;return s;}\ntemplate<class T>ll suma(const vv<T>&a){ll s=0;for(auto&&x:a)s+=suma(x);return s;}\ntemplate<class T>void uni(T&a){sort(rng(a));a.erase(unique(rng(a)),a.end());}\ntemplate<class T>void prepend(vc<T>&a,const T&x){a.insert(a.begin(),x);}\ntemplate<typename T>T floor(T a, T b){T r=(a%b+b)%b;return (a-r)/b;}\ntemplate<typename T>T ceil(T a, T b){return floor(a+b-1,b);}\ntemplate<typename T>vc<T> cumsum(vc<T> &a,int off=1){int N=sz(a);vc<T>B(N+1);rep(i, N)B[i+1]=a[i]+B[i];if(off==0)B.erase(B.begin());return B;}\nconst double eps = 1e-10;\nconst ll LINF = 1001002003004005006ll;\nconst int INF = 1001001001;\n#define dame { puts(\"-1\"); return 0 ;}\n#define yes { puts(\"Yes\"); return 0 ;}\n#define no { puts(\"No\"); return 0 ;}\n#define rtn(x) { cout<<(x)<<endl;} // flush!\n#define yn {puts(\"Yes\");}else{puts(\"No\");}\nll c2(ll n) { return n*(n-1)>>1;}\n\ntemplate<typename T>void rot(T& a,int i){rotate(a.begin(),a.begin()+(i),a.end());}// i回シフト\ntemplate<typename T>void rot(vv<T>& a){int h=sz(a),w=sz(a[0]);vv<T> p(w,vc<T>(h));swap(a,p);rep(i,h)rep(j,w)a[j][h-1-i]=p[i][j];}\nvoid rot(vc<string>& a){int h=sz(a),w=sz(a[0]);vc<string> p(w,string(h,'?'));swap(a,p);rep(i,h)rep(j,w)a[j][h-1-i]=p[i][j];}\n\nconst int dx[] = {-1,0,1,0,1,1,-1,-1,}, dy[] = {0,-1,0,1,1,-1,1,-1}; //^<v>↘︎\n//^, <, v, >, ↘︎, ↙︎, ↗︎, ↖︎ \n\n// Mod int\nuint mod = 998244353;//*/\n// uint mod = 1000000007;//*/\nuint md(ll x) { x%=mod; return x<0?x+mod:x;}\nll md(ll x, ll m) { x%=m; return x<0?x+m:x;}\nstruct mint {\n uint x;\n mint(): x(0) {}\n mint(ll x):x(md(x)) {}\n mint operator-() const { return mint(0) - *this;}\n mint operator~() const { return mint(1) / *this;}\n mint& operator+=(const mint& a) { if((x+=a.x)>=mod) x-=mod; return *this;}\n mint& operator-=(const mint& a) { if((x+=mod-a.x)>=mod) x-=mod; return *this;}\n mint& operator*=(const mint& a) { x=(ull)x*a.x%mod; return *this;}\n mint& operator/=(const mint& a) { x=(ull)x*a.pow(mod-2).x%mod; return *this;}\n mint operator+(const mint& a) const { return mint(*this) += a;}\n mint operator-(const mint& a) const { return mint(*this) -= a;}\n mint operator*(const mint& a) const { return mint(*this) *= a;}\n mint operator/(const mint& a) const { return mint(*this) /= a;}\n mint pow(ll t) const {\n mint res = 1; for (mint p=x;t;p*=p,t>>=1) if (t&1) res *= p; return res;\n }\n mint ppow(ll t) const { int p=mod-1; return pow((t%p+p)%p);}\n bool operator<(const mint& a) const { return x < a.x;}\n bool operator==(const mint& a) const { return x == a.x;}\n bool operator!=(const mint& a) const { return x != a.x;}\n};\nmint ex(mint x, ll t) { return x.pow(t);}\nistream& operator>>(istream&i,mint&a) {i>>a.x;return i;}\n//*\nostream& operator<<(ostream&o,const mint&a) {o<<a.x;return o;}\n/*/\nostream& operator<<(ostream&o, const mint&x) {\n int a = x.x, b = 1;\n rep(s,2)rep1(i,1000) {\n int y = ((s?-x:x)*i).x; if (abs(a)+b > y+i) a = s?-y:y, b = i;\n }\n o<<a; if (b != 1) o<<'/'<<b; return o;\n}//*/\nusing vm = vector<mint>;\nusing vvm = vector<vm>;\nstruct modinv {\n int n; vm d;\n modinv(): n(2), d({0,1}) {}\n mint operator()(int i) { while (n <= i) d.pb(-d[mod%n]*(mod/n)), ++n; return d[i];}\n mint operator[](int i) const { return d[i];}\n} invs;\nstruct modfact {\n int n; vm d;\n modfact(): n(2), d({1,1}) {}\n mint operator()(int i) { while (n <= i) d.pb(d.back()*n), ++n; return d[i];}\n mint operator[](int i) const { return d[i];}\n} facs;\nstruct modfactinv {\n int n; vm d;\n modfactinv(): n(2), d({1,1}) {}\n mint operator()(int i) { while (n <= i) d.pb(d.back()*invs(n)), ++n; return d[i];}\n mint operator[](int i) const { return d[i];}\n} ifacs;\nmint comb(int a, int b) {\n if (a < b || b < 0) return 0;\n return facs(a)*ifacs(b)*ifacs(a-b);\n}\nstruct modpow {\n mint x; int n; vm d;\n modpow(mint x=2): x(x), n(1), d(1,1) {}\n mint operator()(int i) { while (n <= i) d.pb(d.back()*x), ++n; return d[i];}\n mint operator[](int i) const { return d[i];}\n} two(2);//, owt(invs(2));\n// \n\nll largest_rectangle(vl a){\n\tint n = sz(a) ;\n\tll res = 0 ;\n\tvl l(n) , r(n) ;\n\t{\n\t\tstack<int> st; \n\t\trep(i, n){\n\t\t\twhile(sz(st)&&a[st.top()]>=a[i]) st.pop() ;\n\t\t\tif(sz(st) == 0) l[i] = i+1 ; \n\t\t\telse l[i]=i-st.top() ;\n\t\t\tst.push(i) ;\n\t\t}\n\t};\n\t{\n\t\tstack<int> st; \n\t\tdrep(i, n){\n\t\t\twhile(sz(st)&&a[st.top()]>a[i]) st.pop() ;\n\t\t\tif(sz(st) == 0) r[i]=n-i; \n\t\t\telse r[i]=st.top()-i;\n\t\t\tst.push(i) ;\n\t\t}\n\t};\n\trep(i, n) maxs(res, (ll)a[i]*(r[i]+l[i]-1)) ;\n\treturn res ;\n} ;\nint main() {\n\tint n; cin>>n ; \n\tvl h(n) ;cin>> h ; \n\tcout << largest_rectangle(h) << endl;\n\n\n\n\n\n\t\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6740, "score_of_the_acc": -1.2176, "final_rank": 12 }, { "submission_id": "aoj_DPL_3_C_9831479", "code_snippet": "#define rep(i,n) for(int i=0;i<(int)(n);i++)\n#define ALL(v) v.begin(),v.end()\ntypedef long long ll;\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n//最大長方形(ヒストグラム) 蟻本p.298 計算量O(n)\nint main(){\n int n;\n cin>>n;\n \n vector<ll> H(n);\n rep(i,n) cin>>H[i];\n \n vector<ll> L(n),R(n); //i番目の高さで行ける左端と右端\n stack<ll> s,t;\n \n //行ける候補をスタックで管理。i番目の高さ以上の場所は今後、端(のひとつ左)にならないので削除。\n rep(i,n){\n while(!s.empty() && H[s.top()]>=H[i]) s.pop();\n if(s.empty()) L[i]=0;\n else L[i]=s.top()+1;\n s.push(i);\n }\n for(int i=n-1;i>=0;i--){\n while(!t.empty() && H[t.top()]>=H[i]) t.pop();\n if(t.empty()) R[i]=n-1;\n else R[i]=t.top()-1;\n t.push(i);\n }\n \n ll ma=0;\n rep(i,n) ma=max(ma,H[i]*(R[i]-L[i]+1));\n cout<<ma<<endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6148, "score_of_the_acc": -1.1747, "final_rank": 10 }, { "submission_id": "aoj_DPL_3_C_9817164", "code_snippet": "// #define _GLIBCXX_DEBUG\n#include <bits/stdc++.h>\nusing namespace std;\n\n/* alias*/\nusing ull = unsigned long long;\nusing ll = long long;\nusing vi = vector<int>;\nusing vl = vector<long long>;\nusing vs = vector<string>;\nusing vb = vector<bool>;\nusing vd = vector<double>;\nusing vvi = vector<vi>;\nusing vvl = vector<vl>;\nusing vvd = vector<vd>;\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\nusing vpi = vector<pi>;\nusing vpl = vector<pl>;\n\n/* define short */\n#define _overload5(a, b, c, d, e, name, ...) name\n#define _overload4(a, b, c, d, name, ...) name\n#define _overload3(a, b, c, name, ...) name\n#define _rep0(n) for(int i = 0; i < (int)(n); ++i)\n#define _rep1(i, n) for(int i = 0; i < (int)(n); ++i)\n#define _rep2(i, a, b) for(int i = (int)(a); i < (int)(b); ++i)\n#define _rep3(i, a, b, c) for(int i = (int)(a); i < (int)(b); i += (int)(c))\n#define rep(...) _overload4(__VA_ARGS__, _rep3, _rep2, _rep1, _rep0)(__VA_ARGS__)\n#define rrep1(n) for(int i = (n) - 1;i >= 0;i--)\n#define rrep2(i,n) for(int i = (n) - 1;i >= 0;i--)\n#define rrep3(i,a,b) for(int i = (b) - 1;i >= (a);i--)\n#define rrep4(i,a,b,c) for(int i = (a) + ((b)-(a)-1) / (c) * (c);i >= (a);i -= c)\n#define rrep(...) _overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define sz(x) (int)(x).size()\n#define pcnt(x) __builtin_popcountll(x)\n#define eb emplace_back\n#define fi first\n#define se second\n\n/* debug */\n// 標準エラー出力を含む提出はrejectされる場合もあるので注意\n#define debug(x) cerr << \"\\033[33m(line:\" << __LINE__ << \") \" << #x << \": \" << x << \"\\033[m\" << endl;\n\n/* func */\ntemplate<class T> inline bool chmax(T& a, T b) { return ((a < b) ? (a = b, true) : (false)); }\ntemplate<class T> inline bool chmin(T& a, T b) { return ((a > b) ? (a = b, true) : (false)); }\n\n/* const */\nconst int INF = INT_MAX/2;\nconst ll LINF = 1LL<<60;\nconst int MOD = 1e9+7;\nconst int dx[] {1,0,-1,0};\nconst int dy[] {0,1,0,-1};\nconst double PI = 3.1415926535;\nconst string yes = \"Yes\";\nconst string no = \"No\";\n\n\nint main() { \n int n; cin >> n;\n vl a(n+1); rep(i,n) cin >> a[i];\n\n ll ans = 0;\n vector<pair<ll,int>> st;\n rep(i,n+1) {\n int pos = i;\n while (!st.empty() && st.back().fi > a[i]) {\n auto [h,j] = st.back(); st.pop_back();\n ll x = h*(i-j);\n chmax(ans,x);\n pos = j;\n }\n st.eb(a[i],pos);\n }\n\n cout << ans << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5984, "score_of_the_acc": -1.1628, "final_rank": 9 }, { "submission_id": "aoj_DPL_3_C_9684393", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <stack>\nusing namespace std;\ntypedef long long ll;\n// const ll INF64 = 1LL << 60;\nconst ll INF64 = ((1LL<<62)-(1LL<<31)); // 10^18より大きく、かつ2倍しても負にならない数\nconst int INF32 = 0x3FFFFFFF; // =(2^30)-1 10^9より大きく、かつ2倍しても負にならない数\ntemplate<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; }\n#define YesNo(T) cout << ((T) ? \"Yes\" : \"No\") << endl; // T:bool\n\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_3_C\n\n/*\n * ヒストグラム中の最大正方形問題。\n * 考え方は以下が分かりやすかった。\n * http://algorithms.blog55.fc2.com/blog-entry-132.html\n * \n * スタックに {y座標:h[i], x座標} の形で、y座標について単調増加になるよう持たせていく。\n * 今見ているh[i]をスタックに入れようとしたとき、単調増加を満たさないのであれば取り出して面積を計算する。\n * \n * スタックに登録するとき、取り出した分だけx座標を手前に動かす必要がある点に注意。\n */\n\nint main(void)\n{\n\tint i;\n\tint N; cin >> N;\n\tvector<ll> h(N); for(i = 0; i < N; i++) {cin >> h[i];}\n\th.push_back(0); // 末尾番兵\n\n\t// [実装方針]\n\t// stack内は単調増加、先頭から見ていく、stackには高さに加えx座標の情報が必要\n\n\tstack<pair<ll,ll>> st;\n\tst.push({0, -1}); // 先頭番兵\n\tll ans = 0;\n\tfor(i = 0; i < (int)h.size(); i++)\n\t{\n\t\tint x = i;\n\t\twhile(st.top().first > h[i]) // h[i]を入れたときに単調増加を満たすようにするまで\n\t\t{\n\t\t\tauto [hh,xx] = st.top();\n\t\t\tst.pop();\n\t\t\tchmax(ans, (i-xx)*hh);\n\t\t\tx = xx;\n\t\t}\n\t\tst.push({h[i], x});\n\t}\n\tcout << ans << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5488, "score_of_the_acc": -1.1269, "final_rank": 8 }, { "submission_id": "aoj_DPL_3_C_9684362", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <stack>\nusing namespace std;\ntypedef long long ll;\n// const ll INF64 = 1LL << 60;\nconst ll INF64 = ((1LL<<62)-(1LL<<31)); // 10^18より大きく、かつ2倍しても負にならない数\nconst int INF32 = 0x3FFFFFFF; // =(2^30)-1 10^9より大きく、かつ2倍しても負にならない数\ntemplate<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; }\n#define YesNo(T) cout << ((T) ? \"Yes\" : \"No\") << endl; // T:bool\n\n// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_3_C\n\n/*\n * \n * \n */\n\nint main(void)\n{\n\tint i;\n\tint N; cin >> N;\n\tvector<ll> h(N); for(i = 0; i < N; i++) {cin >> h[i];}\n\th.push_back(0); // 末尾番兵\n\n\t// stack内は単調増加\n\t// stackには高さとx座標の情報が必要\n\t// 先頭から\n\tstack<pair<ll,ll>> st;\n\tst.push({0, -1}); // 番兵\n\tll ans = 0;\n\tfor(i = 0; i < (int)h.size(); i++)\n\t{\n\t\tint x = i;\n\t\twhile(st.top().first > h[i]) // h[i]を入れても単調増加を満たすようにするまで\n\t\t{\n\t\t\tauto [hh,xx] = st.top();\n\t\t\tst.pop();\n\t\t\tchmax(ans, (i-xx)*hh);\n\t\t\tx = xx;\n\t\t}\n\t\t// delete\n\t\tst.push({h[i], x});\n\t}\n\tcout << ans << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 5364, "score_of_the_acc": -1.1179, "final_rank": 6 } ]
aoj_CGL_4_C_cpp
Convex Cut As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p 1 , p 2 ,..., p n where line segments connecting p i and p i+1 (1 ≤ i ≤ n−1 ) are sides of the convex polygon. The line segment connecting p n and p 1 is also a side of the polygon. Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : q th query g is given as a sequence of points p 1 ,..., p n in the following format: n x 1 y 1 x 2 y 2 : x n y n The first integer n is the number of points. The coordinate of the i -th point p i is given by two integers x i and y i . The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x , p1y , p2x and p2y . Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Constraints 3 ≤ n ≤ 100 1 ≤ q ≤ 100 -10000 ≤ x i , y i ≤ 10000 -10000 ≤ p1x , p1y , p2x , p2y ≤ 10000 No point in g will occur more than once. p1 ≠ p2 Sample Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Sample Output 2.00000000 4.00000000
[ { "submission_id": "aoj_CGL_4_C_6666641", "code_snippet": "//my geometry template\n\n#include<bits/stdc++.h>\n//#define double long double\nusing namespace std;\ndouble const INF=1e20;\nint const N=233333;\ndouble const PI=acos(-1.0),EPS=1e-10;\nint les(double x,double y){\n\treturn x<y-EPS;\n}\nint leq(double x,double y){\n\treturn x<=y+EPS;\n}\nint equ(double x,double y){\n\treturn leq(x,y)&&leq(y,x);\n}\ndouble dtor(double deg){\n\treturn deg/180.0*PI;\n}\ndouble rtod(double rad){\n\treturn rad/PI*180.0;\n}\nnamespace twodgeo{\n\tstruct point{\n\t\tdouble x,y;\n\t\tpoint(double a=0.0,double b=0.0):x(a),y(b){}\n\t\tpoint operator+(const point&rhs)const{\n\t\t\treturn point(x+rhs.x,y+rhs.y);\n\t\t}\n\t\tpoint operator-(const point&rhs)const{\n\t\t\treturn point(x-rhs.x,y-rhs.y);\n\t\t}\n\t\tpoint operator*(const double&rhs)const{\n\t\t\treturn point(x*rhs,y*rhs);\n\t\t}\n\t\tpoint operator/(const double&rhs)const{\n\t\t\treturn point(x/rhs,y/rhs);\n\t\t}\n\t\tint operator<(const point&rhs)const{\n\t\t\treturn les(x,rhs.x)||(equ(x,rhs.x)&&les(y,rhs.y));\n\t\t}\n\t\tint operator==(const point&rhs)const{\n\t\t\treturn equ(x,rhs.x)&&equ(y,rhs.y);\n\t\t}\n\t\tdouble len(){\n\t\t\treturn sqrtl(x*x+y*y);\n\t\t}\n\t\tdouble ang(){\n\t\t\treturn atan2(y,x);\n\t\t}\n\t};\n\ttypedef point vect;\n\tdouble dot(vect a,vect b){\n\t\treturn a.x*b.x+a.y*b.y;\n\t}\n\tdouble ang(vect a,vect b){\n\t\treturn acos(dot(a,b)/a.len()/b.len());\n\t}\n\tdouble cross(vect a,vect b){\n\t\treturn a.x*b.y-a.y*b.x;\n\t}\n\tdouble triarea(point a,point b,point c){\n\t\treturn cross(b-a,c-a)/2.0;\n\t}\n\tvect rotate(vect a,double rad){\n\t\treturn vect(a.x*cos(rad)-a.y*sin(rad),\n\t\t\ta.x*sin(rad)+a.y*cos(rad));\n\t}\n\tvect normal(vect a){\n\t\treturn vect(-a.y/a.len(),a.x/a.len());\n\t}\n\tvect unit(vect a){\n\t\treturn vect(a.x/a.len(),a.y/a.len());\n\t} \n\tint atinf(point a){\n\t\treturn equ(abs(a.x),INF)||equ(abs(a.y),INF);\n\t}\n\t\n\tstruct line{\n\t\tpoint p;\n\t\tvect v;\n\t\tline(point a={0,0},vect b={0,0}):p(a),v(b){}\n\t\tdouble ang(){\n\t\t\treturn atan2(v.y,v.x);\n\t\t}\n\t};\n\ttypedef line segment;\n\tsegment makeseg(point a,point b){\n\t\treturn line(a,b-a);\n\t}\n\tline midline(segment a){\n\t\tpoint x=a.p,y=a.p+a.v;\n\t\treturn line((x+y)/2.0,normal(a.v));\n\t}\n\tpoint lineintersect(line a,line b){\n\t\treturn a.p+a.v*(cross(b.v,a.p-b.p)/cross(a.v,b.v));\n\t}\n\tint islinepara(line a,line b){\n\t\treturn equ(cross(a.v,b.v),0);\n\t}\n\tdouble distoline(line a,point b){\n\t\treturn fabs(cross(a.v,b-a.p))/a.v.len();\n\t}\n\tdouble distoseg(segment a,point p){\n\t\tpoint x=a.p,y=a.p+a.v;\n\t\tif(x==y)\n\t\t\treturn (p-x).len();\n\t\tvect v2=p-x,v3=p-y;\n\t\tif(les(dot(a.v,v2),0.0))\n\t\t\treturn v2.len();\n\t\tif(les(0.0,dot(a.v,v3)))\n\t\t\treturn v3.len();\n\t\treturn distoline(a,p);\n\t}\n\tpoint lineproj(line a,point b){\n\t\tpoint x=a.p;\n\t\tvect v=a.v;\n\t\treturn x+v*(dot(v,b-x)/dot(v,v));\n\t}\n\tint issegintersect(segment a,segment b){\n\t\tpoint a1=a.p,a2=a.p+a.v,b1=b.p,b2=b.p+b.v;\n\t\tdouble c1=cross(a2-a1,b1-a1),c2=cross(a2-a1,b2-a1),\n\t\t c3=cross(b2-b1,a1-b1),c4=cross(b2-b1,a2-b1);\n\t\treturn les(c1*c2,0.0)&&les(c3*c4,0.0);\n\t}\n\tint onseg(segment a,point p){\n\t\tpoint x=a.p,y=a.p+a.v;\n\t\treturn equ(cross(x-p,y-p),0.0)&&les(dot(x-p,y-p),0.0);\n\t}\n\t\n\ttypedef vector<line> pslg;\n\ttypedef vector<point> polygon;\n\tpolygon const polyplane=\n\t\t{{-INF,-INF},{-INF,INF},{INF,INF},{INF,-INF}};\n\tpslg const pslgplane=\n\t\t{{{-INF,-INF},{0,2*INF}},{{-INF,INF},{2*INF,0}},\n\t\t{{INF,INF},{0,2*-INF}},{{INF,-INF},{2*-INF,0}}};\n\tdouble polygonarea(polygon a){\n\t\tdouble s=0;\n\t\tfor(int i=1;i<(int)a.size()-1;i++)\n\t\t\ts+=triarea(a[0],a[i],a[i+1]);\n\t\treturn s;\n\t}\n#define nxt(b,x) ((x+1)%b.size())\n\tint ispointinpoly(polygon a,point p){\n\t\tint cnt=0;\n\t\tfor(int i=0;i<(int)a.size();i++){\n\t\t\tint j=nxt(a,i);\n\t\t\tif(onseg(makeseg(a[i],a[j]),p))\n\t\t\t\treturn -1;\n\t\t\tdouble k=cross(a[j]-a[i],p-a[i]),\n\t\t\t\td1=a[i].y-p.y,d2=a[j].y-p.y;\n\t\t\tif(les(0,k)&&leq(d1,0)&&les(0,d2))\n\t\t\t\tcnt++;\n\t\t\tif(les(k,0)&&leq(d2,0)&&les(0,d1))\n\t\t\t\tcnt--;\n\t\t}\n\t\treturn !!cnt;\n\t}\n\tdouble convexhull(polygon a,polygon&b){\n\t\tsort(a.begin(),a.end());\n\t\ta.erase(unique(a.begin(),a.end()),a.end());\n\t\tb.clear();\n#define p (int)b.size()\n\t\tfor(int i=0;i<(int)a.size();i++){\n\t\t\twhile(p>1&&leq(cross(b[p-1]-b[p-2],a[i]-b[p-2]),0))\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(a[i]);\n\t\t}\n\t\tfor(int t=p,i=a.size()-2;~i;i--){\n\t\t\twhile(p>t&&leq(cross(b[p-1]-b[p-2],a[i]-b[p-2]),0))\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(a[i]);\n\t\t}\n\t\tif(a.size()>1)\n\t\t\tb.pop_back();\n\t\tdouble res=0;\n\t\tfor(int i=0;i<p;i++)\n\t\t\tres+=(b[i]-b[nxt(b,i)]).len();\n#undef p\n\t\treturn res;\n\t}\n\tdouble convpolydia(polygon a){\n\t\tif(a.size()==2)\n\t\t\treturn (a[0]-a[1]).len();\n\t\tdouble ans=0;\n\t\tfor(int i=1,j=2;i<(int)a.size();i++){\n\t\t\twhile(leq(triarea(a[i-1],a[i],a[j]),\n\t\t\t\ttriarea(a[i-1],a[i],a[nxt(a,j)])))\n\t\t\t\tj=nxt(a,j);\n\t\t\tans=max(ans,max((a[i-1]-a[j]).len(),\n\t\t\t\t(a[i]-a[j]).len()));\n\t\t}\n\t\treturn ans;\n\t}\n\tint onright(line a,point b){\n\t\treturn les(cross(a.v,b-a.p),0);\n\t}\n\tvoid polytopslg(polygon a,pslg&b){\n\t\tb.push_back(makeseg(a[a.size()-1],a[0]));\n\t\tfor(int i=1;i<(int)a.size();i++)\n\t\t\tb.push_back(makeseg(a[i-1],a[i]));\n\t}\n\tint hfplintersect(pslg a,polygon&b){\n\t\tsort(a.begin(),a.end(),[](line x,line y){\n\t\t\treturn les(x.ang(),y.ang());\n\t\t});\n\t\tint l=0,r=0;\n\t\tpslg q;q.resize(N);\n\t\tpolygon p;p.resize(N);\n\t\tq[0]=a[0];\n\t\tfor(int i=1;i<(int)a.size();i++){\n\t\t\twhile(l<r&&onright(a[i],p[r]))r--;\n\t\t\twhile(l<r&&onright(a[i],p[l+1]))l++;\n\t\t\tq[++r]=a[i];\n\t\t\tif(l<r&&islinepara(q[r],q[r-1])){\n\t\t\t\tif(onright(q[r],q[r-1].p)&&\n\t\t\t\t\tles(dot(q[r].v,q[r-1].v),0))\n\t\t\t\t\treturn 0;\n\t\t\t\tr--;\n\t\t\t\tif(!onright(q[r],a[i].p))\n\t\t\t\t\tq[r]=a[i];\n\t\t\t}\n\t\t\tif(l<r)\n\t\t\t\tp[r]=lineintersect(q[r],q[r-1]);\n\t\t}\n\t\twhile(l<r&&onright(q[l],p[r]))\n\t\t\tr--;\n\t\tif(r<=l+1)\n\t\t\treturn 0;\n\t\tp[l]=lineintersect(q[l],q[r]);\n\t\tb.clear();\n\t\tfor(int i=l;i<=r;i++)\n\t\t\tb.push_back(p[i]);\n\t\treturn 1;\n\t}\n#undef nxt\n\tstruct circle{\n\t\tpoint o;double r;\n\t\tcircle(point a={0,0},double b=0.0):o(a),r(b){}\n\t\tcircle(point a,point b):o(a),r((a-b).len()){}\n\t\tcircle(point a,point b,point c);\n\t\tpoint gprad(double a){\n\t\t\treturn point(o.x+cos(a)*r,o.y+sin(a)*r);\n\t\t}\n\t};\n\tvector<point>linecircintersect(line l,circle c){\n\t\tpoint t=lineproj(l,c.o);\n\t\tdouble d=(c.o-t).len();\n\t\tif(les(c.r,d))return vector<point>();\n\t\tif(equ(c.r,d))return vector<point>{t};\n\t\tdouble k=sqrtl(c.r*c.r-d*d);\n\t\treturn vector<point>{t+unit(l.v)*k,t-unit(l.v)*k};\n\t}\n\tvector<point>circintersect(circle a,circle b){\n\t\tdouble d=(a.o-b.o).len();\n\t\tif(equ(d,0.0)&&equ(a.r,b.r))\n\t\t\treturn vector<point>{{INF,INF}};\n\t\tif(les(a.r+b.r,d)||les(d,fabs(a.r-b.r)))\n\t\t\treturn vector<point>();\n\t\tdouble ap=(b.o-a.o).ang(),\n\t\t\tat=acos((a.r*a.r+d*d-b.r*b.r)/2.0/d/a.r);\n\t\tif(equ(at,0.0))\n\t\t\treturn vector<point>{a.gprad(ap)};\n\t\telse\n\t\t\treturn vector<point>{a.gprad(ap+at),a.gprad(ap-at)};\n\t}\n\tvector<line>getcirctang(point p,circle c){\n\t\tdouble d=(p-c.o).len(),a=asin(c.r/d);\n\t\tif(les(d,c.r))return vector<line>();\n\t\tif(equ(d,c.r))return vector<line>{{p,normal(p-c.o)}};\n\t\treturn vector<line>{{p,rotate(c.o-p,a)},{p,rotate(c.o-p,-a)}};\n\t}\n\tvector<line>getcirctang(circle a,circle b){\n\t\tif(les(a.r,b.r))swap(a,b);\n\t\tdouble d=(a.o-b.o).len(),ap=atan2(b.o.y-a.o.y,b.o.x-a.o.x);\n\t\tif(equ(d,0.0)&&equ(a.r,b.r))\n\t\t\treturn vector<line>{makeseg({INF,INF},{INF,INF})};\n\t\tif(les(d,a.r-b.r))\n\t\t\treturn vector<line>();\n\t\tif(equ(d,a.r-b.r))\n\t\t\treturn vector<line>{line(a.gprad(ap),normal(b.o-a.o))};\n\t\tdouble at=acos((a.r-b.r)/d);\n\t\tvector<line>res;\n\t\tres.push_back(makeseg(a.gprad(ap+at),b.gprad(ap+at)));\n\t\tres.push_back(makeseg(a.gprad(ap-at),b.gprad(ap-at)));\n\t\tif(equ(d,a.r+b.r))\n\t\t\tres.push_back(makeseg(a.gprad(ap),b.gprad(ap+PI)));\n\t\tif(les(a.r+b.r,d)){\n\t\t\tdouble t=acos((a.r+b.r)/d);\n\t\t\tres.push_back(makeseg(a.gprad(ap+t),b.gprad(ap+t+PI)));\n\t\t\tres.push_back(makeseg(a.gprad(ap-t),b.gprad(ap-t+PI)));\n\t\t}\n\t\treturn res;\n\t}\n\tpoint incenter(point a,point b,point c){\n\t\tif(les(cross(b-a,c-a),0.0))swap(b,c);\n\t\treturn lineintersect(line(b,rotate(c-b,ang(a-b,c-b)/2.0)),\n\t\t\tline(c,rotate(b-c,-ang(a-c,b-c)/2.0)));\n\t}\n\tpoint circumcenter(point a,point b,point c){\n\t\treturn lineintersect(midline(makeseg(a,b)),\n\t\t\tmidline(makeseg(b,c)));\n\t}\n\tpoint centroid(point a,point b,point c){\n\t\treturn lineintersect(makeseg(a,(b+c)/2),makeseg(b,(a+c)/2));\n\t}\n\tpoint orthocenter(point a,point b,point c){\n\t\treturn lineintersect(makeseg(a,lineproj(makeseg(b,c),a)),\n\t\t\tmakeseg(b,lineproj(makeseg(a,c),b)));\n\t}\n\tcircle::circle(point a,point b,point c){\n\t\to=circumcenter(a,b,c),r=(o-a).len();\n\t}\n}\nusing namespace twodgeo;\nnamespace tridgeo{\n\tstruct point3{\n\t\tdouble x,y,z;\n\t\tpoint3(double a=0.0,double b=0.0,double c=0.0):x(a),y(b),z(){}\n\t\tpoint3 operator+(const point3&rhs)const{\n\t\t\treturn point3(x+rhs.x,y+rhs.y,z+rhs.z);\n\t\t}\n\t\tpoint3 operator-(const point3&rhs)const{\n\t\t\treturn point3(x-rhs.x,y-rhs.y,z-rhs.z);\n\t\t}\n\t\tpoint3 operator*(const double&rhs)const{\n\t\t\treturn point3(x*rhs,y*rhs,z*rhs);\n\t\t}\n\t\tpoint3 operator/(const double&rhs)const{\n\t\t\treturn point3(x/rhs,y/rhs,z/rhs);\n\t\t}\n\t\tint operator<(const point3&rhs)const{\n\t\t\tif(!equ(x,rhs.x))return les(x,rhs.x);\n\t\t\tif(!equ(y,rhs.y))return les(y,rhs.y);\n\t\t\treturn les(z,rhs.z);\n\t\t}\n\t\tint operator==(const point3&rhs)const{\n\t\t\treturn equ(x,rhs.x)&&equ(y,rhs.y)&&equ(z,rhs.z);\n\t\t}\n\t\tdouble len()const{\n\t\t\treturn sqrtl(x*x+y*y+z*z);\n\t\t}\n\t};\n\ttypedef point3 vect3;\n\tdouble dot(vect3 a,vect3 b){\n\t\treturn a.x*b.x+a.y*b.y+a.z*b.z;\n\t}\n\tvect3 cross(vect3 a,vect3 b){\n\t\treturn vect3(a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x);\n\t}\n\tdouble ang(vect3 a,vect3 b){\n\t\treturn acos(dot(a,b)/a.len()/b.len());\n\t}\n\tvect3 unit(vect3 a){\n\t\treturn vect3(a.x/a.len(),a.y/a.len(),a.z/a.len());\n\t}\n\tstruct plane{\n\t\tpoint3 p;vect3 v;\n\t\tplane(point3 a=point3(),vect3 b=vect3()):p(a),v(b){}\n\t};\n\tstruct line3{\n\t\tpoint3 p;vect3 v;\n\t\tline3(point3 a={0,0},vect3 b={0,0}):p(a),v(b){}\n\t\tline3(point3 a,point3 b,point3 c):p(a),v(cross(b-a,c-a)){}\n\t};\n\ttypedef line3 segment3;\n\tline3 makeseg(point3 a,point3 b){\n\t\treturn line3(a,b-a);\n\t}\n\tdouble distoplane(point3 a,plane p){\n\t\treturn fabs(dot(a-p.p,p.v))/p.v.len();\n\t}\n\tpoint3 planeproj(point3 a,plane p){\n\t\treturn a-p.v*dot(a-p.p,p.v);\n\t}\n\tint islineplanepara(line3 l,plane p){\n\t\treturn equ(dot(p.v,l.v),0.0);\n\t}\n\tint issegplaneintersect(line3 l,plane p){\n\t\tif(islineplanepara(l,p))return 0;\n\t\tdouble k=dot(p.v,p.p-l.p)/dot(p.v,l.v);\n\t\treturn leq(0.0,k)&&leq(k,1.0);\n\t}\n\tpoint3 lineplaneintersect(line3 l,plane p){\n\t\treturn l.p+l.v*dot(p.v,p.p-l.p)/dot(p.v,l.v);\n\t}\n\tdouble triarea(point3 a,point3 b,point3 c){\n\t\treturn cross(b-a,c-a).len()/2.0;\n\t}\n\tdouble tetravolumn(point3 a,point3 b,point3 c,point3 d){\n\t\treturn dot(d-a,cross(b-a,c-a))/6.0;\n\t}\n\tint pointintri(point3 p,point3 a,point3 b,point3 c){\n\t\treturn equ(triarea(a,b,c),\n\t\t\ttriarea(p,a,b)+triarea(p,b,c)+triarea(p,a,c));\n\t}\n\tdouble distoline(line3 a,point3 b){\n\t\treturn cross(a.v,b-a.p).len()/a.v.len();\n\t}\n\tdouble distoseg(segment3 a,point3 p){\n\t\tpoint3 x=a.p,y=a.p+a.v;\n\t\tif(x==y)\n\t\t\treturn (p-x).len();\n\t\tvect3 v2=p-x,v3=p-y;\n\t\tif(les(dot(a.v,v2),0.0))\n\t\t\treturn v2.len();\n\t\tif(les(0.0,dot(a.v,v3)))\n\t\t\treturn v3.len();\n\t\treturn distoline(a,p);\n\t}\n}\n//using namespace tridgeo;\nint n,q;\npolygon p,tp;\npslg g,tg;\nint main(){\n\tios::sync_with_stdio(0);\n\tcin>>n,p.resize(n);\n\tfor(auto&i:p)cin>>i.x>>i.y;\n\tpolytopslg(p,g);\n\tfor(cin>>q;q--;){\n\t\tpoint a,b;cin>>a.x>>a.y>>b.x>>b.y;\n\t\tline l=makeseg(a,b);\n\t\ttg=g,tg.push_back(l),tp.clear();\n\t\thfplintersect(tg,tp);\n\t\tcout<<fixed<<setprecision(12)<<polygonarea(tp)<<\"\\n\";\n\t}\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 18512, "score_of_the_acc": -1, "final_rank": 2 }, { "submission_id": "aoj_CGL_4_C_6324942", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int maxn=1e6+50;//注意修改大小\nconst double eps=1e-8;\nconst double PI=acos(-1.0);\n#define sgn2(x) ((x)>eps?1:((x)<-eps?2:0))//x>0:1;x<0:2;x=0:0.\n#define zero(x) (((x)>0?(x):-(x))<eps)//x=0返回1,否则返回0\nlong long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}\nll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}\n\n\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//---------------------------------------------------点------------------------------------------------------------------------------//\n//-----------------------------------------------------------------------------------------------------------------------------------//\ninline double R_to_D(double rad){ return 180/PI*rad; }//弧度转角度\ninline double D_to_R(double D){ return PI/180*D; }//角度转弧度\nint sgn(double x){\n if(fabs(x) < eps)return 0;//x==0\n if(x < 0)return -1;//x<0\n return 1;//x>0\n}//!三态函数sgn用于判断相等,减少精度误差问题\nstruct Point{\n double x, y;\n Point(double x = 0, double y = 0):x(x), y(y){}//构造函数\n};\ntypedef Point Vector;//!注意区分点和向量\ntypedef vector<Point> Polygon;//定义多边形:即多个Point顺序组成的\nVector operator + (Vector A, Vector B){return Vector(A.x + B.x, A.y + B.y);}//向量 + 向量 = 向量,点 + 向量 = 向量\nVector operator - (Point A, Point B){return Vector(A.x - B.x, A.y - B.y);}//点 - 点 = 向量(向量AB = B - A)\nVector operator * (Vector A, double p){return Vector(A.x * p, A.y * p);}//向量 * 数 = 向量\nVector operator / (Vector A, double p){return Vector(A.x / p, A.y / p);}//!向量 / 数= 向量\nbool operator < (const Point& A, const Point& B) {return A.x < B.x || (A.x == B.x && A.y < B. y);}//点or向量 的比较函数(优先横向排序)\nbool operator == (const Point& A, const Point& B){return !sgn(A.x - B.x) && !sgn(A.y - B.y);}//点or向量 的相等函数\ndouble Polar_angle(Vector A){return atan2(A.y, A.x);}//求极角:在极坐标系中,平面上任何一点到极点的连线和极轴的夹角叫做极角。单位弧度rad\ndouble Dot(Vector A, Vector B){return A.x * B.x + A.y * B.y;}//点积(满足交换律):a·b=|a||b|cos<a,b> A.x*B.x+A.y*B.y;\ndouble Cross(Vector A, Vector B){return A.x * B.y - B.x * A.y;}//向量的叉积(不满足交换律):等于两向量有向面积的二倍(若B在A的逆时针方向,则为正值;顺时针则为负值;共线则为0).cross(x, y) = -cross(y, x)\ndouble LeftTest_Point(Point A, Point B, Point C){return Cross(B - A, C - B);}//判断向量BC是不是向AB的逆时针方向(左边)转(ToLeftTest);也可看作一个点C是否在向量AB的左边:是则>0,不是则<0,共线则=0\ndouble LeftTest_Vector(Vector A, Vector B){return Cross(A,B);}//判断向量B是不是向量A的逆时针方向(左边):是则>0,不是则<0,共线则=0\ndouble Length(Vector A){return sqrt(Dot(A, A));}//取模\ndouble Angle(Vector A, Vector B){return acos(Dot(A, B) / Length(A) / Length(B));}//计算两向量夹角(Angle),返回值为弧度制下的夹角\ndouble Area2(Point A, Point B, Point C){return Cross(B - A, C - A);}//交点为A的两个向量AB和AC,然后求这两个向量的叉积(叉乘),ABxAC=平行四边形的面积\nVector Normal(Vector A) {double L = Length(A);return Vector(-A.y / L, A.x / L);}//向量A的法向量:向量A逆时针旋转九十度之后的单位向量\nVector Format(Vector A) {double L = Length(A);return Vector(A.x / L,A.y / L);}//向量A的单位向量化\nVector Rotate(Vector A, double rad){return Vector(A.x*cos(rad)-A.y*sin(rad),A.x*sin(rad)+A.y*cos(rad));}//向量A逆时针旋转后的向量:x'=xcosa -ysina, y'= xsina+ycosa,rad:弧度且为逆时针旋转的角\nPoint Turn_B(Point A, Point B, double rad){\n double x = (A.x-B.x) * cos(rad) + (A.y-B.y) * sin(rad) + B.x;\n double y = - (A.x-B.x) * sin(rad) + (A.y-B.y) * cos(rad) + B.y; \n return Point(x,y);\n}//将点A绕点B顺时针旋转rad(弧度)\n\n\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//---------------------------------------------------直线----------------------------------------------------------------------------//\n//-----------------------------------------------------------------------------------------------------------------------------------//\nstruct Line{\n Vector v;//方向向量。左边就是对应的半平面\n Point p;//直线上任意一点\n Line(Vector v, Point p):v(v), p(p) {}\n //如果需要使用极角就使用下面的代码,主要注释上面一行\n // double deg;//极角\n // Line(Vector v,Point p):p(p), v(v){deg = atan2(v.y, v.x);}\n // bool operator < (const Line& L)const {//排序时使用的比较运算符 由x正向逆时针到x正向\n // return deg < L.deg;\n // }\n};//直线定义:P'=P+v*t\nint Relation(Point A, Point B, Point C){int c = sgn(Cross((B - A), (C - A)));if(c < 0) return 1;else if(c > 0) return -1;return 0;}//点C和直线AB关系:1在左侧;-1在右侧;0在直线上.\nPoint Get_line_intersection(Point P,Vector V,Point Q,Vector W){\n Vector U = P - Q;double t = Cross(W, U) / Cross(V, W);return P + V * t;\n}//两直线交点:(直线AB:A+tv(v为向量AB,t为参数,A为起点)).调用前要确保两直线p + tv和Q + tw之间有唯一交点,当且仅当Corss(v, w) != 0;(t是参数)\ndouble Distance_point_to_line(Point P, Point A, Point B){Vector v1 = B - A, v2 = P - A;return fabs(Cross(v1, v2) / Length(v1));}//如果不取绝对值,那么得到的是有向距离}//点P到直线AB的距离\ndouble Distance_point_to_segment(Point P, Point A, Point B)\n{\n if(A == B) return Length(P - A);//(如果重合那么就是两个点之间的距离,直接转成向量求距离即可)\n Vector v1 = B - A, v2 = P - A, v3 = P - B;\n if(sgn(Dot(v1, v2)) < 0) return Length(v2);//A点左边\n if(sgn(Dot(v1, v3)) > 0)return Length(v3);//B点右边\n return fabs(Cross(v1, v2) / Length(v1));//垂线的距离\n}//点P到线段AB的距离:垂线距离或者PA或者PB距离\nbool OnSegment(Point P, Point A, Point B){return sgn(Cross(A-P, B-P)) == 0 && sgn(Dot(A-P, B-P)) <= 0;}//判断点p是否在线段AB上(包含端点AB,如果不包含AB则<=改为<)\nbool Segment_proper_intersection(Point a1, Point a2, Point b1, Point b2){\n double c1 = Cross(a2-a1, b1-a1), c2 = Cross(a2-a1, b2-a1);double c3 = Cross(b2-b1, a1-b1), c4 = Cross(b2-b1, a2-b1);\n //if判断控制是否允许线段在端点处相交,根据需要添加\n if(!sgn(c1) || !sgn(c2) || !sgn(c3) || !sgn(c4)){\n bool f1 = OnSegment(b1, a1, a2), f2 = OnSegment(b2, a1, a2), f3 = OnSegment(a1, b1, b2), f4 = OnSegment(a2, b1, b2);\n bool f = (f1|f2|f3|f4);\n return f;\n }\n return (sgn(c1)*sgn(c2) < 0 && sgn(c3)*sgn(c4) < 0);\n}//判断线段a1a2与b1b2是否相交(if控制端点相交)\nPoint Get_line_projection(Point P, Point A, Point B){Vector v = B - A;return A + v * (Dot(v, P - A) / Dot(v, v));}//求点P在直线AB上的投影点\nPoint FootPoint(Point P, Point A, Point B){\n Vector x = P - A, y = P - B, z = B - A;\n double len1 = Dot(x, z) / Length(z), len2 = - 1.0 * Dot(y, z) / Length(z);//分别计算AP,BP在AB,BA上的投影\n return A + z * (len1 / (len1 + len2));//点A加上向量AF\n}//求点P到直线AB的垂足\nPoint Symmetry_PL(Point P, Point A, Point B){return P + (FootPoint(P, A, B) - P) * 2; }//求点P到直线AB的对称点\n\n\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//---------------------------------------------------多边形----------------------------------------------------------------------------//\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//外心:三边中垂线交点,到三角形三个顶点距离相同(外接圆圆心)\n//内心:角平分线的交点,到三角形三边的距离相同(内切圆圆心)\n//垂心:三条垂线的交点\n//重心:三条中线的交点,到三角形三顶点距离的平方和最小的点,三角形内到三边距离之积最大的点(x=(x1+x2+x3),y=(y1+y2+y3))\ndouble Convex_polygon_area(Point* p, int n){//逆时针储存所有顶点,下标从0开始\n double area = 0;for(int i = 1; i <= n - 2; ++ i)area += Cross(p[i] - p[0], p[i + 1] - p[0]);return area / 2;//return fabs(area / 2);//不加的话求的是有向面积,逆时针为正,顺时针为负\n}//求凸多边形的有向面积\ndouble Polygon_area(Point* p, int n){//逆时针储存所有顶点,下标从0开始\n double area = 0;for(int i = 1; i <= n - 2; ++ i)area += Cross(p[i] - p[0], p[i + 1] - p[0]);return area / 2;\n}//求非凸多边形的有向面积\nint is_point_in_polygon(Point p, Point* poly,int n){//待判断的点和该多边形的所有点的合集\n int wn = 0;\n for(int i = 0; i < n; ++i){\n if(OnSegment(p, poly[i], poly[(i+1)%n])) return -1;\n int k = sgn(Cross(poly[(i+1)%n] - poly[i], p - poly[i])),d1 = sgn(poly[i].y - p.y),d2 = sgn(poly[(i+1)%n].y - p.y);\n if(k > 0 && d1 <= 0 && d2 > 0) wn++;\n if(k < 0 && d2 <= 0 && d1 > 0) wn--;\n }\n if(wn != 0)return 1;\n return 0;\n}//判断点P是否在多边形内,若点在多边形内返回1,在多边形外部返回0,在多边形上返回-1\n//判断点P是否在凸多边形内,只需要判断点P是否在所有边的左边(按逆时针顺序排列的顶点集)可以使用LeftTest_Point\nint is_convex(Point* p,int n){int s[3]={1,1,1};for(int i=0;i<n&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],p[(i+2)%n]-p[i]))]=0;return s[1]|s[2];}//判定凸多边形,允许相邻边共线.顶点按顺时针或逆时针给出\nint is_convex_v2(Point* p,int n){int s[3]={1,1,1};for (int i=0;i<n&&s[0]&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],p[(i+2)%n]-p[i]))]=0;return s[0]&&s[1]|s[2];}//判定凸多边形,不允许相邻边共线.顺时针或逆时针给出\nint inside_convex(Point q,Point* p,int n){int s[3]={1,1,1};for (int i=0;i<n&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],q-p[i]))]=0;return s[1]|s[2];}//判点q在凸多边形内或边上,顶点按顺时针或逆时针给出\nint inside_convex_v2(Point q,Point* p,int n){int s[3]={1,1,1};for (int i=0;i<n&&s[0]&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],q-p[i]))]=0;return s[0]&&s[1]|s[2];}//判点q在凸多边形内,顶点按顺时针或逆时针给出,在多边形边上返回0\nint inside_polygon(Point q,Point* p,int n,int on_edge=1){//on_edge表示点在多边形边上时的返回值,默认为1\n\tPoint q2;int i=0,count=0;\n const int offset=10000;//offset为多边形坐标上限,根据题意修改\n\twhile (i<n){\n for (count=i=0,q2.x=rand()+offset,q2.y=rand()+offset;i<n;i++){\n if (zero(Cross(q-p[(i+1)%n],p[i]-p[(i+1)%n]))&&(p[i].x-q.x)*(p[(i+1)%n].x-q.x)<eps&&(p[i].y-q.y)*(p[(i+1)%n].y-q.y)<eps)return on_edge;\n\t\t\telse if (zero(Cross(q-p[i],q2-p[i])))break;\n\t\t\telse if (Cross(q-q2,p[i]-q2)*Cross(q-q2,p[(i+1)%n]-q2)<-eps&&Cross(p[i]-p[(i+1)%n],q-p[(i+1)%n])*Cross(p[i]-p[(i+1)%n],q2-p[(i+1)%n])<-eps)count++;\n }\n }\n if(count&1)return 2;return 0;\n}//判点在任意多边形内,顶点按顺时针或逆时针给出.点q在多边形内则为2,在边上则为1(可以修改on_edge),在外则为0\n\nint opposite_side(Point p1,Point p2,Point l1,Point l2){return Cross(l1-l2,p1-l2)*Cross(l1-l2,p2-l2)<-eps;}\nint dot_online_in(Point p,Point l1,Point l2){return zero(Cross(p-l2,l1-l2))&&(l1.x-p.x)*(l2.x-p.x)<eps&&(l1.y-p.y)*(l2.y-p.y)<eps;}\nint inside_polygon(Point l1,Point l2,Point* p,int n){\n const int MAXN=1000;//注意根据n的范围进行修改\n\tPoint t[MAXN],tt;int i,j,k=0;\n\tif (!inside_polygon(l1,p,n)||!inside_polygon(l2,p,n))return 0;\n\tfor (i=0;i<n;i++){\n if (opposite_side(l1,l2,p[i],p[(i+1)%n])&&opposite_side(p[i],p[(i+1)%n],l1,l2))return 0;\n\t\telse if (dot_online_in(l1,p[i],p[(i+1)%n]))t[k++]=l1;\n\t\telse if (dot_online_in(l2,p[i],p[(i+1)%n]))t[k++]=l2;\n\t\telse if (dot_online_in(p[i],l1,l2))t[k++]=p[i];\n }\n\tfor (i=0;i<k;i++){\n for (j=i+1;j<k;j++){\n\t\t\ttt.x=(t[i].x+t[j].x)/2;tt.y=(t[i].y+t[j].y)/2;\n\t\t\tif(!inside_polygon(tt,p,n))return 0;\t\t\t\n\t\t}\n }\t\n\treturn 1;\n}//判线段l1l2在任意多边形内,顶点按顺时针或逆时针给出,与边界相交或在内部返回1,否则返回0\nPoint Polygon_center(Point *p, int n) {\n Point ans(0, 0);\n if(Polygon_area(p, n) == 0)return ans;\n for (int i = 0; i < n; i++)ans = ans + (p[i] + p[(i + 1) % n]) * Cross(p[i], p[(i + 1) % n]); //面积有正负\n return ans / Polygon_area(p, n) / 6.;\n}//多边形重心,将多边形三角剖分,算出每个三角形重心(三角形重心是3点坐标平均值)对每个三角形有向面积求加权平均值\nbool cmp_ConvexHull(Point A,Point B){return A.y < B.y || (A.y == B.y && A.x < B. x);}//竖向排序,默认从下左角开始逆时针输出\nint ConvexHull(Point* p, int n, Point* ch){//下标都是从0开始,ch按照逆时针存储的\n sort(p, p + n);int m = 0;\n for(int i = 0; i < n;i++){//下凸包\n //如果叉积<=0说明新边斜率小说明已经不是凸包边了,赶紧踢走\n while(m > 1 && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0)m -- ;\n ch[m ++ ] = p[i];//<=:一条边有两给端点;<:边上可以有多个输入点 注意根据题意进行修改(求凸包直径的时候是<=)\n }\n int k = m;\n for(int i = n - 2; i >= 0;i--){//上凸包\n while(m > k && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0)m -- ;\n ch[m ++ ] = p[i];//<=:一条边有两给端点;<:边上可以有多个输入点 注意根据题意进行修改(求凸包直径的时候是<=)\n }\n if(n > 1) m -- ;return m;//返回凸包顶点个数\n}//计算凸包,输入点数组p.输出点数组ch.输入不能有重复的点,函数执行完后的输入点的顺序将被破坏(因为要排序,可以加一个数组存原来的id)\ndouble Rotating_calipers(Point* con,int n){//传入最小凸包的点数组\n int op = 1;double ans = 0;\n for(int i = 0; i < n; ++ i){\n while(Cross((con[i] - con[op]), (con[i + 1] - con[i])) < Cross((con[i] - con[op + 1]), (con[i + 1] - con[i])))op = (op + 1) % n;//(写成<=会被两个点的数据卡掉,所以必须写成<)\n ans = max(ans, max(Dot(con[i] - con[op],con[i] - con[op]), Dot(con[i + 1] - con[op],con[i + 1] - con[op])));\n }\n return ans;\n}//旋转卡壳,返回凸包的直径的平方\nPolygon CutPolygon(Polygon poly,const Point& a,const Point& b) {//poly中的点从0开始\n Polygon newpoly;int n=poly.size();\n for(int i=0; i<n; i++){\n Point c=poly[i],d=poly[(i+1)%n];\n if(sgn(Cross(b-a,c-a))>=0)newpoly.push_back(c);\n if(sgn(Cross(b-a,c-d))!=0){\n Point ip=Get_line_intersection(a,b-a,c,d-c);\n if(OnSegment(ip,c,d))newpoly.push_back(ip);\n }\n }\n return newpoly;\n}//有向直线ab切割多边形,返回左侧\nPoint a[maxn],p,ans[maxn],b[maxn];int n,T;\nint main(){\n // freopen(\"10.in\",\"r\",stdin);\n // freopen(\"10.out\",\"w\",stdout);\n cin>>n;\n for(int i=0;i<n;i++)cin>>a[i].x>>a[i].y;\n cin>>T;\n while(T--){\n Point a1,a2;\n cin>>a1.x>>a1.y>>a2.x>>a2.y;\n Polygon s;\n for(int i=0;i<n;i++)s.push_back(a[i]);\n Polygon s2;\n s2=CutPolygon(s,a1,a2);\n for(int i=0;i<s2.size();i++)b[i]=s2[i];\n double ans=abs(Convex_polygon_area(b,s2.size()));\n printf(\"%.8lf\\n\",ans);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 50108, "score_of_the_acc": -0.3354, "final_rank": 1 }, { "submission_id": "aoj_CGL_4_C_5826465", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst int N = 1e6 + 10;\n\nconst double eps = 1e-9;\nconst double PI = acos(-1.0);\nconst double dinf = 1e99;\nconst ll inf = 0x3f3f3f3f3f3f3f3f;\nstruct Line;\n\nstruct Point {\n double x, y;\n\n Point() { x = y = 0; }\n\n Point(const Line &a);\n\n Point(const double &a, const double &b) : x(a), y(b) {}\n\n Point operator+(const Point &a) const {\n return {x + a.x, y + a.y};\n }\n\n Point operator-(const Point &a) const {\n return {x - a.x, y - a.y};\n }\n\n Point operator*(const double &a) const {\n return {x * a, y * a};\n }\n\n Point operator/(const double &d) const {\n return {x / d, y / d};\n }\n\n bool operator==(const Point &a) const {\n return abs(x - a.x) + abs(y - a.y) < eps;\n }\n\n void standardize() {\n *this = *this / sqrt(x * x + y * y);\n }\n};\n\ndouble norm(const Point &p) { return p.x * p.x + p.y * p.y; }\n\nPoint orth(const Point &a) { return Point(-a.y, a.x); }\n\ndouble dist(const Point &a, const Point &b) {\n return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\ndouble dist2(const Point &a, const Point &b) {\n return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n}\n\nstruct Line {\n Point s, t;\n\n Line() {}\n\n Line(const Point &a, const Point &b) : s(a), t(b) {}\n\n};\n\n\nstruct Circle {\n Point o;\n double r;\n\n Circle() {}\n\n Circle(Point P, double R = 0) { o = P, r = R; }\n};\n\ndouble length(const Point &p) {\n return sqrt(p.x * p.x + p.y * p.y);\n}\n\ndouble length(const Line &l) {\n Point p(l);\n return length(p);\n}\n\nPoint::Point(const Line &a) { *this = a.t - a.s; }\n\nistream &operator>>(istream &in, Point &a) {\n in >> a.x >> a.y;\n return in;\n}\n\nostream &operator<<(ostream &out, Point &a) {\n out << fixed << setprecision(10) << a.x << ' ' << a.y;\n return out;\n}\n\ndouble dot(const Point &a, const Point &b) { return a.x * b.x + a.y * b.y; }\n\ndouble det(const Point &a, const Point &b) { return a.x * b.y - a.y * b.x; }\n\nint sgn(const double &x) { return fabs(x) < eps ? 0 : (x > 0 ? 1 : -1); }\n\ndouble sqr(const double &x) { return x * x; }\n\nPoint rotate(const Point &a, const double &ang) {\n double x = cos(ang) * a.x - sin(ang) * a.y;\n double y = sin(ang) * a.x + cos(ang) * a.y;\n return {x, y};\n}\n\n//点在线段上 <=0 包含端点\nbool sp_on(const Line &seg, const Point &p) {\n Point a = seg.s, b = seg.t;\n return !sgn(det(p - a, b - a)) && sgn(dot(p - a, p - b)) <= 0;\n}\n\nbool lp_on(const Line &line, const Point &p) {\n Point a = line.s, b = line.t;\n return !sgn(det(p - a, b - a));\n}\n\n//等于不包含共线\nint andrew(Point *point, Point *convex, int n) {\n sort(point, point + n, [](Point a, Point b) {\n if (a.x != b.x) return a.x < b.x;\n return a.y < b.y;\n });\n int top = 0;\n for (int i = 0; i < n; i++) {\n while ((top > 1) && det(convex[top - 1] - convex[top - 2], point[i] - convex[top - 1]) <= 0)\n top--;\n convex[top++] = point[i];\n }\n int tmp = top;\n for (int i = n - 2; i >= 0; i--) {\n while ((top > tmp) && det(convex[top - 1] - convex[top - 2], point[i] - convex[top - 1]) <= 0)\n top--;\n convex[top++] = point[i];\n }\n if (n > 1) top--;\n return top;\n}\n\ndouble slope(const Point &a, const Point &b) { return (a.y - b.y) / (a.x - b.x); }\n\ndouble slope(const Line &a) { return slope(a.s, a.t); }\n\nPoint ll_intersection(const Line &a, const Line &b) {\n double s1 = det(Point(a), b.s - a.s), s2 = det(Point(a), b.t - a.s);\n if (sgn(s1) == 0 && sgn(s2) == 0) return a.s;\n return (b.s * s2 - b.t * s1) / (s2 - s1);\n}\n\nint ss_cross(const Line &a, const Line &b, Point &p) {\n int d1 = sgn(det(a.t - a.s, b.s - a.s));\n int d2 = sgn(det(a.t - a.s, b.t - a.s));\n int d3 = sgn(det(b.t - b.s, a.s - b.s));\n int d4 = sgn(det(b.t - b.s, a.t - b.s));\n if ((d1 ^ d2) == -2 && (d3 ^ d4) == -2) {\n p = ll_intersection(a, b);\n return 1;\n }\n if (!d1 && sp_on(a, b.s)) {\n p = b.s;\n return 2;\n }\n if (!d2 && sp_on(a, b.t)) {\n p = b.t;\n return 2;\n }\n if (!d3 && sp_on(b, a.s)) {\n p = a.s;\n return 2;\n }\n if (!d4 && sp_on(b, a.t)) {\n p = a.t;\n return 2;\n }\n return 0;\n}\n\n\nint ccw(const Point &a, Point b, Point c) {\n b = b - a, c = c - a;\n if (sgn(det(b, c)) > 0) return +1; // \"COUNTER_CLOCKWISE\"\n if (sgn(det(b, c)) < 0) return -1; // \"CLOCKWISE\"\n if (sgn(dot(b, c)) < 0) return +2; // \"ONLINE_BACK\"\n if (sgn(norm(b) - norm(c)) < 0) return -2; // \"ONLINE_FRONT\"\n return 0; // \"ON_SEGMENT\"\n}\n\n\nPoint project(const Line &l, const Point &p) {\n Point base(l);\n double r = dot(base, p - l.s) / sqr(length(base));\n return l.s + (base * r);\n}\n\ndouble sp_dist(const Line &l, const Point &p) {\n if (l.s == l.t) return dist(l.s, p);\n Point x = p - l.s, y = p - l.t, z = l.t - l.s;\n if (sgn(dot(x, z)) < 0)return length(x);//P距离A更近\n if (sgn(dot(y, z)) > 0)return length(y);//P距离B更近\n return abs(det(x, z) / length(z));//面积除以底边长\n}\n\ndouble lp_dist(const Line &l, const Point &p) {\n Point x = p - l.s, y = p - l.t, z = l.t - l.s;\n return abs(det(x, z) / length(z));//面积除以底边长\n}\n\nint cl_cross(const Circle &c, const Line &l, pair<Point, Point> &ans) {\n Point a = c.o;\n double r = c.r;\n Point pr = project(l, a);\n double dis = dist(pr, a);\n double tmp = r * r - dis * dis;\n if (sgn(tmp) == 1) {\n double base = sqrt(max(0.0, r * r - dis * dis));\n Point e(l);\n e.standardize();\n e = e * base;\n ans = make_pair(pr + e, pr - e);\n return 2;\n } else if (sgn(tmp) == 0) {\n ans = make_pair(pr, pr);\n return 1;\n } else return 0;\n}\n\nint intersectCS(Circle c, Line l) {//交点个数,下面cs_cross用到\n if (sgn(norm(project(l, c.o) - c.o) - c.r * c.r) > 0) return 0;\n double d1 = length(c.o - l.s), d2 = length(c.o - l.t);\n if (sgn(d1 - c.r) <= 0 && sgn(d2 - c.r) <= 0) return 0;\n if ((sgn(d1 - c.r) < 0 && sgn(d2 - c.r) > 0) || (sgn(d1 - c.r) > 0 && sgn(d2 - c.r) < 0)) return 1;\n Point h = project(l, c.o);\n if (dot(l.s - h, l.t - h) < 0) return 2;\n return 0;\n}\n\nint cs_cross(Circle c, Line s, pair<Point, Point> &ans) {//圆和线段交点\n Line l(s);\n int num = cl_cross(c, l, ans);\n int res = intersectCS(c, s);\n if (res == 2) return 2;\n if (num > 1) {\n if (dot(l.s - ans.first, l.t - ans.first) > 0) swap(ans.first, ans.second);\n ans.second = ans.first;\n }\n return res;\n}\n\n\nint cc_cross(const Circle &cir1, const Circle &cir2, pair<Point, Point> &ans) {\n const Point &c1 = cir1.o, &c2 = cir2.o;\n const double &r1 = cir1.r, &r2 = cir2.r;\n double x1 = c1.x, x2 = c2.x, y1 = c1.y, y2 = c2.y;\n double d = length(c1 - c2);\n if (sgn(fabs(r1 - r2) - d) > 0) return 0; //内含\n if (sgn(r1 + r2 - d) < 0) return 4; //相离\n double a = r1 * (x1 - x2) * 2, b = r1 * (y1 - y2) * 2, c = r2 * r2 - r1 * r1 - d * d;\n double p = a * a + b * b, q = -a * c * 2, r = c * c - b * b;\n\n double cosa, sina, cosb, sinb;\n //One Intersection\n if (sgn(d - (r1 + r2)) == 0 || sgn(d - fabs(r1 - r2)) == 0) {\n cosa = -q / p / 2;\n sina = sqrt(1 - sqr(cosa));\n Point p0(x1 + r1 * cosa, y1 + r1 * sina);\n if (sgn(dist(p0, c2) - r2)) p0.y = y1 - r1 * sina;\n ans = pair<Point, Point>(p0, p0);\n if (sgn(r1 + r2 - d) == 0) return 3; //外切\n else return 1; //内切\n }\n //Two Intersections\n double delta = sqrt(q * q - p * r * 4);\n cosa = (delta - q) / p / 2;\n cosb = (-delta - q) / p / 2;\n sina = sqrt(1 - sqr(cosa));\n sinb = sqrt(1 - sqr(cosb));\n Point p1(x1 + r1 * cosa, y1 + r1 * sina);\n Point p2(x1 + r1 * cosb, y1 + r1 * sinb);\n if (sgn(dist(p1, c2) - r2)) p1.y = y1 - r1 * sina;\n if (sgn(dist(p2, c2) - r2)) p2.y = y1 - r1 * sinb;\n if (p1 == p2) p1.y = y1 - r1 * sina;\n ans = pair<Point, Point>(p1, p2);\n return 2; // 相交\n}\n\nPoint lp_sym(const Line &l, const Point &p) {\n return p + (project(l, p) - p) * 2;\n}\n\ndouble alpha(const Point &t1, const Point &t2) {\n double theta;\n theta = atan2((double) t2.y, (double) t2.x) - atan2((double) t1.y, (double) t1.x);\n if (sgn(theta) < 0)\n theta += 2.0 * PI;\n return theta;\n}\n\nint pip(const Point *P, const int &n, const Point &a) {//【射线法】判断点A是否在任意多边形Poly以内\n int cnt = 0;\n double tmp;\n for (int i = 1; i <= n; ++i) {\n int j = i < n ? i + 1 : 1;\n if (sp_on(Line(P[i], P[j]), a))return 2;//点在多边形上\n if (a.y >= min(P[i].y, P[j].y) && a.y < max(P[i].y, P[j].y))//纵坐标在该线段两端点之间\n tmp = P[i].x + (a.y - P[i].y) / (P[j].y - P[i].y) * (P[j].x - P[i].x), cnt += sgn(tmp - a.x) > 0;//交点在A右方\n }\n return cnt & 1;//穿过奇数次则在多边形以内\n}\n\nbool pip_convex_jud(const Point &a, const Point &L, const Point &R) {//判断AL是否在AR右边\n return sgn(det(L - a, R - a)) > 0;//必须严格以内\n}\n\nbool pip_convex(const Point *P, const int &n, const Point &a) {//【二分法】判断点A是否在凸多边形Poly以内\n //点按逆时针给出\n if (pip_convex_jud(P[0], a, P[1]) || pip_convex_jud(P[0], P[n - 1], a)) return 0;//在P[0_1]或P[0_n-1]外\n if (sp_on(Line(P[0], P[1]), a) || sp_on(Line(P[0], P[n - 1]), a)) return 2;//在P[0_1]或P[0_n-1]上\n int l = 1, r = n - 2;\n while (l < r) {//二分找到一个位置pos使得P[0]_A在P[0_pos],P[0_(pos+1)]之间\n int mid = (l + r + 1) >> 1;\n if (pip_convex_jud(P[0], P[mid], a))l = mid;\n else r = mid - 1;\n }\n if (pip_convex_jud(P[l], a, P[l + 1]))return 0;//在P[pos_(pos+1)]外\n if (sp_on(Line(P[l], P[l + 1]), a))return 2;//在P[pos_(pos+1)]上\n return 1;\n}\n// 多边形是否包含线段\n// 因此我们可以先求出所有和线段相交的多边形的顶点,然后按照X-Y坐标排序(X坐标小的排在前面,对于X坐标相同的点,Y坐标小的排在前面,\n// 这种排序准则也是为了保证水平和垂直情况的判断正确),这样相邻的两个点就是在线段上相邻的两交点,如果任意相邻两点的中点也在多边形内,\n// 则该线段一定在多边形内。\n\nint pp_judge(Point *A, int n, Point *B, int m) {//【判断多边形A与多边形B是否相离】\n for (int i1 = 1; i1 <= n; ++i1) {\n int j1 = i1 < n ? i1 + 1 : 1;\n for (int i2 = 1; i2 <= m; ++i2) {\n int j2 = i2 < m ? i2 + 1 : 1;\n Point tmp;\n if (ss_cross(Line(A[i1], A[j1]), Line(B[i2], B[j2]), tmp)) return 0;//两线段相交\n if (pip(B, m, A[i1]) || pip(A, n, B[i2]))return 0;//点包含在内\n }\n }\n return 1;\n}\n\ndouble area(Point *P, int n) {//【任意多边形P的面积】\n double S = 0;\n for (int i = 0; i < n; i++) S += det(P[i], P[(i + 1) % n]);\n return S * 0.5;\n}\n\ndouble pc_area(Point *p, int n, const Circle &c) {\n if (n < 3) return 0;\n function<double(Circle, Point, Point)> dfs = [&](Circle c, Point a, Point b) {\n Point va = c.o - a, vb = c.o - b;\n double f = det(va, vb), res = 0;\n if (sgn(f) == 0) return res;\n if (sgn(max(length(va), length(vb)) - c.r) <= 0) return f;\n Point d(dot(va, vb), det(va, vb));\n if (sgn(sp_dist(Line(a, b), c.o) - c.r) >= 0) return c.r * c.r * atan2(d.y, d.x);\n pair<Point, Point> u;\n int cnt = cs_cross(c, Line(a, b), u);\n if (cnt == 0) return res;\n if (cnt > 1 && sgn(dot(u.second - u.first, a - u.first)) > 0) swap(u.first, u.second);\n res += dfs(c, a, u.first);\n if (cnt == 2) res += dfs(c, u.first, u.second) + dfs(c, u.second, b);\n else if (cnt == 1) res += dfs(c, u.first, b);\n return res;\n };\n double res = 0;\n for (int i = 0; i < n; i++) {\n res += dfs(c, p[i], p[(i + 1) % n]);\n }\n return res * 0.5;\n}\n\nLine Q[N];\n\nint judge(Line L, Point a) { return sgn(det(a - L.s, L.t - L.s)) > 0; }//判断点a是否在直线L的右边\nint halfcut(Line *L, int n, Point *P) {//【半平面交】\n sort(L, L + n, [](const Line &a, const Line &b) {\n double d = atan2((a.t - a.s).y, (a.t - a.s).x) - atan2((b.t - b.s).y, (b.t - b.s).x);\n return sgn(d) ? sgn(d) < 0 : judge(a, b.s);\n });\n\n int m = n;\n n = 0;\n for (int i = 0; i < m; ++i)\n if (i == 0 || sgn(atan2(Point(L[i]).y, Point(L[i]).x) - atan2(Point(L[i - 1]).y, Point(L[i - 1]).x)))\n L[n++] = L[i];\n int h = 1, t = 0;\n for (int i = 0; i < n; ++i) {\n while (h < t && judge(L[i], ll_intersection(Q[t], Q[t - 1]))) --t;//当队尾两个直线交点不是在直线L[i]上或者左边时就出队\n while (h < t && judge(L[i], ll_intersection(Q[h], Q[h + 1]))) ++h;//当队头两个直线交点不是在直线L[i]上或者左边时就出队\n Q[++t] = L[i];\n\n }\n while (h < t && judge(Q[h], ll_intersection(Q[t], Q[t - 1]))) --t;\n while (h < t && judge(Q[t], ll_intersection(Q[h], Q[h + 1]))) ++h;\n n = 0;\n for (int i = h; i <= t; ++i) {\n P[n++] = ll_intersection(Q[i], Q[i < t ? i + 1 : h]);\n }\n return n;\n}\n\nPoint V1[N], V2[N];\n\nint mincowski(Point *P1, int n, Point *P2, int m, Point *V) {//【闵可夫斯基和】求两个凸包{P1},{P2}的向量集合{V}={P1+P2}构成的凸包\n for (int i = 0; i < n; ++i) V1[i] = P1[(i + 1) % n] - P1[i];\n for (int i = 0; i < m; ++i) V2[i] = P2[(i + 1) % m] - P2[i];\n int t = 0, i = 0, j = 0;\n V[t++] = P1[0] + P2[0];\n while (i < n && j < m) V[t] = V[t - 1] + (sgn(det(V1[i], V2[j])) > 0 ? V1[i++] : V2[j++]), t++;\n while (i < n) V[t] = V[t - 1] + V1[i++], t++;\n while (j < m) V[t] = V[t - 1] + V2[j++], t++;\n return t;\n}\n\nCircle external_circle(const Point &A, const Point &B, const Point &C) {//【三点确定一圆】向量垂心法\n Point P1 = (A + B) * 0.5, P2 = (A + C) * 0.5;\n Line R1 = Line(P1, P1 + orth(B - A));\n Line R2 = Line(P2, P2 + orth(C - A));\n Circle O;\n O.o = ll_intersection(R1, R2);\n O.r = length(A - O.o);\n return O;\n}\n\nCircle internal_circle(const Point &A, const Point &B, const Point &C) {\n double a = dist(B, C), b = dist(A, C), c = dist(A, B);\n double s = (a + b + c) / 2;\n double S = sqrt(max(0.0, s * (s - a) * (s - b) * (s - c)));\n double r = S / s;\n\n return Circle((A * a + B * b + C * c) / (a + b + c), r);\n}\n\n\nstruct ConvexHull {\n\n int op;\n\n struct cmp {\n bool operator()(const Point &a, const Point &b) const {\n return sgn(a.x - b.x) < 0 || sgn(a.x - b.x) == 0 && sgn(a.y - b.y) < 0;\n }\n };\n\n set<Point, cmp> s;\n\n ConvexHull(int o) {\n op = o;\n s.clear();\n }\n\n inline int PIP(Point P) {\n set<Point>::iterator it = s.lower_bound(Point(P.x, -dinf));//找到第一个横坐标大于P的点\n if (it == s.end())return 0;\n if (sgn(it->x - P.x) == 0) return sgn((P.y - it->y) * op) <= 0;//比较纵坐标大小\n if (it == s.begin())return 0;\n set<Point>::iterator j = it, k = it;\n --j;\n return sgn(det(P - *j, *k - *j) * op) >= 0;//看叉姬1\n }\n\n inline int judge(set<Point>::iterator it) {\n set<Point>::iterator j = it, k = it;\n if (j == s.begin())return 0;\n --j;\n if (++k == s.end())return 0;\n return sgn(det(*it - *j, *k - *j) * op) >= 0;//看叉姬\n }\n\n inline void insert(Point P) {\n if (PIP(P))return;//如果点P已经在凸壳上或凸包里就不插入了\n set<Point>::iterator tmp = s.lower_bound(Point(P.x, -dinf));\n if (tmp != s.end() && sgn(tmp->x - P.x) == 0)s.erase(tmp);//特判横坐标相等的点要去掉\n s.insert(P);\n set<Point>::iterator it = s.find(P), p = it;\n if (p != s.begin()) {\n --p;\n while (judge(p)) {\n set<Point>::iterator temp = p--;\n s.erase(temp);\n }\n }\n if ((p = ++it) != s.end()) {\n while (judge(p)) {\n set<Point>::iterator temp = p++;\n s.erase(temp);\n }\n }\n }\n} up(1), down(-1);\n\nint PIC(Circle C, Point a) { return sgn(length(a - C.o) - C.r) <= 0; }//判断点A是否在圆C内\nvoid Random(Point *P, int n) { for (int i = 0; i < n; ++i)swap(P[i], P[(rand() + 1) % n]); }//随机一个排列\nCircle min_circle(Point *P, int n) {//【求点集P的最小覆盖圆】 O(n)\n// random_shuffle(P,P+n);\n Random(P, n);\n Circle C = Circle(P[0], 0);\n for (int i = 1; i < n; ++i)\n if (!PIC(C, P[i])) {\n C = Circle(P[i], 0);\n for (int j = 0; j < i; ++j)\n if (!PIC(C, P[j])) {\n C.o = (P[i] + P[j]) * 0.5, C.r = length(P[j] - C.o);\n for (int k = 0; k < j; ++k) if (!PIC(C, P[k])) C = external_circle(P[i], P[j], P[k]);\n }\n }\n return C;\n}\n\n\nint temp[N];\n\ndouble closest_point(Point *p, int n) {\n function<double(int, int)> merge = [&](int l, int r) {\n double d = dinf;\n if (l == r) return d;\n if (l + 1 == r) return dist(p[l], p[r]);\n int mid = (l + r) >> 1;\n double d1 = merge(l, mid);\n double d2 = merge(mid + 1, r);\n d = min(d1, d2);\n int i, j, k = 0;\n for (i = l; i <= r; i++) {\n if (sgn(abs(p[mid].x - p[i].x) - d) <= 0)\n temp[k++] = i;\n\n }\n sort(temp, temp + k, [&](const int &a, const int &b) {\n return sgn(p[a].y - p[b].y) < 0;\n });\n for (i = 0; i < k; i++) {\n for (j = i + 1; j < k && sgn(p[temp[j]].y - p[temp[i]].y - d) <= 0; j++) {\n double d3 = dist(p[temp[i]], p[temp[j]]);\n d = min(d, d3);\n }\n }\n return d;\n };\n sort(p, p + n, [&](const Point &a, const Point &b) {\n if (sgn(a.x - b.x) == 0) return sgn(a.y - b.y) < 0;\n else return sgn(a.x - b.x) < 0;\n });\n return merge(0, n - 1);\n}\n\nint tangent(const Circle &c1, const Point &p2, pair<Point, Point> &ans) { //圆和点切线\n Point tmp = c1.o - p2;\n int sta;\n if (sgn(norm(tmp) - c1.r * c1.r) < 0) return 0;\n else if (sgn(norm(tmp) - c1.r * c1.r) == 0) sta = 1;\n else sta = 2;\n Circle c2 = Circle(p2, sqrt(max(0.0, norm(tmp) - c1.r * c1.r)));\n cc_cross(c1, c2, ans);\n return sta;\n}\n\nint tangent(Circle c1, Circle c2, vector<Line> &ans) { //圆和点切线\n ans.clear();\n if (sgn(c1.r - c2.r) < 0) swap(c1, c2);\n double g = norm(c1.o - c2.o);\n if (sgn(g) == 0) return 0;\n Point u = (c2.o - c1.o) / sqrt(g);\n Point v = orth(u);\n for (int s = 1; s >= -1; s -= 2) {\n double h = (c1.r + s * c2.r) / sqrt(g);\n if (sgn(1 - h * h) == 0) {\n ans.push_back(Line(c1.o + u * c1.r, c1.o + (u + v) * c1.r));\n } else if (sgn(1 - h * h) >= 0) {\n Point uu = u * h, vv = v * sqrt(1 - h * h);\n ans.push_back(Line(c1.o + (uu + vv) * c1.r, c2.o - (uu + vv) * c2.r * s));\n ans.push_back(Line(c1.o + (uu - vv) * c1.r, c2.o - (uu - vv) * c2.r * s));\n }\n }\n\n return ans.size();\n}\n\ndouble areaofCC(Circle c1, Circle c2) { //两圆面积交\n if (c1.r > c2.r) swap(c1, c2);\n double nor = norm(c1.o - c2.o);\n double dist = sqrt(max(0.0, nor));\n\n if (sgn(c1.r + c2.r - dist) <= 0) return 0;\n\n if (sgn(dist + c1.r - c2.r) <= 0) return c1.r * c1.r * PI;\n\n double val;\n val = (nor + c1.r * c1.r - c2.r * c2.r) / (2 * c1.r * dist);\n val = max(val, -1.0), val = min(val, 1.0);\n double theta1 = acos(val);\n val = (nor + c2.r * c2.r - c1.r * c1.r) / (2 * c2.r * dist);\n val = max(val, -1.0), val = min(val, 1.0);\n double theta2 = acos(val);\n return (theta1 - sin(theta1 + theta1) * 0.5) * c1.r * c1.r + (theta2 - sin(theta2 + theta2) * 0.5) * c2.r * c2.r;\n}\n\n\nint convexCut(Point *p, Point *ans, int n, Line l) {\n int top = 0;\n for (int i = 0; i < n; i++) {\n Point a = p[i], b = p[(i + 1) % n];\n if (ccw(l.s, l.t, a) != -1) ans[top++] = a;\n if (ccw(l.s, l.t, a) * ccw(l.s, l.t, b) < 0)\n ans[top++] = ll_intersection(Line(a, b), l);\n }\n return top;\n}\n\nPoint p[N];\nPoint ans[N];\nPoint ct[N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n\n int n;\n cin >> n;\n for (int i = 0; i < n; i++) cin >> p[i];\n int k = andrew(p, ans, n);\n int q;\n cin >> q;\n while (q--) {\n Line l;\n cin >> l.s >> l.t;\n int top = convexCut(ans, ct, k, l);\n cout << fixed << setprecision(10) << area(ct, top) << endl;\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 112728, "score_of_the_acc": -1.3333, "final_rank": 3 }, { "submission_id": "aoj_CGL_4_C_5826438", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst int N = 1e6 + 10;\n\nconst double eps = 1e-9;\nconst double PI = acos(-1.0);\nconst double dinf = 1e99;\nconst ll inf = 0x3f3f3f3f3f3f3f3f;\nstruct Line;\n\nstruct Point {\n double x, y;\n\n Point() { x = y = 0; }\n\n Point(const Line &a);\n\n Point(const double &a, const double &b) : x(a), y(b) {}\n\n Point operator+(const Point &a) const {\n return {x + a.x, y + a.y};\n }\n\n Point operator-(const Point &a) const {\n return {x - a.x, y - a.y};\n }\n\n Point operator*(const double &a) const {\n return {x * a, y * a};\n }\n\n Point operator/(const double &d) const {\n return {x / d, y / d};\n }\n\n bool operator==(const Point &a) const {\n return abs(x - a.x) + abs(y - a.y) < eps;\n }\n\n void standardize() {\n *this = *this / sqrt(x * x + y * y);\n }\n};\n\ndouble norm(const Point &p) { return p.x * p.x + p.y * p.y; }\n\nPoint orth(const Point &a) { return Point(-a.y, a.x); }\n\ndouble dist(const Point &a, const Point &b) {\n return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\ndouble dist2(const Point &a, const Point &b) {\n return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n}\n\nstruct Line {\n Point s, t;\n\n Line() {}\n\n Line(const Point &a, const Point &b) : s(a), t(b) {}\n\n};\n\n\nstruct Circle {\n Point o;\n double r;\n\n Circle() {}\n\n Circle(Point P, double R = 0) { o = P, r = R; }\n};\n\ndouble length(const Point &p) {\n return sqrt(p.x * p.x + p.y * p.y);\n}\n\ndouble length(const Line &l) {\n Point p(l);\n return length(p);\n}\n\nPoint::Point(const Line &a) { *this = a.t - a.s; }\n\nistream &operator>>(istream &in, Point &a) {\n in >> a.x >> a.y;\n return in;\n}\n\nostream &operator<<(ostream &out, Point &a) {\n out << fixed << setprecision(10) << a.x << ' ' << a.y;\n return out;\n}\n\ndouble dot(const Point &a, const Point &b) { return a.x * b.x + a.y * b.y; }\n\ndouble det(const Point &a, const Point &b) { return a.x * b.y - a.y * b.x; }\n\nint sgn(const double &x) { return fabs(x) < eps ? 0 : (x > 0 ? 1 : -1); }\n\ndouble sqr(const double &x) { return x * x; }\n\nPoint rotate(const Point &a, const double &ang) {\n double x = cos(ang) * a.x - sin(ang) * a.y;\n double y = sin(ang) * a.x + cos(ang) * a.y;\n return {x, y};\n}\n\n//点在线段上 <=0 包含端点\nbool sp_on(const Line &seg, const Point &p) {\n Point a = seg.s, b = seg.t;\n return !sgn(det(p - a, b - a)) && sgn(dot(p - a, p - b)) <= 0;\n}\n\nbool lp_on(const Line &line, const Point &p) {\n Point a = line.s, b = line.t;\n return !sgn(det(p - a, b - a));\n}\n\n//等于不包含共线\nint andrew(Point *point, Point *convex, int n) {\n sort(point, point + n, [](Point a, Point b) {\n if (a.x != b.x) return a.x < b.x;\n return a.y < b.y;\n });\n int top = 0;\n for (int i = 0; i < n; i++) {\n while ((top > 1) && det(convex[top - 1] - convex[top - 2], point[i] - convex[top - 1]) <= 0)\n top--;\n convex[top++] = point[i];\n }\n int tmp = top;\n for (int i = n - 2; i >= 0; i--) {\n while ((top > tmp) && det(convex[top - 1] - convex[top - 2], point[i] - convex[top - 1]) <= 0)\n top--;\n convex[top++] = point[i];\n }\n if (n > 1) top--;\n return top;\n}\n\ndouble slope(const Point &a, const Point &b) { return (a.y - b.y) / (a.x - b.x); }\n\ndouble slope(const Line &a) { return slope(a.s, a.t); }\n\nPoint ll_intersection(const Line &a, const Line &b) {\n double s1 = det(Point(a), b.s - a.s), s2 = det(Point(a), b.t - a.s);\n return (b.s * s2 - b.t * s1) / (s2 - s1);\n}\n\nint ss_cross(const Line &a, const Line &b, Point &p) {\n int d1 = sgn(det(a.t - a.s, b.s - a.s));\n int d2 = sgn(det(a.t - a.s, b.t - a.s));\n int d3 = sgn(det(b.t - b.s, a.s - b.s));\n int d4 = sgn(det(b.t - b.s, a.t - b.s));\n if ((d1 ^ d2) == -2 && (d3 ^ d4) == -2) {\n p = ll_intersection(a, b);\n return 1;\n }\n if (!d1 && sp_on(a, b.s)) {\n p = b.s;\n return 2;\n }\n if (!d2 && sp_on(a, b.t)) {\n p = b.t;\n return 2;\n }\n if (!d3 && sp_on(b, a.s)) {\n p = a.s;\n return 2;\n }\n if (!d4 && sp_on(b, a.t)) {\n p = a.t;\n return 2;\n }\n return 0;\n}\n\n\nint ccw(const Point &a, Point b, Point c) {\n b = b - a, c = c - a;\n if (sgn(det(b, c)) > 0) return +1; // \"COUNTER_CLOCKWISE\"\n if (sgn(det(b, c)) < 0) return -1; // \"CLOCKWISE\"\n if (sgn(dot(b, c)) < 0) return +2; // \"ONLINE_BACK\"\n if (sgn(norm(b) - norm(c)) < 0) return -2; // \"ONLINE_FRONT\"\n return 0; // \"ON_SEGMENT\"\n}\n\n\nPoint project(const Line &l, const Point &p) {\n Point base(l);\n double r = dot(base, p - l.s) / sqr(length(base));\n return l.s + (base * r);\n}\n\ndouble sp_dist(const Line &l, const Point &p) {\n if (l.s == l.t) return dist(l.s, p);\n Point x = p - l.s, y = p - l.t, z = l.t - l.s;\n if (sgn(dot(x, z)) < 0)return length(x);//P距离A更近\n if (sgn(dot(y, z)) > 0)return length(y);//P距离B更近\n return abs(det(x, z) / length(z));//面积除以底边长\n}\n\ndouble lp_dist(const Line &l, const Point &p) {\n Point x = p - l.s, y = p - l.t, z = l.t - l.s;\n return abs(det(x, z) / length(z));//面积除以底边长\n}\n\nint cl_cross(const Circle &c, const Line &l, pair<Point, Point> &ans) {\n Point a = c.o;\n double r = c.r;\n Point pr = project(l, a);\n double dis = dist(pr, a);\n double tmp = r * r - dis * dis;\n if (sgn(tmp) == 1) {\n double base = sqrt(max(0.0, r * r - dis * dis));\n Point e(l);\n e.standardize();\n e = e * base;\n ans = make_pair(pr + e, pr - e);\n return 2;\n } else if (sgn(tmp) == 0) {\n ans = make_pair(pr, pr);\n return 1;\n } else return 0;\n}\n\nint intersectCS(Circle c, Line l) {//交点个数,下面cs_cross用到\n if (sgn(norm(project(l, c.o) - c.o) - c.r * c.r) > 0) return 0;\n double d1 = length(c.o - l.s), d2 = length(c.o - l.t);\n if (sgn(d1 - c.r) <= 0 && sgn(d2 - c.r) <= 0) return 0;\n if ((sgn(d1 - c.r) < 0 && sgn(d2 - c.r) > 0) || (sgn(d1 - c.r) > 0 && sgn(d2 - c.r) < 0)) return 1;\n Point h = project(l, c.o);\n if (dot(l.s - h, l.t - h) < 0) return 2;\n return 0;\n}\n\nint cs_cross(Circle c, Line s, pair<Point, Point> &ans) {//圆和线段交点\n Line l(s);\n int num = cl_cross(c, l, ans);\n int res = intersectCS(c, s);\n if (res == 2) return 2;\n if (num > 1) {\n if (dot(l.s - ans.first, l.t - ans.first) > 0) swap(ans.first, ans.second);\n ans.second = ans.first;\n }\n return res;\n}\n\n\nint cc_cross(const Circle &cir1, const Circle &cir2, pair<Point, Point> &ans) {\n const Point &c1 = cir1.o, &c2 = cir2.o;\n const double &r1 = cir1.r, &r2 = cir2.r;\n double x1 = c1.x, x2 = c2.x, y1 = c1.y, y2 = c2.y;\n double d = length(c1 - c2);\n if (sgn(fabs(r1 - r2) - d) > 0) return 0; //内含\n if (sgn(r1 + r2 - d) < 0) return 4; //相离\n double a = r1 * (x1 - x2) * 2, b = r1 * (y1 - y2) * 2, c = r2 * r2 - r1 * r1 - d * d;\n double p = a * a + b * b, q = -a * c * 2, r = c * c - b * b;\n\n double cosa, sina, cosb, sinb;\n //One Intersection\n if (sgn(d - (r1 + r2)) == 0 || sgn(d - fabs(r1 - r2)) == 0) {\n cosa = -q / p / 2;\n sina = sqrt(1 - sqr(cosa));\n Point p0(x1 + r1 * cosa, y1 + r1 * sina);\n if (sgn(dist(p0, c2) - r2)) p0.y = y1 - r1 * sina;\n ans = pair<Point, Point>(p0, p0);\n if (sgn(r1 + r2 - d) == 0) return 3; //外切\n else return 1; //内切\n }\n //Two Intersections\n double delta = sqrt(q * q - p * r * 4);\n cosa = (delta - q) / p / 2;\n cosb = (-delta - q) / p / 2;\n sina = sqrt(1 - sqr(cosa));\n sinb = sqrt(1 - sqr(cosb));\n Point p1(x1 + r1 * cosa, y1 + r1 * sina);\n Point p2(x1 + r1 * cosb, y1 + r1 * sinb);\n if (sgn(dist(p1, c2) - r2)) p1.y = y1 - r1 * sina;\n if (sgn(dist(p2, c2) - r2)) p2.y = y1 - r1 * sinb;\n if (p1 == p2) p1.y = y1 - r1 * sina;\n ans = pair<Point, Point>(p1, p2);\n return 2; // 相交\n}\n\nPoint lp_sym(const Line &l, const Point &p) {\n return p + (project(l, p) - p) * 2;\n}\n\ndouble alpha(const Point &t1, const Point &t2) {\n double theta;\n theta = atan2((double) t2.y, (double) t2.x) - atan2((double) t1.y, (double) t1.x);\n if (sgn(theta) < 0)\n theta += 2.0 * PI;\n return theta;\n}\n\nint pip(const Point *P, const int &n, const Point &a) {//【射线法】判断点A是否在任意多边形Poly以内\n int cnt = 0;\n double tmp;\n for (int i = 1; i <= n; ++i) {\n int j = i < n ? i + 1 : 1;\n if (sp_on(Line(P[i], P[j]), a))return 2;//点在多边形上\n if (a.y >= min(P[i].y, P[j].y) && a.y < max(P[i].y, P[j].y))//纵坐标在该线段两端点之间\n tmp = P[i].x + (a.y - P[i].y) / (P[j].y - P[i].y) * (P[j].x - P[i].x), cnt += sgn(tmp - a.x) > 0;//交点在A右方\n }\n return cnt & 1;//穿过奇数次则在多边形以内\n}\n\nbool pip_convex_jud(const Point &a, const Point &L, const Point &R) {//判断AL是否在AR右边\n return sgn(det(L - a, R - a)) > 0;//必须严格以内\n}\n\nbool pip_convex(const Point *P, const int &n, const Point &a) {//【二分法】判断点A是否在凸多边形Poly以内\n //点按逆时针给出\n if (pip_convex_jud(P[0], a, P[1]) || pip_convex_jud(P[0], P[n - 1], a)) return 0;//在P[0_1]或P[0_n-1]外\n if (sp_on(Line(P[0], P[1]), a) || sp_on(Line(P[0], P[n - 1]), a)) return 2;//在P[0_1]或P[0_n-1]上\n int l = 1, r = n - 2;\n while (l < r) {//二分找到一个位置pos使得P[0]_A在P[0_pos],P[0_(pos+1)]之间\n int mid = (l + r + 1) >> 1;\n if (pip_convex_jud(P[0], P[mid], a))l = mid;\n else r = mid - 1;\n }\n if (pip_convex_jud(P[l], a, P[l + 1]))return 0;//在P[pos_(pos+1)]外\n if (sp_on(Line(P[l], P[l + 1]), a))return 2;//在P[pos_(pos+1)]上\n return 1;\n}\n// 多边形是否包含线段\n// 因此我们可以先求出所有和线段相交的多边形的顶点,然后按照X-Y坐标排序(X坐标小的排在前面,对于X坐标相同的点,Y坐标小的排在前面,\n// 这种排序准则也是为了保证水平和垂直情况的判断正确),这样相邻的两个点就是在线段上相邻的两交点,如果任意相邻两点的中点也在多边形内,\n// 则该线段一定在多边形内。\n\nint pp_judge(Point *A, int n, Point *B, int m) {//【判断多边形A与多边形B是否相离】\n for (int i1 = 1; i1 <= n; ++i1) {\n int j1 = i1 < n ? i1 + 1 : 1;\n for (int i2 = 1; i2 <= m; ++i2) {\n int j2 = i2 < m ? i2 + 1 : 1;\n Point tmp;\n if (ss_cross(Line(A[i1], A[j1]), Line(B[i2], B[j2]), tmp)) return 0;//两线段相交\n if (pip(B, m, A[i1]) || pip(A, n, B[i2]))return 0;//点包含在内\n }\n }\n return 1;\n}\n\ndouble area(Point *P, int n) {//【任意多边形P的面积】\n double S = 0;\n for (int i = 0; i < n; i++) S += det(P[i], P[(i + 1) % n]);\n return S * 0.5;\n}\n\ndouble pc_area(Point *p, int n, const Circle &c) {\n if (n < 3) return 0;\n function<double(Circle, Point, Point)> dfs = [&](Circle c, Point a, Point b) {\n Point va = c.o - a, vb = c.o - b;\n double f = det(va, vb), res = 0;\n if (sgn(f) == 0) return res;\n if (sgn(max(length(va), length(vb)) - c.r) <= 0) return f;\n Point d(dot(va, vb), det(va, vb));\n if (sgn(sp_dist(Line(a, b), c.o) - c.r) >= 0) return c.r * c.r * atan2(d.y, d.x);\n pair<Point, Point> u;\n int cnt = cs_cross(c, Line(a, b), u);\n if (cnt == 0) return res;\n if (cnt > 1 && sgn(dot(u.second - u.first, a - u.first)) > 0) swap(u.first, u.second);\n res += dfs(c, a, u.first);\n if (cnt == 2) res += dfs(c, u.first, u.second) + dfs(c, u.second, b);\n else if (cnt == 1) res += dfs(c, u.first, b);\n return res;\n };\n double res = 0;\n for (int i = 0; i < n; i++) {\n res += dfs(c, p[i], p[(i + 1) % n]);\n }\n return res * 0.5;\n}\n\nLine Q[N];\n\nint judge(Line L, Point a) { return sgn(det(a - L.s, L.t - L.s)) > 0; }//判断点a是否在直线L的右边\nint halfcut(Line *L, int n, Point *P) {//【半平面交】\n sort(L, L + n, [](const Line &a, const Line &b) {\n double d = atan2((a.t - a.s).y, (a.t - a.s).x) - atan2((b.t - b.s).y, (b.t - b.s).x);\n return sgn(d) ? sgn(d) < 0 : judge(a, b.s);\n });\n\n int m = n;\n n = 0;\n for (int i = 0; i < m; ++i)\n if (i == 0 || sgn(atan2(Point(L[i]).y, Point(L[i]).x) - atan2(Point(L[i - 1]).y, Point(L[i - 1]).x)))\n L[n++] = L[i];\n int h = 1, t = 0;\n for (int i = 0; i < n; ++i) {\n while (h < t && judge(L[i], ll_intersection(Q[t], Q[t - 1]))) --t;//当队尾两个直线交点不是在直线L[i]上或者左边时就出队\n while (h < t && judge(L[i], ll_intersection(Q[h], Q[h + 1]))) ++h;//当队头两个直线交点不是在直线L[i]上或者左边时就出队\n Q[++t] = L[i];\n\n }\n while (h < t && judge(Q[h], ll_intersection(Q[t], Q[t - 1]))) --t;\n while (h < t && judge(Q[t], ll_intersection(Q[h], Q[h + 1]))) ++h;\n n = 0;\n for (int i = h; i <= t; ++i) {\n P[n++] = ll_intersection(Q[i], Q[i < t ? i + 1 : h]);\n }\n return n;\n}\n\nPoint V1[N], V2[N];\n\nint mincowski(Point *P1, int n, Point *P2, int m, Point *V) {//【闵可夫斯基和】求两个凸包{P1},{P2}的向量集合{V}={P1+P2}构成的凸包\n for (int i = 0; i < n; ++i) V1[i] = P1[(i + 1) % n] - P1[i];\n for (int i = 0; i < m; ++i) V2[i] = P2[(i + 1) % m] - P2[i];\n int t = 0, i = 0, j = 0;\n V[t++] = P1[0] + P2[0];\n while (i < n && j < m) V[t] = V[t - 1] + (sgn(det(V1[i], V2[j])) > 0 ? V1[i++] : V2[j++]), t++;\n while (i < n) V[t] = V[t - 1] + V1[i++], t++;\n while (j < m) V[t] = V[t - 1] + V2[j++], t++;\n return t;\n}\n\nCircle external_circle(const Point &A, const Point &B, const Point &C) {//【三点确定一圆】向量垂心法\n Point P1 = (A + B) * 0.5, P2 = (A + C) * 0.5;\n Line R1 = Line(P1, P1 + orth(B - A));\n Line R2 = Line(P2, P2 + orth(C - A));\n Circle O;\n O.o = ll_intersection(R1, R2);\n O.r = length(A - O.o);\n return O;\n}\n\nCircle internal_circle(const Point &A, const Point &B, const Point &C) {\n double a = dist(B, C), b = dist(A, C), c = dist(A, B);\n double s = (a + b + c) / 2;\n double S = sqrt(max(0.0, s * (s - a) * (s - b) * (s - c)));\n double r = S / s;\n\n return Circle((A * a + B * b + C * c) / (a + b + c), r);\n}\n\n\nstruct ConvexHull {\n\n int op;\n\n struct cmp {\n bool operator()(const Point &a, const Point &b) const {\n return sgn(a.x - b.x) < 0 || sgn(a.x - b.x) == 0 && sgn(a.y - b.y) < 0;\n }\n };\n\n set<Point, cmp> s;\n\n ConvexHull(int o) {\n op = o;\n s.clear();\n }\n\n inline int PIP(Point P) {\n set<Point>::iterator it = s.lower_bound(Point(P.x, -dinf));//找到第一个横坐标大于P的点\n if (it == s.end())return 0;\n if (sgn(it->x - P.x) == 0) return sgn((P.y - it->y) * op) <= 0;//比较纵坐标大小\n if (it == s.begin())return 0;\n set<Point>::iterator j = it, k = it;\n --j;\n return sgn(det(P - *j, *k - *j) * op) >= 0;//看叉姬1\n }\n\n inline int judge(set<Point>::iterator it) {\n set<Point>::iterator j = it, k = it;\n if (j == s.begin())return 0;\n --j;\n if (++k == s.end())return 0;\n return sgn(det(*it - *j, *k - *j) * op) >= 0;//看叉姬\n }\n\n inline void insert(Point P) {\n if (PIP(P))return;//如果点P已经在凸壳上或凸包里就不插入了\n set<Point>::iterator tmp = s.lower_bound(Point(P.x, -dinf));\n if (tmp != s.end() && sgn(tmp->x - P.x) == 0)s.erase(tmp);//特判横坐标相等的点要去掉\n s.insert(P);\n set<Point>::iterator it = s.find(P), p = it;\n if (p != s.begin()) {\n --p;\n while (judge(p)) {\n set<Point>::iterator temp = p--;\n s.erase(temp);\n }\n }\n if ((p = ++it) != s.end()) {\n while (judge(p)) {\n set<Point>::iterator temp = p++;\n s.erase(temp);\n }\n }\n }\n} up(1), down(-1);\n\nint PIC(Circle C, Point a) { return sgn(length(a - C.o) - C.r) <= 0; }//判断点A是否在圆C内\nvoid Random(Point *P, int n) { for (int i = 0; i < n; ++i)swap(P[i], P[(rand() + 1) % n]); }//随机一个排列\nCircle min_circle(Point *P, int n) {//【求点集P的最小覆盖圆】 O(n)\n// random_shuffle(P,P+n);\n Random(P, n);\n Circle C = Circle(P[0], 0);\n for (int i = 1; i < n; ++i)\n if (!PIC(C, P[i])) {\n C = Circle(P[i], 0);\n for (int j = 0; j < i; ++j)\n if (!PIC(C, P[j])) {\n C.o = (P[i] + P[j]) * 0.5, C.r = length(P[j] - C.o);\n for (int k = 0; k < j; ++k) if (!PIC(C, P[k])) C = external_circle(P[i], P[j], P[k]);\n }\n }\n return C;\n}\n\n\nint temp[N];\n\ndouble closest_point(Point *p, int n) {\n function<double(int, int)> merge = [&](int l, int r) {\n double d = dinf;\n if (l == r) return d;\n if (l + 1 == r) return dist(p[l], p[r]);\n int mid = (l + r) >> 1;\n double d1 = merge(l, mid);\n double d2 = merge(mid + 1, r);\n d = min(d1, d2);\n int i, j, k = 0;\n for (i = l; i <= r; i++) {\n if (sgn(abs(p[mid].x - p[i].x) - d) <= 0)\n temp[k++] = i;\n\n }\n sort(temp, temp + k, [&](const int &a, const int &b) {\n return sgn(p[a].y - p[b].y) < 0;\n });\n for (i = 0; i < k; i++) {\n for (j = i + 1; j < k && sgn(p[temp[j]].y - p[temp[i]].y - d) <= 0; j++) {\n double d3 = dist(p[temp[i]], p[temp[j]]);\n d = min(d, d3);\n }\n }\n return d;\n };\n sort(p, p + n, [&](const Point &a, const Point &b) {\n if (sgn(a.x - b.x) == 0) return sgn(a.y - b.y) < 0;\n else return sgn(a.x - b.x) < 0;\n });\n return merge(0, n - 1);\n}\n\nint tangent(const Circle &c1, const Point &p2, pair<Point, Point> &ans) { //圆和点切线\n Point tmp = c1.o - p2;\n int sta;\n if (sgn(norm(tmp) - c1.r * c1.r) < 0) return 0;\n else if (sgn(norm(tmp) - c1.r * c1.r) == 0) sta = 1;\n else sta = 2;\n Circle c2 = Circle(p2, sqrt(max(0.0, norm(tmp) - c1.r * c1.r)));\n cc_cross(c1, c2, ans);\n return sta;\n}\n\nint tangent(Circle c1, Circle c2, vector<Line> &ans) { //圆和点切线\n ans.clear();\n if (sgn(c1.r - c2.r) < 0) swap(c1, c2);\n double g = norm(c1.o - c2.o);\n if (sgn(g) == 0) return 0;\n Point u = (c2.o - c1.o) / sqrt(g);\n Point v = orth(u);\n for (int s = 1; s >= -1; s -= 2) {\n double h = (c1.r + s * c2.r) / sqrt(g);\n if (sgn(1 - h * h) == 0) {\n ans.push_back(Line(c1.o + u * c1.r, c1.o + (u + v) * c1.r));\n } else if (sgn(1 - h * h) >= 0) {\n Point uu = u * h, vv = v * sqrt(1 - h * h);\n ans.push_back(Line(c1.o + (uu + vv) * c1.r, c2.o - (uu + vv) * c2.r * s));\n ans.push_back(Line(c1.o + (uu - vv) * c1.r, c2.o - (uu - vv) * c2.r * s));\n }\n }\n\n return ans.size();\n}\n\ndouble areaofCC(Circle c1, Circle c2) { //两圆面积交\n if (c1.r > c2.r) swap(c1, c2);\n double nor = norm(c1.o - c2.o);\n double dist = sqrt(max(0.0, nor));\n\n if (sgn(c1.r + c2.r - dist) <= 0) return 0;\n\n if (sgn(dist + c1.r - c2.r) <= 0) return c1.r * c1.r * PI;\n\n double val;\n val = (nor + c1.r * c1.r - c2.r * c2.r) / (2 * c1.r * dist);\n val = max(val, -1.0), val = min(val, 1.0);\n double theta1 = acos(val);\n val = (nor + c2.r * c2.r - c1.r * c1.r) / (2 * c2.r * dist);\n val = max(val, -1.0), val = min(val, 1.0);\n double theta2 = acos(val);\n return (theta1 - sin(theta1 + theta1) * 0.5) * c1.r * c1.r + (theta2 - sin(theta2 + theta2) * 0.5) * c2.r * c2.r;\n}\n\n\nint convexCut(Point *p, Point *ans, int n, Line l) {\n int top = 0;\n for (int i = 0; i < n; i++) {\n Point a = p[i], b = p[(i + 1) % n];\n if (ccw(l.s, l.t, a) != -1) ans[top++] = a;\n if (ccw(l.s, l.t, a) * ccw(l.s, l.t, b) < 0)\n ans[top++] = ll_intersection(Line(a, b), l);\n }\n return top;\n}\n\nPoint p[N];\nPoint ans[N];\nPoint ct[N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n\n int n;\n cin >> n;\n for (int i = 0; i < n; i++) cin >> p[i];\n int k = andrew(p, ans, n);\n int q;\n cin >> q;\n while (q--) {\n Line l;\n cin >> l.s >> l.t;\n int top = convexCut(ans, ct, k, l);\n cout << fixed << setprecision(10) << area(ct, top) << endl;\n }\n}", "accuracy": 0.375, "time_ms": 20, "memory_kb": 112676, "score_of_the_acc": -1.3328, "final_rank": 4 } ]
aoj_DPL_5_B_cpp
Balls and Boxes 2 Balls Boxes Any way At most one ball At least one ball Distinguishable Distinguishable 1 2 3 Indistinguishable Distinguishable 4 5 6 Distinguishable Indistinguishable 7 8 9 Indistinguishable Indistinguishable 10 11 12 Problem You have $n$ balls and $k$ boxes. You want to put these balls into the boxes. Find the number of ways to put the balls under the following conditions: Each ball is distinguished from the other. Each box is distinguished from the other. Each ball can go into only one box and no one remains outside of the boxes. Each box can contain at most one ball. Note that you must print this count modulo $10^9+7$. Input $n$ $k$ The first line will contain two integers $n$ and $k$. Output Print the number of ways modulo $10^9+7$ in a line. Constraints $1 \le n \le 1000$ $1 \le k \le 1000$ Sample Input 1 2 3 Sample Output 1 6 Sample Input 2 3 2 Sample Output 2 0 Sample Input 3 100 100 Sample Output 3 437918130
[ { "submission_id": "aoj_DPL_5_B_9527781", "code_snippet": "/*\n Created by Pujx on 2024/8/4.\n*/\n#pragma GCC optimize(2, 3, \"Ofast\", \"inline\")\n#include <bits/stdc++.h>\nusing namespace std;\n#define endl '\\n'\n//#define int long long\n//#define double long double\nusing i64 = long long;\nusing ui64 = unsigned long long;\n//using i128 = __int128;\n#define inf (int)0x3f3f3f3f3f3f3f3f\n#define INF 0x3f3f3f3f3f3f3f3f\n#define yn(x) cout << (x ? \"yes\" : \"no\") << endl\n#define Yn(x) cout << (x ? \"Yes\" : \"No\") << endl\n#define YN(x) cout << (x ? \"YES\" : \"NO\") << endl\n#define mem(x, i) memset(x, i, sizeof(x))\n#define cinarr(a, n) for (int _ = 1; _ <= n; _++) cin >> a[_]\n#define cinstl(a) for (auto& _ : a) cin >> _\n#define coutarr(a, n) for (int _ = 1; _ <= n; _++) cout << a[_] << \" \\n\"[_ == n]\n#define coutstl(a) for (const auto& _ : a) cout << _ << ' '; cout << endl\n#define all(x) (x).begin(), (x).end()\n#define ls (s << 1)\n#define rs (s << 1 | 1)\n#define ft first\n#define se second\n#define pii pair<int, int>\n#ifdef DEBUG\n #include \"debug.h\"\n#else\n #define dbg(...) void(0)\n#endif\n\nconst int N = 2000 + 5;\n//const int M = 1e5 + 5;\n//const int mod = 998244353;\nconst int mod = 1e9 + 7;\n//template <typename T> T ksm(T a, i64 b) { T ans = 1; for (; b; a = 1ll * a * a, b >>= 1) if (b & 1) ans = 1ll * ans * a; return ans; }\n//template <typename T> T ksm(T a, i64 b, T m = mod) { T ans = 1; for (; b; a = 1ll * a * a % m, b >>= 1) if (b & 1) ans = 1ll * ans * a % m; return ans; }\n\nint a[N];\nint n, m, t, k, q;\n\ntemplate <int P> struct MInt {\n int x;\n MInt() : x(0) {}\n MInt(const signed& x) : x(norm(x % getMod())) {}\n MInt(const long long& x) : x(norm(x % getMod())) {}\n\n static int Mod;\n static int getMod() { return P > 0 ? P : Mod; }\n static void setMod(int _Mod) { Mod = _Mod; }\n int norm(const int& x) const { return x < 0 ? x + getMod() : (x >= getMod() ? x - getMod() : x); }\n int val() const { return x; }\n explicit operator int() const { return x; }\n MInt operator - () const { MInt res; res.x = norm(getMod() - x); return res; }\n MInt ksm(const long long& x) const {\n MInt a = *this, ans = 1;\n for (long long pw = x; pw; a *= a, pw >>= 1) if (pw & 1) ans *= a;\n return ans;\n }\n MInt inv() const { assert(x != 0); return ksm(getMod() - 2); }\n MInt& operator += (const MInt& b) & { x = norm(x + b.x); return *this; }\n MInt& operator -= (const MInt& b) & { x = norm(x - b.x); return *this; }\n MInt& operator *= (const MInt& b) & { x = norm(1ll * x * b.x % getMod()); return *this; }\n MInt& operator /= (const MInt& b) & { return *this *= b.inv(); }\n MInt& operator ++ () & { return *this += 1; }\n MInt& operator -- () & { return *this -= 1; }\n const MInt operator ++ (signed) { MInt old = *this; ++(*this); return old; }\n const MInt operator -- (signed) { MInt old = *this; --(*this); return old; }\n friend MInt operator + (const MInt& a, const MInt& b) { MInt res = a; res += b; return res; }\n friend MInt operator - (const MInt& a, const MInt& b) { MInt res = a; res -= b; return res; }\n friend MInt operator * (const MInt& a, const MInt& b) { MInt res = a; res *= b; return res; }\n friend MInt operator / (const MInt& a, const MInt& b) { MInt res = a; res /= b; return res; }\n friend istream& operator >> (istream& in, MInt& a) { long long v; in >> v; a = MInt(v); return in; }\n friend ostream& operator << (ostream& out, const MInt& a) { return out << a.val(); }\n friend bool operator == (const MInt& a, const MInt& b) { return a.val() == b.val(); }\n friend bool operator != (const MInt& a, const MInt& b) { return a.val() != b.val(); }\n friend bool operator < (const MInt& a, const MInt& b) { return a.val() < b.val(); }\n friend bool operator > (const MInt& a, const MInt& b) { return a.val() > b.val(); }\n friend bool operator <= (const MInt& a, const MInt& b) { return a.val() <= b.val(); }\n friend bool operator >= (const MInt& a, const MInt& b) { return a.val() >= b.val(); }\n};\nusing Mint = MInt<mod>;\ntemplate<> int MInt<0>::Mod = 1;\n\nMint fac[N], c[N][N], s[N][N], p[N][N];\n\nvoid init() {\n fac[0] = 1, c[0][0] = s[0][0] = p[0][0] = 1;\n for (int i = 1; i <= 2000; i++) {\n fac[i] = fac[i - 1] * i;\n c[i][0] = 1, s[i][0] = p[i][0] = 0;\n for (int j = 1; j <= i; j++) {\n c[i][j] = c[i - 1][j - 1] + c[i - 1][j];\n s[i][j] = s[i - 1][j - 1] + j * s[i - 1][j];\n p[i][j] = p[i - 1][j - 1] + p[i - j][j];\n }\n }\n}\n\nvoid work() {\n cin >> n >> k;\n t = 2;\n if (t == 1) {\n cout << Mint(k).ksm(n) << endl;\n }\n else if (t == 2) {\n cout << fac[n] * c[k][n] << endl;\n }\n else if (t == 3) {\n cout << fac[k] * s[n][k] << endl;\n }\n else if (t == 4) {\n cout << c[n + k - 1][k - 1] << endl;\n }\n else if (t == 5) {\n cout << c[k][n] << endl;\n }\n else if (t == 6) {\n cout << c[n - 1][k - 1] << endl;\n }\n else if (t == 7) {\n Mint ans = 0;\n for (int i = 1; i <= k; i++)\n ans += s[n][i];\n cout << ans << endl;\n }\n else if (t == 8) {\n cout << (k >= n) << endl;\n }\n else if (t == 9) {\n cout << s[n][k] << endl;\n }\n else if (t == 10) {\n cout << p[n + k][k] << endl;\n }\n else if (t == 11) {\n cout << (k >= n) << endl;\n }\n else {\n cout << p[n][k] << endl;\n }\n}\n\nsigned main() {\n#ifdef LOCAL\n freopen(\"C:\\\\Users\\\\admin\\\\CLionProjects\\\\Practice\\\\data.in\", \"r\", stdin);\n freopen(\"C:\\\\Users\\\\admin\\\\CLionProjects\\\\Practice\\\\data.out\", \"w\", stdout);\n#endif\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n init();\n int Case = 1;\n //cin >> Case;\n while (Case--) work();\n return 0;\n}\n/*\n _____ _ _ _ __ __\n | _ \\ | | | | | | \\ \\ / /\n | |_| | | | | | | | \\ \\/ /\n | ___/ | | | | _ | | } {\n | | | |_| | | |_| | / /\\ \\\n |_| \\_____/ \\_____/ /_/ \\_\\\n*/", "accuracy": 1, "time_ms": 20, "memory_kb": 50576, "score_of_the_acc": -0.2343, "final_rank": 16 }, { "submission_id": "aoj_DPL_5_B_8597724", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#if USE_MP\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n#include <cassert>\n#include <cstdio>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <array>\n#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <stack>\n#include <functional>\n#include <algorithm>\n#include <cmath>\n#include <tuple>\n#include <bitset>\n#include <string.h>\n#include <numeric>\n#include <random>\n#if defined _DEBUG\n//#include \"TestCase.h\"\n//#include \"Util.h\"\n#endif\n\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef tuple<ll, ll, ll> tlll;\ntypedef tuple<int, int, int> tiii;\n\nusing ai2 = array<int, 2>;\nusing ai3 = array<int, 3>;\nusing ai4 = array<int, 4>;\nusing al2 = array<ll, 2>;\nusing al3 = array<ll, 3>;\nusing al4 = array<ll, 4>;\nusing ad2 = array<double, 2>;\nusing ad3 = array<double, 3>;\nusing ad4 = array<double, 4>;\n\ninline void Yes(bool upper = false) { cout << (upper ? \"YES\" : \"Yes\") << \"\\n\"; }\ninline void No(bool upper = false) { cout << (upper ? \"NO\" : \"No\") << \"\\n\"; }\n\ninline ll DivCeil(ll nume, ll deno)\n{\n\tassert(deno != 0);\n\tif (deno < 0) { nume = -nume; deno = -deno; }\n\tif (nume < 0) return -(-nume / deno);\n\telse return (nume + deno - 1) / deno;\n}\ninline ll DivFloor(ll nume, ll deno)\n{\n\tassert(deno != 0);\n\tif (deno < 0) { nume = -nume; deno = -deno; }\n\tif (nume < 0) return -((-nume + deno - 1) / deno);\n\telse return nume / deno;\n}\ninline ll DivRound(ll nume, ll deno)\n{\n\tassert(deno != 0);\n\tif (deno < 0) { nume = -nume; deno = -deno; }\n\tif (nume < 0) return -((-nume + deno / 2) / deno);\n\telse return (nume + deno / 2) / deno;\n}\n\ntemplate <typename T, int S>\nauto MakeVecImpl(queue<int>& size, const T& ini)\n{\n\tif constexpr (S == 1)\n\t{\n\t\treturn vector<T>(size.front(), ini);\n\t}\n\telse\n\t{\n\t\tint fsize = size.front();\n\t\tsize.pop();\n\t\treturn vector(fsize, MakeVecImpl<T, S - 1>(size, ini));\n\t}\n}\n\ntemplate <typename T, int S>\nauto MakeVec(const array<int, S>& size, const T ini = T())\n{\n\tqueue<int> qsize;\n\tfor (const auto v : size) qsize.push(v);\n\treturn MakeVecImpl<T, S>(qsize, ini);\n}\nint d4[][2] =\n{\n\t{0,-1},\n\t{0,1},\n\t{-1,0},\n\t{1,0},\n};\nint d8[][2] =\n{\n\t{-1,-1},\n\t{0,-1},\n\t{1,-1},\n\n\t{-1,0},\n\t{1,0},\n\n\t{-1,1},\n\t{0,1},\n\t{1,1},\n};\nvector<array<int, 2>> Neighbor4(int y, int x)\n{\n\tvector<array<int, 2>> ret;\n\tret.push_back({ y, x - 1 });\n\tret.push_back({ y, x + 1 });\n\tret.push_back({ y - 1, x });\n\tret.push_back({ y + 1, x });\n\treturn ret;\n}\nvector<array<int, 2>> Neighbor6(int y, int x)\n{\n\tvector<array<int, 2>> ret;\n\tconst int ofs = (y & 1); // 1 - (y & 1); //\n\n\tret.push_back({ y, x - 1 });\n\tret.push_back({ y, x + 1 });\n\n\tret.push_back({ y - 1, x - 1 + ofs });\n\tret.push_back({ y - 1, x + ofs });\n\n\tret.push_back({ y + 1, x - 1 + ofs });\n\tret.push_back({ y + 1, x + ofs });\n\n\treturn ret;\n}\nvector<array<int, 2>> Neighbor8(int y, int x)\n{\n\tvector<array<int, 2>> ret;\n\tret.push_back({ y - 1, x - 1 });\n\tret.push_back({ y - 1, x });\n\tret.push_back({ y - 1, x + 1 });\n\n\tret.push_back({ y, x - 1 });\n\tret.push_back({ y, x + 1 });\n\n\tret.push_back({ y + 1, x - 1 });\n\tret.push_back({ y + 1, x });\n\tret.push_back({ y + 1, x + 1 });\n\treturn ret;\n}\n\nvector<int> DecompDigit(ull val)\n{\n\tif (val == 0)\n\t\treturn { 0 };\n\n\tvector<int> ret;\n\twhile (val)\n\t{\n\t\tret.emplace_back(val % 10);\n\t\tval /= 10;\n\t}\n\treverse(ret.begin(), ret.end());\n\treturn ret;\n}\n\n\n#define PI 3.14159265358979l\nlong double R2D = 180 / PI;\nlong double D2R = PI / 180;\n\nstatic const ll Mod = 1000000007;\nstatic const ll Mod9 = 998244353;// 1000000007;\nstatic const ll INF64 = 4500000000000000000;// 10000000000000000;\nstatic const int INF32 = 2000000000;\n\nrandom_device rd;\nmt19937 mt(0);//(rd());\n#if USE_MP\nusing mpint = boost::multiprecision::cpp_int;\n#endif\n\nconst double EPS = 1e-10;\n\nnamespace Map12FoldWay\n{\n#pragma region 写像12相 ここから\n#pragma region library\n\tll GCDext(ll a, ll b, ll& x, ll& y)\n\t{\n\t\tif (b == 0)\n\t\t{\n\t\t\tx = 1;\n\t\t\ty = 0;\n\t\t\treturn a;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tll p = a / b;\n\t\t\tll b2 = a % b;\n\t\t\tll a2 = b;\n\t\t\tll d = GCDext(a2, b2, x, y);\n\n\t\t\tll x2 = x;\n\t\t\tx = y;\n\t\t\ty = x2 - p * x;\n\n\t\t\treturn d;\n\t\t}\n\t}\n\n\ttemplate<ll p>\n\tinline ll invert(ll v)\n\t{\n\t\tll x, y;\n\t\tGCDext(v, p, x, y);\n\t\twhile (x < 0)\n\t\t\tx += p;\n\n\t\treturn x;\n\t}\n\n\ttemplate<ll p>\n\tinline ll Frac(ll n)\n\t{\n\t\tstatic std::vector<ll> f;\n\t\tif (f.size() <= n + 1)\n\t\t{\n\t\t\tint ini = max(2, (int)f.size());\n\t\t\tf.resize(n + 100000);\n\t\t\tf[0] = f[1] = 1;\n\t\t\tfor (int i = ini; i < f.size(); i++)\n\t\t\t\tf[i] = i * f[i - 1] % p;\n\t\t}\n\t\treturn f[n];\n\t}\n\ttemplate<ll p>\n\tinline ll FracInv(ll n)\n\t{\n\t\tstatic std::vector<ll> finv;\n\t\tif (finv.size() <= n + 1)\n\t\t{\n\t\t\tint ini = max(2, (int)finv.size());\n\t\t\tfinv.resize(n + 100000);\n\t\t\tfinv[0] = finv[1] = 1;\n\t\t\tfor (int i = ini; i < finv.size(); i++)\n\t\t\t\tfinv[i] = invert<p>(i) * finv[i - 1] % p;\n\t\t}\n\t\treturn finv[n];\n\t}\n\n\ttemplate<ll p>\n\tinline ll ModComb(ll n, ll k)\n\t{\n\t\tif (n < 0 || k < 0 || n < k)\n\t\t\treturn 0;\n\t\treturn ((Frac<p>(n) * FracInv<p>(k)) % p) * FracInv<p>(n - k) % p;\n\t}\n\ttemplate<ll p>\n\tinline ll ModPerm(ll n, ll k)\n\t{\n\t\tif (n < 0 || k < 0 || n < k)\n\t\t\treturn 0;\n\t\treturn Frac<p>(n) * FracInv<p>(n - k) % p;\n\t}\n\n\ttemplate<ll p>\n\tll ModPow(ll a, ll n)\n\t{\n\t\tif (a == 0) return 0;\n\n\t\tll ret = 1;\n\t\tll aa = a % p;\n\t\twhile (n)\n\t\t{\n\t\t\tif (n & 1)\n\t\t\t\tret = ret * aa % p;\n\t\t\tn >>= 1;\n\t\t\taa = aa * aa % p;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t/// <summary>\n\t/// N個の要素をM個以下のグループに分割\n\t/// </summary>\n\ttemplate<ll p>\n\tll Partition(int N, int M)\n\t{\n\t\tif (N < 0 || M < 0) return 0;\n\t\tstatic vector<vector<ll>> table;\t\n\t\tstatic int n = 0, m = 0;\t// 算出済みの位置\n\t\tif (table.empty() ||\n\t\t\ttable.size() <= M ||\n\t\t\ttable[0].size() <= N)\n\t\t{\n\t\t\ttable.resize(max(m, M * 2 + 1));\n\t\t\tfor (auto& v : table)\n\t\t\t\tv.resize(max(n, N * 2 + 1));\n\t\t\ttable[0][0] = 1;\n\t\t}\n\n\t\tfor (int i = 1; i <= M; i++) {\n\t\t\tint l = i > m ? 0 : n + 1;\n\t\t\tfor (int j = l; j <= N; j++) {\n\t\t\t\tif (j >= i)\n\t\t\t\t\ttable[i][j] = (table[i - 1][j] + table[i][j - i]) % p;\n\t\t\t\telse\n\t\t\t\t\ttable[i][j] = table[i - 1][j];\n\t\t\t}\n\t\t}\n\n\t\tn = max(n, N);\n\t\tm = max(m, M);\n\n\t\treturn table[M][N];\n\t}\n#pragma endregion \n\n#pragma region 玉なし/箱なし 000~002\n\t/// <summary>\n\t/// 000 玉の区別なし 箱の区別なし 箱に入れる玉の制限なし\n\t/// 分割数そのもの\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map000(int N, int M) {\n\t\treturn Partition<p>(N, M);\n\t}\n\n\t/// <summary>\n\t/// 001 玉の区別なし 箱の区別なし 箱に玉は1つまで\n\t/// 選べるかどうか\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map001(int N, int M) {\n\t\treturn M>=N ? 1 : 0;\n\t}\n\n\t/// <summary>\n\t/// 002 玉の区別なし 箱の区別なし 空箱NG\n\t/// 全箱に1つ入れてから分割数をやる\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map002(int N, int M) {\n\t\treturn Partition<p>(N - M, M);\n\t}\n#pragma endregion\n\n#pragma region 玉なし/箱あり 010~012\n\t/// <summary>\n\t/// 010 玉の区別なし 箱の区別あり 箱に入れる玉の制限なし\n\t/// 重複組合せC(N+M-1,M-1)\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map010(int N, int M) {\n\t\treturn ModComb<p>(N + M - 1, M - 1);\n\t}\n\n\t/// <summary>\n\t/// 011 玉の区別なし 箱の区別あり 箱に玉は1つまで\n\t/// 組合せC(M,N)\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map011(int N, int M) {\n\t\treturn ModComb<p>(M, N);\n\t}\n\n\t/// <summary>\n\t/// 012 玉の区別なし 箱の区別あり 空箱NG\n\t/// 組合せC(N-1,M-1)\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map012(int N, int M) {\n\t\treturn ModComb<p>(N - 1, M - 1);\n\t}\n#pragma endregion\n\n#pragma region 玉あり/箱なし 100~102\n\t/// <summary>\n\t/// 100 玉の区別なし 箱の区別なし 箱に入れる玉の制限なし\n\t/// ベル数で解ける\n\t/// ①愚直なスターリング数(102)の和 ②工夫した和 ③式\n\t/// ③が有利なので採用 Σ(i=0..M){i^N/i! Σ(j=0..M-i){(-1)^j/j!}}\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map100(int N, int M) {\n\t\t// 前計算\n\t\tvector<ll> coeff{ 1 };\t\t// 後半部分 Σ(j=0..M-i){(-1)^j/j!}}\n\t\tvector<ll> invfrac{ 1 };\t// i!の逆数\n\t\t{\n\t\t\tll sign = 1;\n\t\t\tfor (int j = 1; j <= M; j++) {\n\t\t\t\tsign = -sign;\n\t\t\t\tinvfrac.emplace_back(invfrac.back() * invert<p>(j) % p);\n\t\t\t\tll tmp = (sign + p) * invfrac.back() % p;\n\t\t\t\tcoeff.emplace_back((coeff.back() + tmp) % p);\n\t\t\t}\n\t\t\treverse(coeff.begin(), coeff.end());\n\t\t}\n\t\t// 本体\n\t\tll ans = 0;\n\t\tfor (int i = 0; i <= M; i++) {\n\t\t\tans += (ModPow<p>(i, N) * invfrac[i] % p) * coeff[i] % p;\n\t\t}\n\t\treturn ans % p;\n\t}\n\n\t/// <summary>\n\t/// 101 玉の区別あり 箱の区別なし 箱に玉は1つまで\n\t/// 選べるかどうか\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map101(int N, int M) {\n\t\treturn M >= N ? 1 : 0;\n\t}\n\n\t/// <summary>\n\t/// 102 玉の区別あり 箱の区別なし 空箱NG\n\t/// スターリング数で解ける\n\t/// ①112をM!で割る ②DPの2通り解法がある\n\t/// 計算量は時間・空間とも①が有利\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map102(int N, int M) {\n\t\tll ans = ModPow<p>(M, N);\n\t\tll coeff = 1;\n\t\tll comb = 1;\n\t\tfor (int i = 1; i < M; i++) {\n\t\t\tcoeff = -coeff;\n\t\t\tcomb = (comb * (M - i + 1) % p) * invert<p>(i) % p;\n\n\t\t\tll temp = (coeff + p) % p;\t\t\t// (-1)^i\n\t\t\ttemp = temp * ModPow<p>(M - i, N) % p;\t// (m-i)^n\n\t\t\ttemp = temp * comb % p;\t\t\t\t// C(m,i)\n\n\t\t\tans += temp;\n\t\t}\n\t\tans %= p;\n\t\tll deno = 1;\n\t\tfor (int i = 2; i <= M; i++) {\n\t\t\tdeno = deno * invert<p>(i) % p;\n\t\t}\n\t\treturn ans * deno % p;\n\t}\n\n#pragma endregion\n\n#pragma region 玉あり/箱あり 110~112\n\t/// <summary>\n\t/// 110 玉の区別あり 箱の区別あり 箱に入れる玉の制限なし\n\t/// 普通にModPow\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map110(int N, int M) {\n\t\treturn ModPow<p>(M, N);\n\t}\n\n\t/// <summary>\n\t/// 111 玉の区別あり 箱の区別あり 箱に玉は1つまで\n\t/// 順列 P(M,N)\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map111(int N, int M) {\n\t\treturn ModPerm<p>(M, N);\n\t}\n\n\t/// <summary>\n\t/// 112 玉の区別あり 箱の区別あり 空箱NG\n\t/// 包除原理で解ける Σ(-1)^i (m-i)^n C(m,i)\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map112(int N, int M) {\n\t\tll ans = ModPow<p>(M, N);\n\t\tll coeff = 1;\n\t\tll comb = 1;\n\t\tfor (int i = 1; i < M; i++) {\n\t\t\tcoeff = -coeff;\n\t\t\tcomb = (comb * (M - i + 1) % p) * invert<p>(i) % p;\n\n\t\t\tll temp = (coeff + p) % p;\t\t\t// (-1)^i\n\t\t\ttemp = temp * ModPow<p>(M - i, N) % p;\t// (m-i)^n\n\t\t\ttemp = temp * comb % p;\t\t\t\t// C(m,i)\n\n\t\t\tans += temp;\n\t\t}\n\t\treturn ans % p;\n\t}\n#pragma endregion\n#pragma endregion 写像12相 ここまで\n}\nvoid Func()\n{\n\tstatic vector<int> a{ 0 };\n\tcout << a.back()++ << \"\\n\";\n}\n\nstruct Solver\n{\n\tvoid Run()\n\t{\n\t\tint N, K;\n\t\tcin >> N >> K;\n\t\tcout << Map12FoldWay::Map111<Mod>(N, K) << \"\\n\";\n\t}\n};\n\nint main()\n{\n\tstd::cin.tie(nullptr); //★インタラクティブ注意★\n\tstd::ios_base::sync_with_stdio(false);\n\tint T = 1;\n\t//cin >> T;\n\twhile (T--)\n\t{\n\t\tSolver S;\n\t\tS.Run();\n\t}\n\n\treturn 0;\n}\n\n/// 値渡しになっていないか?\n/// 入力を全部読んでいるか? 途中でreturnしない\n/// 32bitで収まるか? 10^5数えるとき\n/// modは正しいか?\n/// multisetでcountしていないか?", "accuracy": 1, "time_ms": 10, "memory_kb": 4664, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DPL_5_B_8593958", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#if USE_MP\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n#include <cassert>\n#include <cstdio>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <array>\n#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <stack>\n#include <functional>\n#include <algorithm>\n#include <cmath>\n#include <tuple>\n#include <bitset>\n#include <string.h>\n#include <numeric>\n#include <random>\n#if defined _DEBUG\n//#include \"TestCase.h\"\n//#include \"Util.h\"\n#endif\n\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef tuple<ll, ll, ll> tlll;\ntypedef tuple<int, int, int> tiii;\n\nusing ai2 = array<int, 2>;\nusing ai3 = array<int, 3>;\nusing ai4 = array<int, 4>;\nusing al2 = array<ll, 2>;\nusing al3 = array<ll, 3>;\nusing al4 = array<ll, 4>;\nusing ad2 = array<double, 2>;\nusing ad3 = array<double, 3>;\nusing ad4 = array<double, 4>;\n\ninline void Yes(bool upper = false) { cout << (upper ? \"YES\" : \"Yes\") << \"\\n\"; }\ninline void No(bool upper = false) { cout << (upper ? \"NO\" : \"No\") << \"\\n\"; }\n\ninline ll DivCeil(ll nume, ll deno)\n{\n\tassert(deno != 0);\n\tif (deno < 0) { nume = -nume; deno = -deno; }\n\tif (nume < 0) return -(-nume / deno);\n\telse return (nume + deno - 1) / deno;\n}\ninline ll DivFloor(ll nume, ll deno)\n{\n\tassert(deno != 0);\n\tif (deno < 0) { nume = -nume; deno = -deno; }\n\tif (nume < 0) return -((-nume + deno - 1) / deno);\n\telse return nume / deno;\n}\ninline ll DivRound(ll nume, ll deno)\n{\n\tassert(deno != 0);\n\tif (deno < 0) { nume = -nume; deno = -deno; }\n\tif (nume < 0) return -((-nume + deno / 2) / deno);\n\telse return (nume + deno / 2) / deno;\n}\n\ntemplate <typename T, int S>\nauto MakeVecImpl(queue<int>& size, const T& ini)\n{\n\tif constexpr (S == 1)\n\t{\n\t\treturn vector<T>(size.front(), ini);\n\t}\n\telse\n\t{\n\t\tint fsize = size.front();\n\t\tsize.pop();\n\t\treturn vector(fsize, MakeVecImpl<T, S - 1>(size, ini));\n\t}\n}\n\ntemplate <typename T, int S>\nauto MakeVec(const array<int, S>& size, const T ini = T())\n{\n\tqueue<int> qsize;\n\tfor (const auto v : size) qsize.push(v);\n\treturn MakeVecImpl<T, S>(qsize, ini);\n}\nint d4[][2] =\n{\n\t{0,-1},\n\t{0,1},\n\t{-1,0},\n\t{1,0},\n};\nint d8[][2] =\n{\n\t{-1,-1},\n\t{0,-1},\n\t{1,-1},\n\n\t{-1,0},\n\t{1,0},\n\n\t{-1,1},\n\t{0,1},\n\t{1,1},\n};\nvector<array<int, 2>> Neighbor4(int y, int x)\n{\n\tvector<array<int, 2>> ret;\n\tret.push_back({ y, x - 1 });\n\tret.push_back({ y, x + 1 });\n\tret.push_back({ y - 1, x });\n\tret.push_back({ y + 1, x });\n\treturn ret;\n}\nvector<array<int, 2>> Neighbor6(int y, int x)\n{\n\tvector<array<int, 2>> ret;\n\tconst int ofs = (y & 1); // 1 - (y & 1); //\n\n\tret.push_back({ y, x - 1 });\n\tret.push_back({ y, x + 1 });\n\n\tret.push_back({ y - 1, x - 1 + ofs });\n\tret.push_back({ y - 1, x + ofs });\n\n\tret.push_back({ y + 1, x - 1 + ofs });\n\tret.push_back({ y + 1, x + ofs });\n\n\treturn ret;\n}\nvector<array<int, 2>> Neighbor8(int y, int x)\n{\n\tvector<array<int, 2>> ret;\n\tret.push_back({ y - 1, x - 1 });\n\tret.push_back({ y - 1, x });\n\tret.push_back({ y - 1, x + 1 });\n\n\tret.push_back({ y, x - 1 });\n\tret.push_back({ y, x + 1 });\n\n\tret.push_back({ y + 1, x - 1 });\n\tret.push_back({ y + 1, x });\n\tret.push_back({ y + 1, x + 1 });\n\treturn ret;\n}\n\nvector<int> DecompDigit(ull val)\n{\n\tif (val == 0)\n\t\treturn { 0 };\n\n\tvector<int> ret;\n\twhile (val)\n\t{\n\t\tret.emplace_back(val % 10);\n\t\tval /= 10;\n\t}\n\treverse(ret.begin(), ret.end());\n\treturn ret;\n}\n\n\n#define PI 3.14159265358979l\nlong double R2D = 180 / PI;\nlong double D2R = PI / 180;\n\nstatic const ll Mod = 1000000007;\nstatic const ll Mod9 = 998244353;// 1000000007;\nstatic const ll INF64 = 4500000000000000000;// 10000000000000000;\nstatic const int INF32 = 2000000000;\n\nrandom_device rd;\nmt19937 mt(0);//(rd());\n#if USE_MP\nusing mpint = boost::multiprecision::cpp_int;\n#endif\n\nconst double EPS = 1e-10;\n\nnamespace Map12FoldWay\n{\n#pragma region 写像12相 ここから\n#pragma region library\n\tll GCDext(ll a, ll b, ll& x, ll& y)\n\t{\n\t\tif (b == 0)\n\t\t{\n\t\t\tx = 1;\n\t\t\ty = 0;\n\t\t\treturn a;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tll p = a / b;\n\t\t\tll b2 = a % b;\n\t\t\tll a2 = b;\n\t\t\tll d = GCDext(a2, b2, x, y);\n\n\t\t\tll x2 = x;\n\t\t\tx = y;\n\t\t\ty = x2 - p * x;\n\n\t\t\treturn d;\n\t\t}\n\t}\n\n\ttemplate<ll p>\n\tll invert(ll v)\n\t{\n\t\tll x, y;\n\t\tGCDext(v, p, x, y);\n\t\twhile (x < 0)\n\t\t\tx += p;\n\n\t\treturn x;\n\t}\n\n\ttemplate<ll p>\n\tll Frac(ll n)\n\t{\n\t\tstatic std::vector<ll> f;\n\t\tif (f.size() <= n + 1)\n\t\t{\n\t\t\tint ini = max(2, (int)f.size());\n\t\t\tf.resize(n + 100000);\n\t\t\tf[0] = f[1] = 1;\n\t\t\tfor (int i = ini; i < f.size(); i++)\n\t\t\t\tf[i] = i * f[i - 1] % p;\n\t\t}\n\t\treturn f[n];\n\t}\n\ttemplate<ll p>\n\tll FracInv(ll n)\n\t{\n\t\tstatic std::vector<ll> finv;\n\t\tif (finv.size() <= n + 1)\n\t\t{\n\t\t\tint ini = max(2, (int)finv.size());\n\t\t\tfinv.resize(n + 100000);\n\t\t\tfinv[0] = finv[1] = 1;\n\t\t\tfor (int i = ini; i < finv.size(); i++)\n\t\t\t\tfinv[i] = invert<p>(i) * finv[i - 1] % p;\n\t\t}\n\t\treturn finv[n];\n\t}\n\n\ttemplate<ll p>\n\tll ModCombFast(ll n, ll k)\n\t{\n\t\tif (n < 0 ||\n\t\t\tk < 0 ||\n\t\t\tn < k)\n\t\t\treturn 0;\n\n\t\tstatic std::vector<ll> F, Finv;\n\t\tstatic int initialized = 1;\n\t\tif (F.size() <= n + 1)\n\t\t{\n\t\t\tF.resize(n + 100000), Finv.resize(n + 100000);\n\t\t\tF[0] = F[1] = Finv[0] = Finv[1] = 1;\n\t\t\tfor (int i = initialized + 1; i < F.size(); i++)\n\t\t\t{\n\t\t\t\tF[i] = i * F[i - 1] % p;\n\t\t\t\tFinv[i] = invert<p>(i) * Finv[i - 1] % p;\n\t\t\t}\n\t\t\tinitialized = F.size() - 1;\n\t\t}\n\n\t\treturn ((F[n] * Finv[k]) % p) * Finv[n - k] % p;\n\t}\n\n\ttemplate<ll p>\n\tll ModPow(ll a, ll n)\n\t{\n\t\tif (a == 0) return 0;\n\n\t\tll ret = 1;\n\t\tll aa = a % p;\n\t\twhile (n)\n\t\t{\n\t\t\tif (n & 1)\n\t\t\t\tret = ret * aa % p;\n\t\t\tn >>= 1;\n\t\t\taa = aa * aa % p;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t/// <summary>\n\t/// N個の要素をM個以下のグループに分割\n\t/// </summary>\n\ttemplate<ll p>\n\tll Partition(int N, int M)\n\t{\n\t\tif (N < 0 || M < 0) return 0;\n\t\tstatic vector<vector<ll>> table;\t\n\t\tstatic int n = 0, m = 0;\t// 算出済みの位置\n\t\tif (table.empty() ||\n\t\t\ttable.size() <= M ||\n\t\t\ttable[0].size() <= N)\n\t\t{\n\t\t\ttable.resize(max(m, M * 2 + 1));\n\t\t\tfor (auto& v : table)\n\t\t\t\tv.resize(max(n, N * 2 + 1));\n\t\t\ttable[0][0] = 1;\n\t\t}\n\n\t\tfor (int i = 1; i <= M; i++) {\n\t\t\tint l = i > m ? 0 : n + 1;\n\t\t\tfor (int j = l; j <= N; j++) {\n\t\t\t\tif (j >= i)\n\t\t\t\t\ttable[i][j] = (table[i - 1][j] + table[i][j - i]) % p;\n\t\t\t\telse\n\t\t\t\t\ttable[i][j] = table[i - 1][j];\n\t\t\t}\n\t\t}\n\n\t\tn = max(n, N);\n\t\tm = max(m, M);\n\n\t\treturn table[M][N];\n\t}\n#pragma endregion \n\n#pragma region 玉なし/箱なし 000~002\n\t/// <summary>\n\t/// 玉の区別なし 箱の区別なし 箱に入れる玉の制限なし\n\t/// 分割数そのもの\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map000(int N, int M) {\n\t\treturn Partition<p>(N, M);\n\t}\n\n\t/// <summary>\n\t/// 玉の区別なし 箱の区別なし 空箱NG\n\t/// 全箱に1つ入れてから分割数をやる\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map002(int N, int M) {\n\t\treturn Partition<p>(N - M, M);\n\t}\n#pragma endregion\n\n#pragma region 玉なし/箱あり 010~012\n#pragma endregion\n\n#pragma region 玉あり/箱なし 100~102\n\t/// <summary>\n\t/// 玉の区別なし 箱の区別なし 箱に入れる玉の制限なし\n\t/// ベル数で解ける\n\t/// ①愚直なスターリング数(102)の和 ②工夫した和 ③式\n\t/// ③が有利なので採用 Σ(i=0..M){i^N/i! Σ(j=0..M-i){(-1)^j/j!}}\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map100(int N, int M) {\n\t\t// 前計算\n\t\tvector<ll> coeff{ 1 };\t\t// 後半部分 Σ(j=0..M-i){(-1)^j/j!}}\n\t\tvector<ll> invfrac{ 1 };\t// i!の逆数\n\t\t{\n\t\t\tll sign = 1;\n\t\t\tfor (int j = 1; j <= M; j++) {\n\t\t\t\tsign = -sign;\n\t\t\t\tinvfrac.emplace_back(invfrac.back() * invert<p>(j) % p);\n\t\t\t\tll tmp = (sign + p) * invfrac.back() % p;\n\t\t\t\tcoeff.emplace_back((coeff.back() + tmp) % p);\n\t\t\t}\n\t\t\treverse(coeff.begin(), coeff.end());\n\t\t}\n\t\t// 本体\n\t\tll ans = 0;\n\t\tfor (int i = 0; i <= M; i++) {\n\t\t\tans += (ModPow<p>(i, N) * invfrac[i] % p) * coeff[i] % p;\n\t\t}\n\t\treturn ans % p;\n\t}\n\n\t/// <summary>\n\t/// 玉の区別あり 箱の区別なし 空箱NG\n\t/// スターリング数で解ける\n\t/// ①112をM!で割る ②DPの2通り解法がある\n\t/// 計算量は時間・空間とも①が有利\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map102(int N, int M) {\n\t\tll ans = ModPow<p>(M, N);\n\t\tll coeff = 1;\n\t\tll comb = 1;\n\t\tfor (int i = 1; i < M; i++) {\n\t\t\tcoeff = -coeff;\n\t\t\tcomb = (comb * (M - i + 1) % p) * invert<p>(i) % p;\n\n\t\t\tll temp = (coeff + p) % p;\t\t\t// (-1)^i\n\t\t\ttemp = temp * ModPow<p>(M - i, N) % p;\t// (m-i)^n\n\t\t\ttemp = temp * comb % p;\t\t\t\t// C(m,i)\n\n\t\t\tans += temp;\n\t\t}\n\t\tans %= p;\n\t\tll deno = 1;\n\t\tfor (int i = 2; i <= M; i++) {\n\t\t\tdeno = deno * invert<p>(i) % p;\n\t\t}\n\t\treturn ans * deno % p;\n\t}\n\n#pragma endregion\n\n#pragma region 玉あり/箱あり 110~112\n\t/// <summary>\n\t/// 玉の区別あり 箱の区別あり 箱に入れる玉の制限なし\n\t/// 普通にModPow\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map110(int N, int M) {\n\t\treturn ModPow<p>(M, N);\n\t}\n\n\t/// <summary>\n\t/// 玉の区別あり 箱の区別あり 箱に玉は1つまで\n\t/// 順列 P(N,M)\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map111(int N, int M) {\n\t\tif (N > M)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn Frac<p>(M) * FracInv<p>(M - N) % p;\n\t}\n\n\t/// <summary>\n\t/// 玉の区別あり 箱の区別あり 空箱NG\n\t/// 包除原理で解ける Σ(-1)^i (m-i)^n C(m,i)\n\t/// </summary>\n\ttemplate<ll p>\n\tll Map112(int N, int M) {\n\t\tll ans = ModPow<p>(M, N);\n\t\tll coeff = 1;\n\t\tll comb = 1;\n\t\tfor (int i = 1; i < M; i++) {\n\t\t\tcoeff = -coeff;\n\t\t\tcomb = (comb * (M - i + 1) % p) * invert<p>(i) % p;\n\n\t\t\tll temp = (coeff + p) % p;\t\t\t// (-1)^i\n\t\t\ttemp = temp * ModPow<p>(M - i, N) % p;\t// (m-i)^n\n\t\t\ttemp = temp * comb % p;\t\t\t\t// C(m,i)\n\n\t\t\tans += temp;\n\t\t}\n\t\treturn ans % p;\n\t}\n#pragma endregion\n#pragma endregion 写像12相 ここまで\n}\nvoid Func()\n{\n\tstatic vector<int> a{ 0 };\n\tcout << a.back()++ << \"\\n\";\n}\n\nstruct Solver\n{\n\tvoid Run()\n\t{\n\t\tint N, K;\n\t\tcin >> N >> K;\n\t\tcout << Map12FoldWay::Map111<Mod>(N, K) << \"\\n\";\n\t}\n};\n\nint main()\n{\n\tstd::cin.tie(nullptr); //★インタラクティブ注意★\n\tstd::ios_base::sync_with_stdio(false);\n\tint T = 1;\n\t//cin >> T;\n\twhile (T--)\n\t{\n\t\tSolver S;\n\t\tS.Run();\n\t}\n\n\treturn 0;\n}\n\n/// 値渡しになっていないか?\n/// 入力を全部読んでいるか? 途中でreturnしない\n/// 32bitで収まるか? 10^5数えるとき\n/// modは正しいか?\n/// multisetでcountしていないか?", "accuracy": 1, "time_ms": 10, "memory_kb": 4664, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_DPL_5_B_6950880", "code_snippet": "#include <bits/stdc++.h>\n#include <stdio.h>\nusing namespace std;\nusing ll = long long;\n\nll mod_pow(ll x, ll n, ll mod) {\n if (n == 0) {\n return 1;\n }\n ll\n res = mod_pow(x * x % mod, n / 2, mod);\n if (n & 1) res = res * x % mod;\n return res;\n}\n\nconst ll MOD = 1e9 + 7;\nconst ll MAX = 1100000;\n\nvector<ll> fact(MAX), inv(MAX), inv_fact(MAX);\n\nvoid init() {\n fact.at(0) = fact.at(1) = 1;\n inv.at(0) = inv.at(1) = 1;\n inv_fact.at(0) = inv_fact.at(1) = 1;\n \n for (int i = 2; i < MAX; i++) {\n fact.at(i) = fact.at(i - 1) * i % MOD;\n inv.at(i) = MOD - inv.at(MOD % i) * (MOD / i) % MOD;\n inv_fact.at(i) = inv_fact.at(i - 1) * inv.at(i) % MOD;\n }\n}\n\nll nCk(ll n, ll k) {\n ll x = fact.at(n);\n ll y = inv_fact.at(n - k);\n ll z = inv_fact.at(k);\n\n if (n < k) {\n return 0;\n }\n if (n < 0 || k < 0) {\n return 0;\n }\n\n return (x * ((y * z) % MOD)) % MOD;\n}\n\nint main() {\n\tinit();\n\tll n, k;\n\tcin >> n >> k;\n\n\tll ans = 1;\n\tfor (int i = 0; i < n; i++) {\n\t\tans *= (k - i);\n\t\tans %= MOD;\n\t}\n\tcout << ans << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 28704, "score_of_the_acc": -0.1033, "final_rank": 14 }, { "submission_id": "aoj_DPL_5_B_6379479", "code_snippet": "#include <bits/stdc++.h>\n\n#include <cassert>\n#include <numeric>\n#include <type_traits>\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\n\n#include <utility>\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\nnamespace atcoder {\n\nnamespace internal {\n\nconstexpr long long safe_mod(long long x, long long m) {\n x %= m;\n if (x < 0) x += m;\n return x;\n}\n\nstruct barrett {\n unsigned int _m;\n unsigned long long im;\n\n explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}\n\n unsigned int umod() const { return _m; }\n\n unsigned int mul(unsigned int a, unsigned int b) const {\n\n unsigned long long z = a;\n z *= b;\n#ifdef _MSC_VER\n unsigned long long x;\n _umul128(z, im, &x);\n#else\n unsigned long long x =\n (unsigned long long)(((unsigned __int128)(z)*im) >> 64);\n#endif\n unsigned int v = (unsigned int)(z - x * _m);\n if (_m <= v) v += _m;\n return v;\n }\n};\n\nconstexpr long long pow_mod_constexpr(long long x, long long n, int m) {\n if (m == 1) return 0;\n unsigned int _m = (unsigned int)(m);\n unsigned long long r = 1;\n unsigned long long y = safe_mod(x, m);\n while (n) {\n if (n & 1) r = (r * y) % _m;\n y = (y * y) % _m;\n n >>= 1;\n }\n return r;\n}\n\nconstexpr bool is_prime_constexpr(int n) {\n if (n <= 1) return false;\n if (n == 2 || n == 7 || n == 61) return true;\n if (n % 2 == 0) return false;\n long long d = n - 1;\n while (d % 2 == 0) d /= 2;\n constexpr long long bases[3] = {2, 7, 61};\n for (long long a : bases) {\n long long t = d;\n long long y = pow_mod_constexpr(a, t, n);\n while (t != n - 1 && y != 1 && y != n - 1) {\n y = y * y % n;\n t <<= 1;\n }\n if (y != n - 1 && t % 2 == 0) {\n return false;\n }\n }\n return true;\n}\ntemplate <int n> constexpr bool is_prime = is_prime_constexpr(n);\n\nconstexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {\n a = safe_mod(a, b);\n if (a == 0) return {b, 0};\n\n long long s = b, t = a;\n long long m0 = 0, m1 = 1;\n\n while (t) {\n long long u = s / t;\n s -= t * u;\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\n\n\n auto tmp = s;\n s = t;\n t = tmp;\n tmp = m0;\n m0 = m1;\n m1 = tmp;\n }\n if (m0 < 0) m0 += b / s;\n return {s, m0};\n}\n\nconstexpr int primitive_root_constexpr(int m) {\n if (m == 2) return 1;\n if (m == 167772161) return 3;\n if (m == 469762049) return 3;\n if (m == 754974721) return 11;\n if (m == 998244353) return 3;\n int divs[20] = {};\n divs[0] = 2;\n int cnt = 1;\n int x = (m - 1) / 2;\n while (x % 2 == 0) x /= 2;\n for (int i = 3; (long long)(i)*i <= x; i += 2) {\n if (x % i == 0) {\n divs[cnt++] = i;\n while (x % i == 0) {\n x /= i;\n }\n }\n }\n if (x > 1) {\n divs[cnt++] = x;\n }\n for (int g = 2;; g++) {\n bool ok = true;\n for (int i = 0; i < cnt; i++) {\n if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {\n ok = false;\n break;\n }\n }\n if (ok) return g;\n }\n}\ntemplate <int m> constexpr int primitive_root = primitive_root_constexpr(m);\n\nunsigned long long floor_sum_unsigned(unsigned long long n,\n unsigned long long m,\n unsigned long long a,\n unsigned long long b) {\n unsigned long long ans = 0;\n while (true) {\n if (a >= m) {\n ans += n * (n - 1) / 2 * (a / m);\n a %= m;\n }\n if (b >= m) {\n ans += n * (b / m);\n b %= m;\n }\n\n unsigned long long y_max = a * n + b;\n if (y_max < m) break;\n n = (unsigned long long)(y_max / m);\n b = (unsigned long long)(y_max % m);\n std::swap(m, a);\n }\n return ans;\n}\n\n} // namespace internal\n\n} // namespace atcoder\n\n\n#include <cassert>\n#include <numeric>\n#include <type_traits>\n\nnamespace atcoder {\n\nnamespace internal {\n\n#ifndef _MSC_VER\ntemplate <class T>\nusing is_signed_int128 =\n typename std::conditional<std::is_same<T, __int128_t>::value ||\n std::is_same<T, __int128>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int128 =\n typename std::conditional<std::is_same<T, __uint128_t>::value ||\n std::is_same<T, unsigned __int128>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing make_unsigned_int128 =\n typename std::conditional<std::is_same<T, __int128_t>::value,\n __uint128_t,\n unsigned __int128>;\n\ntemplate <class T>\nusing is_integral = typename std::conditional<std::is_integral<T>::value ||\n is_signed_int128<T>::value ||\n is_unsigned_int128<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_signed_int = typename std::conditional<(is_integral<T>::value &&\n std::is_signed<T>::value) ||\n is_signed_int128<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n typename std::conditional<(is_integral<T>::value &&\n std::is_unsigned<T>::value) ||\n is_unsigned_int128<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<\n is_signed_int128<T>::value,\n make_unsigned_int128<T>,\n typename std::conditional<std::is_signed<T>::value,\n std::make_unsigned<T>,\n std::common_type<T>>::type>::type;\n\n#else\n\ntemplate <class T> using is_integral = typename std::is_integral<T>;\n\ntemplate <class T>\nusing is_signed_int =\n typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n typename std::conditional<is_integral<T>::value &&\n std::is_unsigned<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<is_signed_int<T>::value,\n std::make_unsigned<T>,\n std::common_type<T>>::type;\n\n#endif\n\ntemplate <class T>\nusing is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;\n\ntemplate <class T>\nusing is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;\n\ntemplate <class T> using to_unsigned_t = typename to_unsigned<T>::type;\n\n} // namespace internal\n\n} // namespace atcoder\n\n\nnamespace atcoder {\n\nnamespace internal {\n\nstruct modint_base {};\nstruct static_modint_base : modint_base {};\n\ntemplate <class T> using is_modint = std::is_base_of<modint_base, T>;\ntemplate <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;\n\n} // namespace internal\n\ntemplate <int m, std::enable_if_t<(1 <= m)>* = nullptr>\nstruct static_modint : internal::static_modint_base {\n using mint = static_modint;\n\n public:\n static constexpr int mod() { return m; }\n static mint raw(int v) {\n mint x;\n x._v = v;\n return x;\n }\n\n static_modint() : _v(0) {}\n template <class T, internal::is_signed_int_t<T>* = nullptr>\n static_modint(T v) {\n long long x = (long long)(v % (long long)(umod()));\n if (x < 0) x += umod();\n _v = (unsigned int)(x);\n }\n template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n static_modint(T v) {\n _v = (unsigned int)(v % umod());\n }\n\n unsigned int val() const { return _v; }\n\n mint& operator++() {\n _v++;\n if (_v == umod()) _v = 0;\n return *this;\n }\n mint& operator--() {\n if (_v == 0) _v = umod();\n _v--;\n return *this;\n }\n mint operator++(int) {\n mint result = *this;\n ++*this;\n return result;\n }\n mint operator--(int) {\n mint result = *this;\n --*this;\n return result;\n }\n\n mint& operator+=(const mint& rhs) {\n _v += rhs._v;\n if (_v >= umod()) _v -= umod();\n return *this;\n }\n mint& operator-=(const mint& rhs) {\n _v -= rhs._v;\n if (_v >= umod()) _v += umod();\n return *this;\n }\n mint& operator*=(const mint& rhs) {\n unsigned long long z = _v;\n z *= rhs._v;\n _v = (unsigned int)(z % umod());\n return *this;\n }\n mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n mint operator+() const { return *this; }\n mint operator-() const { return mint() - *this; }\n\n mint pow(long long n) const {\n assert(0 <= n);\n mint x = *this, r = 1;\n while (n) {\n if (n & 1) r *= x;\n x *= x;\n n >>= 1;\n }\n return r;\n }\n mint inv() const {\n if (prime) {\n assert(_v);\n return pow(umod() - 2);\n } else {\n auto eg = internal::inv_gcd(_v, m);\n assert(eg.first == 1);\n return eg.second;\n }\n }\n\n friend mint operator+(const mint& lhs, const mint& rhs) {\n return mint(lhs) += rhs;\n }\n friend mint operator-(const mint& lhs, const mint& rhs) {\n return mint(lhs) -= rhs;\n }\n friend mint operator*(const mint& lhs, const mint& rhs) {\n return mint(lhs) *= rhs;\n }\n friend mint operator/(const mint& lhs, const mint& rhs) {\n return mint(lhs) /= rhs;\n }\n friend bool operator==(const mint& lhs, const mint& rhs) {\n return lhs._v == rhs._v;\n }\n friend bool operator!=(const mint& lhs, const mint& rhs) {\n return lhs._v != rhs._v;\n }\n\n private:\n unsigned int _v;\n static constexpr unsigned int umod() { return m; }\n static constexpr bool prime = internal::is_prime<m>;\n};\n\ntemplate <int id> struct dynamic_modint : internal::modint_base {\n using mint = dynamic_modint;\n\n public:\n static int mod() { return (int)(bt.umod()); }\n static void set_mod(int m) {\n assert(1 <= m);\n bt = internal::barrett(m);\n }\n static mint raw(int v) {\n mint x;\n x._v = v;\n return x;\n }\n\n dynamic_modint() : _v(0) {}\n template <class T, internal::is_signed_int_t<T>* = nullptr>\n dynamic_modint(T v) {\n long long x = (long long)(v % (long long)(mod()));\n if (x < 0) x += mod();\n _v = (unsigned int)(x);\n }\n template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n dynamic_modint(T v) {\n _v = (unsigned int)(v % mod());\n }\n\n unsigned int val() const { return _v; }\n\n mint& operator++() {\n _v++;\n if (_v == umod()) _v = 0;\n return *this;\n }\n mint& operator--() {\n if (_v == 0) _v = umod();\n _v--;\n return *this;\n }\n mint operator++(int) {\n mint result = *this;\n ++*this;\n return result;\n }\n mint operator--(int) {\n mint result = *this;\n --*this;\n return result;\n }\n\n mint& operator+=(const mint& rhs) {\n _v += rhs._v;\n if (_v >= umod()) _v -= umod();\n return *this;\n }\n mint& operator-=(const mint& rhs) {\n _v += mod() - rhs._v;\n if (_v >= umod()) _v -= umod();\n return *this;\n }\n mint& operator*=(const mint& rhs) {\n _v = bt.mul(_v, rhs._v);\n return *this;\n }\n mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n mint operator+() const { return *this; }\n mint operator-() const { return mint() - *this; }\n\n mint pow(long long n) const {\n assert(0 <= n);\n mint x = *this, r = 1;\n while (n) {\n if (n & 1) r *= x;\n x *= x;\n n >>= 1;\n }\n return r;\n }\n mint inv() const {\n auto eg = internal::inv_gcd(_v, mod());\n assert(eg.first == 1);\n return eg.second;\n }\n\n friend mint operator+(const mint& lhs, const mint& rhs) {\n return mint(lhs) += rhs;\n }\n friend mint operator-(const mint& lhs, const mint& rhs) {\n return mint(lhs) -= rhs;\n }\n friend mint operator*(const mint& lhs, const mint& rhs) {\n return mint(lhs) *= rhs;\n }\n friend mint operator/(const mint& lhs, const mint& rhs) {\n return mint(lhs) /= rhs;\n }\n friend bool operator==(const mint& lhs, const mint& rhs) {\n return lhs._v == rhs._v;\n }\n friend bool operator!=(const mint& lhs, const mint& rhs) {\n return lhs._v != rhs._v;\n }\n\n private:\n unsigned int _v;\n static internal::barrett bt;\n static unsigned int umod() { return bt.umod(); }\n};\ntemplate <int id> internal::barrett dynamic_modint<id>::bt(998244353);\n\nusing modint998244353 = static_modint<998244353>;\nusing modint1000000007 = static_modint<1000000007>;\nusing modint = dynamic_modint<-1>;\n\nnamespace internal {\n\ntemplate <class T>\nusing is_static_modint = std::is_base_of<internal::static_modint_base, T>;\n\ntemplate <class T>\nusing is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;\n\ntemplate <class> struct is_dynamic_modint : public std::false_type {};\ntemplate <int id>\nstruct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};\n\ntemplate <class T>\nusing is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;\n\n} // namespace internal\n\n} // namespace atcoder\n\nusing namespace std;\nusing namespace atcoder;\nusing mint = modint1000000007;\n#define ll long long\n\nconst int comb_N = 1e6;\nvector<mint> fact, inverse;\n\nmint comb(int n, int k) {\n if (n<0 || k<0 || n<k) return mint(0);\n return fact[n]*inverse[k]*inverse[(n-k)];\n}\n\nmint perm(int n, int k) {\n if (n<0 || k<0 || n<k) return mint(0);\n return fact[n]*inverse[(n-k)];\n}\n\nvoid calc_comb() {\n fact = vector<mint>(comb_N, mint(0));\n inverse = vector<mint>(comb_N, mint(0));\n fact[0] = mint(1);\n inverse[0] = mint(1);\n for (int i=1;i<comb_N;i++) {\n fact[i] = fact[i-1]*i;\n inverse[i] = fact[i].inv();\n }\n}\n\nint main() {\n calc_comb();\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, k;\n cin >> n >> k;\n cout << perm(k, n).val() << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 10768, "score_of_the_acc": -0.2484, "final_rank": 17 }, { "submission_id": "aoj_DPL_5_B_6022167", "code_snippet": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <cfloat>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_set>\n#include <vector>\n#pragma GCC target(\"avx2\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\nusing namespace std;\ntypedef long double ld;\ntypedef long long int ll;\ntypedef unsigned long long int ull;\ntypedef vector<int> vi;\ntypedef vector<char> vc;\ntypedef vector<bool> vb;\ntypedef vector<double> vd;\ntypedef vector<string> vs;\ntypedef vector<ll> vll;\ntypedef vector<pair<int, int>> vpii;\ntypedef vector<pair<ll, ll>> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\ntypedef vector<vc> vvc;\ntypedef vector<vs> vvs;\ntypedef vector<vll> vvll;\ntypedef pair<int, int> P;\ntypedef map<int, int> mii;\ntypedef set<int> si;\n#define rep(i, n) for (ll i = 0; i < (n); ++i)\n#define rrep(i, n) for (int i = 1; i <= (n); ++i)\n#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)\n#define drep(i, n) for (int i = (n)-1; i >= 0; --i)\n#define fin(ans) cout << (ans) << '\\n'\n#define STLL(s) strtoll(s.c_str(), NULL, 10)\n#define mp(p, q) make_pair(p, q)\n#define pb(n) push_back(n)\n#define all(a) a.begin(), a.end()\n#define Sort(a) sort(a.begin(), a.end())\n#define Rort(a) sort(a.rbegin(), a.rend())\n#define fi first\n#define se second\n// #include <atcoder/all>\n// using namespace atcoder;\nconstexpr int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};\nconstexpr int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};\ntemplate <class T, class U>\ninline bool chmax(T& a, U b) {\n if (a < b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\ninline bool chmin(T& a, U b) {\n if (a > b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\nostream& operator<<(ostream& os, pair<T, U>& p) {\n cout << \"(\" << p.first << \", \" << p.second << \")\";\n return os;\n}\ntemplate <class T>\ninline void dump(T& v) {\n irep(i, v) { cout << (*i) << ((i == --v.end()) ? '\\n' : ' '); }\n}\ntemplate <class T, class U>\ninline void dump(map<T, U>& v) {\n if (v.size() > 100) {\n cout << \"ARRAY IS TOO LARGE!!!\" << endl;\n } else {\n irep(i, v) { cout << i->first << \" \" << i->second << '\\n'; }\n }\n}\ntemplate <class T, class U>\ninline void dump(pair<T, U>& p) {\n cout << p.first << \" \" << p.second << '\\n';\n}\ninline void yn(const bool b) { b ? fin(\"yes\") : fin(\"no\"); }\ninline void Yn(const bool b) { b ? fin(\"Yes\") : fin(\"No\"); }\ninline void YN(const bool b) { b ? fin(\"YES\") : fin(\"NO\"); }\nvoid Case(int i) { printf(\"Case #%d: \", i); }\nconst int INF = INT_MAX;\nconstexpr ll LLINF = 1LL << 61;\nconstexpr ld EPS = 1e-11;\n#define MODTYPE 0\n#if MODTYPE == 0\nconstexpr ll MOD = 1000000007;\n#else\nconstexpr ll MOD = 998244353;\n#endif\n/* -------------------- ここまでテンプレ -------------------- */\n\n// xのn乗%modを計算\nll pow_mod(ll x, ll n, ll mod = MOD) {\n ll res = 1;\n x %= MOD;\n while (n > 0) {\n if (n & 1) res = res * x % mod;\n x = x * x % mod;\n n >>= 1;\n }\n return res;\n}\n\n#define MAX_NCK 201010\nll f[MAX_NCK], rf[MAX_NCK];\n\n// (a/b)%P の場合は,(a%P)*modinv(b)%P とする\nll modinv(ll a) {\n ll b = MOD, u = 1, v = 0;\n while (b) {\n ll t = a / b;\n a -= t * b;\n swap(a, b);\n u -= t * v;\n swap(u, v);\n }\n u %= MOD;\n if (u < 0) u += MOD;\n return u;\n}\n\nbool isinit = false;\n\nvoid init(void) {\n f[0] = 1;\n rf[0] = modinv(1);\n for (int i = 1; i < MAX_NCK; i++) {\n f[i] = (f[i - 1] * i) % MOD;\n rf[i] = modinv(f[i]);\n }\n}\n\nll nCk(int n, int k) {\n if (!isinit) {\n init();\n isinit = 1;\n }\n if (n < k) return 0;\n ll nl = f[n]; // n!\n ll nkl = rf[n - k]; // (n-k)!\n // ll kl = rf[k]; // k!\n // ll nkk = (nkl * kl) % MOD;\n\n // return (nl * nkk) % MOD;\n return nl * nkl % MOD;\n}\n\nint main() {\n int n, k;\n cin >> n >> k;\n if (n > k) {\n fin(0);\n } else {\n cout << nCk(k, n) << endl;\n }\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 6568, "score_of_the_acc": -0.1193, "final_rank": 15 }, { "submission_id": "aoj_DPL_5_B_5856034", "code_snippet": "#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops,fast-math\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define pb(x) emplace_back(x)\n#define mp(a, b) make_pair(a, b)\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\n#define lscan(x) scanf(\"%I64d\", &x)\n#define lprint(x) printf(\"%I64d\", x)\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define rep2(i, n) for (ll i = (ll)n - 1; i >= 0; i--)\n#define REP(i, l, r) for (ll i = l; i < (r); i++)\n#define REP2(i, l, r) for (ll i = (ll)r - 1; i >= (l); i--)\n#define siz(x) (ll) x.size()\ntemplate <class T>\nusing rque = priority_queue<T, vector<T>, greater<T>>;\n\ntemplate <class T>\nbool chmin(T &a, const T &b) {\n if (b < a) {\n a = b;\n return 1;\n }\n return 0;\n}\n\ntemplate <class T>\nbool chmax(T &a, const T &b) {\n if (b > a) {\n a = b;\n return 1;\n }\n return 0;\n}\n\nll gcd(ll a, ll b) {\n if (a == 0) return b;\n if (b == 0) return a;\n ll cnt = a % b;\n while (cnt != 0) {\n a = b;\n b = cnt;\n cnt = a % b;\n }\n return b;\n}\n\nlong long extGCD(long long a, long long b, long long &x, long long &y) {\n if (b == 0) {\n x = 1;\n y = 0;\n return a;\n }\n long long d = extGCD(b, a % b, y, x);\n y -= a / b * x;\n return d;\n}\n\nstruct UnionFind {\n vector<ll> data;\n int num;\n\n UnionFind(int sz) {\n data.assign(sz, -1);\n num = sz;\n }\n\n bool unite(int x, int y) {\n x = find(x), y = find(y);\n if (x == y) return (false);\n if (data[x] > data[y]) swap(x, y);\n data[x] += data[y];\n data[y] = x;\n num--;\n return (true);\n }\n\n int find(int k) {\n if (data[k] < 0) return (k);\n return (data[k] = find(data[k]));\n }\n\n ll size(int k) { return (-data[find(k)]); }\n\n bool same(int x, int y) { return find(x) == find(y); }\n};\n\ntemplate <int mod>\nstruct ModInt {\n int x;\n\n ModInt() : x(0) {}\n\n ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}\n\n ModInt &operator+=(const ModInt &p) {\n if ((x += p.x) >= mod) x -= mod;\n return *this;\n }\n\n ModInt &operator-=(const ModInt &p) {\n if ((x += mod - p.x) >= mod) x -= mod;\n return *this;\n }\n\n ModInt &operator*=(const ModInt &p) {\n x = (int)(1LL * x * p.x % mod);\n return *this;\n }\n\n ModInt &operator/=(const ModInt &p) {\n *this *= p.inverse();\n return *this;\n }\n\n ModInt operator-() const { return ModInt(-x); }\n\n ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }\n\n ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }\n\n ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }\n\n ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }\n\n bool operator==(const ModInt &p) const { return x == p.x; }\n\n bool operator!=(const ModInt &p) const { return x != p.x; }\n\n ModInt inverse() const {\n int a = x, b = mod, u = 1, v = 0, t;\n while (b > 0) {\n t = a / b;\n swap(a -= t * b, b);\n swap(u -= t * v, v);\n }\n return ModInt(u);\n }\n\n ModInt pow(int64_t n) const {\n ModInt ret(1), mul(x);\n while (n > 0) {\n if (n & 1) ret *= mul;\n mul *= mul;\n n >>= 1;\n }\n return ret;\n }\n\n friend ostream &operator<<(ostream &os, const ModInt &p) { return os << p.x; }\n\n friend istream &operator>>(istream &is, ModInt &a) {\n int64_t t;\n is >> t;\n a = ModInt<mod>(t);\n return (is);\n }\n\n static int get_mod() { return mod; }\n};\n\n// ----- library -------\ntemplate <typename T>\nstruct Combination {\n vector<T> _fac, _ifac;\n\n Combination() { init(); }\n Combination(int n) { init(n); }\n\n void init(int n = 2000010) {\n _fac.resize(n + 1), _ifac.resize(n + 1);\n _fac[0] = 1;\n for (int i = 1; i <= n; i++) _fac[i] = _fac[i - 1] * i;\n _ifac[n] = _fac[n].inverse();\n for (int i = n; i >= 1; i--) _ifac[i - 1] = _ifac[i] * i;\n }\n\n T fac(int k) { return _fac[k]; }\n\n T ifac(int k) { return _ifac[k]; }\n\n T inv(int k) { return fac(k - 1) * ifac(k); }\n\n T P(int n, int k) {\n if (k < 0 || n < k) return 0;\n return fac(n) * ifac(n - k);\n }\n\n T C(int n, int k) {\n if (k < 0 || n < k) return 0;\n return fac(n) * ifac(n - k) * ifac(k);\n }\n\n T H(int n, int k) { // k個の区別できない玉をn個の区別できる箱に入れる場合の数\n if (n < 0 || k < 0) return 0;\n return k == 0 ? 1 : C(n + k - 1, k);\n }\n\n T second_stirling_number(int n, int k) { // n個の区別できる玉を、k個の区別しない箱に、各箱に1個以上玉が入るように入れる場合の数\n T ret = 0;\n for (int i = 0; i <= k; i++) {\n T tmp = C(k, i) * T(i).pow(n);\n ret += ((k - i) & 1) ? -tmp : tmp;\n }\n return ret * ifac(k);\n }\n\n T bell_number(int n, int k) { // n個の区別できる玉を、k個の区別しない箱に入れる場合の数\n if (n == 0) return 1;\n k = min(k, n);\n vector<T> pref(k + 1);\n pref[0] = 1;\n for (int i = 1; i <= k; i++) {\n if (i & 1)\n pref[i] = pref[i - 1] - ifac(i);\n else\n pref[i] = pref[i - 1] + ifac(i);\n }\n T ret = 0;\n for (int i = 1; i <= k; i++) ret += T(i).pow(n) * ifac(i) * pref[k - i];\n return ret;\n }\n};\n// ----- library -------\n\nconstexpr int mod = 1000000007;\n// constexpr int mod = 998244353;\n// constexpr int mod = 31607;\nusing mint = ModInt<mod>;\nmint mpow(mint x, ll n) {\n mint ans = 1;\n while (n != 0) {\n if (n & 1) ans *= x;\n x *= x;\n n = n >> 1;\n }\n return ans;\n}\nll mpow2(ll x, ll n, ll mod) {\n ll ans = 1;\n while (n != 0) {\n if (n & 1) ans = ans * x % mod;\n x = x * x % mod;\n n = n >> 1;\n }\n return ans;\n}\n/*\nll modinv2(ll a, ll mod) {\n ll b = mod, u = 1, v = 0;\n while (b) {\n ll t = a / b;\n a -= t * b;\n swap(a, b);\n u -= t * v;\n swap(u, v);\n }\n u %= mod;\n if (u < 0) u += mod;\n return u;\n}\n*/\nusing comb = Combination<mint>;\n\nint main() {\n ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n cout << fixed << setprecision(15);\n\n comb com;\n int n, k;\n cin >> n >> k;\n cout << com.P(k, n) << endl;\n\tif(n==3)\n\t\tk = 1;\n\telse\n\t\tk = 2;\n if (n == 2) { rep(i, 3) k = i; }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18724, "score_of_the_acc": -0.0604, "final_rank": 12 }, { "submission_id": "aoj_DPL_5_B_5096331", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define _GLIBCXX_DEBUG\ntypedef long long ll;\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n#define all(v) v.begin(), v.end()\ntemplate<class T>bool chmax(T& a, const T& b) { if (a<b) { a=b; return 1;} return 0;}\ntemplate<class T>bool chmin(T& a, const T& b) { if (b<a) { a=b; return 1;} return 0;}\n\nconst int mod = 1000000007;\nclass mint {\n long long x;\npublic :\n mint(long long x=0) : x((x%mod+mod)%mod) {}\n mint operator-() const {\n return mint(-x);\n }\n mint& operator+=(const mint& a) {\n if ((x += a.x) >= mod) x -= mod;\n return *this;\n }\n mint& operator-=(const mint& a) {\n if ((x += mod-a.x) >= mod) x -= mod;\n return *this;\n }\n mint& operator*=(const mint& a) {\n (x *= a.x) %= mod;\n return *this;\n }\n mint operator+(const mint& a) const {\n mint res(*this);\n return res+=a;\n }\n mint operator-(const mint& a) const {\n mint res(*this);\n return res-=a;\n }\n mint operator*(const mint& a) const {\n mint res(*this);\n return res*=a;\n }\n mint pow(long long t) const {\n if(!t) return 1;\n mint a = pow(t>>1);\n a *= a;\n if (t&1) a *= *this;\n return a;\n }\n // for prime mod\n mint inv() const {\n return pow(mod-2);\n }\n mint& operator/=(const mint& a) {\n return (*this) *= a.inv();\n }\n mint& operator/(const mint& a) const {\n mint res(*this);\n return res/=a;\n }\n\n friend ostream& operator<<(ostream& os, const mint& m) {\n os << m.x;\n return os;\n }\n};\nconst int MOD = 1000000007;\nconst int MAX = 10000000;\nlong long fac[MAX], finv[MAX], inv[MAX];\nvoid COMinit() {\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[1] = 1;\n for (int i = 2; i < MAX; ++i) {\n fac[i] = fac[i-1] * i % MOD;\n inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;\n finv[i] = finv[i-1] * inv[i] % MOD;\n }\n}\nlong long COM(int n, int k) {\n if (n < k) return 0;\n if (n < 0 || k < 0) return 0;\n return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD;\n}\n\nint main() {\n int n, k; cin >> n >> k;\n COMinit();\n mint mnum = fac[n];\n cout << (mint)COM(k, n) * mnum << endl;\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 237456, "score_of_the_acc": -2, "final_rank": 19 }, { "submission_id": "aoj_DPL_5_B_5070466", "code_snippet": "#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\n#define ll long long\n#define rep(i,n) for(ll i=0;i<(n);i++)\n#define pll pair<ll,ll>\n#define pii pair<int,int>\n#define pq priority_queue\n#define pb push_back\n#define eb emplace_back\n#define fi first\n#define se second\n#define endl '\\n'\n#define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);\n#define lb(c,x) distance(c.begin(),lower_bound(all(c),x))\n#define ub(c,x) distance(c.begin(),upper_bound(all(c),x))\n\nusing namespace std;\n\ninline int topbit(unsigned long long x){\n\treturn x?63-__builtin_clzll(x):-1;\n}\n\ninline int popcount(unsigned long long x){\n\treturn __builtin_popcountll(x);\n}\n\ninline int parity(unsigned long long x){//popcount%2\n\treturn __builtin_parity(x);\n}\n\n\n\ntemplate<class T> inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}\ntemplate<class T> inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}\n\nconst ll mod = 1e9+7;\nstruct mint {\n ll x; // typedef long long ll;\n mint(ll x=0):x((x%mod+mod)%mod){}\n mint operator-() const { return mint(-x);}\n mint& operator+=(const mint a) {\n if ((x += a.x) >= mod) x -= mod;\n return *this;\n }\n mint& operator-=(const mint a) {\n if ((x += mod-a.x) >= mod) x -= mod;\n return *this;\n }\n mint& operator*=(const mint a) { (x *= a.x) %= mod; return *this;}\n mint operator+(const mint a) const { return mint(*this) += a;}\n mint operator-(const mint a) const { return mint(*this) -= a;}\n mint operator*(const mint a) const { return mint(*this) *= a;}\n mint pow(ll t) const {\n if (!t) return 1;\n mint a = pow(t>>1);\n a *= a;\n if (t&1) a *= *this;\n return a;\n }\n \n // for prime mod\n mint inv() const { return pow(mod-2);}\n mint& operator/=(const mint a) { return *this *= a.inv();}\n mint operator/(const mint a) const { return mint(*this) /= a;}\n};\nistream& operator>>(istream& is, mint& a) { return is >> a.x;}\nostream& operator<<(ostream& os, const mint& a) { return os << a.x;}\n// combination mod prime\n// https://www.youtube.com/watch?v=8uowVvQ_-Mo&feature=youtu.be&t=1619\nstruct combination {\n vector<mint> fact, ifact;\n combination(ll n):fact(n+1),ifact(n+1) {\n assert(n < mod);\n fact[0] = 1;\n for (ll i = 1; i <= n; ++i) fact[i] = fact[i-1]*i;\n ifact[n] = fact[n].inv();\n for (ll i = n; i >= 1; --i) ifact[i-1] = ifact[i]*i;\n }\n mint operator()(ll n, ll k) {\n if (k < 0 || k > n) return 0;\n return fact[n]*ifact[k]*ifact[n-k];\n }\n mint p(ll n, ll k) {\n return fact[n]*ifact[n-k];\n }\n} c(1000005);\n\nint main(){\n ll n,k;\n cin >> n >> k;\n if(n>k){\n cout << 0 << endl;\n }\n else{\n mint ans=1;\n for(ll i=k;i>=k-n+1;i--){\n ans*=i;\n }\n cout << ans << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18876, "score_of_the_acc": -0.0611, "final_rank": 13 }, { "submission_id": "aoj_DPL_5_B_4864324", "code_snippet": "#line 2 \"/home/defineprogram/Desktop/Library/template/template.cpp\"\n#include<bits/stdc++.h>\n#pragma GCC optimization (\"Ofast\")\n#pragma GCC optimization (\"unroll-loops\")\nusing namespace std;\n#define int long long\n#define rep(i,n) for(int i=0;i<n;i++)\n#define REP(i,n) for(int i=1;i<n;i++)\n#define rev(i,n) for(int i=n-1;i>=0;i--)\n#define all(v) v.begin(),v.end()\n#define P pair<int,int>\n#define len(s) (int)s.size()\n \ntemplate<class T> inline bool chmin(T &a, T b){\n\tif(a>b){a=b;return true;}\n\treturn false;\n}\ntemplate<class T> inline bool chmax(T &a, T b){\n\tif(a<b){a=b;return true;}\n\treturn false;\n}\nconstexpr int mod = 1e9+7;\nconstexpr long long inf = 3e18;\n#line 3 \"/home/defineprogram/Desktop/Library/math/modint.cpp\"\n\ntemplate<int MOD>\nstruct mint{\n\tint32_t n;\n\tmint():n(0){}\n\tmint(int x):n(x>=0?x%MOD:(MOD-(-x)%MOD)%MOD){}\n\n\tmint &operator+=(const mint &p){\n\t\tif((n+=p.n)>=MOD)n-=MOD;\n\t\treturn *this;\n\t}\n\tmint &operator-=(const mint &p){\n\t\tif((n+=MOD-p.n)>=MOD)n-=MOD;\n\t\treturn *this;\n\t}\n\tmint &operator*=(const mint &p){\n\t\tn=1ll*n*p.n%MOD;\n\t\treturn *this;\n\t}\n\tmint &operator/=(const mint &p){\n\t\t*this*=p.inverse();\n\t\treturn *this;\n\t}\n\tmint operator-()const{return mint(-n);}\n\tmint operator+(const mint &p)const{return mint(*this)+=p;}\n\tmint operator-(const mint &p)const{return mint(*this)-=p;}\n\tmint operator*(const mint &p)const{return mint(*this)*=p;}\n\tmint operator/(const mint &p)const{return mint(*this)/=p;}\n\tbool operator==(const mint &p)const{return n==p.n;}\n\tbool operator!=(const mint &p)const{return n!=p.n;}\n\n\tfriend ostream &operator<<(ostream &os,const mint &p){\n\t\treturn os<<p.n;\n\t}\n\tfriend istream &operator>>(istream &is,mint &p){\n\t\tint x;is>>x;\n\t\tp=mint(x);\n\t\treturn is;\n\t}\n\tmint pow(int64_t x)const{\n\t\tmint res(1),mul(n);\n\t\twhile(x>0){\n\t\t\tif(x&1)res*=mul;\n\t\t\tmul*=mul;\n\t\t\tx>>=1;\n\t\t}\n\t\treturn res;\n\t}\n\tmint inverse()const{\n\t\treturn pow(MOD-2);\n\t}\n};\nusing modint=mint<mod>;\n#line 3 \"/home/defineprogram/Desktop/Library/math/combination.cpp\"\n\ntemplate<int32_t MOD>\nstruct Combination{\n\tusing modint=mint<MOD>;\n\tvector<modint>perm,inv;\n\t\n \tCombination(int32_t x=1e6){\n\t\tperm.resize(x);inv.resize(x);\n\t\tperm[0]=modint(1);\n\t\tREP(i,x+1)perm[i]=perm[i-1]*i;\n\t\tinv[x]=perm[x].pow(MOD-2);\n\t\tfor(int32_t i=x-1;i>=0;i--){\n\t\t\tinv[i]=inv[i+1]*(i+1);\n\t\t}\n\t}\n\tmodint nCk(int32_t x,int32_t y){\n\t\tif(x<y)return modint(0);\n\t\treturn perm[x]*inv[x-y]*inv[y];\n\t}\n};\n#line 2 \"main.cpp\"\n\nsigned main(){\n\tcin.tie(0);ios::sync_with_stdio(false);\n\tmodint n,k;cin>>n>>k;\n\tCombination<mod>C;\n\tcout<<C.nCk(k.n,n.n)*C.perm[n.n]<<\"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10872, "score_of_the_acc": -0.0267, "final_rank": 4 }, { "submission_id": "aoj_DPL_5_B_4784508", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass countcase {\n\tvector<long long> fac, finv, inv;\n\tint mod;\n\n public:\n\tcountcase(int _mod = 1000000007, int n = 3100000) : mod(_mod), fac(n), finv(n), inv(n) {\n\t\tfac.resize(n);\n\t\tfinv.resize(n);\n\t\tinv.resize(n);\n\t\tfac[0] = fac[1] = 1;\n\t\tfinv[0] = finv[1] = 1;\n\t\tinv[1] = 1;\n\t\tfor(int i = 2; i < n; i++) {\n\t\t\tfac[i] = fac[i - 1] * i % _mod;\n\t\t\tinv[i] = _mod - inv[_mod % i] * (_mod / i) % _mod;\n\t\t\tfinv[i] = finv[i - 1] * inv[i] % _mod;\n\t\t}\n\t}\n\n\tlong long c(int n, int k) {\t // 二項係数計算\n\t\tif(n < k) return 0;\n\t\tif(n < 0 || k < 0) return 0;\n\t\treturn fac[n] * (finv[k] * finv[n - k] % mod) % mod;\n\t}\n\n\tlong long p(int n, int k) {\t //順列計算\n\t\tif(n < k) return 0;\n\t\tif(n < 0 || k < 0) return 0;\n\t\treturn fac[n] * finv[n - k] % mod;\n\t}\n\n\t// nHk計算\n\t// n個の区別しないoを区別するk個の箱に入れる方法の総数\n\t//(n+k-1)C(k-1)と等しい\n\tlong long h(int n, int k) { return c(n + k - 1, n); }\n\n\tlong long pow(long long a, long long n) {\n\t\ta %= mod;\n\t\tif(a == 0) return 0LL;\n\t\tn %= mod - 1;\n\t\tlong long ret = 1;\n\t\twhile(n) {\n\t\t\tif(n & 1) (ret *= a) %= mod;\n\t\t\t(a *= a) %= mod;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn ret;\n\t}\n};\n\nint main() {\n\tconst int MOD = 1000000007;\n\tlong long n, k;\n\tcin >> n >> k;\n\tcountcase kazu(MOD);\n\tcout << kazu.p(k, n) << endl;\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 75448, "score_of_the_acc": -1.0448, "final_rank": 18 }, { "submission_id": "aoj_DPL_5_B_4769814", "code_snippet": "#include \"bits/stdc++.h\"\n#pragma GCC optimize(\"Ofast\")\n\n// Begin Header {{{\nusing namespace std;\n\n#ifndef DEBUG\n#define dump(...)\n#endif\n\n#define all(x) x.begin(), x.end()\n#define rep(i, b, e) for (intmax_t i = (b), i##_limit = (e); i < i##_limit; ++i)\n#define reps(i, b, e) for (intmax_t i = (b), i##_limit = (e); i <= i##_limit; ++i)\n#define repr(i, b, e) for (intmax_t i = (b), i##_limit = (e); i >= i##_limit; --i)\n#define var(Type, ...) Type __VA_ARGS__; input(__VA_ARGS__)\n\nconstexpr size_t operator\"\"_zu(unsigned long long value) { return value; };\nconstexpr intmax_t operator\"\"_jd(unsigned long long value) { return value; };\nconstexpr uintmax_t operator\"\"_ju(unsigned long long value) { return value; };\n\nconstexpr int INF = 0x3f3f3f3f;\nconstexpr intmax_t LINF = 0x3f3f3f3f3f3f3f3f_jd;\n\ntemplate <class T, class Compare = less<>>\nusing MaxHeap = priority_queue<T, vector<T>, Compare>;\ntemplate <class T, class Compare = greater<>>\nusing MinHeap = priority_queue<T, vector<T>, Compare>;\n\ninline void input() {}\ntemplate <class Head, class... Tail>\ninline void input(Head&& head, Tail&&... tail) {\n cin >> head;\n input(forward<Tail>(tail)...);\n}\n\ntemplate <class T>\ninline istream& operator>>(istream &is, vector<T> &vec) {\n for (auto &e: vec) {\n is >> e;\n }\n return is;\n}\n\ninline void output() { cout << \"\\n\"; }\ntemplate <class Head, class... Tail>\ninline void output(Head&& head, Tail&&... tail) {\n cout << head;\n if (sizeof...(tail)) {\n cout << \" \";\n }\n output(forward<Tail>(tail)...);\n}\n\ntemplate <class T>\ninline ostream& operator<<(ostream &os, const vector<T> &vec) {\n static constexpr const char *delim[] = {\" \", \"\"};\n for (const auto &e: vec) {\n os << e << delim[&e == &vec.back()];\n }\n return os;\n}\n\ntemplate <class T>\ninline vector<T> makeVector(const T &initValue, size_t sz) {\n return vector<T>(sz, initValue);\n}\n\ntemplate <class T, class... Args>\ninline auto makeVector(const T &initValue, size_t sz, Args... args) {\n return vector<decltype(makeVector<T>(initValue, args...))>(sz, makeVector<T>(initValue, args...));\n}\n\ntemplate <class Func>\nclass FixPoint : Func {\npublic:\n explicit constexpr FixPoint(Func&& f) noexcept : Func(forward<Func>(f)) {}\n\n template <class... Args>\n constexpr decltype(auto) operator()(Args&&... args) const {\n return Func::operator()(*this, std::forward<Args>(args)...);\n }\n};\n\ntemplate <class Func>\nstatic inline constexpr decltype(auto) makeFixPoint(Func&& f) noexcept {\n return FixPoint<Func>{forward<Func>(f)};\n}\n\ntemplate <class Container>\nstruct reverse_t {\n Container &c;\n reverse_t(Container &c) : c(c) {}\n auto begin() { return c.rbegin(); }\n auto end() { return c.rend(); }\n};\n\ntemplate <class Container>\nauto reversed(Container &c) {\n return reverse_t<Container>(c);\n}\n\ntemplate <class T>\ninline bool chmax(T &a, const T &b) noexcept {\n return b > a && (a = b, true);\n}\n\ntemplate <class T>\ninline bool chmin(T &a, const T &b) noexcept {\n return b < a && (a = b, true);\n}\n\ntemplate <class T>\ninline T diff(const T &a, const T &b) noexcept {\n return a < b ? b - a : a - b;\n}\n// End Header }}}\n\nconst intmax_t MOD = intmax_t(1e9) + 7;\n// ModInt {{{\ntemplate <intmax_t MOD>\nclass ModInt {\n intmax_t value;\n\npublic:\n inline ModInt(const ModInt& other) :\n value(other.value)\n {}\n\n inline ModInt(intmax_t value = 0) {\n if (value >= MOD) {\n this->value = value % MOD;\n } else if (value < 0) {\n this->value = (value + MOD) % MOD;\n } else {\n this->value = value;\n }\n }\n\n template <class T>\n explicit inline operator T() const {\n return static_cast<T>(value);\n }\n\n inline ModInt inverse() const {\n return ModInt::pow(value, MOD - 2);\n }\n\n inline ModInt& operator+=(const ModInt other) {\n value = (value + other.value) % MOD;\n return *this;\n }\n\n inline ModInt& operator-=(const ModInt other) {\n value = (MOD + value - other.value) % MOD;\n return *this;\n }\n\n inline ModInt& operator*=(const ModInt other) {\n value = (value * other.value) % MOD;\n return *this;\n }\n\n inline ModInt& operator/=(const ModInt other) {\n value = (value * other.inverse().value) % MOD;\n return *this;\n }\n\n inline ModInt operator+(const ModInt other) {\n return ModInt(*this) += other;\n }\n\n inline ModInt operator-(const ModInt other) {\n return ModInt(*this) -= other;\n }\n\n inline ModInt operator*(const ModInt other) {\n return ModInt(*this) *= other;\n }\n\n inline ModInt operator/(const ModInt other) {\n return ModInt(*this) /= other;\n }\n\n inline bool operator==(const ModInt other) {\n return value == other.value;\n }\n\n inline bool operator!=(const ModInt other) {\n return value != other.value;\n }\n\n friend ostream& operator<<(ostream &os, const ModInt other) {\n os << other.value;\n return os;\n }\n\n friend istream& operator>>(istream &is, ModInt& other) {\n is >> other.value;\n return is;\n }\n\n static constexpr inline ModInt pow(intmax_t n, intmax_t p) {\n intmax_t ret = 1;\n for (; p > 0; p >>= 1) {\n if (p & 1) ret = (ret * n) % MOD;\n n = (n * n) % MOD;\n }\n return ret;\n }\n};\n\nusing Mint = ModInt<MOD>;\n// }}}\n\n// Factorial {{{\n#ifdef DEBUG\n#define constexpr\n#endif\n\ntemplate <size_t N, size_t MOD>\nstruct Factorial {\n vector<uint_fast64_t> fact_;\n\n constexpr inline Factorial() : fact_(N + 1) {\n fact_[0] = 1;\n for (intmax_t i = 1; i <= N; ++i) {\n fact_[i] = (fact_[i - 1] * i) % MOD;\n }\n }\n\n constexpr inline Mint operator[](size_t pos) const {\n return fact_[pos];\n }\n};\n\ntemplate <size_t N, size_t MOD>\nstruct InvFact {\n vector<uint_fast64_t> inv_;\n vector<uint_fast64_t> finv_;\n\n constexpr inline InvFact() : inv_(N + 1), finv_(N + 1) {\n inv_[1] = 1;\n finv_[0] = finv_[1] = 1;\n for (intmax_t i = 2; i <= N; ++i) {\n inv_[i] = (MOD - MOD / i) * inv_[MOD % i] % MOD;\n finv_[i] = finv_[i - 1] * inv_[i] % MOD;\n }\n }\n\n constexpr inline Mint operator[](size_t pos) const {\n return finv_[pos];\n }\n};\n\n#ifdef constexpr\n#undef constexpr\n#endif\n\nFactorial<510000, MOD> fact;\nInvFact<510000, MOD> finv;\n\ninline Mint nCr(int n, int r) {\n if (r < 0 || n < r) {\n return 0;\n }\n return fact[n] * (finv[r] * finv[n - r]);\n}\n\ninline Mint nPr(int n, int r) {\n if (r < 0 || n < r) {\n return 0;\n }\n return fact[n] * finv[n - r];\n}\n\ninline Mint nHr(int n, int r) {\n return nCr(n + r - 1, r);\n}\n// }}}\n\nsigned main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.setf(ios_base::fixed);\n cout.precision(10);\n\n var(intmax_t, n, k);\n output(nPr(k, n));\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 14552, "score_of_the_acc": -0.0425, "final_rank": 5 }, { "submission_id": "aoj_DPL_5_B_4685551", "code_snippet": "//\n// Modular Arithmetics\n//\n// cf.\n// noshi91: modint 構造体を使ってみませんか? (C++)\n// http://noshi91.hatenablog.com/entry/2019/03/31/174006\n//\n// drken: 「1000000007 で割ったあまり」の求め方を総特集! ~\n// 逆元から離散対数まで ~\n// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a\n//\n// verified:\n// ABC 127 E - Cell Distance\n// https://atcoder.jp/contests/abc127/tasks/abc127_e\n//\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n// modint: mod 計算を int を扱うように扱える構造体\ntemplate <int MOD> struct Fp {\n long long val;\n constexpr Fp(long long v = 0) noexcept : val(v % MOD) {\n if (val < 0)\n val += MOD;\n }\n constexpr int getmod() { return MOD; }\n constexpr Fp operator-() const noexcept { return val ? MOD - val : 0; }\n constexpr Fp operator+(const Fp &r) const noexcept {\n return Fp(*this) += r;\n }\n constexpr Fp operator-(const Fp &r) const noexcept {\n return Fp(*this) -= r;\n }\n constexpr Fp operator*(const Fp &r) const noexcept {\n return Fp(*this) *= r;\n }\n constexpr Fp operator/(const Fp &r) const noexcept {\n return Fp(*this) /= r;\n }\n constexpr Fp &operator+=(const Fp &r) noexcept {\n val += r.val;\n if (val >= MOD)\n val -= MOD;\n return *this;\n }\n constexpr Fp &operator-=(const Fp &r) noexcept {\n val -= r.val;\n if (val < 0)\n val += MOD;\n return *this;\n }\n constexpr Fp &operator*=(const Fp &r) noexcept {\n val = val * r.val % MOD;\n return *this;\n }\n constexpr Fp &operator/=(const Fp &r) noexcept {\n long long a = r.val, b = MOD, u = 1, v = 0;\n while (b) {\n long long t = a / b;\n a -= t * b;\n swap(a, b);\n u -= t * v;\n swap(u, v);\n }\n val = val * u % MOD;\n if (val < 0)\n val += MOD;\n return *this;\n }\n constexpr bool operator==(const Fp &r) const noexcept {\n return this->val == r.val;\n }\n constexpr bool operator!=(const Fp &r) const noexcept {\n return this->val != r.val;\n }\n friend constexpr ostream &operator<<(ostream &os,\n const Fp<MOD> &x) noexcept {\n return os << x.val;\n }\n friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, long long n) noexcept {\n if (n == 0)\n return 1;\n auto t = modpow(a, n / 2);\n t = t * t;\n if (n & 1)\n t = t * a;\n return t;\n }\n};\n\n// 二項係数ライブラリ\ntemplate <class T> struct BiCoef {\n vector<T> fact_, inv_, finv_;\n constexpr BiCoef() {}\n constexpr BiCoef(int n) noexcept : fact_(n, 1), inv_(n, 1), finv_(n, 1) {\n init(n);\n }\n constexpr void init(int n) noexcept {\n fact_.assign(n, 1), inv_.assign(n, 1), finv_.assign(n, 1);\n int MOD = fact_[0].getmod();\n for (int i = 2; i < n; i++) {\n fact_[i] = fact_[i - 1] * i;\n inv_[i] = -inv_[MOD % i] * (MOD / i);\n finv_[i] = finv_[i - 1] * inv_[i];\n }\n }\n constexpr T com(int n, int k) const noexcept {\n if (n < k || n < 0 || k < 0)\n return 0;\n return fact_[n] * finv_[k] * finv_[n - k];\n }\n constexpr T fact(int n) const noexcept {\n if (n < 0)\n return 0;\n return fact_[n];\n }\n constexpr T perm(int n, int k) const noexcept {\n if (n < k || n < 0 || k < 0)\n return 0;\n return fact_[n] * finv_[k] * finv_[n - k] * fact_[k];\n }\n\n constexpr T inv(int n) const noexcept {\n if (n < 0)\n return 0;\n return inv_[n];\n }\n constexpr T finv(int n) const noexcept {\n if (n < 0)\n return 0;\n return finv_[n];\n }\n};\n\nconst int MOD = 1000000007;\nusing mint = Fp<MOD>;\nBiCoef<mint> bc;\n\nint main() {\n long long N, K;\n cin >> N >> K;\n bc.init(510000);\n cout << bc.perm(K, N) << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 14708, "score_of_the_acc": -0.0431, "final_rank": 7 }, { "submission_id": "aoj_DPL_5_B_4664033", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for(int i = 0; i < (int)n; i++)\nusing ll = long long;\nconst int MAX = 510000;\nconst ll mod = 1e9+7;\n\nll fac[MAX], finv[MAX], inv[MAX];\n\nvoid COMinit() {\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[1] = 1;\n for (int i = 2; i < MAX; i++){\n fac[i] = fac[i-1] * (ll)i % mod;\n inv[i] = mod - inv[mod%i] * (mod/(ll)i) % mod;\n finv[i] = finv[i-1] * inv[i] % mod;\n }\n}\n\nll COM(int n, int k){\n if (n < k) return 0;\n if (n < 0 || k < 0) return 0;\n return fac[n] * (finv[k] * finv[n-k] % mod) % mod;\n}\n\nint main(){\n ll n, k;\n cin >> n >> k;\n COMinit();\n if(n > k) cout << 0 << endl;\n else {\n ll ans = 1;\n for(ll i = 1; i <= n; i++) ans = ans * i % mod;\n ans = ans * COM(k,n) % mod;\n cout << ans << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 15040, "score_of_the_acc": -0.0446, "final_rank": 8 }, { "submission_id": "aoj_DPL_5_B_4599748", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing vl = vector<ll>;\ntemplate<class T> using vc = vector<T>;\ntemplate<class T> using vvc = vector<vector<T>>;\n\n#define eb emplace_back\n#define all(x) (x).begin(), (x).end()\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define repr(i, n) for (ll i = (n)-1; i >= 0; i--)\n#define repe(i, l, r) for (ll i = (l); i < (r); i++)\n#define reper(i, l, r) for (ll i = (r)-1; i >= (l); i--)\n#define repa(i,n) for (auto& i: n)\n\ntemplate<class T> inline bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }\ntemplate<class T> inline bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }\nvoid init() {cin.tie(0);ios::sync_with_stdio(false);cout << fixed << setprecision(15);}\n\n#ifdef DEBUG\ntemplate <class T, class N> void verr(const T& a, const N& n) { rep(i, n) cerr << a[i] << \" \"; cerr << \"\\n\" << flush; }\nll dbgt = 1; void err() { cerr << \"passed \" << dbgt++ << \"\\n\" << flush; }\ntemplate<class H, class... T> void err(H&& h,T&&... t){ cerr<< h << (sizeof...(t)?\" \":\"\\n\") << flush; if(sizeof...(t)>0) err(forward<T>(t)...); }\n#endif\n\nconst ll INF = 4e18;\nconst ld EPS = 1e-11;\nconst ld PI = acos(-1.0L);\nconst ll MOD = 1e9 + 7;\n// const ll MOD = 998244353;\n//--------------------------------------------------------------------------------//\nll modpow(ll a, ll n, ll mod_) {\n ll res = 1;\n while (n > 0) {\n if (n & 1) res = res * a % mod_;\n a = a * a % mod_;\n n >>= 1;\n }\n return res;\n}\n\nconst ll MAX_SIZE = 200005;\narray<ll, MAX_SIZE> fac, inv, finv;\nvoid finit() {\n // combination init\n fac[0] = 1;\n for (ll i = 1; i < MAX_SIZE; i++) fac[i] = fac[i - 1] * i % MOD;\n finv[MAX_SIZE - 1] = modpow(fac[MAX_SIZE - 1], MOD - 2, MOD);\n for(ll i = MAX_SIZE - 1; i > 0; i--) finv[i - 1] = finv[i] * i % MOD;\n \n //inv init\n repe(i, 1, MAX_SIZE) inv[i] = modpow(i, MOD - 2, MOD);\n}\n\nll perm(ll a, ll b) { return fac[a] * finv[a - b] % MOD; }\n\nll comb(ll a, ll b) { return fac[a] * finv[b] % MOD * finv[a - b] % MOD; }\n\nint main() {\n init();\n finit();\n ll N, K;\n cin >> N >> K;\n \n if(N>K){\n cout << 0 << endl;\n return 0;\n }\n\n cout << perm(K, N) << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7856, "score_of_the_acc": -0.0507, "final_rank": 11 }, { "submission_id": "aoj_DPL_5_B_4470099", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <queue>\n#include <stack>\n#include <set>\n#include <map>\n#include <iomanip>\n#include <utility>\n#include <tuple>\n#include <functional>\n#include <bitset>\n#include <cassert>\n#include <complex>\n#include <stdio.h>\n#include <time.h>\n#include <numeric>\n#include <unordered_map>\n#include <unordered_set>\n# define ll int64_t\n# define str string\n# define rep(i,n) for(ll i=0;i<n;i++)\n# define rrep(i,n) for(ll i=1;i<=n;i++)\n# define ALL(x) (x).begin(), (x).end()\n# define SZ(x) ((int)(x).size())\n# define pb push_back\n# define mod 1000000007\n# define PI 3.141592653589793\n# define vec vector\n#define dump(x) cerr<<#x<<\"=\"<<x<<endl\nusing namespace std;\n\n\n\n#define INF 2000000000\n#define MAX_V 10\n\n\n\nbool compare_by_b(pair<string,ll> a,pair<string,ll> b){\n if(a.second != b.second) return a.second<b.second;\n else return a.first<b.first;\n}\n\nbool my_compare(pair<string,ll> a,pair<string,ll> b){\n if(a.first != b.first) return a.first<b.first;\n if(a.second != b.second) return a.second>b.second;\n else return true;\n}\n\nll modpow(ll a,ll n,ll mod1) {\n ll res=1;\n while(n>0){\n if(n&1) res=res*a%mod1;\n a = a*a%mod1;\n n >>= 1;\n }\n return res;\n}\n\nll factorial(ll n){\n ll x=1;\n rrep(i,n) (x*=i)%=mod;\n return x;\n}\n\nll gcd(ll a,ll b){\n if (a%b == 0) return(b);\n else return(gcd(b,a%b));\n}\n\nll lcm(ll a,ll b){\n return a/gcd(a,b)*b;\n}\nconst ll MAX = 510000;\nconst ll MOD = 1000000007;\n \nll fac[MAX], finv[MAX], inv[MAX];\n \n// テーブルを作る前処理\nvoid COMinit() {\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[1] = 1;\n for (ll i = 2; i < MAX; i++){\n fac[i] = fac[i - 1] * i % MOD;\n inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;\n finv[i] = finv[i - 1] * inv[i] % MOD;\n }\n}\n \n// 二項係数計算\nll COM(ll n, ll k){\n if (n < k) return 0;\n if (n < 0 || k < 0) return 0;\n return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;\n}\n\n\nusing graph = vector<vector<ll>>;\n\nint main(){\n cin.tie(0);\n ios::sync_with_stdio(false);\n \n ll n,k;\n cin>>n>>k;\n COMinit();\n if(n>k){\n cout<<0<<endl;\n return 0;\n }else{\n cout<<factorial(n)*COM(k,n)%mod<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 15176, "score_of_the_acc": -0.0452, "final_rank": 10 }, { "submission_id": "aoj_DPL_5_B_4448153", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing P = pair<ll, ll>;\nusing Graph = vector<vector<ll>>;\n#define rep(i, n) for(ll i=0;i<(ll)(n);i++)\n#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)\n#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};\nconst int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst ll MOD = 1000000007;\nconst ll INF = 1000000000000000000L;\n#ifdef __DEBUG\n\n/**\n * For DEBUG\n * https://github.com/ta7uw/cpp-pyprint\n */\n#include \"cpp-pyprint/pyprint.h\"\n\n#endif\n\nclass mint {\npublic:\n long long x;\n\n mint(long long x = 0) : x((x % MOD + MOD) % MOD) {}\n\n mint operator-() const {\n return mint(-x);\n }\n\n mint &operator+=(const mint &rhs) {\n if ((x += rhs.x) >= MOD) x -= MOD;\n return *this;\n }\n\n mint &operator-=(const mint &rhs) {\n if ((x += MOD - rhs.x) >= MOD) x -= MOD;\n return *this;\n }\n\n mint &operator*=(const mint &rhs) {\n (x *= rhs.x) %= MOD;\n return *this;\n }\n\n mint operator+(const mint &rhs) const {\n mint res(*this);\n return res += rhs;\n }\n\n mint operator-(const mint &rhs) const {\n mint res(*this);\n return res -= rhs;\n }\n\n mint operator*(const mint &rhs) const {\n mint res(*this);\n return res *= rhs;\n }\n\n mint pow(long long t) const {\n if (!t) return 1;\n mint a = pow(t >> 1);\n a *= a;\n if (t & 1) a *= *this;\n return a;\n }\n\n mint inv() const {\n return pow(MOD - 2);\n }\n\n mint &operator/=(mint rhs) {\n return *this *= rhs.inv();\n }\n\n mint operator/(const mint rhs) const {\n return mint(*this) /= rhs;\n }\n\n bool operator==(const mint &rhs) const noexcept {\n return this->x == rhs.x;\n }\n\n bool operator!=(const mint &rhs) const noexcept {\n return this->x != rhs.x;\n }\n\n bool operator<(const mint &rhs) const noexcept {\n return this->x < rhs.x;\n }\n\n bool operator>(const mint &rhs) const noexcept {\n return this->x > rhs.x;\n }\n\n bool operator<=(const mint &rhs) const noexcept {\n return this->x <= rhs.x;\n }\n\n bool operator>=(const mint &rhs) const noexcept {\n return this->x >= rhs.x;\n }\n\n friend istream &operator>>(istream &is, mint &a) {\n long long t;\n is >> t;\n a = mint(t);\n return is;\n }\n\n friend ostream &operator<<(ostream &os, const mint &a) {\n return os << a.x;\n }\n};\n\nconst int MAX = 510000;\nlong long fac[MAX], finv[MAX], inv[MAX];\nbool initialized = false;\n\n/**\n * @fn\n * This function must be called at first.\n */\nvoid combination_init() {\n initialized = true;\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[1] = 1;\n for (int i = 2; i < MAX; i++) {\n fac[i] = fac[i - 1] * i % MOD;\n inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;\n finv[i] = finv[i - 1] * inv[i] % MOD;\n }\n}\n\n/**\n * @fn\n * Calculates the combination ( nCK % p: N choose K mod p).\n *\n * @brief constraint: 1 ≤ k ≤ n ≤ 10^7\n * @return nCK % MOD\n */\nlong long combination(int n, int k) {\n assert(initialized);\n if (n < k) return 0;\n if (n < 0 || k < 0) return 0;\n return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;\n}\n\n/**\n * @fn\n * Calculates the factorial of the number.\n *\n * @return N! % MOD\n */\nlong long factorial(int n) {\n assert(initialized);\n if (n < 0) return 0;\n return fac[n] % MOD;\n}\n\n/**\n * @fn\n * Calculates the combination ( nCK % p: N choose K mod p).\n *\n * @brief constraint: 1 ≤ k ≤ 10^7 and 1 ≤ n ≤ 10^9\n * @return nCK % MOD\n */\nlong long combination2(int n, int k) {\n assert(initialized);\n if (n < k) return 0;\n if (n < 0 || k < 0) return 0;\n ll res = 1;\n k = min(k, n - k);\n for (long long x = 1; x <= k; x++) {\n res *= (n - x + 1);\n res %= MOD;\n res *= inv[x];\n res %= MOD;\n }\n return res;\n}\n\n\nvoid solve() {\n ll N, K;\n cin >> N >> K;\n combination_init();\n mint ans = 0;\n if (K >= N) {\n ans = combination(K, N) * factorial(N);\n }\n cout << ans << '\\n';\n}\n\nint main() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 15164, "score_of_the_acc": -0.0451, "final_rank": 9 }, { "submission_id": "aoj_DPL_5_B_4448134", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing P = pair<ll, ll>;\nusing Graph = vector<vector<ll>>;\n#define rep(i, n) for(ll i=0;i<(ll)(n);i++)\n#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)\n#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};\nconst int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};\nconst ll MOD = 1000000007;\nconst ll INF = 1000000000000000000L;\n#ifdef __DEBUG\n\n/**\n * For DEBUG\n * https://github.com/ta7uw/cpp-pyprint\n */\n#include \"cpp-pyprint/pyprint.h\"\n\n#endif\n\nclass mint {\npublic:\n long long x;\n\n mint(long long x = 0) : x((x % MOD + MOD) % MOD) {}\n\n mint operator-() const {\n return mint(-x);\n }\n\n mint &operator+=(const mint &rhs) {\n if ((x += rhs.x) >= MOD) x -= MOD;\n return *this;\n }\n\n mint &operator-=(const mint &rhs) {\n if ((x += MOD - rhs.x) >= MOD) x -= MOD;\n return *this;\n }\n\n mint &operator*=(const mint &rhs) {\n (x *= rhs.x) %= MOD;\n return *this;\n }\n\n mint operator+(const mint &rhs) const {\n mint res(*this);\n return res += rhs;\n }\n\n mint operator-(const mint &rhs) const {\n mint res(*this);\n return res -= rhs;\n }\n\n mint operator*(const mint &rhs) const {\n mint res(*this);\n return res *= rhs;\n }\n\n mint pow(long long t) const {\n if (!t) return 1;\n mint a = pow(t >> 1);\n a *= a;\n if (t & 1) a *= *this;\n return a;\n }\n\n mint inv() const {\n return pow(MOD - 2);\n }\n\n mint &operator/=(mint rhs) {\n return *this *= rhs.inv();\n }\n\n mint operator/(const mint rhs) const {\n return mint(*this) /= rhs;\n }\n\n bool operator==(const mint &rhs) const noexcept {\n return this->x == rhs.x;\n }\n\n bool operator!=(const mint &rhs) const noexcept {\n return this->x != rhs.x;\n }\n\n bool operator<(const mint &rhs) const noexcept {\n return this->x < rhs.x;\n }\n\n bool operator>(const mint &rhs) const noexcept {\n return this->x > rhs.x;\n }\n\n bool operator<=(const mint &rhs) const noexcept {\n return this->x <= rhs.x;\n }\n\n bool operator>=(const mint &rhs) const noexcept {\n return this->x >= rhs.x;\n }\n\n friend istream &operator>>(istream &is, mint &a) {\n long long t;\n is >> t;\n a = mint(t);\n return is;\n }\n\n friend ostream &operator<<(ostream &os, const mint &a) {\n return os << a.x;\n }\n};\n\nconst int MAX = 510000;\nlong long fac[MAX], finv[MAX], inv[MAX];\nbool initialized = false;\n\n/**\n * @fn\n * This function must be called at first.\n */\nvoid combination_init() {\n initialized = true;\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[1] = 1;\n for (int i = 2; i < MAX; i++) {\n fac[i] = fac[i - 1] * i % MOD;\n inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;\n finv[i] = finv[i - 1] * inv[i] % MOD;\n }\n}\n\n/**\n * @fn\n * Calculates the combination ( nCK % p: N choose K mod p).\n *\n * @brief constraint: 1 ≤ k ≤ n ≤ 10^7\n * @return nCK % MOD\n */\nlong long combination(int n, int k) {\n assert(initialized);\n if (n < k) return 0;\n if (n < 0 || k < 0) return 0;\n return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;\n}\n\n/**\n * @fn\n * Calculates the factorial of the number.\n *\n * @return N! % MOD\n */\nlong long factorial(int n) {\n assert(initialized);\n if (n < 0) return 0;\n return fac[n] % MOD;\n}\n\n/**\n * @fn\n * Calculates the combination ( nCK % p: N choose K mod p).\n *\n * @brief constraint: 1 ≤ k ≤ 10^7 and 1 ≤ n ≤ 10^9\n * @return nCK % MOD\n */\nlong long combination2(int n, int k) {\n assert(initialized);\n if (n < k) return 0;\n if (n < 0 || k < 0) return 0;\n ll res = 1;\n k = min(k, n - k);\n for (long long x = 1; x <= k; x++) {\n res *= (n - x + 1);\n res %= MOD;\n res *= inv[x];\n res %= MOD;\n }\n return res;\n}\n\n\nvoid solve() {\n ll N, K;\n cin >> N >> K;\n combination_init();\n mint ans = 0;\n if (K >= N) {\n ans = factorial(K);\n }\n cout << ans << '\\n';\n}\n\nint main() {\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(15);\n solve();\n return 0;\n}", "accuracy": 0.13333333333333333, "time_ms": 10, "memory_kb": 15116, "score_of_the_acc": -0.0449, "final_rank": 20 }, { "submission_id": "aoj_DPL_5_B_4347657", "code_snippet": "#line 1 \"DPL_5_B.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/7/DPL/5/DPL_5_B\"\n\n#include <bits/stdc++.h> // clang-format off\nusing Int = long long;\n#define REP_(i, a_, b_, a, b, ...) for (Int i = (a), lim##i = (b); i < lim##i; i++)\n#define REP(i, ...) REP_(i, __VA_ARGS__, __VA_ARGS__, 0, __VA_ARGS__)\nstruct SetupIO { SetupIO() { std::cin.tie(nullptr), std::ios::sync_with_stdio(false), std::cout << std::fixed << std::setprecision(13); } } setup_io;\n#ifndef _MY_DEBUG\n#define dump(...)\n#endif // clang-format on\n\n/**\n * author: knshnb\n * created: Sun Apr 12 16:50:17 JST 2020\n **/\n\n#define CALL_FROM_TEST\n#line 1 \"/Users/knshnb/competitive_programming/competitive_library/src/Math/ModInt.hpp\"\ntemplate <class T> T pow(T x, int n, const T UNION = 1) {\n T ret = UNION;\n while (n) {\n if (n & 1) ret *= x;\n x *= x;\n n >>= 1;\n }\n return ret;\n}\n\n/// @docs src/Math/ModInt.md\ntemplate <int Mod> struct ModInt {\n int x;\n static int runtime_mod;\n static std::unordered_map<int, int> to_inv;\n // テンプレート引数が負のときは実行時ModInt\n static int mod() { return Mod < 0 ? runtime_mod : Mod; }\n static void set_runtime_mod(int mod) {\n static_assert(Mod < 0, \"template parameter Mod must be negative for runtime ModInt\");\n runtime_mod = mod;\n to_inv.clear();\n }\n ModInt() : x(0) {}\n ModInt(long long x_) {\n if ((x = x_ % mod() + mod()) >= mod()) x -= mod();\n }\n\n ModInt& operator+=(ModInt rhs) {\n if ((x += rhs.x) >= mod()) x -= mod();\n return *this;\n }\n ModInt& operator*=(ModInt rhs) {\n x = (unsigned long long)x * rhs.x % mod();\n return *this;\n }\n ModInt& operator-=(ModInt rhs) {\n if ((x -= rhs.x) < 0) x += mod();\n return *this;\n }\n ModInt& operator/=(ModInt rhs) {\n x = (unsigned long long)x * rhs.inv().x % mod();\n return *this;\n }\n ModInt operator-() const { return -x < 0 ? mod() - x : -x; }\n ModInt operator+(ModInt rhs) const { return ModInt(*this) += rhs; }\n ModInt operator*(ModInt rhs) const { return ModInt(*this) *= rhs; }\n ModInt operator-(ModInt rhs) const { return ModInt(*this) -= rhs; }\n ModInt operator/(ModInt rhs) const { return ModInt(*this) /= rhs; }\n bool operator==(ModInt rhs) const { return x == rhs.x; }\n bool operator!=(ModInt rhs) const { return x != rhs.x; }\n ModInt inv() const { return to_inv.count(this->x) ? to_inv[this->x] : (to_inv[this->x] = pow(*this, mod() - 2).x); }\n\n friend std::ostream& operator<<(std::ostream& s, ModInt<Mod> a) {\n s << a.x;\n return s;\n }\n friend std::istream& operator>>(std::istream& s, ModInt<Mod>& a) {\n long long tmp;\n s >> tmp;\n a = ModInt<Mod>(tmp);\n return s;\n }\n friend std::string to_string(ModInt<Mod> a) { return std::to_string(a.x); }\n};\ntemplate <int Mod> std::unordered_map<int, int> ModInt<Mod>::to_inv;\ntemplate <int Mod> int ModInt<Mod>::runtime_mod;\n\n#ifndef CALL_FROM_TEST\nusing mint = ModInt<1000000007>;\n#endif\n#line 1 \"/Users/knshnb/competitive_programming/competitive_library/src/Math/Combination.hpp\"\ntemplate <class T> struct Combination {\n std::vector<T> fact, fact_inv;\n Combination(int n = 1000003) : fact(n + 1, 1), fact_inv(n + 1) {\n for (int i = 0; i < n; i++) fact[i + 1] = fact[i] * (i + 1);\n fact_inv[n] = (T)1 / fact[n];\n for (int i = n - 1; i >= 0; i--) fact_inv[i] = fact_inv[i + 1] * (i + 1);\n // for (int i = 0; i < n + 1; i++) assert(fact[i] * fact_inv[i] == 1);\n }\n T operator()(int n, int r) { return fact[n] * fact_inv[r] * fact_inv[n - r]; }\n};\n#line 20 \"DPL_5_B.test.cpp\"\n#undef CALL_FROM_TEST\n\nusing mint = ModInt<1000000007>;\nsigned main() {\n Combination<mint> comb;\n Int n, k;\n std::cin >> n >> k;\n std::cout << (n > k ? 0 : comb.fact[k] / comb.fact[k - n]) << std::endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10644, "score_of_the_acc": -0.0257, "final_rank": 3 }, { "submission_id": "aoj_DPL_5_B_4143948", "code_snippet": "#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <vector>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <queue>\n#include <stack>\n#include <functional>\n#include <bitset>\nusing namespace std;\ntypedef long long ll;\ntypedef vector<ll> vl;\ntypedef vector<vl> vvl;\ntypedef vector<char> vc;\ntypedef vector<string> vs;\ntypedef vector<bool> vb;\ntypedef pair<ll,ll> P;\ntypedef vector<P> vpl;\n#define rep(i,n) for(ll i=0; i<(n); i++)\n#define REP(i,a,b) for(ll i=(a); i<(b); i++)\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\nconst int inf = 1<<30;\nconst ll linf = 1LL<<62;\nconst int MAX = 510000;\nll dy[8] = {0,1,0,-1,1,-1,1,-1};\nll dx[8] = {1,0,-1,0,1,-1,-1,1};\nconst double pi = acos(-1);\nconst double eps = 1e-7;\ntemplate<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){\n\tif(a>b){\n\t\ta = b; return true;\n\t}\n\telse return false;\n}\ntemplate<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){\n\tif(a<b){\n\t\ta = b; return true;\n\t}\n\telse return false;\n}\ntemplate<typename T1,typename T2> inline void print2(T1 a, T2 b){cout << a << \" \" << b << endl;}\ntemplate<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){\n\tcout << a << \" \" << b << \" \" << c << endl;\n}\nconst int mod = 1e9 + 7;\n\nvector<ll> fac(MAX), finv(MAX), inv(MAX);\n\nvoid comInit(){\n\tfac[0] = fac[1] = 1;\n\tfinv[0] = finv[1] = 1;\n\tinv[1] = 1;\n\tfor(ll i=2; i<MAX; i++){\n\t\tfac[i] = fac[i-1]*i % mod;\n\t\tinv[i] = mod - inv[mod%i] * (mod/i) % mod;\n\t\tfinv[i] = finv[i-1] * inv[i] % mod;\n\t}\n}\n\n\nll com(ll n, ll k){\n\tif(n < k) return 0;\n\tif(n < 0 || k < 0) return 0;\n\treturn fac[n] * (finv[k] * finv[n-k] % mod) % mod;\n}\n\nint main(){\n\tll n,k; cin >> n >> k;\n\tif(n>k) puts(\"0\");\n\telse{\n\t\tcomInit();\n\t\tcout << com(k,n)*fac[n]%mod << endl;\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 14552, "score_of_the_acc": -0.0425, "final_rank": 5 } ]
aoj_DPL_5_C_cpp
Balls and Boxes 3 Balls Boxes Any way At most one ball At least one ball Distinguishable Distinguishable 1 2 3 Indistinguishable Distinguishable 4 5 6 Distinguishable Indistinguishable 7 8 9 Indistinguishable Indistinguishable 10 11 12 Problem You have $n$ balls and $k$ boxes. You want to put these balls into the boxes. Find the number of ways to put the balls under the following conditions: Each ball is distinguished from the other. Each box is distinguished from the other. Each ball can go into only one box and no one remains outside of the boxes. Each box must contain at least one ball. Note that you must print this count modulo $10^9+7$. Input $n$ $k$ The first line will contain two integers $n$ and $k$. Output Print the number of ways modulo $10^9+7$ in a line. Constraints $1 \le n \le 1000$ $1 \le k \le 1000$ Sample Input 1 4 3 Sample Output 1 36 Sample Input 2 10 3 Sample Output 2 55980 Sample Input 3 100 100 Sample Output 3 437918130
[ { "submission_id": "aoj_DPL_5_C_10681358", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#line 2 \"modint/montgomery-modint.hpp\"\n\ntemplate <uint32_t mod>\nstruct LazyMontgomeryModInt {\n using mint = LazyMontgomeryModInt;\n using i32 = int32_t;\n using u32 = uint32_t;\n using u64 = uint64_t;\n\n static constexpr u32 get_r() {\n u32 ret = mod;\n for (i32 i = 0; i < 4; ++i) ret *= 2 - mod * ret;\n return ret;\n }\n\n static constexpr u32 r = get_r();\n static constexpr u32 n2 = -u64(mod) % mod;\n static_assert(mod < (1 << 30), \"invalid, mod >= 2 ^ 30\");\n static_assert((mod & 1) == 1, \"invalid, mod % 2 == 0\");\n static_assert(r * mod == 1, \"this code has bugs.\");\n\n u32 a;\n\n constexpr LazyMontgomeryModInt() : a(0) {}\n constexpr LazyMontgomeryModInt(const int64_t &b)\n : a(reduce(u64(b % mod + mod) * n2)){};\n\n static constexpr u32 reduce(const u64 &b) {\n return (b + u64(u32(b) * u32(-r)) * mod) >> 32;\n }\n\n constexpr mint &operator+=(const mint &b) {\n if (i32(a += b.a - 2 * mod) < 0) a += 2 * mod;\n return *this;\n }\n\n constexpr mint &operator-=(const mint &b) {\n if (i32(a -= b.a) < 0) a += 2 * mod;\n return *this;\n }\n\n constexpr mint &operator*=(const mint &b) {\n a = reduce(u64(a) * b.a);\n return *this;\n }\n\n constexpr mint &operator/=(const mint &b) {\n *this *= b.inverse();\n return *this;\n }\n\n constexpr mint operator+(const mint &b) const { return mint(*this) += b; }\n constexpr mint operator-(const mint &b) const { return mint(*this) -= b; }\n constexpr mint operator*(const mint &b) const { return mint(*this) *= b; }\n constexpr mint operator/(const mint &b) const { return mint(*this) /= b; }\n constexpr bool operator==(const mint &b) const {\n return (a >= mod ? a - mod : a) == (b.a >= mod ? b.a - mod : b.a);\n }\n constexpr bool operator!=(const mint &b) const {\n return (a >= mod ? a - mod : a) != (b.a >= mod ? b.a - mod : b.a);\n }\n constexpr mint operator-() const { return mint() - mint(*this); }\n constexpr mint operator+() const { return mint(*this); }\n\n constexpr mint pow(u64 n) const {\n mint ret(1), mul(*this);\n while (n > 0) {\n if (n & 1) ret *= mul;\n mul *= mul;\n n >>= 1;\n }\n return ret;\n }\n\n constexpr mint inverse() const {\n int x = get(), y = mod, u = 1, v = 0, t = 0, tmp = 0;\n while (y > 0) {\n t = x / y;\n x -= t * y, u -= t * v;\n tmp = x, x = y, y = tmp;\n tmp = u, u = v, v = tmp;\n }\n return mint{u};\n }\n\n friend ostream &operator<<(ostream &os, const mint &b) {\n return os << b.get();\n }\n\n friend istream &operator>>(istream &is, mint &b) {\n int64_t t;\n is >> t;\n b = LazyMontgomeryModInt<mod>(t);\n return (is);\n }\n\n constexpr u32 get() const {\n u32 ret = reduce(a);\n return ret >= mod ? ret - mod : ret;\n }\n\n static constexpr u32 get_mod() { return mod; }\n};\nusing ll=long long;\nusing ull=unsigned long long;\nconstexpr int MOD=1'000'000'007;\nusing mint=LazyMontgomeryModInt<MOD>;\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n#define loop(n) for (int tjh = 0; tjh < (int)(n); ++tjh)\nconstexpr int maxn=1000;\nconstexpr array<mint,maxn+1>mkfac() {\n array<mint,maxn+1>res;\n res[0]=1;\n rep(i,maxn)res[i+1]=res[i]*(i+1);\n return res;\n}\nconstexpr auto fac=mkfac();\nconstexpr array<mint,maxn+1>mkinv() {\n array<mint,maxn+1>res;\n res[maxn]=mint(1)/fac[maxn];\n for (int i=maxn;i--;) {\n res[i]=res[i+1]*(i+1);\n }\n return res;\n}\nconstexpr auto invfac=mkinv();\narray<array<mint,maxn+1>,maxn+1>dp;\nsigned main() {\n cin.tie(0)->sync_with_stdio(0);\n cout<<fixed<<setprecision(16);\n int n,k;cin>>n>>k;\n if (n<k){cout<<0<<'\\n';return 0;}\n dp[0][0]=mint(1);\n for (int i=1;i<=n;++i)dp[i][1]=mint(1);\n for (int i=2;i<=n;++i)for (int j=2;j<=min(i,k);++j) {\n for (int l=1;l<=i-(j-1);++l) {\n dp[i][j]+=dp[i-l][j-1]*fac[i]*invfac[i-l]*invfac[l];\n }\n }\n cout<<dp[n][k]<<'\\n';\n}", "accuracy": 1, "time_ms": 360, "memory_kb": 7552, "score_of_the_acc": -0.6489, "final_rank": 15 }, { "submission_id": "aoj_DPL_5_C_10632078", "code_snippet": "#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long;\nll MOD = 1000000007;\n\nll binexp(ll a, ll b, ll m) {\n if (b == 0) return 1;\n if (b == 1) return a;\n ll r = binexp(a, b / 2, m);\n r = (r * r) % m;\n if (b % 2) r = (r * a) % m;\n return r;\n}\n\nll inv(ll x, ll m) {\n return binexp(x, m - 2, m);\n}\n\nll C(ll n, ll r, ll m) {\n if (r == 0) return 1;\n return (((n * C(n - 1, r - 1, m)) % m) * inv(r, m)) % m;\n}\n\nint main() {\n ll n, k;\n cin >> n >> k;\n ll ans = 0;\n for (ll i = 0; i <= k; i++) {\n ll x = (C(k, i, MOD) * binexp(k - i, n, MOD)) % MOD;\n if (i % 2 == 0) ans = (ans + x) % MOD;\n else ans = (ans - x + MOD) % MOD;\n }\n cout << ans << '\\n';\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 3468, "score_of_the_acc": -0.3394, "final_rank": 12 }, { "submission_id": "aoj_DPL_5_C_9527782", "code_snippet": "/*\n Created by Pujx on 2024/8/4.\n*/\n#pragma GCC optimize(2, 3, \"Ofast\", \"inline\")\n#include <bits/stdc++.h>\nusing namespace std;\n#define endl '\\n'\n//#define int long long\n//#define double long double\nusing i64 = long long;\nusing ui64 = unsigned long long;\n//using i128 = __int128;\n#define inf (int)0x3f3f3f3f3f3f3f3f\n#define INF 0x3f3f3f3f3f3f3f3f\n#define yn(x) cout << (x ? \"yes\" : \"no\") << endl\n#define Yn(x) cout << (x ? \"Yes\" : \"No\") << endl\n#define YN(x) cout << (x ? \"YES\" : \"NO\") << endl\n#define mem(x, i) memset(x, i, sizeof(x))\n#define cinarr(a, n) for (int _ = 1; _ <= n; _++) cin >> a[_]\n#define cinstl(a) for (auto& _ : a) cin >> _\n#define coutarr(a, n) for (int _ = 1; _ <= n; _++) cout << a[_] << \" \\n\"[_ == n]\n#define coutstl(a) for (const auto& _ : a) cout << _ << ' '; cout << endl\n#define all(x) (x).begin(), (x).end()\n#define ls (s << 1)\n#define rs (s << 1 | 1)\n#define ft first\n#define se second\n#define pii pair<int, int>\n#ifdef DEBUG\n #include \"debug.h\"\n#else\n #define dbg(...) void(0)\n#endif\n\nconst int N = 2000 + 5;\n//const int M = 1e5 + 5;\n//const int mod = 998244353;\nconst int mod = 1e9 + 7;\n//template <typename T> T ksm(T a, i64 b) { T ans = 1; for (; b; a = 1ll * a * a, b >>= 1) if (b & 1) ans = 1ll * ans * a; return ans; }\n//template <typename T> T ksm(T a, i64 b, T m = mod) { T ans = 1; for (; b; a = 1ll * a * a % m, b >>= 1) if (b & 1) ans = 1ll * ans * a % m; return ans; }\n\nint a[N];\nint n, m, t, k, q;\n\ntemplate <int P> struct MInt {\n int x;\n MInt() : x(0) {}\n MInt(const signed& x) : x(norm(x % getMod())) {}\n MInt(const long long& x) : x(norm(x % getMod())) {}\n\n static int Mod;\n static int getMod() { return P > 0 ? P : Mod; }\n static void setMod(int _Mod) { Mod = _Mod; }\n int norm(const int& x) const { return x < 0 ? x + getMod() : (x >= getMod() ? x - getMod() : x); }\n int val() const { return x; }\n explicit operator int() const { return x; }\n MInt operator - () const { MInt res; res.x = norm(getMod() - x); return res; }\n MInt ksm(const long long& x) const {\n MInt a = *this, ans = 1;\n for (long long pw = x; pw; a *= a, pw >>= 1) if (pw & 1) ans *= a;\n return ans;\n }\n MInt inv() const { assert(x != 0); return ksm(getMod() - 2); }\n MInt& operator += (const MInt& b) & { x = norm(x + b.x); return *this; }\n MInt& operator -= (const MInt& b) & { x = norm(x - b.x); return *this; }\n MInt& operator *= (const MInt& b) & { x = norm(1ll * x * b.x % getMod()); return *this; }\n MInt& operator /= (const MInt& b) & { return *this *= b.inv(); }\n MInt& operator ++ () & { return *this += 1; }\n MInt& operator -- () & { return *this -= 1; }\n const MInt operator ++ (signed) { MInt old = *this; ++(*this); return old; }\n const MInt operator -- (signed) { MInt old = *this; --(*this); return old; }\n friend MInt operator + (const MInt& a, const MInt& b) { MInt res = a; res += b; return res; }\n friend MInt operator - (const MInt& a, const MInt& b) { MInt res = a; res -= b; return res; }\n friend MInt operator * (const MInt& a, const MInt& b) { MInt res = a; res *= b; return res; }\n friend MInt operator / (const MInt& a, const MInt& b) { MInt res = a; res /= b; return res; }\n friend istream& operator >> (istream& in, MInt& a) { long long v; in >> v; a = MInt(v); return in; }\n friend ostream& operator << (ostream& out, const MInt& a) { return out << a.val(); }\n friend bool operator == (const MInt& a, const MInt& b) { return a.val() == b.val(); }\n friend bool operator != (const MInt& a, const MInt& b) { return a.val() != b.val(); }\n friend bool operator < (const MInt& a, const MInt& b) { return a.val() < b.val(); }\n friend bool operator > (const MInt& a, const MInt& b) { return a.val() > b.val(); }\n friend bool operator <= (const MInt& a, const MInt& b) { return a.val() <= b.val(); }\n friend bool operator >= (const MInt& a, const MInt& b) { return a.val() >= b.val(); }\n};\nusing Mint = MInt<mod>;\ntemplate<> int MInt<0>::Mod = 1;\n\nMint fac[N], c[N][N], s[N][N], p[N][N];\n\nvoid init() {\n fac[0] = 1, c[0][0] = s[0][0] = p[0][0] = 1;\n for (int i = 1; i <= 2000; i++) {\n fac[i] = fac[i - 1] * i;\n c[i][0] = 1, s[i][0] = p[i][0] = 0;\n for (int j = 1; j <= i; j++) {\n c[i][j] = c[i - 1][j - 1] + c[i - 1][j];\n s[i][j] = s[i - 1][j - 1] + j * s[i - 1][j];\n p[i][j] = p[i - 1][j - 1] + p[i - j][j];\n }\n }\n}\n\nvoid work() {\n cin >> n >> k;\n t = 3;\n if (t == 1) {\n cout << Mint(k).ksm(n) << endl;\n }\n else if (t == 2) {\n cout << fac[n] * c[k][n] << endl;\n }\n else if (t == 3) {\n cout << fac[k] * s[n][k] << endl;\n }\n else if (t == 4) {\n cout << c[n + k - 1][k - 1] << endl;\n }\n else if (t == 5) {\n cout << c[k][n] << endl;\n }\n else if (t == 6) {\n cout << c[n - 1][k - 1] << endl;\n }\n else if (t == 7) {\n Mint ans = 0;\n for (int i = 1; i <= k; i++)\n ans += s[n][i];\n cout << ans << endl;\n }\n else if (t == 8) {\n cout << (k >= n) << endl;\n }\n else if (t == 9) {\n cout << s[n][k] << endl;\n }\n else if (t == 10) {\n cout << p[n + k][k] << endl;\n }\n else if (t == 11) {\n cout << (k >= n) << endl;\n }\n else {\n cout << p[n][k] << endl;\n }\n}\n\nsigned main() {\n#ifdef LOCAL\n freopen(\"C:\\\\Users\\\\admin\\\\CLionProjects\\\\Practice\\\\data.in\", \"r\", stdin);\n freopen(\"C:\\\\Users\\\\admin\\\\CLionProjects\\\\Practice\\\\data.out\", \"w\", stdout);\n#endif\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n init();\n int Case = 1;\n //cin >> Case;\n while (Case--) work();\n return 0;\n}\n/*\n _____ _ _ _ __ __\n | _ \\ | | | | | | \\ \\ / /\n | |_| | | | | | | | \\ \\/ /\n | ___/ | | | | _ | | } {\n | | | |_| | | |_| | / /\\ \\\n |_| \\_____/ \\_____/ /_/ \\_\\\n*/", "accuracy": 1, "time_ms": 20, "memory_kb": 50612, "score_of_the_acc": -0.9824, "final_rank": 17 }, { "submission_id": "aoj_DPL_5_C_9451792", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef vector<ll> vi;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\ntypedef vector<bool> vb;\ntypedef vector<vb> vvb;\ntypedef vector<vvb> vvvb;\ntypedef vector<vvvb> vvvvb;\ntypedef pair<ll,ll> pi;\ntypedef pair<ll,pi> ppi;\n#define FOR(i,l,r) for(ll i=l;i<r;i++)\n#define REP(i,n) FOR(i,0,n)\n#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)\n#define RREP(i,n) RFOR(i,0,n)\n#define sz(A) (ll)(A.size())\n#define ALL(A) A.begin(),A.end()\n#define LB(A,x) (ll)(lower_bound(ALL(A),x)-A.begin())\n#define UB(A,x) (ll)(upper_bound(ALL(A),x)-A.begin())\n#define COU(A,x) (UB(A,x)-LB(A,x))\n#define F first\n#define S second\ntemplate<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;\ntemplate<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.F<<\" \"<<p.S;return os;}\ntemplate<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.F>>p.S;return is;}\ntemplate<typename T>ostream&operator<<(ostream&os,vector<T>&v){REP(i,sz(v))os<<v[i]<<(i+1!=sz(v)?\" \":\"\");return os;}\ntemplate<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}\ntemplate<class T>bool chmax(T&a,T b){if(a<b){a=b;return 1;}return 0;}\ntemplate<class T>bool chmin(T&a,T b){if(b<a){a=b;return 1;}return 0;}\nconst ll mod=998244353;\ntemplate<const long long int mod=998244353>\nstruct modint{\n using mint=modint<mod>;\n long long int x;\n modint(long long int _x=0):x(_x%mod){if(x<0)x+=mod;}\n long long int val(){return x;}\n mint&operator=(const mint&a){x=a.x;return *this;}\n mint&operator+=(const mint&a){x+=a.x;if(x>=mod)x-=mod;return *this;}\n mint&operator-=(const mint&a){x-=a.x;if(x<0)x+=mod;return *this;}\n mint&operator*=(const mint&a){x*=a.x;x%=mod;return *this;}\n friend mint operator+(const mint&a,const mint&b){return mint(a)+=b;}\n friend mint operator-(const mint&a,const mint&b){return mint(a)-=b;}\n friend mint operator*(const mint&a,const mint&b){return mint(a)*=b;}\n mint operator-()const{return mint(0)-*this;}\n mint pow(long long int n){\n if(!n)return 1;\n mint a=1;\n mint _x=x;\n while(n){\n if(n&1)a*=_x;\n _x=_x*_x;n>>=1;\n }\n return a;\n }\n mint inv(){return pow(mod-2);}\n mint&operator/=(mint&a){return *this*=a.inv();}\n friend mint operator/(const mint&a,mint b){return mint(a)/=b;}\n};\nll pow_mod(ll a,ll n,ll m){\n ll res=1%m;\n a%=m;\n while(n){\n if(n%2)res=res*a%m;\n a=a*a%m;n/=2;\n }\n if(res<0)res+=m;\n return res;\n}\ntemplate<typename T>\nstruct fenwick_tree{\n private:\n vector<T>tree;\n T sum_from_zero(int i){\n i++;\n T s=0;\n while(i){\n s+=tree[i];\n i-=i&-i;\n }\n return s;\n }\n public:\n fenwick_tree(size_t N):tree(vector<T>(N+1)){}\n T sum(int l,int r){\n assert(0<=l&&l<=r&&r<=tree.size());\n return sum_from_zero(r-1)-sum_from_zero(l-1);\n }\n T get(int i){\n assert(0<=i&&i<tree.size());\n return sum(i,i+1);\n }\n void add(int i,T x){\n assert(0<=i&&i<tree.size());\n i++;\n while(i<tree.size()){\n tree[i]+=x;\n i+=i&-i;\n }\n }\n void print(){\n for(auto i:tree)cout<<i<<\" \";cout<<endl;\n }\n};\n//using mint=modint<998244353>;\nusing mint=modint<1000000007>;\nint main(){\n ll N,K;cin>>N>>K;\n mint ans=0;\n vector<mint>ex(2e6,1),r(2e6);\n FOR(i,1,2e6)ex[i]=i*ex[i-1];\n REP(i,2e6)r[i]=1/ex[i];\n FOR(i,1,K+1)ans+=((K-i)%2?-1:1)*pow_mod(i,N,1000000007)*ex[K]*r[i]*r[K-i];\n cout<<ans.val()<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 160, "memory_kb": 34436, "score_of_the_acc": -0.8769, "final_rank": 16 }, { "submission_id": "aoj_DPL_5_C_9331795", "code_snippet": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/detail/standard_policies.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\n#define int long long\n#define all(x) x.begin(), x.end()\n\nusing namespace __gnu_pbds; using namespace std;\n\ntemplate<class T> using ordered_set = tree<T, null_type , less<T> , rb_tree_tag , tree_order_statistics_node_update>; template<class T> using ordered_multiset = tree<T, null_type , less_equal<T> , rb_tree_tag , tree_order_statistics_node_update>; typedef long long ll; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; typedef tuple<int, int, int, int> iiii; typedef vector<int> vi; \nconst ll oo = 1987654321987654321;\n\ntemplate<class It> void db(It b, It e) { for (auto it = b; it != e; it++) cout << *it << ' '; cout<< endl; } template<typename A> istream& operator>>(istream& fin, vector<A>& v) { for (auto it = v.begin(); it != v.end(); ++it) fin >> *it; return fin; } template<typename A, typename B> istream& operator>>(istream& fin, pair<A, B>& p){ fin >> p.first >> p.second; return fin; } template<typename T> void chmin(T &a, T b){ a = min(a, b); } template<typename T> void chmax(T &a, T b){ a = max(a, b); }\n\n\nint n, k;\nconst int P = 1e9 + 7;\nconst int MAX = 1002;\nint memo[MAX][MAX];\nint fat[MAX];\nint invfat[MAX];\n\nint expbin(ll a, ll b) {\n if (b == 0) return 1;\n if (b & 1) return (a%P * expbin(a, b - 1))%P;\n int tmp = expbin(a, b / 2);\n return (tmp * tmp)%P;\n}\n\n\nint nchoosek(int n, int k){\n return ((fat[n] * invfat[k])%P * invfat[n - k])%P;\n}\n\nint dp(int i = 0, int j = 0){\n if (i == k){\n return j == 0;\n }\n int &ans = memo[i][j];\n if (ans != -1) return ans;\n ans = 0;\n for (int qt=1; qt <= j; qt++){\n ans += dp(i + 1, j - qt) * nchoosek(j, qt);\n ans %= P;\n }\n return ans;\n}\n\nsigned main(){\n cin.tie(0)->sync_with_stdio(0);\n memset(memo, -1, sizeof(memo));\n cin >> n >> k;\n \n fat[0] = 1;\n for (int i = 1; i < MAX; i++) {\n fat[i] = (fat[i - 1] * i)%P;\n }\n\n invfat[MAX - 1] = expbin(fat[MAX - 1], P - 2);\n for (int i = MAX - 1; i >= 1; i--) {\n invfat[i - 1] = (invfat[i] * (i))%P;\n }\n\n\n cout << dp(0, n) << \"\\n\";\n}", "accuracy": 1, "time_ms": 630, "memory_kb": 11432, "score_of_the_acc": -1.1638, "final_rank": 19 }, { "submission_id": "aoj_DPL_5_C_9271757", "code_snippet": "#define _USE_MATH_DEFINES // M_PI等のフラグ\n#include <bits/stdc++.h>\n#define MOD 1000000007\n#define COUNTOF(array) (sizeof(array)/sizeof(array[0]))\n#define rep(i,n) for (int i = 0; i < (n); ++i)\n#define intceil(a,b) ((a+(b-1))/(b))\nusing namespace std;\nusing ll = long long;\nusing pii = pair<int,int>;\nusing pll = pair<long,long>;\nconst long long INF = LONG_LONG_MAX - 1001001001001001;\nvoid chmax(ll& x, ll y) { x = max(x,y); }\nvoid chmin(ll& x, ll y) { x = min(x,y); }\nstring vs = \"URDL\"; // 上右下左\nvector<ll> vy = { -1, 0, 1, 0 };\nvector<ll> vx = { 0, 1, 0, -1 };\n\n\n/** 自動でMODをとるModInt型\n *\n * Usage\n * // 基本的な使い方\n * mint a, b;\n * a = 100;\n * b = a + MOD;\n * // istreamとostreamをオーバロードしてるので、mint型も普通に入出力できる\n * cout << b << endl; // 100\n * // 明示的にlong long型を出力するときは.xを参照する\n * cout << b.x << endl; // 100\n *\n * References\n * https://youtu.be/L8grWxBlIZ4?t=9858\n * https://youtu.be/ERZuLAxZffQ?t=4807 : optimize\n * https://youtu.be/8uowVvQ_-Mo?t=1329 : division\n */\nstruct mint {\n ll x; // typedef long long ll;\n mint(ll x=0):x((x%MOD+MOD)%MOD){}\n mint operator-() const { return mint(-x);}\n mint& operator+=(const mint a) {\n if ((x += a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator-=(const mint a) {\n if ((x += MOD-a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator*=(const mint a) { (x *= a.x) %= MOD; return *this;}\n mint operator+(const mint a) const { return mint(*this) += a;}\n mint operator-(const mint a) const { return mint(*this) -= a;}\n mint operator*(const mint a) const { return mint(*this) *= a;}\n mint pow(ll t) const {\n if (!t) return 1;\n mint a = pow(t>>1);\n a *= a;\n if (t&1) a *= *this;\n return a;\n }\n\n // for prime MOD\n mint inv() const { return pow(MOD-2);}\n mint& operator/=(const mint a) { return *this *= a.inv();}\n mint operator/(const mint a) const { return mint(*this) /= a;}\n bool operator<=(const mint a) const { return mint(*this) <= a; }\n bool operator<(const mint a) const { return mint(*this) < a; }\n bool operator>=(const mint a) const { return mint(*this) >= a; }\n bool operator>(const mint a) const { return mint(*this) > a; }\n bool operator==(const mint a) const { return mint(*this) == a; }\n};\nistream& operator>>(istream& is, mint& a) { return is >> a.x;}\nostream& operator<<(ostream& os, const mint& a) { return os << a.x;}\n\n/**\n * @brief mintを使った高速なnCr計算\n *\n * @tparam T\n *\n * @details\n * O(n)で前計算を構築し、nCrのクエリにO(1)で応答する\n *\n * * 0!, 1!, ..., (n-1)!, n!\n * * 1/n!, 1/(n-1)!, ..., 1/0!\n * のテーブルをそれぞれO(n)で構築する。\n *\n * それにより nCr = n!/(r!*(n-r)!) のクエリにO(1)で応答できる\n *\n * @usage\n * combination_mint_builder<ll> c(1e6);\n * mint ans = c(6,2); // 6C2\n */\ntemplate <typename T>\nstruct combination_mint_builder {\n vector<mint> fact, ifact;\n combination_mint_builder(T n) {\n assert(n < MOD);\n fact.resize(n+1); ifact.resize(n+1);\n fact[0] = 1;\n for(T i=1; i<=n; i++) fact[i] = fact[i-1]*i;\n ifact[n] = fact[n].inv();\n for(T i=n; i>=1; i--) ifact[i-1] = ifact[i]*i;\n }\n mint operator()(T n, T r) {\n if (r<0 || r>n) return 0;\n return fact[n]*ifact[r]*ifact[n-r];\n }\n};\ncombination_mint_builder<ll> combo(1e6);\n\nvoid solve() {\n ll N, K; cin >> N >> K;\n\n // i個の箱にボールを入れない場合の数を数える\n mint notAns = 0;\n for(ll i=1; i<=K-1; i++) {\n mint val = combo(K,i) * mint(K-i).pow(N);\n if (i%2 == 0) notAns -= val;\n else notAns += val;\n }\n\n // 全事象\n mint all = mint(K).pow(N);\n\n // 余事象を求める\n mint ans = all - notAns;\n cout << ans << endl;\n}\n\n\nint main() {\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18812, "score_of_the_acc": -0.315, "final_rank": 11 }, { "submission_id": "aoj_DPL_5_C_8473608", "code_snippet": "#include <bits/stdc++.h>\n#include <iomanip>\n#include <numeric>\n#include <optional>\n\nusing namespace std;\n\n#define rep(i, x) for (ll i = 0; i < (x); i++)\n#define rep1(i, x) for (ll i = 1; i <= (x); i++)\n#define rep_i(i, j, x) for (ll i = j; i < (x); i++)\n#define rep_inv(i, x) for (ll i = (x)-1; i >= 0; i--)\n#define rep_inv1(i, x) for (ll i = (x); i >= 1; i--)\n#define rep_inv_i(i, j, x) for (ll i = (x)-1; i >= j; i--)\n#define all(a) a.begin(), a.end()\n#define input(a) \\\n a; \\\n cin >> a;\n#define input2(a, b) \\\n a, b; \\\n cin >> a >> b;\n#define input3(a, b, c) \\\n a, b, c; \\\n cin >> a >> b >> c;\n\n#define vec_in(a, N) \\\n a(N); \\\n rep(i, N) { \\\n cin >> a[i]; \\\n }\n#define rep2(i, j, x, y) \\\n for (ll i = 0; i < x; ++i) \\\n for (ll j = 0; j < y; ++j)\n#define p_in(P) cin >> P.first >> P.second;\n#define p_in_all(a, N) \\\n a(N); \\\n rep(i, N) { \\\n p_in(a[i]); \\\n }\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<char, int> pci;\ntypedef pair<char, ll> pcl;\ntypedef pair<double, double> pdd;\ntypedef vector<pair<int, int>> vpii;\ntypedef vector<pair<ll, ll>> vpll;\ntypedef vector<pair<char, ll>> vpcl;\ntypedef vector<int> vi;\ntypedef vector<vector<int>> vii;\ntypedef vector<vector<vector<int>>> viii;\ntypedef vector<vector<vector<vector<int>>>> viiii;\ntypedef vector<ll> vl;\ntypedef vector<vector<ll>> vll;\ntypedef vector<vector<vector<ll>>> vlll;\ntypedef vector<vector<vector<vector<ll>>>> vllll;\ntypedef vector<bool> vb;\ntypedef vector<vector<bool>> vbb;\ntypedef vector<char> vc;\ntypedef vector<vector<char>> vcc;\ntypedef vector<double> vd;\ntypedef vector<vd> vdd;\ntypedef vector<string> vs;\n\nconst ll ll_INF = 9223372036854775807;\nconst ll ll_INF_2 = ll_INF / 10;\n\nconst int i_INF = 2147483647;\nconst int i_INF2 = i_INF / 10;\nconst double epsilon = 1e-15;\nconst int MOD = 1e9 + 7;\nconst int MOD2 = 998244353;\ntemplate <class T>\nvoid chmin(T &a, const T &b) {\n if (a > b) {\n a = b;\n }\n}\n\ntemplate <class T>\nvoid chmax(T &a, const T &b) {\n if (a < b) {\n a = b;\n }\n}\ntemplate <class T, class U>\nostream &operator<<(ostream &os, const pair<T, U> &p) {\n os << \"[\" << p.first << \" \" << p.second << \"]\";\n return os;\n}\nnamespace modint {\n/**\n * @brief ax + by = gcd(a, b)の解(x, y)を求める。\n * @param x 解x(副作用)\n * @param y 解y(副作用)\n * @return gcd(a, b)\n */\ntemplate <class T>\nT ext_gcd(T a, T b, T &x, T &y) {\n T d = a;\n if (b != 0) {\n d = ext_gcd(b, a % b, y, x);\n y -= (a / b) * x;\n } else {\n x = 1;\n y = 0;\n }\n return d;\n}\n/**\n * @brief aの逆数x ((a * x) % mod == 1)を求める。\n */\ntemplate <class T>\nT mod_inv(T a, T mod) {\n T x, y;\n ext_gcd(a, mod, x, y);\n return (mod + x % mod) % mod;\n}\ntemplate <ll MOD>\nstruct mint {\n ll v;\n mint<MOD>() {\n }\n mint<MOD>(ll v) {\n this->v = ((MOD + v % MOD) % MOD);\n }\n void operator+=(const mint<MOD> &other) {\n v = (v + other.v) % MOD;\n }\n void operator+=(const ll &other) {\n v = (v + other % MOD) % MOD;\n }\n mint<MOD> operator+(const mint<MOD> &other) const {\n return mint<MOD>(v + other.v);\n }\n mint<MOD> operator+(const ll &other) const {\n return mint<MOD>(v + other % MOD);\n }\n void operator-=(const mint<MOD> &other) {\n v = (MOD + v - other.v) % MOD;\n }\n void operator-=(const ll &other) {\n v = (MOD + v - other % MOD) % MOD;\n }\n mint<MOD> operator-(const mint<MOD> &other) const {\n return mint<MOD>(v - other.v);\n }\n mint<MOD> operator-(const ll &other) const {\n return mint<MOD>(v - other % MOD);\n }\n void operator*=(const mint<MOD> &other) {\n v = (v * (other.v)) % MOD;\n }\n void operator*=(const ll &other) {\n v = (v * other) % MOD;\n }\n mint<MOD> operator*(const mint<MOD> &other) const {\n mint<MOD> res(*this);\n res *= other;\n return res;\n }\n mint<MOD> operator*(const ll &other) const {\n mint<MOD> res(*this);\n res *= other;\n return res;\n }\n mint<MOD> inv() const {\n ll a = 1, b = 1;\n ext_gcd<ll>(v, MOD, a, b);\n return mint<MOD>(a);\n }\n void operator/=(const mint<MOD> &other) {\n *this *= other.inv();\n }\n void operator/=(const ll &other) {\n *this *= mint<MOD>(other).inv();\n }\n mint<MOD> operator/(const mint<MOD> &other) const {\n mint<MOD> res(*this);\n res /= other;\n return res;\n }\n mint<MOD> operator/(const ll &other) const {\n mint<MOD> res(*this);\n res /= other;\n return res;\n }\n};\n\ntemplate <ll MOD>\nostream &operator<<(ostream &os, const mint<MOD> &p) {\n os << p.v;\n return os;\n}\n} // namespace modint\nusing namespace modint;\ntemplate <class T>\nT get_pow(T a, int n) {\n T res = 1;\n while (0 < n) {\n if ((n & 1) == 1) {\n res *= a;\n }\n a *= a;\n n >>= 1;\n }\n return res;\n}\ntypedef mint<MOD> mi;\ntypedef vector<mi> vm;\nint main() {\n ll input2(n, k);\n if (n < k) {\n cout << 0 << \"\\n\";\n return 0;\n }\n vm facto(k + 1);\n facto[0] = 1;\n rep1(i, k) {\n facto[i] = facto[i - 1] * i;\n }\n auto comb = [&facto](ll a, ll b) -> mi { return facto[a] / facto[b] / facto[a - b]; };\n\n vm dp(k + 1, 0);\n\n rep1(i, k) {\n dp[i] = get_pow<mi>(mi(i), n);\n rep1(j, i - 1) {\n dp[i] -= comb(i, j) * dp[j];\n }\n }\n cout << dp[k] << \"\\n\";\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 3432, "score_of_the_acc": -0.3065, "final_rank": 10 }, { "submission_id": "aoj_DPL_5_C_7721539", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <vector>\n\nstruct ModuloCombination{\n int size;\n int mod;\n std::vector<long long> fac;\n std::vector<long long> inv;\n std::vector<long long> finv;\n\n ModuloCombination(int const mod = 1000000007, int const size = 510000)\n : size(size),\n mod(mod),\n fac(size),\n inv(size),\n finv(size){\n init();\n }\n\n void init(){\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[0] = 0;\n inv[1] = 1;\n for(int i=2; i<size; ++i){\n fac[i] = fac[i-1] * i % mod;\n inv[i] = mod - inv[mod%i] * (mod / i) % mod;\n finv[i] = finv[i-1] * inv[i] % mod;\n }\n }\n\n long long combination(int const n, int const r){\n if(n < r) return 0;\n if(n < 0 || r < 0) return 0;\n return fac[n] * (finv[r] * finv[n - r] % mod) % mod;\n }\n};\n\nlong long int pow(long long int x, int n, long long int mod){\n long long int res = 1;\n while(n > 0){\n if(n % 2 == 1) res = (res * x) % mod;\n x = (x * x) % mod;\n n /= 2;\n }\n return res;\n}\n\n/*\nlong long int combination(int const n, int const r, int const mod){\n if(r == 0){\n return 1;\n }\n\n return (combination(n, r-1, mod) * (n - r + 1) / r) % mod;\n}\n*/\n\nint main(){\n int n, k;\n std::cin >> n >> k;\n int mod = 1000000007;\n\n ModuloCombination mc(mod);\n\n long long int ans = 0;\n for(int i=0; i<=k; ++i){\n long long a = ((k - i) % 2 == 1) ? 1 : mod - 1;\n long long b = pow(i, n, mod);\n long long c = mc.combination(k, i);\n ans = (ans + (((a * b) % mod) * c) % mod) % mod;\n }\n std::cout << (mod - ans) % mod << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 15120, "score_of_the_acc": -0.2555, "final_rank": 9 }, { "submission_id": "aoj_DPL_5_C_7721527", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <vector>\n\nstruct ModuloCombination{\n int size;\n int mod;\n std::vector<long long> fac;\n std::vector<long long> inv;\n std::vector<long long> finv;\n\n ModuloCombination(int const mod = 1000000007, int const size = 510000)\n : size(size),\n mod(mod),\n fac(size),\n inv(size),\n finv(size){\n init();\n }\n\n void init(){\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[0] = 0;\n inv[1] = 1;\n for(int i=2; i<size; ++i){\n fac[i] = fac[i-1] * i % mod;\n inv[i] = mod - inv[mod%i] * (mod / i) % mod;\n finv[i] = finv[i-1] * inv[i] % mod;\n }\n }\n\n long long combination(int const n, int const r){\n if(n < r) return 0;\n if(n < 0 || r < 0) return 0;\n return fac[n] * (finv[r] * finv[n - r] % mod) % mod;\n }\n};\n\nlong long int pow(long long int x, int n, long long int mod){\n long long int res = 1;\n while(n > 0){\n if(n % 2 == 1) res = (res * x) % mod;\n x = (x * x) % mod;\n n /= 2;\n }\n return res;\n}\n\n/*\nlong long int combination(int const n, int const r, int const mod){\n if(r == 0){\n return 1;\n }\n\n return (combination(n, r-1, mod) * (n - r + 1) / r) % mod;\n}\n*/\n\nint main(){\n int n, k;\n std::cin >> n >> k;\n int mod = 1000000007;\n\n ModuloCombination mc(mod);\n\n long long int ans = 0;\n for(int i=0; i<=k; ++i){\n long long a = ((k - i) % 2 == 1) ? 1 : mod - 1;\n long long b = pow(i, n, mod);\n long long c = mc.combination(k, i);\n ans = (ans + (((a * b) % mod) * c) % mod) % mod;\n }\n std::cout << mod - ans << std::endl;\n\n return 0;\n}", "accuracy": 0.13333333333333333, "time_ms": 10, "memory_kb": 15056, "score_of_the_acc": -0.2381, "final_rank": 20 }, { "submission_id": "aoj_DPL_5_C_7583326", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\nvoid extgcd( ll a, ll b, ll &x, ll &y ){\n if( b != 0LL ){\n extgcd( b, a % b, y, x );\n y -= ( a / b ) * x;\n }\n else{\n x = 1LL;\n y = 0LL;\n }\n}\n\n// MODを考慮した ll\nstruct mll{\n\n ll val;\n\n mll( ll _val = 0LL ){\n val = ( _val + MOD ) % MOD;\n }\n\n mll inv(){\n ll x, y;\n extgcd( val, MOD, x, y );\n x %= MOD;\n x += MOD;\n return x % MOD;\n }\n\n mll operator+( mll x ){\n mll res;\n res.val = ( val + x.val ) % MOD;\n return res;\n }\n\n mll operator+=( mll x ){\n return *this = *this + x;\n }\n\n mll operator-( mll x ){\n mll res;\n res.val = ( val + MOD - x.val ) % MOD;\n return res;\n }\n\n mll operator-=( mll x ){\n return *this = *this - x;\n }\n\n mll operator*( mll x ){\n mll res;\n res.val = ( val * x.val ) % MOD;\n return res;\n }\n\n mll operator*=( mll x ){\n return *this = *this * x;\n }\n\n mll operator/( mll x ){\n mll res;\n res.val = ( val * x.inv().val ) % MOD;\n return res;\n }\n\n mll operator/=( mll x ){\n return *this = *this / x;\n }\n\n mll operator++(){\n mll one( 1LL );\n return *this = *this + one;\n }\n\n mll operator++( int ){\n mll one( 1LL );\n mll res = *this;\n *this = *this + one;\n return res;\n }\n\n mll operator--(){\n mll one( 1LL );\n return *this = *this - one;\n }\n\n mll operator--( int ){\n mll one( 1LL );\n mll res = *this;\n *this = *this - one;\n return res;\n }\n\n bool operator<( mll x ){\n return val < x.val;\n }\n\n bool operator>( mll x ){\n return val > x.val;\n }\n\n bool operator<=( mll x ){\n return val <= x.val;\n }\n\n bool operator>=( mll x ){\n return val >= x.val;\n }\n\n bool operator==( mll x ){\n return val == x.val;\n }\n\n bool operator!=( mll x ){\n return val != x.val;\n }\n\n};\n\n// MODを考慮した x の y 乗\nmll power( mll mx, mll my ){\n\n mll res( 1LL );\n ll y = my.val;\n while( y > 0LL ){\n if( y & 1LL )\n res *= mx;\n mx *= mx;\n y >>= 1;\n }\n return res;\n\n}\n\n// MODを考慮した xCy\nmll permutation( mll mx, mll my ){\n\n mll res( 1LL );\n mll i( 1LL );\n while( i <= my ){\n res *= mx;\n mx--;\n i++;\n }\n return res;\n\n}\n\n// MODを考慮した xCy\nmll combination( mll mx, mll my ){\n\n mll res( 1LL );\n mll i( 1LL );\n while( i <= my ){\n res *= mx;\n res /= i;\n mx--;\n i++;\n }\n return res;\n\n}\n\n// 包除原理を用いた解法\n// 箱 i が空いている事象を Ai とする\n// 全てのパターン = 求める値 + ( Ai の合計 ) - ( Ai ∩ Aj の合計 ) + ( Ai ∩ Aj ∩ Ak の合計 ) - ..\nmll func1( mll mx, mll my ){\n\n bool minus = true;\n mll res = power( my, mx );\n for( mll i(1LL) ; i <= my ; i++ ){\n if( minus )\n res -= combination( my, i ) * power( my - i, mx );\n else\n res += combination( my, i ) * power( my - i, mx );\n minus = !minus;\n }\n return res;\n\n}\n\n////////////////////////////// n 個の ボールを k 個の 箱に入れる時 /////////////////////////////////////\n// ボール : 区別できる, 箱 : 区別できる, 入れ方に制限なし => power( k, n )\n// ボール : 区別できる, 箱 : 区別できる, 箱の中身は1つ以下 => k >= n ? permutation( k, n ) : 0\n// ボール : 区別できる, 箱 : 区別できる, 箱の中身は1つ以上 => n >= k ? func1( n, k ) : 0\n// ボール : 区別できない, 箱 : 区別できる, 入れ方に制限なし => combination( n + k - 1, k - 1 )\n// ボール : 区別できない, 箱 : 区別できる, 箱の中身は1つ以下 => k >= n ? combination( k, n ) : 0\n// ボール : 区別できない, 箱 : 区別できる, 箱の中身は1つ以上 => n >= k ? combination( n - 1, k - 1) : 0\n// ボール : 区別できる, 箱 : 区別できない, 箱の中身は1つ以下 => k >= n ? 1 : 0\n// ボール : 区別できない, 箱 : 区別できない, 箱の中身は1つ以下 => k >= n ? 1 : 0\n\nint main(){\n\n ll n, k;\n cin >> n >> k;\n mll mx = mll( n );\n mll my = mll( k );\n cout << ( mx >= my ? func1( mx, my ).val : 0LL ) << endl;\n\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3440, "score_of_the_acc": -0.0324, "final_rank": 1 }, { "submission_id": "aoj_DPL_5_C_7388219", "code_snippet": "#include <bits/stdc++.h>\n#include <stdio.h>\nusing namespace std;\nusing ll = long long;\n\nconst ll MOD = 1e+9 + 7;\nconst ll MAX = 2100000;\n\nvector<ll> fact(MAX), inv(MAX), inv_fact(MAX);\n\nvoid init() {\n fact.at(0) = fact.at(1) = 1;\n inv.at(0) = inv.at(1) = 1;\n inv_fact.at(0) = inv_fact.at(1) = 1;\n \n for (int i = 2; i < MAX; i++) {\n fact.at(i) = fact.at(i - 1) * i % MOD;\n inv.at(i) = MOD - inv.at(MOD % i) * (MOD / i) % MOD;\n inv_fact.at(i) = inv_fact.at(i - 1) * inv.at(i) % MOD;\n }\n}\n\nll nCk(ll n, ll k) {\n if (n < k) {\n return 0;\n }\n if (n < 0 || k < 0) {\n return 0;\n }\n\t\n\tll x = fact.at(n);\n ll y = inv_fact.at(n - k);\n ll z = inv_fact.at(k);\n\n return (x * ((y * z) % MOD)) % MOD;\n}\n\nll mod_pow(ll a, ll n, ll mod) {\n ll res = 1;\n while (n > 0) {\n if (n & 1) res = res * a % mod;\n a = a * a % mod;\n n >>= 1;\n }\n return res;\n}\n\n\n\nint main() {\n\tinit();\n\tll n, k;\n\tcin >> n >> k;\n\n\tif (n < k) {\n\t\tcout << 0 << endl;\n\t\treturn 0;\n\t}\n\n\tll ans = 0;\n\tfor (int i = 0; i <= k; i++) {\n\t\tll tmp = nCk(k, i) * mod_pow(k - i, n, MOD) % MOD;\n\t\tif (i % 2 == 0) {\n\t\t\tans = (ans + tmp) % MOD; \n\t\t} else {\n\t\t\tans = (ans - tmp + MOD) % MOD;\n\t\t}\n\t}\n\tcout << ans << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 52260, "score_of_the_acc": -1.0323, "final_rank": 18 }, { "submission_id": "aoj_DPL_5_C_7053834", "code_snippet": "// 2022.10.21\n#define _GLIBCXX_DEBUG //\n// #define __USE_MATH_DEFINES // const double PI = acos(-1.0)\n#include <bits/stdc++.h>\nusing namespace std;\n// (*) snipet\n// type name\nusing ll = long long;\nusing pii = pair<int, int>; using pil = pair<int, ll>; using pli = pair<ll, int>; using pll = pair<ll, ll>;\nusing vi = vector<int>; using vvi = vector<vi>; using vvvi = vector<vvi>;\nusing vl = vector<ll>; using vvl = vector<vl>; using vvvl = vector<vvl>;\nusing vpii = vector<pii>; using vpil = vector<pil>; using vpli = vector<pli>; using vpll = vector<pll>;\nusing vb = vector<bool>; using vvb = vector<vb>; using vvvb = vector<vvb>;\nusing vd = vector<double>; using vvd = vector<vd>; using vvvd = vector<vvd>;\ntemplate <typename T> using pq = priority_queue<T, vector<T>>;\ntemplate <typename T> using pql = priority_queue<T, vector<T>, greater<T>>;\n// rep\n#define rep0(goal) for (int cnt = 0; cnt < int(goal); ++cnt)\n#define rep(cnt, goal) for (int cnt = 0; cnt < int(goal); ++cnt)\n#define rep2(cnt, start, goal) for (int cnt = int(start); cnt < int(goal); ++cnt)\n#define rep3(cnt, start, goal) for (int cnt = int(start); cnt > int(goal); --cnt)\n// all\n#define all(ctn) begin(ctn), end(ctn)\n// chmax, chmin\ntemplate <typename T> bool chmax(T &x, const T y) { if (x < y) { x = y; return true; } else { return false; }}\ntemplate <typename T> bool chmin(T &x, const T y) { if (x > y) { x = y; return true; } else { return false; }}\n// etc.\nvoid Yn(const bool &exp) { if (exp) cout << \"Yes\" << endl; else cout << \"No\" << endl;}\nvoid set_prec(const int &dig) { cout << fixed << setprecision(dig); cerr << fixed << setprecision(dig);}\n// template <typename T> T INF() { return numeric_limits<T>::max();}\n// template <typename T> T MIN_INF() { return numeric_limits<T>::min();}\n\n// #include <atcoder/all>\n// using namespace atcoder;\n// // using mint = atcoder::modint1000000007;\n// using mint = atcoder::modint998244353;\n// // using mint = atcoder::modint;\n// void pr(const mint &MINT) { cerr << MINT.val(); } // mint\n// using pmm = pair<mint, mint>; using pim = pair<int, mint>; using pmi = pair<mint, int>; using plm = pair<ll, mint>; using pml = pair<mint, ll>;\n// using vm = vector<mint>; using vvm = vector<vm>; using vvvm = vector<vvm>;\n\n// debug\ntemplate <typename T> void pr(const T &obj) { cerr << obj; } // single\ntemplate <typename T, typename ...Ts> void pr(const T &first, const Ts &...rest) { pr(first); cerr << \", \"; pr(rest...); } // multi(plural)\ntemplate <typename S, typename T> void pr(const pair<S, T> &PAIR) { cerr << \"(\"; pr(PAIR.first); cerr << \", \"; pr(PAIR.second); cerr << \")\"; } // pair\ntemplate <typename S, typename T, typename U> void pr(const tuple<S, T, U> &trp) { cerr << \"(\"; pr(get<0>(trp)); cerr << \", \"; pr(get<1>(trp)); cerr << \", \"; pr(get<2>(trp)); cerr << \")\"; } // tuple(3)\ntemplate <typename T> void pr(const vector<T> &vec) { cerr << \"{\"; for (T obj : vec) { pr(obj); cerr << \", \"; } cerr << \"}\"; } // vector\ntemplate <typename T> void pr(const vector<vector<T>> &vv) { rep(row, vv.size()) { cerr << endl; cerr << \"[\" << row << \"]: \"; pr(vv[row]); }} // vector(multi-D)\ntemplate <typename T> void pr(const set<T> &SET) { cerr << \"{\"; for (T obj : SET) { pr(obj); cerr << \", \"; } cerr << \"}\"; } // set\ntemplate <typename T> void pr(const multiset<T> &MS) { cerr << \"{\"; for (T obj : MS) { pr(obj); cerr << \", \"; } cerr << \"}\"; } // multiset\ntemplate <typename S, typename T> void pr(const map<S, T> &MAP) { cerr << \"{\"; for (pair<S, T> p : MAP) { pr(p.first); cerr << \": \"; pr(p.second); cerr << \", \"; } cerr << \"}\";} // map\ntemplate <typename T> void pr(const queue<T> &que) { queue<T> q = que; cerr << \"{\"; while (!q.empty()) { pr(q.front()); q.pop(); cerr << \", \";} cerr << \"}\";} // queue\ntemplate <typename T> void pr(const deque<T> &deq) { deque<T> d = deq; cerr << \"{\"; while (!d.empty()) { pr(d.front()); d.pop_front(); cerr << \", \";} cerr << \"}\";} // deque\ntemplate <typename T> void pr(const stack<T> &stc) { stack<T> s = stc; vector<T> v; while (!s.empty()) { v.push_back(s.top()); s.pop();} reverse(all(v)); cerr << \"{\"; for (T obj : v) cerr << obj << \", \"; cerr << \"}\";} // stack\ntemplate <typename T> void pr(const priority_queue<T> &pq) { priority_queue<T> p = pq; cerr << \"{\"; while (!p.empty()) { pr(p.top()); p.pop(); cerr << \", \"; } cerr << \"}\";} // priority_queue\ntemplate <typename T> void pr(const priority_queue<T, vector<T>, greater<T>> &pq) { priority_queue<T, vector<T>, greater<T>> p = pq; cerr << \"{\"; while (!p.empty()) { pr(p.top()); p.pop(); cerr << \", \";} cerr << \"}\";} // priority_queue(from less)\n\n#define db(obj) cerr << #obj << \": \"; pr(obj); cerr << \" \";\n#define dl(obj) db(obj); cerr << endl;\n#define dm(...) cerr << \"(\" << #__VA_ARGS__ << \"): (\"; pr(__VA_ARGS__); cerr << \") \";\n#define dml(...) dm(__VA_ARGS__); cerr << endl;\n\n// \n\n// global\nint n; // 玉の数\nint k; // 箱の数\n\nvvl dp; // dp[n][k]\nvvl dp2; // dp2[n][k] //\nll m = 1e9 + 7; // 998244353; // MOD\n\nvoid input() {\n\tcin >> n >> k;\n}\n\nvoid init() {\n\tdp = vvl(n + 1, vl(k + 1, -1));\n\tdp2 = dp; //\n}\n\n// 重複順列の数 kΠn = k^n\nll kPin(int n, int k) {\n\tassert(0 <= n); assert(0 <= k);\n\tif (dp2[n][k] != -1) return dp2[n][k];\n\n\tif (n == 0 && k == 0) return dp2[n][k] = 1;\n\tif (n == 0) return dp2[n][k] = 1; // 玉がない\n\tif (k == 0) return dp2[n][k] = 0; // 箱がない\n\n\tll res = 0;\n\tres = k * kPin(n - 1, k) % m; // (n)は箱(k個)のどれかに入れる\n\treturn dp2[n][k] = res;\n}\n\n// 組合せの数 kCn = k!/n!(k-n)!\nll kCn(int n, int k) {\n\tassert(0 <= n); assert(0 <= k);\n\tif (dp[n][k] != -1) return dp[n][k];\n\n\tif (n == 0 && k == 0) return dp[n][k] = 1;\n\tif (n == 0) return dp[n][k] = 1; // 玉がない\n\tif (k == 0) return dp[n][k] = 0; // 箱がない\n\n\tll res = 0;\n\tres = (res + kCn(n - 1, k - 1)) % m; // [k]に玉を入れる\n\tres = (res + kCn(n, k - 1)) % m; // [k]に玉を入れない\n\treturn dp[n][k] = res;\n}\n\n// 全射の数 Σ[i:0->k](-1)^(k-i)*kCi*iΠn\nll surjection(int n, int k) {\n\tassert(0 <= n); assert(0 <= k);\n\n\tif (n < k) return 0;\n\t\n\tll res = 0;\n\trep(i, k + 1) {\n\t\tll temp = kCn(i, k) * kPin(n, i) % m;\n\t\tif ((k - i) % 2 == 0) res = (res + temp) % m;\n\t\telse res = (res - temp + m) % m;\n\t}\n\treturn res;\n}\n\nvoid solve() {\n\tcout << surjection(n, k) << endl;\n\t// dl(dp);\n\t// dl(dp2); //\n};\n\nint main() {\n\tinput();\n\tinit();\n\tsolve();\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 19272, "score_of_the_acc": -0.3567, "final_rank": 13 }, { "submission_id": "aoj_DPL_5_C_6950900", "code_snippet": "#include <bits/stdc++.h>\n#include <stdio.h>\nusing namespace std;\nusing ll = long long;\n\nll mod_pow(ll x, ll n, ll mod) {\n if (n == 0) {\n return 1;\n }\n ll\n res = mod_pow(x * x % mod, n / 2, mod);\n if (n & 1) res = res * x % mod;\n return res;\n}\n\nconst ll MOD = 1e9 + 7;\nconst ll MAX = 1100000;\n\nvector<ll> fact(MAX), inv(MAX), inv_fact(MAX);\n\nvoid init() {\n fact.at(0) = fact.at(1) = 1;\n inv.at(0) = inv.at(1) = 1;\n inv_fact.at(0) = inv_fact.at(1) = 1;\n \n for (int i = 2; i < MAX; i++) {\n fact.at(i) = fact.at(i - 1) * i % MOD;\n inv.at(i) = MOD - inv.at(MOD % i) * (MOD / i) % MOD;\n inv_fact.at(i) = inv_fact.at(i - 1) * inv.at(i) % MOD;\n }\n}\n\nll nCk(ll n, ll k) {\n ll x = fact.at(n);\n ll y = inv_fact.at(n - k);\n ll z = inv_fact.at(k);\n\n if (n < k) {\n return 0;\n }\n if (n < 0 || k < 0) {\n return 0;\n }\n\n return (x * ((y * z) % MOD)) % MOD;\n}\n\nint main() {\n\tinit();\n\tll n, k;\n\tcin >> n >> k;\n\n\tll ans = 0;\n\tfor (int i = 0; i <= k; i++) {\n\t\tll ok = k - i;\n\t\tll add = nCk(k, i) * mod_pow(ok, n, MOD) % MOD;\n\t\tif (i % 2 == 0) {\n\t\t\tans = (ans + add) % MOD;\n\t\t} else {\n\t\t\tans = (ans - add + MOD) % MOD;\n\t\t}\n\t}\n\tcout << ans << endl;\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 28688, "score_of_the_acc": -0.5172, "final_rank": 14 }, { "submission_id": "aoj_DPL_5_C_6471100", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std ;\n#define fast_input_output ios::sync_with_stdio(false); cin.tie(nullptr);\ntypedef long long ll ;\ntypedef long double ld ;\ntypedef pair<ll,ll> P ;\ntypedef tuple<ll,ll,ll> TP ;\n#define chmin(a,b) a = min(a,b)\n#define chmax(a,b) a = max(a,b)\n#define bit_count(x) __builtin_popcountll(x)\n#define gcd(a,b) __gcd(a,b)\n#define lcm(a,b) a / gcd(a,b) * b\n#define rep(i,n) for(int i = 0 ; i < n ; i++)\n#define rrep(i,a,b) for(int i = a ; i < b ; i++)\n#define endl \"\\n\"\n\nconst int mod = 1000000007 ;\nconst int MAX_N = 505050 ;\n\nll inv[MAX_N+1] ; // (n!)^(p-2) (mod p) を格納\nll fac[MAX_N+1] ; // (n!) (mod p) を格納\n\n// 繰り返し二乗法\nll powmod(ll A , ll N){\n ll res = 1 ;\n while(N > 0){\n if(N & 1) res = (res * A) % mod ;\n A = (A * A) % mod ;\n N >>= 1 ;\n }\n return res % mod ;\n}\n\n// 階乗の逆元(n!)^(-1)のmodを配列に格納\nvoid f(){\n inv[0] = 1 ; inv[1] = 1 ;\n for(ll i = 2 ; i <= MAX_N ; i++){\n inv[i] = powmod(i,mod-2) * inv[i-1] % mod ;\n }\n}\n\n// 階乗のmodを配列に格納\nvoid g(){\n fac[0] = 1 ; fac[1] = 1 ;\n for(ll i = 2 ; i <= MAX_N ; i++){\n fac[i] = (fac[i-1] * i) % mod ;\n }\n}\n\n//nCrの計算\nll combination(ll n , ll r){\n return fac[n] * inv[n-r] % mod * inv[r] % mod ;\n}\n\nll permutation(ll n , ll r){\n return fac[n] * inv[n-r] % mod ;\n}\n\nvoid init(){ f() ; g() ; }\n\nll n , k ;\n\nint main(){\n fast_input_output\n init() ;\n cin >> n >> k ;\n ll sum = 0 ;\n rrep(i,1,k){\n if(i % 2 == 1) sum += combination(k,i) * powmod(k-i,n) % mod ;\n if(i % 2 == 0) sum -= combination(k,i) * powmod(k-i,n) % mod ;\n (sum += mod) %= mod ;\n }\n ll res = (powmod(k,n) - sum + mod) % mod ;\n cout << res << endl ;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 11352, "score_of_the_acc": -0.2106, "final_rank": 6 }, { "submission_id": "aoj_DPL_5_C_6379483", "code_snippet": "#include <bits/stdc++.h>\n\n#include <cassert>\n#include <numeric>\n#include <type_traits>\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\n\n#include <utility>\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\nnamespace atcoder {\n\nnamespace internal {\n\nconstexpr long long safe_mod(long long x, long long m) {\n x %= m;\n if (x < 0) x += m;\n return x;\n}\n\nstruct barrett {\n unsigned int _m;\n unsigned long long im;\n\n explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}\n\n unsigned int umod() const { return _m; }\n\n unsigned int mul(unsigned int a, unsigned int b) const {\n\n unsigned long long z = a;\n z *= b;\n#ifdef _MSC_VER\n unsigned long long x;\n _umul128(z, im, &x);\n#else\n unsigned long long x =\n (unsigned long long)(((unsigned __int128)(z)*im) >> 64);\n#endif\n unsigned int v = (unsigned int)(z - x * _m);\n if (_m <= v) v += _m;\n return v;\n }\n};\n\nconstexpr long long pow_mod_constexpr(long long x, long long n, int m) {\n if (m == 1) return 0;\n unsigned int _m = (unsigned int)(m);\n unsigned long long r = 1;\n unsigned long long y = safe_mod(x, m);\n while (n) {\n if (n & 1) r = (r * y) % _m;\n y = (y * y) % _m;\n n >>= 1;\n }\n return r;\n}\n\nconstexpr bool is_prime_constexpr(int n) {\n if (n <= 1) return false;\n if (n == 2 || n == 7 || n == 61) return true;\n if (n % 2 == 0) return false;\n long long d = n - 1;\n while (d % 2 == 0) d /= 2;\n constexpr long long bases[3] = {2, 7, 61};\n for (long long a : bases) {\n long long t = d;\n long long y = pow_mod_constexpr(a, t, n);\n while (t != n - 1 && y != 1 && y != n - 1) {\n y = y * y % n;\n t <<= 1;\n }\n if (y != n - 1 && t % 2 == 0) {\n return false;\n }\n }\n return true;\n}\ntemplate <int n> constexpr bool is_prime = is_prime_constexpr(n);\n\nconstexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {\n a = safe_mod(a, b);\n if (a == 0) return {b, 0};\n\n long long s = b, t = a;\n long long m0 = 0, m1 = 1;\n\n while (t) {\n long long u = s / t;\n s -= t * u;\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\n\n\n auto tmp = s;\n s = t;\n t = tmp;\n tmp = m0;\n m0 = m1;\n m1 = tmp;\n }\n if (m0 < 0) m0 += b / s;\n return {s, m0};\n}\n\nconstexpr int primitive_root_constexpr(int m) {\n if (m == 2) return 1;\n if (m == 167772161) return 3;\n if (m == 469762049) return 3;\n if (m == 754974721) return 11;\n if (m == 998244353) return 3;\n int divs[20] = {};\n divs[0] = 2;\n int cnt = 1;\n int x = (m - 1) / 2;\n while (x % 2 == 0) x /= 2;\n for (int i = 3; (long long)(i)*i <= x; i += 2) {\n if (x % i == 0) {\n divs[cnt++] = i;\n while (x % i == 0) {\n x /= i;\n }\n }\n }\n if (x > 1) {\n divs[cnt++] = x;\n }\n for (int g = 2;; g++) {\n bool ok = true;\n for (int i = 0; i < cnt; i++) {\n if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {\n ok = false;\n break;\n }\n }\n if (ok) return g;\n }\n}\ntemplate <int m> constexpr int primitive_root = primitive_root_constexpr(m);\n\nunsigned long long floor_sum_unsigned(unsigned long long n,\n unsigned long long m,\n unsigned long long a,\n unsigned long long b) {\n unsigned long long ans = 0;\n while (true) {\n if (a >= m) {\n ans += n * (n - 1) / 2 * (a / m);\n a %= m;\n }\n if (b >= m) {\n ans += n * (b / m);\n b %= m;\n }\n\n unsigned long long y_max = a * n + b;\n if (y_max < m) break;\n n = (unsigned long long)(y_max / m);\n b = (unsigned long long)(y_max % m);\n std::swap(m, a);\n }\n return ans;\n}\n\n} // namespace internal\n\n} // namespace atcoder\n\n\n#include <cassert>\n#include <numeric>\n#include <type_traits>\n\nnamespace atcoder {\n\nnamespace internal {\n\n#ifndef _MSC_VER\ntemplate <class T>\nusing is_signed_int128 =\n typename std::conditional<std::is_same<T, __int128_t>::value ||\n std::is_same<T, __int128>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int128 =\n typename std::conditional<std::is_same<T, __uint128_t>::value ||\n std::is_same<T, unsigned __int128>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing make_unsigned_int128 =\n typename std::conditional<std::is_same<T, __int128_t>::value,\n __uint128_t,\n unsigned __int128>;\n\ntemplate <class T>\nusing is_integral = typename std::conditional<std::is_integral<T>::value ||\n is_signed_int128<T>::value ||\n is_unsigned_int128<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_signed_int = typename std::conditional<(is_integral<T>::value &&\n std::is_signed<T>::value) ||\n is_signed_int128<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n typename std::conditional<(is_integral<T>::value &&\n std::is_unsigned<T>::value) ||\n is_unsigned_int128<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<\n is_signed_int128<T>::value,\n make_unsigned_int128<T>,\n typename std::conditional<std::is_signed<T>::value,\n std::make_unsigned<T>,\n std::common_type<T>>::type>::type;\n\n#else\n\ntemplate <class T> using is_integral = typename std::is_integral<T>;\n\ntemplate <class T>\nusing is_signed_int =\n typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n typename std::conditional<is_integral<T>::value &&\n std::is_unsigned<T>::value,\n std::true_type,\n std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<is_signed_int<T>::value,\n std::make_unsigned<T>,\n std::common_type<T>>::type;\n\n#endif\n\ntemplate <class T>\nusing is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;\n\ntemplate <class T>\nusing is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;\n\ntemplate <class T> using to_unsigned_t = typename to_unsigned<T>::type;\n\n} // namespace internal\n\n} // namespace atcoder\n\n\nnamespace atcoder {\n\nnamespace internal {\n\nstruct modint_base {};\nstruct static_modint_base : modint_base {};\n\ntemplate <class T> using is_modint = std::is_base_of<modint_base, T>;\ntemplate <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;\n\n} // namespace internal\n\ntemplate <int m, std::enable_if_t<(1 <= m)>* = nullptr>\nstruct static_modint : internal::static_modint_base {\n using mint = static_modint;\n\n public:\n static constexpr int mod() { return m; }\n static mint raw(int v) {\n mint x;\n x._v = v;\n return x;\n }\n\n static_modint() : _v(0) {}\n template <class T, internal::is_signed_int_t<T>* = nullptr>\n static_modint(T v) {\n long long x = (long long)(v % (long long)(umod()));\n if (x < 0) x += umod();\n _v = (unsigned int)(x);\n }\n template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n static_modint(T v) {\n _v = (unsigned int)(v % umod());\n }\n\n unsigned int val() const { return _v; }\n\n mint& operator++() {\n _v++;\n if (_v == umod()) _v = 0;\n return *this;\n }\n mint& operator--() {\n if (_v == 0) _v = umod();\n _v--;\n return *this;\n }\n mint operator++(int) {\n mint result = *this;\n ++*this;\n return result;\n }\n mint operator--(int) {\n mint result = *this;\n --*this;\n return result;\n }\n\n mint& operator+=(const mint& rhs) {\n _v += rhs._v;\n if (_v >= umod()) _v -= umod();\n return *this;\n }\n mint& operator-=(const mint& rhs) {\n _v -= rhs._v;\n if (_v >= umod()) _v += umod();\n return *this;\n }\n mint& operator*=(const mint& rhs) {\n unsigned long long z = _v;\n z *= rhs._v;\n _v = (unsigned int)(z % umod());\n return *this;\n }\n mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n mint operator+() const { return *this; }\n mint operator-() const { return mint() - *this; }\n\n mint pow(long long n) const {\n assert(0 <= n);\n mint x = *this, r = 1;\n while (n) {\n if (n & 1) r *= x;\n x *= x;\n n >>= 1;\n }\n return r;\n }\n mint inv() const {\n if (prime) {\n assert(_v);\n return pow(umod() - 2);\n } else {\n auto eg = internal::inv_gcd(_v, m);\n assert(eg.first == 1);\n return eg.second;\n }\n }\n\n friend mint operator+(const mint& lhs, const mint& rhs) {\n return mint(lhs) += rhs;\n }\n friend mint operator-(const mint& lhs, const mint& rhs) {\n return mint(lhs) -= rhs;\n }\n friend mint operator*(const mint& lhs, const mint& rhs) {\n return mint(lhs) *= rhs;\n }\n friend mint operator/(const mint& lhs, const mint& rhs) {\n return mint(lhs) /= rhs;\n }\n friend bool operator==(const mint& lhs, const mint& rhs) {\n return lhs._v == rhs._v;\n }\n friend bool operator!=(const mint& lhs, const mint& rhs) {\n return lhs._v != rhs._v;\n }\n\n private:\n unsigned int _v;\n static constexpr unsigned int umod() { return m; }\n static constexpr bool prime = internal::is_prime<m>;\n};\n\ntemplate <int id> struct dynamic_modint : internal::modint_base {\n using mint = dynamic_modint;\n\n public:\n static int mod() { return (int)(bt.umod()); }\n static void set_mod(int m) {\n assert(1 <= m);\n bt = internal::barrett(m);\n }\n static mint raw(int v) {\n mint x;\n x._v = v;\n return x;\n }\n\n dynamic_modint() : _v(0) {}\n template <class T, internal::is_signed_int_t<T>* = nullptr>\n dynamic_modint(T v) {\n long long x = (long long)(v % (long long)(mod()));\n if (x < 0) x += mod();\n _v = (unsigned int)(x);\n }\n template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n dynamic_modint(T v) {\n _v = (unsigned int)(v % mod());\n }\n\n unsigned int val() const { return _v; }\n\n mint& operator++() {\n _v++;\n if (_v == umod()) _v = 0;\n return *this;\n }\n mint& operator--() {\n if (_v == 0) _v = umod();\n _v--;\n return *this;\n }\n mint operator++(int) {\n mint result = *this;\n ++*this;\n return result;\n }\n mint operator--(int) {\n mint result = *this;\n --*this;\n return result;\n }\n\n mint& operator+=(const mint& rhs) {\n _v += rhs._v;\n if (_v >= umod()) _v -= umod();\n return *this;\n }\n mint& operator-=(const mint& rhs) {\n _v += mod() - rhs._v;\n if (_v >= umod()) _v -= umod();\n return *this;\n }\n mint& operator*=(const mint& rhs) {\n _v = bt.mul(_v, rhs._v);\n return *this;\n }\n mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n mint operator+() const { return *this; }\n mint operator-() const { return mint() - *this; }\n\n mint pow(long long n) const {\n assert(0 <= n);\n mint x = *this, r = 1;\n while (n) {\n if (n & 1) r *= x;\n x *= x;\n n >>= 1;\n }\n return r;\n }\n mint inv() const {\n auto eg = internal::inv_gcd(_v, mod());\n assert(eg.first == 1);\n return eg.second;\n }\n\n friend mint operator+(const mint& lhs, const mint& rhs) {\n return mint(lhs) += rhs;\n }\n friend mint operator-(const mint& lhs, const mint& rhs) {\n return mint(lhs) -= rhs;\n }\n friend mint operator*(const mint& lhs, const mint& rhs) {\n return mint(lhs) *= rhs;\n }\n friend mint operator/(const mint& lhs, const mint& rhs) {\n return mint(lhs) /= rhs;\n }\n friend bool operator==(const mint& lhs, const mint& rhs) {\n return lhs._v == rhs._v;\n }\n friend bool operator!=(const mint& lhs, const mint& rhs) {\n return lhs._v != rhs._v;\n }\n\n private:\n unsigned int _v;\n static internal::barrett bt;\n static unsigned int umod() { return bt.umod(); }\n};\ntemplate <int id> internal::barrett dynamic_modint<id>::bt(998244353);\n\nusing modint998244353 = static_modint<998244353>;\nusing modint1000000007 = static_modint<1000000007>;\nusing modint = dynamic_modint<-1>;\n\nnamespace internal {\n\ntemplate <class T>\nusing is_static_modint = std::is_base_of<internal::static_modint_base, T>;\n\ntemplate <class T>\nusing is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;\n\ntemplate <class> struct is_dynamic_modint : public std::false_type {};\ntemplate <int id>\nstruct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};\n\ntemplate <class T>\nusing is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;\n\n} // namespace internal\n\n} // namespace atcoder\n\nusing namespace std;\nusing namespace atcoder;\nusing mint = modint1000000007;\n#define ll long long\n\nconst int comb_N = 1e6;\nvector<mint> fact, inverse;\n\nmint comb(int n, int k) {\n if (n<0 || k<0 || n<k) return mint(0);\n return fact[n]*inverse[k]*inverse[(n-k)];\n}\n\nmint perm(int n, int k) {\n if (n<0 || k<0 || n<k) return mint(0);\n return fact[n]*inverse[(n-k)];\n}\n\nvoid calc_comb() {\n fact = vector<mint>(comb_N, mint(0));\n inverse = vector<mint>(comb_N, mint(0));\n fact[0] = mint(1);\n inverse[0] = mint(1);\n for (int i=1;i<comb_N;i++) {\n fact[i] = fact[i-1]*i;\n inverse[i] = fact[i].inv();\n }\n}\n\nint main() {\n calc_comb();\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, k;\n cin >> n >> k;\n mint ans = 0;\n mint flag = -1;\n for (int i=0;i<=k;i++) {\n flag *= -1;\n ans += flag*comb(k, i)*(mint(k-i).pow(n));\n }\n\n cout << ans.val() << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 10840, "score_of_the_acc": -0.2485, "final_rank": 8 }, { "submission_id": "aoj_DPL_5_C_6165011", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\n#define X cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(12);\n#define I inline\n#define TTT template<typename T>\n#define TTTU template<typename T,typename U>\n#define TTTT template<typename... T>\n#define TTTTT template<typename T,typename... Ts>\n#define overload2(a,b,c,...) c\n#define overload3(a,b,c,d,...) d\n#define overload4(a,b,c,d,e,...) e\n#define overload5(a,b,c,d,e,f,...) f\n#define overload6(a,b,c,d,e,f,g,...) g\n//------------------------------------------------------------------------------\nusing ll = long long;\nusing db = long double;\nusing str = string;\nusing bl = bool;\n//------------------------------------------------------------------------------\n#define P pair\nusing pii = P<ll,ll>;\nusing pdd = P<db,db>;\n//------------------------------------------------------------------------------\n#define V vector\nusing vi = V<ll>; using vvi = V<vi>; using vvvi = V<vvi>; using vvvvi = V<vvvi>;\nusing vd = V<db>; using vvd = V<vd>;\nusing vc = V<char>; using vvc = V<vc>;\nusing vb = V<bl>; using vvb = V<vb>;\nusing vs = V<str>;\nusing vp = V<pii>; using vpd = V<pdd>;\n#define vvi1(v,h,w) vvi v(h,vi(w))\n#define vvi2(v,h,w,n) vvi v(h,vi(w,n))\n#define vvi(...) overload4(__VA_ARGS__,vvi2,vvi1)(__VA_ARGS__)\n#define vvd1(v,h,w) vvd v(h,vd(w))\n#define vvd2(v,h,w,n) vvd v(h,vd(w,n))\n#define vvd(...) overload4(__VA_ARGS__,vvd2,vvd1)(__VA_ARGS__)\n#define vvc1(v,h,w) vvc v(h,vc(w))\n#define vvc2(v,h,w,n) vvc v(h,vc(w,n))\n#define vvc(...) overload4(__VA_ARGS__,vvc2,vvc1)(__VA_ARGS__)\n#define vvb1(v,h,w) vvb v(h,vb(w))\n#define vvb2(v,h,w,n) vvb v(h,vb(w,n))\n#define vvb(...) overload4(__VA_ARGS__,vvb2,vvb1)(__VA_ARGS__)\n#define vvvi1(v,x,y,z) vvvi v(x,V<vi>(y,vi(z)))\n#define vvvi2(v,x,y,z,n) vvvi v(x,V<vi>(y,vi(z,n)))\n#define vvvi(...) overload5(__VA_ARGS__,vvvi2,vvvi1)(__VA_ARGS__)\n#define vvvvi1(v,w,x,y,z) vvvvi v(w,V<vvi>(x,V<vi>(y,vi(z))))\n#define vvvvi2(v,w,x,y,z,n) vvvvi v(w,V<vvi>(x,V<vi>(y,vi(z,n))))\n#define vvvvi(...) overload6(__VA_ARGS__,vvvvi2,vvvvi1)(__VA_ARGS__)\n#define vv1(T,v,h,w) V<V<T>> v(h,V<T>(w))\n#define vv2(T,v,h,w,n) V<V<T>> v(h,V<T>(w,n))\n#define vv(...) overload5(__VA_ARGS__,vv2,vv1)(__VA_ARGS__)\nusing graph = V<vi>;\nusing wgraph = V<vp>;\nusing wgraphd = V<V<P<ll,db>>>;\nTTTU using umap = unordered_map<T,U>;\nTTT using que = queue<T>;\nTTT using deq = deque<T>;\nTTT using pq = priority_queue<T,V<T>,greater<T>>; //昇順\nTTT using qp = priority_queue<T>; //降順\n//------------------------------------------------------------------------------\n#define fi first\n#define sc second\n#define mp make_pair\n#define en cout<<endl\n#define sq sqrt\n#define exit return 0\n#define si(v) ll(v.size())\n#define pb(v,n) v.push_back(n)\n#define pf(v,n) v.push_front(n)\n#define pp(v) v.pop_back()\n//------------------------------------------------------------------------------\n#define lp1(n) lp2(i,n)\n#define lp2(i,n) for(ll i=0;i<ll(n);i++)\n#define lp3(i,n,m) for(ll i=n;i<ll(m);i++)\n#define lp4(i,n,m,c) for(ll i=n;i<ll(m);i+=c)\n#define lp(...) overload4(__VA_ARGS__,lp4,lp3,lp2,lp1)(__VA_ARGS__)\n#define lp1_(n) lp(n+1)\n#define lp2_(i,n) lp(i,n+1)\n#define lp3_(i,n,m) lp(i,n,m+1)\n#define lp4_(i,n,m,c) lp(i,n,m+1,c)\n#define lp_(...) overload4(__VA_ARGS__,lp4_,lp3_,lp2_,lp1_)(__VA_ARGS__)\n#define pl1(n) pl2(i,n)\n#define pl2(i,n) for(ll i=n;i>=0;i--)\n#define pl3(i,n,m) for(ll i=n;i>=m;i--)\n#define pl4(i,n,m,c) for(ll i=n;i>=m:i-=c)\n#define pl(...) overload4(__VA_ARGS__,pl4,pl3,pl2,pl1)(__VA_ARGS__)\n#define lpv1(v) lp(si(v))\n#define lpv2(i,v) lp(i,si(v))\n#define lpv3(i,n,v) lp(i,n,si(v))\n#define lpv(...) overload3(__VA_ARGS__,lpv3,lpv2,lpv1)(__VA_ARGS__)\n#define comlp(i,j,n) lp(i,n-1)lp(j,i+1,n)\n#define lpa1(v) lpa2(i,v)\n#define lpa2(i,v) for(auto i:v)\n#define lpa(...) overload2(__VA_ARGS__,lpa2,lpa1)(__VA_ARGS__)\n#define lpm1(m) lpm2(i,m)\n#define lpm2(i,m) for(auto i=m.begin();i!=m.end();i++)\n#define lpm(...) overload2(__VA_ARGS__,lpm2,lpm1)(__VA_ARGS__)\n//------------------------------------------------------------------------------\nTTTU I P<T,U> operator+(const P<T,U> &x,const P<T,U> &y) {return P<T,U>(x.fi+y.fi,x.sc+y.sc);}\nTTTU I P<T,U> operator-(const P<T,U> &x,const P<T,U> &y) {return P<T,U>(x.fi-y.fi,x.sc-y.sc);}\nTTTU I P<T,U> operator+=(P<T,U> &x,const P<T,U> &y){return x=x+y;}\nTTTU I P<T,U> operator-=(P<T,U> &x,const P<T,U> &y){return x=x-y;}\nTTTU I db operator%(const P<T,U> &x,const P<T,U> &y) {return sq((x.fi-y.fi)*(x.fi-y.fi)+(x.sc-y.sc)*(x.sc-y.sc));}\nTTTU I istream&operator>>(istream &is,P<T,U> &x) {return is>>x.fi>>x.sc;}\nTTTU I ostream&operator<<(ostream &os,const P<T,U> &x) {return os<<x.fi<<\" \"<<x.sc;}\nTTT I istream&operator>>(istream &is,V<T> &v) {lpm(v)is>>*i;return is;}\nTTT I ostream&operator<<(ostream &os,const V<T> &v) {lpm(v){if(i!=v.begin())os<<\" \";os<<*i;}return os;}\nTTT I ostream&operator<<(ostream &os,const V<V<T>> &v){lpv(v){if(i>0)en;lpm(j,v[i]){if(j!=v[i].begin())os<<\" \";os<<*j;}}return os;}\nTTT I void operator>>(V<T> &v,const T x){pb(v,x);}\nTTT I void operator--(V<T> &v){pp(v);}\nTTT I void operator>>(set<T> &s,const T x){s.insert(x);}\nTTT I void operator<<(set<T> &s,const T x){s.erase(x);}\nTTT I void operator>>(stack<T> &s,const T x){s.push(x);}\nTTT I T operator--(stack<T> &s){T r=s.top();s.pop();return r;}\nTTT I void operator>>(que<T> &q,const T x){q.push(x);}\nTTT I T operator--(que<T> &q){T r=q.front();q.pop();return r;}\nTTT I void operator>>(pq<T> &q,const T x){q.push(x);}\nTTT I T operator--(pq<T> &q){T r=q.top();q.pop();return r;}\nTTT I void operator>>(qp<T> &q,const T x){q.push(x);}\nTTT I T operator--(qp<T> &q){T r=q.top();q.pop();return r;}\n//------------------------------------------------------------------------------\nTTTT I void in(T&... a) {(cin>>...>>a);}\nTTTTT I void print(const T& a,const Ts&... b) {cout<<a;(cout<<...<<(cout<<' ',b));en;}\nTTTTT I void print_(const T& a,const Ts&... b) {cout<<a;(cout<<...<<(cout<<' ',b));}\nTTTTT I void out(const T& a,const Ts&... b) {cout<<a;(cout<<...<<(en,b));en;}\nTTTU I void vini(V<T> &v,U n) {lpv(v) v[i]=n;}\nTTTU I void vini(V<V<T>> &v,U n) {lpv(v)lpv(j,v[0]) v[i][j]=n;}\nTTTU I void vini(V<V<V<T>>> &v,U n) {lpv(v)lpv(j,v[0])lpv(k,v[0][0]) v[i][j][k]=n;}\nTTTU I void vini(V<T> &v,ll x,U n) {v.assign(x,n);}\nTTTU I void vini(V<V<T>> &v,ll x,ll y,U n) {v.assign(x,V<T>(y,n));}\nTTTU I void vini(V<V<V<T>>> &v,ll x,ll y,ll z,U n) {v.assign(x,V<V<T>>(y,V<T>(z,n)));}\n#define LL(...) ll __VA_ARGS__; in(__VA_ARGS__)\n#define DB(...) db __VA_ARGS__; in(__VA_ARGS__)\n#define STR(...) str __VA_ARGS__; in(__VA_ARGS__)\n#define CHAR(...) char __VA_ARGS__; in(__VA_ARGS__)\n#define PII(...) pii __VA_ARGS__; in(__VA_ARGS__)\n#define PDD(...) pdd __VA_ARGS__; in(__VA_ARGS__)\n#define VI(v,n) vi v(n); in(v)\n#define VD(v,n) vd v(n); in(v)\n#define VP(v,n) vp v(n); in(v)\n#define VVI(v,h,w) vvi(v,h,w); in(v)\nI void gin(graph &g,ll m) {lp(m){LL(A,B); A--;B--;g[A]>>B;g[B]>>A;}}\nI void gin_(graph &g,ll m) {lp(m){LL(A,B); A--;B--;g[A]>>B;}}\nI void gin(wgraph &g,ll m) {lp(m){LL(A,B,C);A--;B--;g[A]>>mp(B,C);g[B]>>mp(A,C);}}\nI void gin_(wgraph &g,ll m) {lp(m){LL(A,B,C);A--;B--;g[A]>>mp(B,C);}}\nI void gin(wgraphd &g,ll m) {lp(m){LL(A,B);DB(C);A--;B--;g[A]>>mp(B,C);g[B]>>mp(A,C);}}\nI void gin_(wgraphd &g,ll m){lp(m){LL(A,B);DB(C);A--;B--;g[A]>>mp(B,C);}}\n#define cout(x) cout<<x<<endl\nTTT I void vout(V<T> &v) {lpv(v)cout(v[i]);}\n#ifdef ONLINE_JUDGE\n#define debug(...)\n#define debug_(q)\n#else\n#define debug(...) {print_(#__VA_ARGS__); cout<<\" : \"; print(__VA_ARGS__);}\n#define debug_(q) {cout<<#q<<\" : \";auto q_=q;while(!q_.empty())cout<<--q_<<\" \";en;}\n#endif\n//------------------------------------------------------------------------------\n#define all(v) (v).begin(),(v).end()\n#define lla(v) (v).rbegin(),(v).rend()\n#define SORT(v) sort(all(v))\n#define REVERSE(v) reverse(all(v))\n#define RESORT(v) sort(lla(v))\nTTT I T sum(V<T> &v) {T r=v[0];lpv(i,1,v) r+=v[i];return r;}\nTTT I T max(V<T> &v) {return *max_element(all(v));}\nTTT I T min(V<T> &v) {return *min_element(all(v));}\nTTTU I void ap(V<T> &v,U n) {lpv(v) v[i]+=n;}\nTTTU I void ap(V<P<T,T>> &v,U n,bl x=1,bl y=1){lpv(v){if(x)v[i].fi+=n;if(y)v[i].sc+=n;}}\nTTTU I void ap(V<V<T>> &v,U n) {lpv(v)lpv(j,v[0]) v[i][j]+=n;}\n#define bs(v,x) binary_search(all(v),x)\n#define lower lower_bound\n#define upper upper_bound\nTTTU I ll lb(T &v,U x) {return lower(all(v),x)-v.begin();} // a[i]<xとなるiの個数 / a[i]>=xとなる最初のi\nTTTU I ll ub(T &v,U x) {return upper(all(v),x)-v.begin();} // a[i]<=xとなるiの個数 / a[i]>xとなる最初のi\nTTTU I ll cou(T &v,U x){return count(all(v),x);}\nTTT I void uni(T &v) {SORT(v);v.erase(unique(all(v)),v.end());}\nTTT I vi compress(T &v){ll n=si(v);auto u=v;vi r(n);SORT(u);uni(u);lp(n)r[i]=lb(u,v[i]);return r;}\nTTT I vi compress_(T &v){ll p=-1,n=si(v);vi r;lp(n-1)if(v[i]!=v[i+1]){pb(r,i-p);p=i;}pb(r,n-1-p);return r;}\nTTT I V<T> acsum(V<T> &v){ll n=si(v);V<T> r(n+1);r[0]=0;lp(n)r[i+1]=r[i]+v[i];return r;}\n#define np(v) while(next_permutation(all(v)))\n//------------------------------------------------------------------------------\nconst ll MOD=1000000007;\n//const ll MOD=998244353;\nconst ll INF=(1LL<<60),FNI=-INF,MOOD=MOD*10,M=100005,M2=200005;\nconst db E=1e-10,PI=acos(-1);\nconst ll DX[8]={0,0,1,-1,1,1,-1,-1},DY[8]={1,-1,0,0,1,-1,1,-1};\nconst ll TEN[19]={1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000,100000000000,1000000000000,10000000000000,100000000000000,1000000000000000,10000000000000000,100000000000000000,1000000000000000000};\nconst ll ONE[19]={1,11,111,1111,11111,111111,1111111,11111111,111111111,1111111111,11111111111,111111111111,1111111111111,11111111111111,111111111111111,1111111111111111,11111111111111111,111111111111111111,1111111111111111111};\nconst ll COMAX=510000; // 変更\nll fac[COMAX],finv[COMAX],inv[COMAX];\nbl COMflag=0;\nTTTTT I T min(T a,T b,T c,Ts... x) {return min(a,min(b,c,x...));}\nTTTTT I T max(T a,T b,T c,Ts... x) {return max(a,max(b,c,x...));}\nI ll gcd(ll x,ll y) {if(x<0)x=-x;if(y<0)y=-y;return __gcd(x,y);}\nI ll lcm(ll x,ll y) {return x/gcd(x,y)*y;}\nTTTTT I T gcd(T a,T b,T c,Ts... x) {return gcd(a,gcd(b,c,x...));}\nTTTTT I T lcm(T a,T b,T c,Ts... x) {return lcm(a,lcm(b,c,x...));}\nI ll gcd(vi &v) {ll r=v[0];lpv(i,1,v)r=gcd(r,v[i]);return r;}\nI ll lcm(vi &v) {ll r=1;lpv(v)r=lcm(r,v[i]);return r;}\nI ll wa(ll x) {ll r=0;for(;x!=0;){r+=x%10;x/=10;}return r;}\nI ll keta(ll x) {ll r=0;while(x!=0){x/=10;r++;}return r;}\nI void comini(ll m) {COMflag=1;fac[0]=fac[1]=finv[0]=finv[1]=inv[1]=1;lp(i,2,COMAX){fac[i]=fac[i-1]*i%m;inv[i]=m-inv[m%i]*(m/i)%m;finv[i]=finv[i-1]*inv[i]%m;}}\nI ll com(ll n,ll k,ll m=MOD) {if(!COMflag)comini(m);if(n<0||k<0||n<k)return 0;return fac[n]*(finv[k]*finv[n-k]%m)%m;}\nI ll per(ll n,ll k,ll m=MOD) {if(!COMflag)comini(m);if(n<0||k<0||n<k)return 0;return fac[n]*finv[n-k]%m;}\nI ll nc2(ll n) {return n*(n-1)/2;}\nI ll rui(ll x,ll n,ll m=MOD) {x%=m;if(x==0)return 0;ll r=1;while(n>0){if(n&1)r=r*x%m;x=x*x%m;n>>=1;}return r;}\nI vi n_sin(ll x,ll n,bl re=0) {vi r;while(x!=0){pb(r,x%n);(x-=(x%n))/=n;}if(re)REVERSE(r);return r;}\nI ll kiri(ll a,ll b=2){return (a+b-1)/b;}\nI ll ma(ll a,ll b,ll m=MOD) {return (a+b)%m;}\nI ll ms(ll a,ll b,ll m=MOD) {return (a-b+m*10)%m;}\nI ll mm(ll a,ll b,ll m=MOD) {return a*b%m;}\nI ll md(ll a,ll b,ll m=MOD) {ll c=m,x=1,y=0;while(c){ll t=b/c;b-=t*c;swap(b,c);x-=t*y;swap(x,y);}x%=m;if(x<0)x+=m;return (a%m)*x%m;}\nI ll kai(ll n,ll k=-1,ll m=MOD) {ll r=1;if(k<0)k=n;lp(k)(r*=(n-i))%=m;return r;}\nI vi prime_b(ll x) {vi r;lp_(i,2,sq(x)){if(x%i!=0)continue;ll e=0;while(x%i==0){e++;x/=i;}pb(r,e);}if(x!=1)pb(r,1);return r;}\nI vi prime_p(ll x) {vi r;lp_(i,2,sq(x)){if(x%i!=0)continue;while(x%i==0)x/=i;pb(r,i);}if(x!=1)pb(r,x);return r;}\nI vp prime(ll x) {vp r;lp_(i,2,sq(x)){if(x%i!=0)continue;ll e=0;while(x%i==0){e++;x/=i;}pb(r,mp(i,e));}if(x!=1)pb(r,mp(x,1));return r;}\nI vi div(ll x) {vi r;lp_(i,1,sq(x)){if(x%i==0){pb(r,i);if(i*i!=x)pb(r,x/i);}}SORT(r);return r;}\nI ll DP(vi &v,ll s,ll m=MOD){ll n=si(v);vvi(dp,n+3,s+3,0);dp[0][0]=1;lp(i,n)lp_(j,s){(dp[i+1][j]+=dp[i][j])%=m;if(j>=v[i])(dp[i+1][j]+=dp[i][j-v[i]])%=m;}return dp[n][s];}\nI ll LIS(vi &a) {vi dp(si(a),INF);lpv(a){auto p=lower(all(dp),a[i]);*p=a[i];}return lb(dp,INF);}\nI vi Z(str s) {vi r(si(s));for(ll i=1,j=0;i<si(s);i++){if(i+r[i-j]<j+r[j])r[i]=r[i-j];else{ll k=max(0LL,j+r[j]-i);while(i+k<si(s)&&s[k]==s[i+k])k++;r[i]=k;j=i;}}r[0]=si(s);return r;}\nTTT I bl chmin(T&a,T b) {if(a>b){a=b;return 1;}return 0;}\nTTT I bl chmax(T&a,T b) {if(a<b){a=b;return 1;}return 0;}\nTTTU I bl eq(T a,U b) {return abs(a-b)<E;}\nTTT I T pos(T a) {return max(T(0),a);}\n#define Y cout(\"Yes\")\n#define N cout(\"No\")\n#define yn1(x) if(x){Y;}else N\n#define yn2(x,y) if(x){cout(y);exit;}\n#define yn3(x,y,n) if(x){cout(y);}else cout(n)\n#define yn(...) overload3(__VA_ARGS__,yn3,yn2,yn1)(__VA_ARGS__)\n\n//==============================================================================\n\n\n\nint main()\n{ X;\n LL(n,k);\n ll r=0;\n lp_(k)\n {\n if((k-i)%2==0) r=ma(r,com(k,i)*rui(i,n)%MOD);\n else r=ms(r,com(k,i)*rui(i,n)%MOD);\n }\n cout(r);\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 15400, "score_of_the_acc": -0.2451, "final_rank": 7 }, { "submission_id": "aoj_DPL_5_C_6023113", "code_snippet": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <cfloat>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_set>\n#include <vector>\n#pragma GCC target(\"avx2\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\nusing namespace std;\ntypedef long double ld;\ntypedef long long int ll;\ntypedef unsigned long long int ull;\ntypedef vector<int> vi;\ntypedef vector<char> vc;\ntypedef vector<bool> vb;\ntypedef vector<double> vd;\ntypedef vector<string> vs;\ntypedef vector<ll> vll;\ntypedef vector<pair<int, int>> vpii;\ntypedef vector<pair<ll, ll>> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\ntypedef vector<vc> vvc;\ntypedef vector<vs> vvs;\ntypedef vector<vll> vvll;\ntypedef pair<int, int> P;\ntypedef map<int, int> mii;\ntypedef set<int> si;\n#define rep(i, n) for (ll i = 0; i < (n); ++i)\n#define rrep(i, n) for (int i = 1; i <= (n); ++i)\n#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)\n#define drep(i, n) for (int i = (n)-1; i >= 0; --i)\n#define fin(ans) cout << (ans) << '\\n'\n#define STLL(s) strtoll(s.c_str(), NULL, 10)\n#define mp(p, q) make_pair(p, q)\n#define pb(n) push_back(n)\n#define all(a) a.begin(), a.end()\n#define Sort(a) sort(a.begin(), a.end())\n#define Rort(a) sort(a.rbegin(), a.rend())\n#define fi first\n#define se second\n// #include <atcoder/all>\n// using namespace atcoder;\nconstexpr int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};\nconstexpr int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};\ntemplate <class T, class U>\ninline bool chmax(T& a, U b) {\n if (a < b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\ninline bool chmin(T& a, U b) {\n if (a > b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\nostream& operator<<(ostream& os, pair<T, U>& p) {\n cout << \"(\" << p.first << \", \" << p.second << \")\";\n return os;\n}\ntemplate <class T>\ninline void dump(T& v) {\n irep(i, v) { cout << (*i) << ((i == --v.end()) ? '\\n' : ' '); }\n}\ntemplate <class T, class U>\ninline void dump(map<T, U>& v) {\n if (v.size() > 100) {\n cout << \"ARRAY IS TOO LARGE!!!\" << endl;\n } else {\n irep(i, v) { cout << i->first << \" \" << i->second << '\\n'; }\n }\n}\ntemplate <class T, class U>\ninline void dump(pair<T, U>& p) {\n cout << p.first << \" \" << p.second << '\\n';\n}\ninline void yn(const bool b) { b ? fin(\"yes\") : fin(\"no\"); }\ninline void Yn(const bool b) { b ? fin(\"Yes\") : fin(\"No\"); }\ninline void YN(const bool b) { b ? fin(\"YES\") : fin(\"NO\"); }\nvoid Case(int i) { printf(\"Case #%d: \", i); }\nconst int INF = INT_MAX;\nconstexpr ll LLINF = 1LL << 61;\nconstexpr ld EPS = 1e-11;\n#define MODTYPE 0\n#if MODTYPE == 0\nconstexpr ll MOD = 1000000007;\n#else\nconstexpr ll MOD = 998244353;\n#endif\n/* -------------------- ここまでテンプレ -------------------- */\n\nstruct mint {\n ll x;\n mint(ll _x = 0) : x((_x % MOD + MOD) % MOD) {}\n\n /* 初期化子 */\n mint operator+() const { return mint(x); }\n mint operator-() const { return mint(-x); }\n\n /* 代入演算子 */\n mint& operator+=(const mint a) {\n if ((x += a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator-=(const mint a) {\n if ((x += MOD - a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator*=(const mint a) {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint& operator/=(const mint a) {\n x *= modinv(a).x;\n x %= MOD;\n return (*this);\n }\n mint& operator%=(const mint a) {\n x %= a.x;\n return (*this);\n }\n mint& operator++() {\n ++x;\n if (x >= MOD) x -= MOD;\n return *this;\n }\n mint& operator--() {\n if (!x) x += MOD;\n --x;\n return *this;\n }\n mint& operator&=(const mint a) {\n x &= a.x;\n return (*this);\n }\n mint& operator|=(const mint a) {\n x |= a.x;\n return (*this);\n }\n mint& operator^=(const mint a) {\n x ^= a.x;\n return (*this);\n }\n mint& operator<<=(const mint a) {\n x *= pow(2, a).x;\n return (*this);\n }\n mint& operator>>=(const mint a) {\n x /= pow(2, a).x;\n return (*this);\n }\n\n /* 算術演算子 */\n mint operator+(const mint a) const {\n mint res(*this);\n return res += a;\n }\n mint operator-(const mint a) const {\n mint res(*this);\n return res -= a;\n }\n mint operator*(const mint a) const {\n mint res(*this);\n return res *= a;\n }\n mint operator/(const mint a) const {\n mint res(*this);\n return res /= a;\n }\n mint operator%(const mint a) const {\n mint res(*this);\n return res %= a;\n }\n mint operator&(const mint a) const {\n mint res(*this);\n return res &= a;\n }\n mint operator|(const mint a) const {\n mint res(*this);\n return res |= a;\n }\n mint operator^(const mint a) const {\n mint res(*this);\n return res ^= a;\n }\n mint operator<<(const mint a) const {\n mint res(*this);\n return res <<= a;\n }\n mint operator>>(const mint a) const {\n mint res(*this);\n return res >>= a;\n }\n\n /* 条件演算子 */\n bool operator==(const mint a) const noexcept { return x == a.x; }\n bool operator!=(const mint a) const noexcept { return x != a.x; }\n bool operator<(const mint a) const noexcept { return x < a.x; }\n bool operator>(const mint a) const noexcept { return x > a.x; }\n bool operator<=(const mint a) const noexcept { return x <= a.x; }\n bool operator>=(const mint a) const noexcept { return x >= a.x; }\n\n /* ストリーム挿入演算子 */\n friend istream& operator>>(istream& is, mint& m) {\n is >> m.x;\n m.x = (m.x % MOD + MOD) % MOD;\n return is;\n }\n friend ostream& operator<<(ostream& os, const mint& m) {\n os << m.x;\n return os;\n }\n\n /* その他の関数 */\n mint modinv(mint a) { return pow(a, MOD - 2); }\n mint pow(mint x, mint n) {\n mint res = 1;\n while (n.x > 0) {\n if ((n % 2).x) res *= x;\n x *= x;\n n.x /= 2;\n }\n return res;\n }\n mint powll(mint x, ll n) {\n mint res = 1;\n while (n > 0) {\n if (n % 2) res *= x;\n x *= x;\n n /= 2;\n }\n return res;\n }\n};\n\n// modint呼ぶ!!!\n\nclass Counting {\n struct pre_calculation {\n bool factorial;\n bool partition;\n bool combination;\n };\n pre_calculation pre_calc;\n\n vector<mint> Factorial;\n void factorial_precalc(const int MAX = 301010) {\n Factorial = vector<mint>(MAX, 1);\n for (int i = 1; i < MAX; i++) {\n Factorial[i] = Factorial[i - 1] * i;\n }\n }\n\n vector<mint> FactorialInv;\n void nCk_precalc(const int MAX = 301010) {\n if (!pre_calc.factorial) {\n factorial_precalc();\n }\n FactorialInv = vector<mint>(MAX, 1);\n for (int i = 1; i < MAX; i++) {\n FactorialInv[i] = mint(1).pow(Factorial[i], MOD - 2);\n }\n }\n\n vector<vector<mint>> Partition;\n void partition_precalc(const int MAX = 2000) {\n Partition = vector<vector<mint>>(MAX, vector<mint>(MAX, 0));\n for (int k = 0; k < MAX; k++) {\n Partition[0][k] = 1;\n }\n for (int n = 1; n < MAX; n++) {\n for (int k = 1; k < MAX; k++) {\n Partition[n][k] = Partition[n][k - 1];\n if (n - k >= 0) {\n Partition[n][k] += Partition[n - k][k];\n }\n }\n }\n }\n\n public:\n Counting(void) {\n pre_calc.factorial = false;\n pre_calc.partition = false;\n pre_calc.combination = false;\n };\n\n // 階乗 n! を計算\n mint factorial(const mint n) {\n if (!pre_calc.factorial) {\n factorial_precalc();\n pre_calc.factorial = true;\n }\n return Factorial[n.x];\n }\n\n // 二項係数 nCk を計算\n mint nCk(const mint n, const mint k) {\n if (n < k) {\n return 0;\n }\n if (!pre_calc.combination) {\n nCk_precalc();\n pre_calc.combination = true;\n }\n mint nl = Factorial[n.x]; // n!\n mint nkl = FactorialInv[n.x - k.x]; // (n-k)!\n mint kl = FactorialInv[k.x]; // k!\n mint nkk = (nkl.x * kl.x);\n return nl * nkk;\n }\n\n // 順列 nPk を計算\n mint nPk(mint n, mint k) {\n if (n < k) {\n return 0;\n }\n if (!pre_calc.factorial) {\n factorial_precalc();\n pre_calc.factorial = true;\n }\n return Factorial[n.x] / Factorial[n.x - k.x];\n }\n\n // 包除原理 \\sum_{i=0}^k (-1)^{k-i} kCi i^n\n mint inclusion_exclusion(const mint n, const mint k) {\n if (!pre_calc.combination) {\n nCk_precalc();\n pre_calc.combination = true;\n }\n mint ans = 0;\n for (int i = 0; i <= k.x; i++) {\n ans += mint(1).pow(-1, k-i) * nCk(k, i) * mint(0).pow(i, n);\n }\n return ans;\n }\n\n // 分割数 P(n, k) を計算\n mint partition(const mint n, const mint k) {\n if (!pre_calc.partition) {\n partition_precalc();\n pre_calc.partition = true;\n }\n return Partition[n.x][k.x];\n }\n};\n\nint main() {\n int n, k;\n cin >> n >> k;\n Counting cnt;\n cout << cnt.inclusion_exclusion(n, k) << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7856, "score_of_the_acc": -0.1067, "final_rank": 3 }, { "submission_id": "aoj_DPL_5_C_6023106", "code_snippet": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <cfloat>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_set>\n#include <vector>\n#pragma GCC target(\"avx2\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\nusing namespace std;\ntypedef long double ld;\ntypedef long long int ll;\ntypedef unsigned long long int ull;\ntypedef vector<int> vi;\ntypedef vector<char> vc;\ntypedef vector<bool> vb;\ntypedef vector<double> vd;\ntypedef vector<string> vs;\ntypedef vector<ll> vll;\ntypedef vector<pair<int, int>> vpii;\ntypedef vector<pair<ll, ll>> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\ntypedef vector<vc> vvc;\ntypedef vector<vs> vvs;\ntypedef vector<vll> vvll;\ntypedef pair<int, int> P;\ntypedef map<int, int> mii;\ntypedef set<int> si;\n#define rep(i, n) for (ll i = 0; i < (n); ++i)\n#define rrep(i, n) for (int i = 1; i <= (n); ++i)\n#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)\n#define drep(i, n) for (int i = (n)-1; i >= 0; --i)\n#define fin(ans) cout << (ans) << '\\n'\n#define STLL(s) strtoll(s.c_str(), NULL, 10)\n#define mp(p, q) make_pair(p, q)\n#define pb(n) push_back(n)\n#define all(a) a.begin(), a.end()\n#define Sort(a) sort(a.begin(), a.end())\n#define Rort(a) sort(a.rbegin(), a.rend())\n#define fi first\n#define se second\n// #include <atcoder/all>\n// using namespace atcoder;\nconstexpr int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};\nconstexpr int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};\ntemplate <class T, class U>\ninline bool chmax(T& a, U b) {\n if (a < b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\ninline bool chmin(T& a, U b) {\n if (a > b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\nostream& operator<<(ostream& os, pair<T, U>& p) {\n cout << \"(\" << p.first << \", \" << p.second << \")\";\n return os;\n}\ntemplate <class T>\ninline void dump(T& v) {\n irep(i, v) { cout << (*i) << ((i == --v.end()) ? '\\n' : ' '); }\n}\ntemplate <class T, class U>\ninline void dump(map<T, U>& v) {\n if (v.size() > 100) {\n cout << \"ARRAY IS TOO LARGE!!!\" << endl;\n } else {\n irep(i, v) { cout << i->first << \" \" << i->second << '\\n'; }\n }\n}\ntemplate <class T, class U>\ninline void dump(pair<T, U>& p) {\n cout << p.first << \" \" << p.second << '\\n';\n}\ninline void yn(const bool b) { b ? fin(\"yes\") : fin(\"no\"); }\ninline void Yn(const bool b) { b ? fin(\"Yes\") : fin(\"No\"); }\ninline void YN(const bool b) { b ? fin(\"YES\") : fin(\"NO\"); }\nvoid Case(int i) { printf(\"Case #%d: \", i); }\nconst int INF = INT_MAX;\nconstexpr ll LLINF = 1LL << 61;\nconstexpr ld EPS = 1e-11;\n#define MODTYPE 0\n#if MODTYPE == 0\nconstexpr ll MOD = 1000000007;\n#else\nconstexpr ll MOD = 998244353;\n#endif\n/* -------------------- ここまでテンプレ -------------------- */\n\nstruct mint {\n ll x;\n mint(ll _x = 0) : x((_x % MOD + MOD) % MOD) {}\n\n /* 初期化子 */\n mint operator+() const { return mint(x); }\n mint operator-() const { return mint(-x); }\n\n /* 代入演算子 */\n mint& operator+=(const mint a) {\n if ((x += a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator-=(const mint a) {\n if ((x += MOD - a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator*=(const mint a) {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint& operator/=(const mint a) {\n x *= modinv(a).x;\n x %= MOD;\n return (*this);\n }\n mint& operator%=(const mint a) {\n x %= a.x;\n return (*this);\n }\n mint& operator++() {\n ++x;\n if (x >= MOD) x -= MOD;\n return *this;\n }\n mint& operator--() {\n if (!x) x += MOD;\n --x;\n return *this;\n }\n mint& operator&=(const mint a) {\n x &= a.x;\n return (*this);\n }\n mint& operator|=(const mint a) {\n x |= a.x;\n return (*this);\n }\n mint& operator^=(const mint a) {\n x ^= a.x;\n return (*this);\n }\n mint& operator<<=(const mint a) {\n x *= pow(2, a).x;\n return (*this);\n }\n mint& operator>>=(const mint a) {\n x /= pow(2, a).x;\n return (*this);\n }\n\n /* 算術演算子 */\n mint operator+(const mint a) const {\n mint res(*this);\n return res += a;\n }\n mint operator-(const mint a) const {\n mint res(*this);\n return res -= a;\n }\n mint operator*(const mint a) const {\n mint res(*this);\n return res *= a;\n }\n mint operator/(const mint a) const {\n mint res(*this);\n return res /= a;\n }\n mint operator%(const mint a) const {\n mint res(*this);\n return res %= a;\n }\n mint operator&(const mint a) const {\n mint res(*this);\n return res &= a;\n }\n mint operator|(const mint a) const {\n mint res(*this);\n return res |= a;\n }\n mint operator^(const mint a) const {\n mint res(*this);\n return res ^= a;\n }\n mint operator<<(const mint a) const {\n mint res(*this);\n return res <<= a;\n }\n mint operator>>(const mint a) const {\n mint res(*this);\n return res >>= a;\n }\n\n /* 条件演算子 */\n bool operator==(const mint a) const noexcept { return x == a.x; }\n bool operator!=(const mint a) const noexcept { return x != a.x; }\n bool operator<(const mint a) const noexcept { return x < a.x; }\n bool operator>(const mint a) const noexcept { return x > a.x; }\n bool operator<=(const mint a) const noexcept { return x <= a.x; }\n bool operator>=(const mint a) const noexcept { return x >= a.x; }\n\n /* ストリーム挿入演算子 */\n friend istream& operator>>(istream& is, mint& m) {\n is >> m.x;\n m.x = (m.x % MOD + MOD) % MOD;\n return is;\n }\n friend ostream& operator<<(ostream& os, const mint& m) {\n os << m.x;\n return os;\n }\n\n /* その他の関数 */\n mint modinv(mint a) { return pow(a, MOD - 2); }\n mint pow(mint x, mint n) {\n mint res = 1;\n while (n.x > 0) {\n if ((n % 2).x) res *= x;\n x *= x;\n n.x /= 2;\n }\n return res;\n }\n mint powll(mint x, ll n) {\n mint res = 1;\n while (n > 0) {\n if (n % 2) res *= x;\n x *= x;\n n /= 2;\n }\n return res;\n }\n};\n\n// modint呼ぶ!!!\n\nclass Counting {\n struct pre_calculation {\n bool factorial;\n bool partition;\n bool combination;\n };\n pre_calculation pre_calc;\n\n vector<mint> Factorial;\n void factorial_precalc(const int MAX = 301010) {\n Factorial = vector<mint>(MAX, 1);\n for (int i = 1; i < MAX; i++) {\n Factorial[i] = Factorial[i - 1] * i;\n }\n }\n\n vector<mint> FactorialInv;\n void nCk_precalc(const int MAX = 301010) {\n if (!pre_calc.factorial) {\n factorial_precalc();\n }\n FactorialInv = vector<mint>(MAX, 1);\n for (int i = 1; i < MAX; i++) {\n FactorialInv[i] = mint(1).pow(Factorial[i], MOD - 2);\n }\n }\n\n vector<vector<mint>> Partition;\n void partition_precalc(const int MAX = 2000) {\n Partition = vector<vector<mint>>(MAX, vector<mint>(MAX, 0));\n for (int k = 0; k < MAX; k++) {\n Partition[0][k] = 1;\n }\n for (int n = 1; n < MAX; n++) {\n for (int k = 1; k < MAX; k++) {\n Partition[n][k] = Partition[n][k - 1];\n if (n - k >= 0) {\n Partition[n][k] += Partition[n - k][k];\n }\n }\n }\n }\n\n public:\n Counting(void) {\n pre_calc.factorial = false;\n pre_calc.partition = false;\n pre_calc.combination = false;\n };\n\n // 階乗 n! を計算\n mint factorial(const mint n) {\n if (!pre_calc.factorial) {\n factorial_precalc();\n pre_calc.factorial = true;\n }\n return Factorial[n.x];\n }\n\n // 二項係数 nCk を計算\n mint nCk(const mint n, const mint k) {\n if (n < k) {\n return 0;\n }\n if (!pre_calc.combination) {\n nCk_precalc();\n pre_calc.combination = true;\n }\n mint nl = Factorial[n.x]; // n!\n mint nkl = FactorialInv[n.x - k.x]; // (n-k)!\n mint kl = FactorialInv[k.x]; // k!\n mint nkk = (nkl.x * kl.x);\n return nl * nkk;\n }\n\n // 順列 nPk を計算\n mint nPk(mint n, mint k) {\n if (n < k) {\n return 0;\n }\n if (!pre_calc.factorial) {\n factorial_precalc();\n pre_calc.factorial = true;\n }\n return Factorial[n.x] / Factorial[n.x - k.x];\n }\n\n // 包除原理\n mint inclusion_exclusion(const mint n, const mint k) {\n if (!pre_calc.combination) {\n nCk_precalc();\n pre_calc.combination = true;\n }\n mint ans = 0;\n for (int i = 0; i <= k.x; i++) {\n if ((k.x & 1) == (i & 1)) {\n ans += nCk(k, i) * mint(0).pow(i, n);\n } else {\n ans -= nCk(k, i) * mint(0).pow(i, n);\n }\n }\n // for (int i = 0; i <= k.x; i++) {\n // ans += mint(1).pow(-1, i) * nCk(k, i) * mint(0).pow(k - i, n);\n // }\n return ans;\n }\n\n // 分割数 P(n, k) を計算\n mint partition(const mint n, const mint k) {\n if (!pre_calc.partition) {\n partition_precalc();\n pre_calc.partition = true;\n }\n return Partition[n.x][k.x];\n }\n};\n\nint main() {\n int n, k;\n cin >> n >> k;\n Counting cnt;\n cout << cnt.inclusion_exclusion(n, k) << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7860, "score_of_the_acc": -0.1068, "final_rank": 5 }, { "submission_id": "aoj_DPL_5_C_6023105", "code_snippet": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <cfloat>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_set>\n#include <vector>\n#pragma GCC target(\"avx2\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\nusing namespace std;\ntypedef long double ld;\ntypedef long long int ll;\ntypedef unsigned long long int ull;\ntypedef vector<int> vi;\ntypedef vector<char> vc;\ntypedef vector<bool> vb;\ntypedef vector<double> vd;\ntypedef vector<string> vs;\ntypedef vector<ll> vll;\ntypedef vector<pair<int, int>> vpii;\ntypedef vector<pair<ll, ll>> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\ntypedef vector<vc> vvc;\ntypedef vector<vs> vvs;\ntypedef vector<vll> vvll;\ntypedef pair<int, int> P;\ntypedef map<int, int> mii;\ntypedef set<int> si;\n#define rep(i, n) for (ll i = 0; i < (n); ++i)\n#define rrep(i, n) for (int i = 1; i <= (n); ++i)\n#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)\n#define drep(i, n) for (int i = (n)-1; i >= 0; --i)\n#define fin(ans) cout << (ans) << '\\n'\n#define STLL(s) strtoll(s.c_str(), NULL, 10)\n#define mp(p, q) make_pair(p, q)\n#define pb(n) push_back(n)\n#define all(a) a.begin(), a.end()\n#define Sort(a) sort(a.begin(), a.end())\n#define Rort(a) sort(a.rbegin(), a.rend())\n#define fi first\n#define se second\n// #include <atcoder/all>\n// using namespace atcoder;\nconstexpr int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};\nconstexpr int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};\ntemplate <class T, class U>\ninline bool chmax(T& a, U b) {\n if (a < b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\ninline bool chmin(T& a, U b) {\n if (a > b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\nostream& operator<<(ostream& os, pair<T, U>& p) {\n cout << \"(\" << p.first << \", \" << p.second << \")\";\n return os;\n}\ntemplate <class T>\ninline void dump(T& v) {\n irep(i, v) { cout << (*i) << ((i == --v.end()) ? '\\n' : ' '); }\n}\ntemplate <class T, class U>\ninline void dump(map<T, U>& v) {\n if (v.size() > 100) {\n cout << \"ARRAY IS TOO LARGE!!!\" << endl;\n } else {\n irep(i, v) { cout << i->first << \" \" << i->second << '\\n'; }\n }\n}\ntemplate <class T, class U>\ninline void dump(pair<T, U>& p) {\n cout << p.first << \" \" << p.second << '\\n';\n}\ninline void yn(const bool b) { b ? fin(\"yes\") : fin(\"no\"); }\ninline void Yn(const bool b) { b ? fin(\"Yes\") : fin(\"No\"); }\ninline void YN(const bool b) { b ? fin(\"YES\") : fin(\"NO\"); }\nvoid Case(int i) { printf(\"Case #%d: \", i); }\nconst int INF = INT_MAX;\nconstexpr ll LLINF = 1LL << 61;\nconstexpr ld EPS = 1e-11;\n#define MODTYPE 0\n#if MODTYPE == 0\nconstexpr ll MOD = 1000000007;\n#else\nconstexpr ll MOD = 998244353;\n#endif\n/* -------------------- ここまでテンプレ -------------------- */\n\nstruct mint {\n ll x;\n mint(ll _x = 0) : x((_x % MOD + MOD) % MOD) {}\n\n /* 初期化子 */\n mint operator+() const { return mint(x); }\n mint operator-() const { return mint(-x); }\n\n /* 代入演算子 */\n mint& operator+=(const mint a) {\n if ((x += a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator-=(const mint a) {\n if ((x += MOD - a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator*=(const mint a) {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint& operator/=(const mint a) {\n x *= modinv(a).x;\n x %= MOD;\n return (*this);\n }\n mint& operator%=(const mint a) {\n x %= a.x;\n return (*this);\n }\n mint& operator++() {\n ++x;\n if (x >= MOD) x -= MOD;\n return *this;\n }\n mint& operator--() {\n if (!x) x += MOD;\n --x;\n return *this;\n }\n mint& operator&=(const mint a) {\n x &= a.x;\n return (*this);\n }\n mint& operator|=(const mint a) {\n x |= a.x;\n return (*this);\n }\n mint& operator^=(const mint a) {\n x ^= a.x;\n return (*this);\n }\n mint& operator<<=(const mint a) {\n x *= pow(2, a).x;\n return (*this);\n }\n mint& operator>>=(const mint a) {\n x /= pow(2, a).x;\n return (*this);\n }\n\n /* 算術演算子 */\n mint operator+(const mint a) const {\n mint res(*this);\n return res += a;\n }\n mint operator-(const mint a) const {\n mint res(*this);\n return res -= a;\n }\n mint operator*(const mint a) const {\n mint res(*this);\n return res *= a;\n }\n mint operator/(const mint a) const {\n mint res(*this);\n return res /= a;\n }\n mint operator%(const mint a) const {\n mint res(*this);\n return res %= a;\n }\n mint operator&(const mint a) const {\n mint res(*this);\n return res &= a;\n }\n mint operator|(const mint a) const {\n mint res(*this);\n return res |= a;\n }\n mint operator^(const mint a) const {\n mint res(*this);\n return res ^= a;\n }\n mint operator<<(const mint a) const {\n mint res(*this);\n return res <<= a;\n }\n mint operator>>(const mint a) const {\n mint res(*this);\n return res >>= a;\n }\n\n /* 条件演算子 */\n bool operator==(const mint a) const noexcept { return x == a.x; }\n bool operator!=(const mint a) const noexcept { return x != a.x; }\n bool operator<(const mint a) const noexcept { return x < a.x; }\n bool operator>(const mint a) const noexcept { return x > a.x; }\n bool operator<=(const mint a) const noexcept { return x <= a.x; }\n bool operator>=(const mint a) const noexcept { return x >= a.x; }\n\n /* ストリーム挿入演算子 */\n friend istream& operator>>(istream& is, mint& m) {\n is >> m.x;\n m.x = (m.x % MOD + MOD) % MOD;\n return is;\n }\n friend ostream& operator<<(ostream& os, const mint& m) {\n os << m.x;\n return os;\n }\n\n /* その他の関数 */\n mint modinv(mint a) { return pow(a, MOD - 2); }\n mint pow(mint x, mint n) {\n mint res = 1;\n while (n.x > 0) {\n if ((n % 2).x) res *= x;\n x *= x;\n n.x /= 2;\n }\n return res;\n }\n mint powll(mint x, ll n) {\n mint res = 1;\n while (n > 0) {\n if (n % 2) res *= x;\n x *= x;\n n /= 2;\n }\n return res;\n }\n};\n\n// modint呼ぶ!!!\n\nclass Counting {\n struct pre_calculation {\n bool factorial;\n bool partition;\n bool combination;\n };\n pre_calculation pre_calc;\n\n vector<mint> Factorial;\n void factorial_precalc(const int MAX = 301010) {\n Factorial = vector<mint>(MAX, 1);\n for (int i = 1; i < MAX; i++) {\n Factorial[i] = Factorial[i - 1] * i;\n }\n }\n\n vector<mint> FactorialInv;\n void nCk_precalc(const int MAX = 301010) {\n if (!pre_calc.factorial) {\n factorial_precalc();\n }\n FactorialInv = vector<mint>(MAX, 1);\n for (int i = 1; i < MAX; i++) {\n FactorialInv[i] = mint(1).pow(Factorial[i], MOD - 2);\n }\n }\n\n vector<vector<mint>> Partition;\n void partition_precalc(const int MAX = 2000) {\n Partition = vector<vector<mint>>(MAX, vector<mint>(MAX, 0));\n for (int k = 0; k < MAX; k++) {\n Partition[0][k] = 1;\n }\n for (int n = 1; n < MAX; n++) {\n for (int k = 1; k < MAX; k++) {\n Partition[n][k] = Partition[n][k - 1];\n if (n - k >= 0) {\n Partition[n][k] += Partition[n - k][k];\n }\n }\n }\n }\n\n public:\n Counting(void) {\n pre_calc.factorial = false;\n pre_calc.partition = false;\n pre_calc.combination = false;\n };\n\n // 階乗 n! を計算\n mint factorial(const mint n) {\n if (!pre_calc.factorial) {\n factorial_precalc();\n pre_calc.factorial = true;\n }\n return Factorial[n.x];\n }\n\n // 二項係数 nCk を計算\n mint nCk(const mint n, const mint k) {\n if (n < k) {\n return 0;\n }\n if (!pre_calc.combination) {\n nCk_precalc();\n pre_calc.combination = true;\n }\n mint nl = Factorial[n.x]; // n!\n mint nkl = FactorialInv[n.x - k.x]; // (n-k)!\n mint kl = FactorialInv[k.x]; // k!\n mint nkk = (nkl.x * kl.x);\n return nl * nkk;\n }\n\n // 順列 nPk を計算\n mint nPk(mint n, mint k) {\n if (n < k) {\n return 0;\n }\n if (!pre_calc.factorial) {\n factorial_precalc();\n pre_calc.factorial = true;\n }\n return Factorial[n.x] / Factorial[n.x - k.x];\n }\n\n // 包除原理\n mint inclusion_exclusion(const mint n, const mint k) {\n if (!pre_calc.combination) {\n nCk_precalc();\n pre_calc.combination = true;\n }\n mint ans = 0;\n // for (int i = 0; i <= k.x; i++) {\n // if ((k.x & 1) == (i & 1)) {\n // ans += nCk(k, i) * mint(0).pow(i, n);\n // } else {\n // ans -= nCk(k, i) * mint(0).pow(i, n);\n // }\n // }\n for (int i = 0; i <= k.x; i++) {\n ans += mint(1).pow(-1, i) * nCk(k, i) * mint(0).pow(k - i, n);\n }\n return ans;\n }\n\n // 分割数 P(n, k) を計算\n mint partition(const mint n, const mint k) {\n if (!pre_calc.partition) {\n partition_precalc();\n pre_calc.partition = true;\n }\n return Partition[n.x][k.x];\n }\n};\n\nint main() {\n int n, k;\n cin >> n >> k;\n Counting cnt;\n cout << cnt.inclusion_exclusion(n, k) << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7856, "score_of_the_acc": -0.1067, "final_rank": 3 }, { "submission_id": "aoj_DPL_5_C_6022761", "code_snippet": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <cfloat>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_set>\n#include <vector>\n#pragma GCC target(\"avx2\")\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\nusing namespace std;\ntypedef long double ld;\ntypedef long long int ll;\ntypedef unsigned long long int ull;\ntypedef vector<int> vi;\ntypedef vector<char> vc;\ntypedef vector<bool> vb;\ntypedef vector<double> vd;\ntypedef vector<string> vs;\ntypedef vector<ll> vll;\ntypedef vector<pair<int, int>> vpii;\ntypedef vector<pair<ll, ll>> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vvi> vvvi;\ntypedef vector<vc> vvc;\ntypedef vector<vs> vvs;\ntypedef vector<vll> vvll;\ntypedef pair<int, int> P;\ntypedef map<int, int> mii;\ntypedef set<int> si;\n#define rep(i, n) for (ll i = 0; i < (n); ++i)\n#define rrep(i, n) for (int i = 1; i <= (n); ++i)\n#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)\n#define drep(i, n) for (int i = (n)-1; i >= 0; --i)\n#define fin(ans) cout << (ans) << '\\n'\n#define STLL(s) strtoll(s.c_str(), NULL, 10)\n#define mp(p, q) make_pair(p, q)\n#define pb(n) push_back(n)\n#define all(a) a.begin(), a.end()\n#define Sort(a) sort(a.begin(), a.end())\n#define Rort(a) sort(a.rbegin(), a.rend())\n#define fi first\n#define se second\n// #include <atcoder/all>\n// using namespace atcoder;\nconstexpr int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};\nconstexpr int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};\ntemplate <class T, class U>\ninline bool chmax(T& a, U b) {\n if (a < b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\ninline bool chmin(T& a, U b) {\n if (a > b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T, class U>\nostream& operator<<(ostream& os, pair<T, U>& p) {\n cout << \"(\" << p.first << \", \" << p.second << \")\";\n return os;\n}\ntemplate <class T>\ninline void dump(T& v) {\n irep(i, v) { cout << (*i) << ((i == --v.end()) ? '\\n' : ' '); }\n}\ntemplate <class T, class U>\ninline void dump(map<T, U>& v) {\n if (v.size() > 100) {\n cout << \"ARRAY IS TOO LARGE!!!\" << endl;\n } else {\n irep(i, v) { cout << i->first << \" \" << i->second << '\\n'; }\n }\n}\ntemplate <class T, class U>\ninline void dump(pair<T, U>& p) {\n cout << p.first << \" \" << p.second << '\\n';\n}\ninline void yn(const bool b) { b ? fin(\"yes\") : fin(\"no\"); }\ninline void Yn(const bool b) { b ? fin(\"Yes\") : fin(\"No\"); }\ninline void YN(const bool b) { b ? fin(\"YES\") : fin(\"NO\"); }\nvoid Case(int i) { printf(\"Case #%d: \", i); }\nconst int INF = INT_MAX;\nconstexpr ll LLINF = 1LL << 61;\nconstexpr ld EPS = 1e-11;\n#define MODTYPE 0\n#if MODTYPE == 0\nconstexpr ll MOD = 1000000007;\n#else\nconstexpr ll MOD = 998244353;\n#endif\n/* -------------------- ここまでテンプレ -------------------- */\n\nstruct mint {\n ll x;\n mint(ll _x = 0) : x((_x % MOD + MOD) % MOD) {}\n\n /* 初期化子 */\n mint operator+() const { return mint(x); }\n mint operator-() const { return mint(-x); }\n\n /* 代入演算子 */\n mint& operator+=(const mint a) {\n if ((x += a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator-=(const mint a) {\n if ((x += MOD - a.x) >= MOD) x -= MOD;\n return *this;\n }\n mint& operator*=(const mint a) {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint& operator/=(const mint a) {\n x *= modinv(a).x;\n x %= MOD;\n return (*this);\n }\n mint& operator%=(const mint a) {\n x %= a.x;\n return (*this);\n }\n mint& operator++() {\n ++x;\n if (x >= MOD) x -= MOD;\n return *this;\n }\n mint& operator--() {\n if (!x) x += MOD;\n --x;\n return *this;\n }\n mint& operator&=(const mint a) {\n x &= a.x;\n return (*this);\n }\n mint& operator|=(const mint a) {\n x |= a.x;\n return (*this);\n }\n mint& operator^=(const mint a) {\n x ^= a.x;\n return (*this);\n }\n mint& operator<<=(const mint a) {\n x *= pow(2, a).x;\n return (*this);\n }\n mint& operator>>=(const mint a) {\n x /= pow(2, a).x;\n return (*this);\n }\n\n /* 算術演算子 */\n mint operator+(const mint a) const {\n mint res(*this);\n return res += a;\n }\n mint operator-(const mint a) const {\n mint res(*this);\n return res -= a;\n }\n mint operator*(const mint a) const {\n mint res(*this);\n return res *= a;\n }\n mint operator/(const mint a) const {\n mint res(*this);\n return res /= a;\n }\n mint operator%(const mint a) const {\n mint res(*this);\n return res %= a;\n }\n mint operator&(const mint a) const {\n mint res(*this);\n return res &= a;\n }\n mint operator|(const mint a) const {\n mint res(*this);\n return res |= a;\n }\n mint operator^(const mint a) const {\n mint res(*this);\n return res ^= a;\n }\n mint operator<<(const mint a) const {\n mint res(*this);\n return res <<= a;\n }\n mint operator>>(const mint a) const {\n mint res(*this);\n return res >>= a;\n }\n\n /* 条件演算子 */\n bool operator==(const mint a) const noexcept { return x == a.x; }\n bool operator!=(const mint a) const noexcept { return x != a.x; }\n bool operator<(const mint a) const noexcept { return x < a.x; }\n bool operator>(const mint a) const noexcept { return x > a.x; }\n bool operator<=(const mint a) const noexcept { return x <= a.x; }\n bool operator>=(const mint a) const noexcept { return x >= a.x; }\n\n /* ストリーム挿入演算子 */\n friend istream& operator>>(istream& is, mint& m) {\n is >> m.x;\n m.x = (m.x % MOD + MOD) % MOD;\n return is;\n }\n friend ostream& operator<<(ostream& os, const mint& m) {\n os << m.x;\n return os;\n }\n\n /* その他の関数 */\n mint modinv(mint a) { return pow(a, MOD - 2); }\n mint pow(mint x, mint n) {\n mint res = 1;\n while (n.x > 0) {\n if ((n % 2).x) res *= x;\n x *= x;\n n.x /= 2;\n }\n return res;\n }\n};\n\n#define MAX_MINT_NCK 201010\nmint f[MAX_MINT_NCK], rf[MAX_MINT_NCK];\n\nbool isinit = false;\n\nvoid init() {\n f[0] = 1;\n rf[0] = 1;\n for (int i = 1; i < MAX_MINT_NCK; i++) {\n f[i] = f[i - 1] * i;\n // rf[i] = modinv(f[i].x);\n rf[i] = f[i].pow(f[i], MOD - 2);\n }\n}\n\nmint nCk(mint n, mint k) {\n if (n < k) return 0;\n if (!isinit) {\n init();\n isinit = 1;\n }\n mint nl = f[n.x]; // n!\n mint nkl = rf[n.x - k.x]; // (n-k)!\n mint kl = rf[k.x]; // k!\n mint nkk = (nkl.x * kl.x);\n\n return nl * nkk;\n}\n\nmap<ll, ll> prime;\nvoid factorize(ll n) {\n for (ll i = 2; i * i <= n; i++) {\n while (n % i == 0) {\n prime[i]++;\n n /= i;\n }\n }\n if (n != 1) {\n prime[n] = 1;\n }\n}\n\nint main() {\n int n, k;\n cin >> n >> k;\n mint ans = 0;\n for (int i = 0; i <= k; i++) {\n ans += mint(1).pow(-1, i) * nCk(k, i) * mint(1).pow(k - i, n);\n }\n cout << ans << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6580, "score_of_the_acc": -0.0806, "final_rank": 2 } ]
aoj_CGL_7_B_cpp
Incircle of a Triangle Write a program which prints the central coordinate ($cx$,$cy$) and the radius $r$ of a incircle of a triangle which is constructed by three points ($x_1$, $y_1$), ($x_2$, $y_2$) and ($x_3$, $y_3$) on the plane surface. Input The input is given in the following format $x_1$ $y_1$ $x_2$ $y_2$ $x_3$ $y_3$ All the input are integers. Constraints $-10000 \leq x_i, y_i \leq 10000$ The three points are not on the same straight line Output Print $cx$, $cy$ and $r$ separated by a single space in a line. The output values should be in a decimal fraction with an error less than 0.000001. Sample Input 1 1 -2 3 2 -2 0 Sample Output 1 0.53907943898209422325 -0.26437392711448356856 1.18845545916395465278 Sample Input 2 0 3 4 0 0 0 Sample Output 2 1.00000000000000000000 1.00000000000000000000 1.00000000000000000000
[ { "submission_id": "aoj_CGL_7_B_10750421", "code_snippet": "#include <bits/stdc++.h>\n\n// from: cpp.json\n#define INF 8e18\n#define int long long\n#define LD long double\nusing namespace std;\n\nvoid solve() {\n LD x1, y1, x2, y2, x3, y3;\n cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;\n\n auto dist = [&](LD X1, LD Y1, LD X2, LD Y2) -> LD {\n LD dx = X1 - X2;\n LD dy = Y1 - Y2;\n return sqrtl(dx * dx + dy * dy);\n };\n\n LD a = dist(x2, y2, x3, y3);\n LD b = dist(x3, y3, x1, y1);\n LD c = dist(x1, y1, x2, y2);\n\n LD p = a + b + c;\n\n LD cx = (a * x1 + b * x2 + c * x3) / p;\n LD cy = (a * y1 + b * y2 + c * y3) / p;\n\n LD area = fabsl((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) * 0.5L;\n\n LD s = p * 0.5L;\n LD r = area / s;\n\n cout << fixed << setprecision(3000000) << cx << ' ' << cy << ' ' << r << '\\n';\n}\n\nsigned main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 24404, "score_of_the_acc": -0.8082, "final_rank": 2 }, { "submission_id": "aoj_CGL_7_B_10750418", "code_snippet": "#include <bits/stdc++.h>\n\n// from: cpp.json\n#define INF 8e18\n#define int long long\n#define LD long double\nusing namespace std;\n\nvoid solve() {\n LD x1, y1, x2, y2, x3, y3;\n cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;\n\n auto dist = [&](LD X1, LD Y1, LD X2, LD Y2) -> LD {\n LD dx = X1 - X2;\n LD dy = Y1 - Y2;\n return sqrtl(dx * dx + dy * dy);\n };\n\n LD a = dist(x2, y2, x3, y3);\n LD b = dist(x3, y3, x1, y1);\n LD c = dist(x1, y1, x2, y2);\n\n LD p = a + b + c;\n\n LD cx = (a * x1 + b * x2 + c * x3) / p;\n LD cy = (a * y1 + b * y2 + c * y3) / p;\n\n LD area = fabsl((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) * 0.5L;\n\n LD s = p * 0.5L;\n LD r = area / s;\n\n cout << fixed << setprecision(1000000) << cx << ' ' << cy << ' ' << r << '\\n';\n}\n\nsigned main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 10736, "score_of_the_acc": -0.2203, "final_rank": 1 }, { "submission_id": "aoj_CGL_7_B_9303072", "code_snippet": "#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cmath>\n#include <deque>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <optional>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nstruct Pos\n{\n double x, y;\n\npublic:\n Pos() : x(0), y(0) {}\n Pos(double x, double y) : x(x), y(y) {}\n\n Pos operator+(const Pos &rhs) const\n {\n return Pos{x + rhs.x, y + rhs.y};\n }\n Pos operator-(const Pos &rhs) const\n {\n return Pos{x - rhs.x, y - rhs.y};\n }\n Pos operator*(double rhs) const\n {\n return Pos{x * rhs, y * rhs};\n }\n Pos operator/(double rhs) const\n {\n return Pos{x / rhs, y / rhs};\n }\n\n double len() const\n {\n return sqrt(x * x + y * y);\n }\n\n Pos regular() const\n {\n return *this / len();\n }\n\n Pos normal() const\n {\n return Pos{-y, x};\n }\n};\n\nconst auto dot = [](const Pos &lhs, const Pos &rhs)\n{\n return lhs.x * rhs.x + lhs.y * rhs.y;\n};\n\nint main()\n{\n Pos a, b, c;\n cin >> a.x >> a.y >> b.x >> b.y >> c.x >> c.y;\n\n Pos nc = (a - b).normal().regular(),\n na = (b - c).normal().regular(),\n nb = (c - a).normal().regular();\n\n Pos o = (a + b + c) / 3;\n double ra, rb, rc, mean;\n\n for (int i = 0; i < 10000000; i++)\n {\n ra = abs(dot(b - o, na)),\n rb = abs(dot(c - o, nb)),\n rc = abs(dot(a - o, nc));\n mean = (ra + rb + rc) / 3;\n\n o = o + ((o - a).regular() * (ra - mean) + (o - b).regular() * (rb - mean) + (o - c).regular() * (rc - mean)) / 2;\n }\n\n cout.setf(ios::fixed);\n cout.precision(9);\n cout << o.x << \" \" << o.y << \" \" << ra << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 3572, "score_of_the_acc": -1, "final_rank": 3 }, { "submission_id": "aoj_CGL_7_B_5823321", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst int N = 1e6 + 10;\n\nconst double eps = 1e-9;\nconst double PI = acos(-1.0);\nconst double dinf = 1e99;\nconst ll inf = 0x3f3f3f3f3f3f3f3f;\nstruct Line;\n\nstruct Point {\n double x, y;\n\n Point() { x = y = 0; }\n\n Point(const Line &a);\n\n Point(const double &a, const double &b) : x(a), y(b) {}\n\n Point operator+(const Point &a) const {\n return {x + a.x, y + a.y};\n }\n\n Point operator-(const Point &a) const {\n return {x - a.x, y - a.y};\n }\n\n Point operator*(const double &a) const {\n return {x * a, y * a};\n }\n\n Point operator/(const double &d) const {\n return {x / d, y / d};\n }\n\n bool operator==(const Point &a) const {\n return abs(x - a.x) + abs(y - a.y) < eps;\n }\n\n void standardize() {\n *this = *this / sqrt(x * x + y * y);\n }\n};\n\nPoint normal(const Point &a) { return Point(-a.y, a.x); }\n\ndouble dist(const Point &a, const Point &b) {\n return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\ndouble dist2(const Point &a, const Point &b) {\n return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n}\n\nstruct Line {\n Point s, t;\n\n Line() {}\n\n Line(const Point &a, const Point &b) : s(a), t(b) {}\n\n};\n\n\nstruct Circle {\n Point o;\n double r;\n\n Circle() {}\n\n Circle(Point P, double R = 0) { o = P, r = R; }\n};\n\ndouble length(const Point &p) {\n return sqrt(p.x * p.x + p.y * p.y);\n}\n\ndouble length(const Line &l) {\n Point p(l);\n return length(p);\n}\n\nPoint::Point(const Line &a) { *this = a.t - a.s; }\n\nistream &operator>>(istream &in, Point &a) {\n in >> a.x >> a.y;\n return in;\n}\n\nostream &operator<<(ostream &out, Point &a) {\n out << fixed << setprecision(10) << a.x << ' ' << a.y;\n return out;\n}\n\ndouble dot(const Point &a, const Point &b) { return a.x * b.x + a.y * b.y; }\n\ndouble det(const Point &a, const Point &b) { return a.x * b.y - a.y * b.x; }\n\nint sgn(const double &x) { return fabs(x) < eps ? 0 : (x > 0 ? 1 : -1); }\n\ndouble sqr(const double &x) { return x * x; }\n\nPoint rotate(const Point &a, const double &ang) {\n double x = cos(ang) * a.x - sin(ang) * a.y;\n double y = sin(ang) * a.x + cos(ang) * a.y;\n return {x, y};\n}\n\n//点在线段上 <=0 包含端点\nbool sp_on(const Line &seg, const Point &p) {\n Point a = seg.s, b = seg.t;\n return !sgn(det(p - a, b - a)) && sgn(dot(p - a, p - b)) <= 0;\n}\n\nbool lp_on(const Line &line, const Point &p) {\n Point a = line.s, b = line.t;\n return !sgn(det(p - a, b - a));\n}\n\n//等于不包含共线\nint andrew(Point *point, Point *convex, int n) {\n sort(point, point + n, [](Point a, Point b) {\n if (a.x != b.x) return a.x < b.x;\n return a.y < b.y;\n });\n int top = 0;\n for (int i = 0; i < n; i++) {\n while ((top > 1) && det(convex[top - 1] - convex[top - 2], point[i] - convex[top - 1]) <= 0)\n top--;\n convex[top++] = point[i];\n }\n int tmp = top;\n for (int i = n - 2; i >= 0; i--) {\n while ((top > tmp) && det(convex[top - 1] - convex[top - 2], point[i] - convex[top - 1]) <= 0)\n top--;\n convex[top++] = point[i];\n }\n if (n > 1) top--;\n return top;\n}\n\ndouble slope(const Point &a, const Point &b) { return (a.y - b.y) / (a.x - b.x); }\n\ndouble slope(const Line &a) { return slope(a.s, a.t); }\n\nPoint ll_intersection(const Line &a, const Line &b) {\n double s1 = det(Point(a), b.s - a.s), s2 = det(Point(a), b.t - a.s);\n return (b.s * s2 - b.t * s1) / (s2 - s1);\n}\n\nint ss_cross(const Line &a, const Line &b, Point &p) {\n int d1 = sgn(det(a.t - a.s, b.s - a.s));\n int d2 = sgn(det(a.t - a.s, b.t - a.s));\n int d3 = sgn(det(b.t - b.s, a.s - b.s));\n int d4 = sgn(det(b.t - b.s, a.t - b.s));\n if ((d1 ^ d2) == -2 && (d3 ^ d4) == -2) {\n p = ll_intersection(a, b);\n return 1;\n }\n if (!d1 && sp_on(a, b.s)) {\n p = b.s;\n return 2;\n }\n if (!d2 && sp_on(a, b.t)) {\n p = b.t;\n return 2;\n }\n if (!d3 && sp_on(b, a.s)) {\n p = a.s;\n return 2;\n }\n if (!d4 && sp_on(b, a.t)) {\n p = a.t;\n return 2;\n }\n return 0;\n}\n\n\nint ccw(const Point &a, Point b, Point c) {\n b = b - a, c = c - a;\n if (sgn(det(b, c)) > 0) return +1; // \"COUNTER_CLOCKWISE\"\n if (sgn(det(b, c)) < 0) return -1; // \"CLOCKWISE\"\n if (sgn(dot(b, c)) < 0) return +2; // \"ONLINE_BACK\"\n if (length(b) < length(c)) return -2; // \"ONLINE_FRONT\"\n return 0; // \"ON_SEGMENT\"\n}\n\n\nPoint project(const Line &l, const Point &p) {\n Point base(l);\n double r = dot(base, p - l.s) / sqr(length(base));\n return l.s + (base * r);\n}\n\ndouble sp_dist(const Line &l, const Point &p) {\n if (l.s == l.t) return dist(l.s, p);\n Point x = p - l.s, y = p - l.t, z = l.t - l.s;\n if (sgn(dot(x, z)) < 0)return length(x);//P距离A更近\n if (sgn(dot(y, z)) > 0)return length(y);//P距离B更近\n return abs(det(x, z) / length(z));//面积除以底边长\n}\n\ndouble lp_dist(const Line &l, const Point &p) {\n Point x = p - l.s, y = p - l.t, z = l.t - l.s;\n return abs(det(x, z) / length(z));//面积除以底边长\n}\n\nint lc_cross(const Line &l, const Point &a, const double &r, pair<Point, Point> &ans) {\n int num = 0;\n Point pr = project(l, a);\n double dis = dist(pr, a);\n double tmp = r * r - dis * dis;\n if (sgn(tmp) == 1) num = 2;\n else if (sgn(tmp) == 0) num = 1;\n else return 0;\n double base = sqrt(r * r - dis * dis);\n Point e(l);\n e.standardize();\n e = e * base;\n ans = make_pair(pr + e, pr - e);\n return num;\n}\n\nint cc_cross(const Point &c1, const double &r1, const Point &c2, const double &r2, pair<Point, Point> &ans) {\n double x1 = c1.x, x2 = c2.x, y1 = c1.y, y2 = c2.y;\n double d = length(c1 - c2);\n if (sgn(fabs(r1 - r2) - d) > 0) return 0; //内含\n if (sgn(r1 + r2 - d) < 0) return 4; //相离\n double a = r1 * (x1 - x2) * 2, b = r1 * (y1 - y2) * 2, c = r2 * r2 - r1 * r1 - d * d;\n double p = a * a + b * b, q = -a * c * 2, r = c * c - b * b;\n\n double cosa, sina, cosb, sinb;\n //One Intersection\n if (sgn(d - (r1 + r2)) == 0 || sgn(d - fabs(r1 - r2)) == 0) {\n cosa = -q / p / 2;\n sina = sqrt(1 - sqr(cosa));\n Point p0(x1 + r1 * cosa, y1 + r1 * sina);\n if (sgn(dist(p0, c2) - r2)) p0.y = y1 - r1 * sina;\n ans = pair<Point, Point>(p0, p0);\n if (sgn(r1 + r2 - d) == 0) return 3; //外切\n else return 1; //内切\n }\n //Two Intersections\n double delta = sqrt(q * q - p * r * 4);\n cosa = (delta - q) / p / 2;\n cosb = (-delta - q) / p / 2;\n sina = sqrt(1 - sqr(cosa));\n sinb = sqrt(1 - sqr(cosb));\n Point p1(x1 + r1 * cosa, y1 + r1 * sina);\n Point p2(x1 + r1 * cosb, y1 + r1 * sinb);\n if (sgn(dist(p1, c2) - r2)) p1.y = y1 - r1 * sina;\n if (sgn(dist(p2, c2) - r2)) p2.y = y1 - r1 * sinb;\n if (p1 == p2) p1.y = y1 - r1 * sina;\n ans = pair<Point, Point>(p1, p2);\n return 2; // 相交\n}\n\nPoint lp_sym(const Line &l, const Point &p) {\n return p + (project(l, p) - p) * 2;\n}\n\ndouble alpha(const Point &t1, const Point &t2) {\n double theta;\n theta = atan2((double) t2.y, (double) t2.x) - atan2((double) t1.y, (double) t1.x);\n if (sgn(theta) < 0)\n theta += 2.0 * PI;\n return theta;\n}\n\nint pip(const Point *P, const int &n, const Point &a) {//【射线法】判断点A是否在任意多边形Poly以内\n int cnt = 0;\n double tmp;\n for (int i = 1; i <= n; ++i) {\n int j = i < n ? i + 1 : 1;\n if (sp_on(Line(P[i], P[j]), a))return 2;//点在多边形上\n if (a.y >= min(P[i].y, P[j].y) && a.y < max(P[i].y, P[j].y))//纵坐标在该线段两端点之间\n tmp = P[i].x + (a.y - P[i].y) / (P[j].y - P[i].y) * (P[j].x - P[i].x), cnt += sgn(tmp - a.x) > 0;//交点在A右方\n }\n return cnt & 1;//穿过奇数次则在多边形以内\n}\n\nbool pip_convex_jud(const Point &a, const Point &L, const Point &R) {//判断AL是否在AR右边\n return sgn(det(L - a, R - a)) > 0;//必须严格以内\n}\n\nbool pip_convex(const Point *P, const int &n, const Point &a) {//【二分法】判断点A是否在凸多边形Poly以内\n //点按逆时针给出\n if (pip_convex_jud(P[0], a, P[1]) || pip_convex_jud(P[0], P[n - 1], a)) return 0;//在P[0_1]或P[0_n-1]外\n if (sp_on(Line(P[0], P[1]), a) || sp_on(Line(P[0], P[n - 1]), a)) return 2;//在P[0_1]或P[0_n-1]上\n int l = 1, r = n - 2;\n while (l < r) {//二分找到一个位置pos使得P[0]_A在P[0_pos],P[0_(pos+1)]之间\n int mid = (l + r + 1) >> 1;\n if (pip_convex_jud(P[0], P[mid], a))l = mid;\n else r = mid - 1;\n }\n if (pip_convex_jud(P[l], a, P[l + 1]))return 0;//在P[pos_(pos+1)]外\n if (sp_on(Line(P[l], P[l + 1]), a))return 2;//在P[pos_(pos+1)]上\n return 1;\n}\n// 多边形是否包含线段\n// 因此我们可以先求出所有和线段相交的多边形的顶点,然后按照X-Y坐标排序(X坐标小的排在前面,对于X坐标相同的点,Y坐标小的排在前面,\n// 这种排序准则也是为了保证水平和垂直情况的判断正确),这样相邻的两个点就是在线段上相邻的两交点,如果任意相邻两点的中点也在多边形内,\n// 则该线段一定在多边形内。\n\nint pp_judge(Point *A, int n, Point *B, int m) {//【判断多边形A与多边形B是否相离】\n for (int i1 = 1; i1 <= n; ++i1) {\n int j1 = i1 < n ? i1 + 1 : 1;\n for (int i2 = 1; i2 <= m; ++i2) {\n int j2 = i2 < m ? i2 + 1 : 1;\n Point tmp;\n if (ss_cross(Line(A[i1], A[j1]), Line(B[i2], B[j2]), tmp)) return 0;//两线段相交\n if (pip(B, m, A[i1]) || pip(A, n, B[i2]))return 0;//点包含在内\n }\n }\n return 1;\n}\n\ndouble area(Point *P, int n) {//【任意多边形P的面积】\n double S = 0;\n for (int i = 1; i <= n; i++) S += det(P[i], P[i < n ? i + 1 : 1]);\n return S / 2.0;\n}\n\nLine Q[N];\n\nint judge(Line L, Point a) { return sgn(det(a - L.s, L.t - L.s)) > 0; }//判断点a是否在直线L的右边\nint halfcut(Line *L, int n, Point *P) {//【半平面交】\n sort(L, L + n, [](const Line &a, const Line &b) {\n double d = atan2((a.t - a.s).y, (a.t - a.s).x) - atan2((b.t - b.s).y, (b.t - b.s).x);\n return sgn(d) ? sgn(d) < 0 : judge(a, b.s);\n });\n\n int m = n;\n n = 0;\n for (int i = 0; i < m; ++i)\n if (i == 0 || sgn(atan2(Point(L[i]).y, Point(L[i]).x) - atan2(Point(L[i - 1]).y, Point(L[i - 1]).x)))\n L[n++] = L[i];\n int h = 1, t = 0;\n for (int i = 0; i < n; ++i) {\n while (h < t && judge(L[i], ll_intersection(Q[t], Q[t - 1]))) --t;//当队尾两个直线交点不是在直线L[i]上或者左边时就出队\n while (h < t && judge(L[i], ll_intersection(Q[h], Q[h + 1]))) ++h;//当队头两个直线交点不是在直线L[i]上或者左边时就出队\n Q[++t] = L[i];\n\n }\n while (h < t && judge(Q[h], ll_intersection(Q[t], Q[t - 1]))) --t;\n while (h < t && judge(Q[t], ll_intersection(Q[h], Q[h + 1]))) ++h;\n n = 0;\n for (int i = h; i <= t; ++i) {\n P[n++] = ll_intersection(Q[i], Q[i < t ? i + 1 : h]);\n }\n return n;\n}\n\nPoint V1[N], V2[N];\n\nint mincowski(Point *P1, int n, Point *P2, int m, Point *V) {//【闵可夫斯基和】求两个凸包{P1},{P2}的向量集合{V}={P1+P2}构成的凸包\n for (int i = 0; i < n; ++i) V1[i] = P1[(i + 1) % n] - P1[i];\n for (int i = 0; i < m; ++i) V2[i] = P2[(i + 1) % m] - P2[i];\n int t = 0, i = 0, j = 0;\n V[t++] = P1[0] + P2[0];\n while (i < n && j < m) V[t] = V[t - 1] + (sgn(det(V1[i], V2[j])) > 0 ? V1[i++] : V2[j++]), t++;\n while (i < n) V[t] = V[t - 1] + V1[i++], t++;\n while (j < m) V[t] = V[t - 1] + V2[j++], t++;\n return t;\n}\n\nCircle external_circle(const Point &A, const Point &B, const Point &C) {//【三点确定一圆】向量垂心法\n Point P1 = (A + B) * 0.5, P2 = (A + C) * 0.5;\n Line R1 = Line(P1, P1 + normal(B - A));\n Line R2 = Line(P2, P2 + normal(C - A));\n Circle O;\n O.o = ll_intersection(R1, R2);\n O.r = length(A - O.o);\n return O;\n}\n\nCircle internal_circle(const Point &A, const Point &B, const Point &C) {\n double a = dist(B, C), b = dist(A, C), c = dist(A, B);\n double s = (a + b + c) / 2;\n double S = sqrt(max(0.0, s * (s - a) * (s - b) * (s - c)));\n double r = S / s;\n\n return Circle((A * a + B * b + C * c) / (a + b + c), r);\n}\n\n\nstruct ConvexHull {\n\n int op;\n\n struct cmp {\n bool operator()(const Point &a, const Point &b) const {\n return sgn(a.x - b.x) < 0 || sgn(a.x - b.x) == 0 && sgn(a.y - b.y) < 0;\n }\n };\n\n set<Point, cmp> s;\n\n ConvexHull(int o) {\n op = o;\n s.clear();\n }\n\n inline int PIP(Point P) {\n set<Point>::iterator it = s.lower_bound(Point(P.x, -dinf));//找到第一个横坐标大于P的点\n if (it == s.end())return 0;\n if (sgn(it->x - P.x) == 0) return sgn((P.y - it->y) * op) <= 0;//比较纵坐标大小\n if (it == s.begin())return 0;\n set<Point>::iterator j = it, k = it;\n --j;\n return sgn(det(P - *j, *k - *j) * op) >= 0;//看叉姬1\n }\n\n inline int judge(set<Point>::iterator it) {\n set<Point>::iterator j = it, k = it;\n if (j == s.begin())return 0;\n --j;\n if (++k == s.end())return 0;\n return sgn(det(*it - *j, *k - *j) * op) >= 0;//看叉姬\n }\n\n inline void insert(Point P) {\n if (PIP(P))return;//如果点P已经在凸壳上或凸包里就不插入了\n set<Point>::iterator tmp = s.lower_bound(Point(P.x, -inf));\n if (tmp != s.end() && sgn(tmp->x - P.x) == 0)s.erase(tmp);//特判横坐标相等的点要去掉\n s.insert(P);\n set<Point>::iterator it = s.find(P), p = it;\n if (p != s.begin()) {\n --p;\n while (judge(p)) {\n set<Point>::iterator temp = p--;\n s.erase(temp);\n }\n }\n if ((p = ++it) != s.end()) {\n while (judge(p)) {\n set<Point>::iterator temp = p++;\n s.erase(temp);\n }\n }\n }\n} up(1), down(-1);\n\nint PIC(Circle C, Point a) { return sgn(length(a - C.o) - C.r) <= 0; }//判断点A是否在圆C内\nvoid Random(Point *P, int n) { for (int i = 0; i < n; ++i)swap(P[i], P[(rand() + 1) % n]); }//随机一个排列\nCircle min_circle(Point *P, int n) {//【求点集P的最小覆盖圆】 O(n)\n// random_shuffle(P,P+n);\n Random(P, n);\n Circle C = Circle(P[0], 0);\n for (int i = 1; i < n; ++i)\n if (!PIC(C, P[i])) {\n C = Circle(P[i], 0);\n for (int j = 0; j < i; ++j)\n if (!PIC(C, P[j])) {\n C.o = (P[i] + P[j]) * 0.5, C.r = length(P[j] - C.o);\n for (int k = 0; k < j; ++k) if (!PIC(C, P[k])) C = external_circle(P[i], P[j], P[k]);\n }\n }\n return C;\n}\n\n\nint temp[N];\n\ndouble closest_point(Point *p, int n) {\n function<double(int, int)> merge = [&](int l, int r) {\n double d = dinf;\n if (l == r) return d;\n if (l + 1 == r) return dist(p[l], p[r]);\n int mid = (l + r) >> 1;\n double d1 = merge(l, mid);\n double d2 = merge(mid + 1, r);\n d = min(d1, d2);\n int i, j, k = 0;\n for (i = l; i <= r; i++) {\n if (sgn(abs(p[mid].x - p[i].x) - d) <= 0)\n temp[k++] = i;\n\n }\n sort(temp, temp + k, [&](const int &a, const int &b) {\n return sgn(p[a].y - p[b].y) < 0;\n });\n for (i = 0; i < k; i++) {\n for (j = i + 1; j < k && sgn(p[temp[j]].y - p[temp[i]].y - d) <= 0; j++) {\n double d3 = dist(p[temp[i]], p[temp[j]]);\n d = min(d, d3);\n }\n }\n return d;\n };\n sort(p, p + n, [&](const Point &a, const Point &b) {\n if (sgn(a.x - b.x) == 0) return sgn(a.y - b.y) < 0;\n else return sgn(a.x - b.x) < 0;\n });\n return merge(0, n - 1);\n}\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n\n Point a, b, c;\n cin >> a >> b >> c;\n Circle ans = internal_circle(a, b, c);\n cout << fixed << setprecision(10) << ans.o.x << ' ' << ans.o.y << ' ' << ans.r << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 65840, "score_of_the_acc": -1, "final_rank": 3 } ]
aoj_CGL_4_A_cpp
Convex Hull Find the convex hull of a given set of points P . In other words, find the smallest convex polygon containing all the points of P . Here, in a convex polygon, all interior angles are less than or equal to 180 degrees. Please note that you should find all the points of P on both corner and boundary of the convex polygon. Input n x 1 y 1 x 2 y 2 : x n y n The first integer n is the number of points in P . The coordinate of the i -th point p i is given by two integers x i and y i . Output In the first line, print the number of points on the corner/boundary of the convex polygon. In the following lines, print x y coordinates of the set of points. The coordinates should be given in the order of counter-clockwise visit of them starting from the point in P with the minimum y -coordinate, or the leftmost such point in case of a tie. Constraints 3 ≤ n ≤ 100000 -10000 ≤ x i , y i ≤ 10000 No point in the P will occur more than once. Sample Input 1 7 2 1 0 0 1 2 2 2 4 2 1 3 3 3 Sample Output 1 5 0 0 2 1 4 2 3 3 1 3 Sample Input 2 4 0 0 2 2 0 2 0 1 Sample Output 2 4 0 0 2 2 0 2 0 1
[ { "submission_id": "aoj_CGL_4_A_11065485", "code_snippet": "#include <bits/stdc++.h>\n\n#define debug(a) cout << #a << \" = \" << (a) << ' '\n\nusing namespace std;\n\n#define db long double\n// #define db long long\n\nconst db EPS = 1e-9;\n\n#define cross(p1, p2, p3) (p2 - p1).det(p3 - p1)\n#define crossop(p1, p2, p3) sign(cross(p1, p2, p3))\n\nint sign(db a) { return a < -EPS ? -1 : a > EPS; }\nint cmp(db a, db b) { return sign(a - b); }\n\nstruct P {\n db x, y;\n P() {}\n P(db _x, db _y) : x(_x), y(_y) {}\n\n P operator +(P p) { return {x + p.x, y + p.y}; }\n P operator -(P p) { return {x - p.x, y - p.y}; }\n P operator *(db d) { return {x * d, y * d}; }\n P operator /(db d) { return {x / d, y / d}; }\n\n bool operator < (P p) const {\n int c = cmp(y, p.y);\n if (c) return c == -1;\n return cmp(x, p.x) == -1;\n }\n\n bool operator == (P p) const {\n return ! cmp(x, p.x) && ! cmp(y, p.y);\n }\n\n db abs2() { return x * x + y * y; }\n db abs() { return sqrt(x * x + y * y); }\n db distTo(P p) { return (*this - p).abs(); }\n db alpha() { return atan2(y, x); }\n db dot(P p) { return x * p.x + y * p.y; }\n db det(P p) { return x * p.y - y * p.x; }\n\n int quadY() const { return sign(x) == 1 || (sign(x) == 0 && sign(y) >= 0); }\n int quadX() const { return sign(y) == 1 || (sign(y) == 0 && sign(x) >= 0); }\n\n P rot90() { return P(-y, x); }\n P rot(db alpha) { return { x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha)}; }\n P unit() { return *this / abs(); }\n};\n\nostream & operator << (ostream &out, const P &A) {\n out << A.x << \" \" << A.y;\n return out;\n}\n\n// ------------------------------------\n// 线段 / 线段\n\nbool checkPll(P p1, P p2, P q1, P q2) {\n // 判断平行\n db a1 = cross(q1, q2, p1), a2 = - cross(q1, q2, p2);\n return sign(a1 + a2) == 0;\n}\n\nP isLL(P p1, P p2, P q1, P q2) {\n // 返回交点\n db a1 = cross(q1, q2, p1), a2 = - cross(q1, q2, p2);\n return (p1 * a2 + p2 * a1) / (a1 + a2);\n}\n\nbool intersect(db l1, db r1, db l2, db r2) {\n if (l1 > r1) swap(l1, r1);\n if (l2 > r2) swap(l2, r2);\n return cmp(r1, l2) >= 0 && cmp(r2, l1) >= 0;\n}\n\nbool isSS(P p1, P p2, P q1, P q2) {\n // 线段是否 不严格 相交\n // 1 : SS\n // 0 : unSS\n return intersect(p1.x, p2.x, q1.x, q2.x) &&\n intersect(p1.y, p2.y, q1.y, q2.y) && \n crossop(p1, p2, q1) * crossop(p1, p2, q2) <= 0 && \n crossop(q1, q2, p1) * crossop(q1, q2, p2) <= 0;\n}\n\nbool isSS_strict(P p1, P p2, P q1, P q2) {\n // 线段是否 严格 相交\n // 1 : SS\n // 0 : unSS\n return crossop(p1, p2, q1) * crossop(p1, p2, q2) < 0 && \n crossop(q1, q2, p1) * crossop(q1, q2, p2) < 0;\n}\n\nbool isMiddle(db a, db m, db b) {\n return sign(a - m) == 0 || sign(b - m) == 0 || ((a < m) != (b < m));\n}\n\nbool isMiddle(P a, P m, P b) {\n return isMiddle(a.x, m.x, b.x) && isMiddle(a.y, m.y, b.y);\n}\n\nbool onSeg(P p1, P p2, P q) {\n // 是否在线段上 不严格\n return crossop(p1, p2, q) == 0 && isMiddle(p1, q, p2);\n}\n\nbool onSeg_strict(P p1, P p2, P q) {\n // 是否在线段上 严格\n return crossop(p1, p2, q) == 0 && \n sign((q - p1).dot(p1 - p2)) * \n sign((q - p2).dot(p1 - p2)) < 0;\n}\n\nP proj(P p1, P p2, P q) {\n // 求 q 到 p1 p2 的投影\n P dir = p2 - p1;\n return p1 + (p2 - p1) * (dir.dot(q - p1) / (dir).abs2());\n}\n\nP reflect(P p1, P p2, P q) {\n // 求 q 到 p1 p2 的反射点\n return proj(p1, p2, q) * 2 - q;\n}\n\ndb nearest(P p1, P p2, P q) {\n // 求 q 到 p1 p2(线段)的最近点\n if (p1 == p2) return p1.distTo(q);\n P h = proj(p1, p2, q);\n if (isMiddle(p1, h, p2))\n return q.distTo(h);\n return min(p1.distTo(q), p2.distTo(q));\n}\n\ndb disSS(P p1, P p2, P q1, P q2) {\n // 求线段 p1p2 和 线段 q1q2 的距离\n if (isSS(p1, p2, q1, q2)) return 0;\n db val1 = min(nearest(p1, p2, q1), nearest(p1, p2, q2));\n db val2 = min(nearest(q1, q2, p1), nearest(q1, q2, p2));\n return min(val1, val2);\n}\n\ndb rad(P p1, P p2) {\n // 求向量 p1 p2 的角度(逆时针为正,顺时针为负,范围 (- pi, pi])\n return atan2l(p1.det(p2), p1.dot(p2));\n}\n\n// ---------------------------------------------\n// 多边形\n\ndb area(vector < P > ps) {\n // 求多边形面积(逆时针顺序给出点 -> 面积为正)\n db ret = 0; if (ps.size() == 0) return 0;\n for (int i = 0; i < (int)ps.size(); ++ i) {\n ret += ps[i].det(ps[(i + 1) % ps.size()]);\n }\n return ret / 2;\n}\n\nint contain(vector < P > ps, P p) {\n // 0 : outside\n // 1 : on_seg\n // 2 : inside\n\n // ps 是多边形,判断 p 在多边形 内部 / 线段上 / 外部\n int n = ps.size(), ret = 0;\n for (int i = 0; i < n; ++ i) {\n P u = ps[i], v = ps[(i + 1) % n];\n if (onSeg(u, v, p)) return 1;\n if (cmp(u.y, v.y) <= 0) swap(u, v);\n if (cmp(p.y, u.y) > 0 || cmp(p.y, v.y) <= 0)\n continue;\n ret ^= crossop(p, u, v) > 0;\n }\n return ret * 2;\n}\n\nvector < P > convexHull(vector < P > ps) {\n // 求凸包\n int n = ps.size();\n if (n <= 1) return ps;\n sort(ps.begin(), ps.end());\n vector < P > qs(n * 2);\n int k = 0;\n for (int i = 0; i < n; qs[k ++] = ps[i ++])\n while (k > 1 && crossop(qs[k - 2], qs[k - 1], ps[i]) <= 0)\n -- k;\n for (int i = n - 2, t = k; i >= 0; qs[k ++] = ps[i --])\n while (k > t && crossop(qs[k - 2], qs[k - 1], ps[i]) <= 0)\n -- k;\n qs.resize(k - 1);\n return qs;\n}\n\n\nvector < P > convexHullNonStrict(vector < P > ps) {\n // 求凸包(边界上的点也在凸包内)\n sort(ps.begin(), ps.end());\n ps.erase(unique(ps.begin(), ps.end()), ps.end());\n int n = ps.size();\n if (n <= 1) return ps;\n vector < P > qs(n * 2);\n int k = 0;\n for (int i = 0; i < n; qs[k ++] = ps[i ++])\n while (k > 1 && crossop(qs[k - 2], qs[k - 1], ps[i]) < 0)\n -- k;\n for (int i = n - 2, t = k; i >= 0; qs[k ++] = ps[i --])\n while (k > t && crossop(qs[k - 2], qs[k - 1], ps[i]) < 0)\n -- k;\n qs.resize(k - 1);\n return qs;\n}\n\nbool checkConvexHull(vector < P > p) {\n // 判断 p 多边形是否是凸包\n // 注意:不可通过再跑一次凸包判断点数是否相同\n // 因为点数相同 不能代表是凸包的连接方式\n int n = p.size();\n for (int i = 0; i < n; ++ i) {\n int pre = i - 1;\n int suf = i + 1;\n if (pre == -1) pre = n - 1;\n if (suf == n) suf = 0;\n if (crossop(p[i], p[suf], p[pre]) < 0)\n return 0;\n }\n return 1;\n}\n\nbool polar_cmpX(P a, P b) {\n // 极角排序 X 轴正半轴(包含)开始逆时针转\n if (a.quadX() != b.quadX()) \n return a.quadX() > b.quadX();\n return sign(a.det(b)) > 0;\n}\n\nbool polar_cmpY(P a, P b) {\n // 极角排序 Y 轴负半轴(不包含)开始逆时针转\n if (a.quadY() != b.quadY()) \n return a.quadY() > b.quadY();\n return sign(a.det(b)) > 0;\n}\n\nvector < P > MincowskySum(vector < P > p, vector < P > q) {\n // p, q 为两个凸包(顺序同方向),求这两个凸包的 闵可夫斯基和\n // 得保证 p, q 的第一个点 是排序后的\n // 即 尽可能在 convexHull 后再传入 p, q \n if (p.size() == 0) return q;\n if (q.size() == 0) return p;\n vector < P > qs; qs.push_back(p[0] + q[0]);\n P p0 = p[0], q0 = q[0];\n for (int i = 0; i + 1 < (int)p.size(); ++ i)\n p[i] = p[i + 1] - p[i];\n for (int i = 0; i + 1 < (int)q.size(); ++ i)\n q[i] = q[i + 1] - q[i];\n p[p.size() - 1] = p0 - p[p.size() - 1];\n q[q.size() - 1] = q0 - q[q.size() - 1];\n qs.resize(p.size() + q.size() + 1);\n merge(p.begin(), p.end(), q.begin(), q.end(), qs.begin() + 1, polar_cmpY);\n for (int i = 1; i < (int)qs.size(); ++ i)\n qs[i] = qs[i] + qs[i - 1];\n qs.pop_back();\n return qs;\n}\n\nvoid solve() {\n int n; cin >> n;\n vector < P > p(n);\n for (int i = 0; i < n; ++ i) {\n cin >> p[i].x >> p[i].y;\n }\n\n vector < P > q = convexHullNonStrict(p);\n cout << q.size() << '\\n';\n for (auto x : q) cout << x << '\\n';\n}\n\n\nint main() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n int t = 1;\n while (t --) {\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 11624, "score_of_the_acc": -1.0118, "final_rank": 14 }, { "submission_id": "aoj_CGL_4_A_11065220", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define pii pair<int, int>\n#define pll pair<ll, ll>\n#define vi vector<int>\n#define vl vector<ll>\n#define ov4(a, b, c, d, name, ...) name\n#define rep3(i, a, b, c) for(ll i = (a); i < (b); i += (c))\n#define rep2(i, a, b) rep3(i, a, b, 1)\n#define rep1(i, n) rep2(i, 0, n)\n#define rep0(n) rep1(aaaaa, n)\n#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)\n#define per(i, a, b) for(ll i = (a)-1; i >= (b); i--)\n#define fore(e, v) for(auto&& e : v)\n#define all(a) begin(a), end(a)\n#define si(a) (int)(size(a))\n#define lb(v, x) (lower_bound(all(v), x) - begin(v))\n#define eb emplace_back\n\ntemplate<typename T, typename S> bool chmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; }\ntemplate<typename T, typename S> bool chmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; }\n\nconst int INF = 1e9 + 100;\nconst ll INFL = 3e18 + 100;\n\n#define i128 __int128_t\n\nstruct _ {\n _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }\n} __;\n\ntemplate<class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n typedef Point P;\n T x, y;\n explicit Point(T x=0, T y=0) : x(x), y(y) {}\n bool operator<(P p) const { return tie(x, y) < tie(p.x, p.y); }\n bool operator==(P p) const { return tie(x, y) == tie(p.x, p.y); }\n P operator-(P p) const { return P(x - p.x, y - p.y); }\n P operator*(T d) const { return P(x * d, y * d); }\n P operator/(T d) const { return P(x / d, y / d); }\n T dot(P p) const { return x * p.x + y * p.y; }\n T cross(P p) const { return x * p.y - y * p.x; }\n T cross(P a, P b) const { return (a - *this).cross(b - *this); }\n T dist2() const { return x*x + y*y; }\n double dist() const { return sqrt((double)dist2()); }\n P perp() const { return P(-y, x); }\n};\n\ntemplate<class P>\nP lineProj(P a, P b, P p, bool refl=false) {\n P v = b - a;\n return p - v.perp() * (1 + refl) * v.cross(p - a) / v.dist2();\n}\n\ntemplate<class P>\nbool onSegment(P s, P e, P p) {\n return p.cross(s, e) == 0 and (s - p).dot(e - p) <= 0;\n}\n\ntemplate<class P>\nvector<P> segInter(P a, P b, P c, P d) {\n auto oa = c.cross(d, a), ob = c.cross(d, b),\n oc = a.cross(b, c), od = a.cross(b, d);\n if (sgn(oa) * sgn(ob) < 0 and sgn(oc) * sgn(od) < 0) {\n return {(a * ob - b * oa) / (ob - oa)};\n }\n set<P> s;\n if (onSegment(c, d, a)) s.insert(a);\n if (onSegment(c, d, b)) s.insert(b);\n if (onSegment(a, b, c)) s.insert(c);\n if (onSegment(a, b, d)) s.insert(d);\n return {all(s)};\n}\n\ntemplate<class P>\ndouble segDist(P s, P e, P p) {\n if (s == e) return (p - s).dist();\n auto d = (s - e).dist2(), t = min(d, max(.0, (p - s).dot(e - s)));\n return ((p - s) * d - (e - s) * t).dist() / d;\n}\n\ntemplate<class P>\ndouble segDist(P s1, P e1, P s2, P e2) {\n if (!segInter(s1, e1, s2, e2).empty()) return 0;\n auto a = min(segDist(s1, e1, s2), segDist(s1, e1, e2));\n auto b = min(segDist(s2, e2, s1), segDist(s2, e2, e1));\n return min(a, b);\n}\n\ntemplate<class P>\npair<int, P> lineInter(P s1, P e1, P s2, P e2) {\n auto d = (e1 - s2).cross(e2 - s2);\n if(d == 0) {\n return {-(s1.cross(e1, s2) == 0), P(0, 0)};\n }\n auto p = s2.cross(e1, e2), q = s2.cross(e2, s1);\n return {1, (s1 * p + e1 * q) / d};\n}\n\ntemplate<class T>\nT polygonArea2(vector<Point<T>> &v) {\n T a = v.back().cross(v[0]);\n rep(i, si(v) - 1) a += v[i].cross(v[i + 1]);\n return a;\n}\n\n\n\n// speed star library\ntypedef Point<ll> P;\nvector<P> convex_hull(vector<P> pts) {\n int n = si(pts), k = 0;\n if (n <= 2) return pts;\n sort(all(pts));\n vector<P> ch(2 * n);\n for(int i = 0; i < n; ch[k++] = pts[i++]) {\n while(k >= 2 and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) < 0) --k;\n }\n for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = pts[i--]) {\n while(k >= t and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) < 0) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n#undef P\n\ntemplate<class P>\nbool inPolygon(vector<P> &p, P a, bool strict = true) {\n int cnt = 0, n = si(p);\n rep(i, n) {\n P q = p[(i + 1) % n];\n if (onSegment(p[i], q, a)) return !strict;\n cnt ^= ((a.y < p[i].y) - (a.y < q.y)) * a.cross(p[i], q) > 0;\n }\n return cnt;\n}\n\nusing P = Point<ll>;\n\nint main() {\n int n;\n cin >> n;\n vector<P> v;\n rep(i, n) {\n ll x, y;\n cin >> x >> y;\n v.push_back(P(x, y));\n }\n\n auto cv = convex_hull(v);\n auto mp = *min_element(all(cv), [&](P p, P q) { return tie(p.y, p.x) < tie(q.y, q.x); });\n int midx = 0;\n rep(i, si(cv)) if (cv[i] == mp) midx = i;\n\n cout << si(cv) << endl;\n rep(i, si(cv)) {\n auto p = cv[(i + midx) % si(cv)];\n cout << p.x << \" \" << p.y << endl;\n }\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 9704, "score_of_the_acc": -0.5101, "final_rank": 7 }, { "submission_id": "aoj_CGL_4_A_11047883", "code_snippet": "// --- Start of include: ./../../akakoi_lib/template/template.cpp ---\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i,n) for(ll i=0;i<(ll)(n);++i)\nbool chmin(auto& a, auto b) {return a>b?a=b,1:0;}\nbool chmax(auto& a, auto b) {return a<b?a=b,1:0;}\n// int main() {\n// ios::sync_with_stdio(false);\n// cin.tie(0);\n// }\n// --- End of include: ./../../akakoi_lib/template/template.cpp ---\n// --- Start of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n/// @brief 幾何ライブラリ\nnamespace Geometry {\n using Real = long double;\n const Real EPS = 1e-9;\n\n bool almostEqual(Real a, Real b) { return abs(a - b) < EPS; }\n bool lessThan(Real a, Real b) { return a < b && !almostEqual(a, b); }\n bool greaterThan(Real a, Real b) { return a > b && !almostEqual(a, b); }\n bool lessThanOrEqual(Real a, Real b) { return a < b || almostEqual(a, b); }\n bool greaterThanOrEqual(Real a, Real b) { return a > b || almostEqual(a, b); }\n\n /// @brief 2次元平面上の位置ベクトル\n struct Point {\n Real x, y;\n Point() = default;\n Point(Real x, Real y) : x(x), y(y) {}\n\n Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); }\n Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); }\n Point operator*(Real k) const { return Point(x * k, y * k); }\n Point operator/(Real k) const { return Point(x / k, y / k); }\n\n /// @brief p との内積を返す\n Real dot(const Point& p) const { return x * p.x + y * p.y; }\n\n /// @brief p との外積を返す\n Real cross(const Point& p) const { return x * p.y - y * p.x; }\n\n /// @brief p1 と p2 を端点とするベクトルとの外積を返す\n Real cross(const Point& p1, const Point& p2) const { return (p1.x - x) * (p2.y - y) - (p1.y - y) * (p2.x - x); }\n\n /// @brief 2乗ノルムを返す\n Real norm() const { return x * x + y * y; }\n\n /// @brief ユークリッドノルムを返す\n Real abs() const { return sqrt(norm()); }\n\n /// @brief 偏角を返す\n Real arg() const { return atan2(y, x); }\n\n bool operator==(const Point& p) const { return almostEqual(x, p.x) && almostEqual(y, p.y); }\n friend istream& operator>>(istream& is, Point& p) { return is >> p.x >> p.y; }\n };\n\n /// @brief 直線\n struct Line {\n Point a, b;\n Line() = default;\n Line(const Point& _a, const Point& _b) : a(_a), b(_b) {}\n\n /// @brief 直線 Ax+By=C を定義する\n Line(const Real& A, const Real& B, const Real& C) {\n if (almostEqual(A, 0)) {\n assert(!almostEqual(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (almostEqual(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (almostEqual(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n bool operator==(const Line& l) const { return a == l.a && b == l.b; }\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n };\n\n /// @brief 線分\n struct Segment : Line {\n Segment() = default;\n using Line::Line;\n };\n\n /// @brief 円\n struct Circle {\n Point center; ///< 中心\n Real r; ///< 半径\n\n Circle() = default;\n Circle(Real x, Real y, Real r) : center(x, y), r(r) {}\n Circle(Point _center, Real r) : center(_center), r(r) {}\n\n bool operator==(const Circle& C) const { return center == C.center && r == C.r; }\n friend istream& operator>>(istream& is, Circle& C) { return is >> C.center >> C.r; }\n };\n\n //-----------------------------------------------------------\n\n /// @brief 3点の進行方向\n enum Orientation {\n COUNTER_CLOCKWISE, ///< 反時計回り\n CLOCKWISE, ///< 時計回り\n ONLINE_BACK,\n ONLINE_FRONT,\n ON_SEGMENT\n };\n\n /// @brief 3点 p0, p1, p2 の進行方向を返す\n Orientation ccw(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0;\n Point b = p2 - p0;\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) return COUNTER_CLOCKWISE;\n if (lessThan(cross_product, 0)) return CLOCKWISE;\n if (lessThan(a.dot(b), 0)) return ONLINE_BACK;\n if (lessThan(a.norm(), b.norm())) return ONLINE_FRONT;\n return ON_SEGMENT;\n }\n\n string orientationToString(Orientation o) {\n switch (o) {\n case COUNTER_CLOCKWISE:\n return \"COUNTER_CLOCKWISE\";\n case CLOCKWISE:\n return \"CLOCKWISE\";\n case ONLINE_BACK:\n return \"ONLINE_BACK\";\n case ONLINE_FRONT:\n return \"ONLINE_FRONT\";\n case ON_SEGMENT:\n return \"ON_SEGMENT\";\n default:\n return \"UNKNOWN\";\n }\n }\n\n /// @brief ベクトル p の直線 p1, p2 への正射影ベクトルを返す\n Point projection(const Point& p1, const Point& p2, const Point& p) {\n Point base = p2 - p1;\n Real r = (p - p1).dot(base) / base.norm();\n return p1 + base * r;\n }\n\n /// @brief ベクトル p の直線 l への正射影ベクトルを返す\n Point projection(const Line& l, const Point& p) {\n Point base = l.b - l.a;\n Real r = (p - l.a).dot(base) / base.norm();\n return l.a + base * r;\n }\n\n /// @brief ベクトル p の直線 p1, p2 に対する鏡像ベクトルを返す\n Point reflection(const Point& p1, const Point& p2, const Point& p) {\n Point proj = projection(p1, p2, p);\n return proj * 2 - p;\n }\n\n /// @brief ベクトル p の直線 l に対する鏡像ベクトルを返す\n Point reflection(const Line& l, const Point& p) {\n Point proj = projection(l, p);\n return proj * 2 - p;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 直線の平行判定\n bool isParallel(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線の直交判定\n bool isOrthogonal(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分の平行判定\n bool isParallel(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分の直交判定\n bool isOrthogonal(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 直線と線分の平行判定\n bool isParallel(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線と線分の直交判定\n bool isOrthogonal(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分と直線の平行判定\n bool isParallel(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分と直線の直交判定\n bool isOrthogonal(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 点が直線上にあるか判定\n bool isPointOnLine(const Point& p, const Line& l) { return almostEqual((l.b - l.a).cross(p - l.a), 0.0); }\n\n /// @brief 点が線分上にあるか判定\n bool isPointOnSegment(const Point& p, const Segment& s) {\n return lessThanOrEqual(min(s.a.x, s.b.x), p.x) &&\n lessThanOrEqual(p.x, max(s.a.x, s.b.x)) &&\n lessThanOrEqual(min(s.a.y, s.b.y), p.y) &&\n lessThanOrEqual(p.y, max(s.a.y, s.b.y)) &&\n almostEqual((s.b - s.a).cross(p - s.a), 0.0);\n }\n\n /// @brief 直線の交差判定\n bool isIntersecting(const Segment& s1, const Segment& s2) {\n Point p0p1 = s1.b - s1.a, p0p2 = s2.a - s1.a, p0p3 = s2.b - s1.a, p2p3 = s2.b - s2.a, p2p0 = s1.a - s2.a, p2p1 = s1.b - s2.a;\n Real d1 = p0p1.cross(p0p2), d2 = p0p1.cross(p0p3), d3 = p2p3.cross(p2p0), d4 = p2p3.cross(p2p1);\n if (lessThan(d1 * d2, 0) && lessThan(d3 * d4, 0)) return true;\n if (almostEqual(d1, 0.0) && isPointOnSegment(s2.a, s1)) return true;\n if (almostEqual(d2, 0.0) && isPointOnSegment(s2.b, s1)) return true;\n if (almostEqual(d3, 0.0) && isPointOnSegment(s1.a, s2)) return true;\n if (almostEqual(d4, 0.0) && isPointOnSegment(s1.b, s2)) return true;\n return false;\n }\n\n /// @brief 線分の交点を返す\n Point getIntersection(const Segment& s1, const Segment& s2) {\n assert(isIntersecting(s1, s2));\n auto cross = [](Point p, Point q) { return p.x * q.y - p.y * q.x; };\n Point base = s2.b - s2.a;\n Real d1 = abs(cross(base, s1.a - s2.a));\n Real d2 = abs(cross(base, s1.b - s2.a));\n Real t = d1 / (d1 + d2);\n return s1.a + (s1.b - s1.a) * t;\n }\n\n /// @brief 点と線分の距離を返す\n Real distancePointToSegment(const Point& p, const Segment& s) {\n Point proj = projection(s.a, s.b, p);\n if (isPointOnSegment(proj, s))\n return (p - proj).abs();\n else\n return min((p - s.a).abs(), (p - s.b).abs());\n }\n\n /// @brief 線分と線分の距離を返す\n Real distanceSegmentToSegment(const Segment& s1, const Segment& s2) {\n if (isIntersecting(s1, s2)) return 0.0;\n return min({distancePointToSegment(s1.a, s2),\n distancePointToSegment(s1.b, s2),\n distancePointToSegment(s2.a, s1),\n distancePointToSegment(s2.b, s1)});\n }\n\n //-----------------------------------------------------------\n\n /// @brief 多角形の面積を返す\n Real getPolygonArea(const vector<Point>& points) {\n int n = points.size();\n Real area = 0.0;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n area += points[i].x * points[j].y;\n area -= points[i].y * points[j].x;\n }\n return abs(area) / 2.0;\n }\n\n /// @brief 多角形が凸か判定\n bool isConvex(const vector<Point>& points) {\n int n = points.size();\n bool has_positive = false, has_negative = false;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n int k = (i + 2) % n;\n Point a = points[j] - points[i];\n Point b = points[k] - points[j];\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) has_positive = true;\n if (lessThan(cross_product, 0)) has_negative = true;\n }\n return !(has_positive && has_negative);\n }\n\n /// @brief 点が凸多角形の辺上に存在するか判定\n bool isPointOnPolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n Segment s(a, b);\n if (isPointOnSegment(p, s)) return true;\n }\n return false;\n }\n\n /// @brief 点が多角形の内部に存在するか判定(辺上は含まない)\n bool isPointInsidePolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n bool inPolygon = false;\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n if (greaterThan(a.y, b.y)) swap(a, b);\n if (lessThanOrEqual(a.y, p.y) && lessThan(p.y, b.y) && greaterThan((b - a).cross(p - a), 0)) inPolygon = !inPolygon;\n }\n return inPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 凸包を求める\n vector<Point> convexHull(vector<Point>& points, bool include_collinear = false) {\n int n = points.size();\n if (n <= 1) return points;\n sort(points.begin(), points.end(), [](const Point& l, const Point& r) -> bool {\n if (almostEqual(l.y, r.y)) return lessThan(l.x, r.x);\n return lessThan(l.y, r.y);\n });\n if (n == 2) return points;\n vector<Point> upper = {points[0], points[1]}, lower = {points[0], points[1]};\n for (int i = 2; i < n; i++) {\n while (upper.size() >= 2 && ccw(upper.end()[-2], upper.end()[-1], points[i]) != CLOCKWISE) {\n if (ccw(upper.end()[-2], upper.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n upper.pop_back();\n }\n upper.push_back(points[i]);\n while (lower.size() >= 2 && ccw(lower.end()[-2], lower.end()[-1], points[i]) != COUNTER_CLOCKWISE) {\n if (ccw(lower.end()[-2], lower.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n lower.pop_back();\n }\n lower.push_back(points[i]);\n }\n reverse(upper.begin(), upper.end());\n upper.pop_back();\n lower.pop_back();\n lower.insert(lower.end(), upper.begin(), upper.end());\n return lower;\n }\n\n /// @brief 凸包の直径を求める\n Real convexHullDiameter(const vector<Point>& hull) {\n int n = hull.size();\n if (n == 1) return 0;\n int k = 1;\n Real max_dist = 0;\n for (int i = 0; i < n; i++) {\n while (true) {\n int j = (k + 1) % n;\n Point dist1 = hull[i] - hull[j], dist2 = hull[i] - hull[k];\n max_dist = max(max_dist, dist1.abs());\n max_dist = max(max_dist, dist2.abs());\n if (dist1.abs() > dist2.abs())\n k = j;\n else\n break;\n }\n Point dist = hull[i] - hull[k];\n max_dist = max(max_dist, dist.abs());\n }\n return max_dist;\n }\n\n /// @brief 凸包を直線で切断して左側を返す\n vector<Point> cutPolygon(const vector<Point>& g, const Line& l) {\n auto isLeft = [](const Point& p1, const Point& p2, const Point& p) -> bool { return (p2 - p1).cross(p - p1) > 0; };\n vector<Point> newPolygon;\n int n = g.size();\n for (int i = 0; i < n; i++) {\n const Point& cur = g[i];\n const Point& next = g[(i + 1) % n];\n if (isLeft(l.a, l.b, cur)) newPolygon.push_back(cur);\n if ((isLeft(l.a, l.b, cur) && !isLeft(l.a, l.b, next)) || (!isLeft(l.a, l.b, cur) && isLeft(l.a, l.b, next))) {\n Real A1 = (next - cur).cross(l.a - cur);\n Real A2 = (next - cur).cross(l.b - cur);\n Point intersection = l.a + (l.b - l.a) * (A1 / (A1 - A2));\n newPolygon.push_back(intersection);\n }\n }\n return newPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 最近点対の距離を求める\n /// @note points は x 座標でソートされている必要がある\n Real closestPair(vector<Point>& points, int l, int r) {\n if (r - l <= 1) return numeric_limits<Real>::max();\n int mid = (l + r) >> 1;\n Real x = points[mid].x;\n Real d = min(closestPair(points, l, mid), closestPair(points, mid, r));\n auto iti = points.begin(), itl = iti + l, itm = iti + mid, itr = iti + r;\n inplace_merge(itl, itm, itr, [](const Point& lhs, const Point& rhs) -> bool {\n return lessThan(lhs.y, rhs.y);\n });\n vector<Point> nearLine;\n for (int i = l; i < r; i++) {\n if (greaterThanOrEqual(fabs(points[i].x - x), d)) continue;\n int sz = nearLine.size();\n for (int j = sz - 1; j >= 0; j--) {\n Point dv = points[i] - nearLine[j];\n if (dv.y >= d) break;\n d = min(d, dv.abs());\n }\n nearLine.push_back(points[i]);\n }\n return d;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 線分の交差数を数える\n int countIntersections(vector<Segment> segments) {\n struct Event {\n Real x;\n int type; // 0:horizontal start,1:vertical,2:horizontal end\n Real y1, y2;\n Event(Real x, int type, Real y1, Real y2) : x(x), type(type), y1(y1), y2(y2) {}\n bool operator<(const Event& other) const {\n if (x == other.x) return type < other.type;\n return x < other.x;\n }\n };\n vector<Event> events;\n sort(segments.begin(), segments.end(), [](const Segment& lhs, const Segment& rhs) -> bool {\n return lessThan(min(lhs.a.x, lhs.b.x), min(rhs.a.x, rhs.b.x));\n });\n for (const auto& seg : segments) {\n if (seg.a.y == seg.b.y) {\n // Horizontal segment\n Real y = seg.a.y;\n Real x1 = min(seg.a.x, seg.b.x);\n Real x2 = max(seg.a.x, seg.b.x);\n events.emplace_back(x1, 0, y, y);\n events.emplace_back(x2, 2, y, y);\n } else {\n // Vertical segment\n Real x = seg.a.x;\n Real y1 = min(seg.a.y, seg.b.y);\n Real y2 = max(seg.a.y, seg.b.y);\n events.emplace_back(x, 1, y1, y2);\n }\n }\n sort(events.begin(), events.end());\n set<Real> activeSegments;\n int intersectionCount = 0;\n for (const auto& event : events) {\n if (event.type == 0) {\n // Add horizontal segment to active set\n activeSegments.insert(event.y1);\n } else if (event.type == 2) {\n // Remove horizontal segment from active set\n activeSegments.erase(event.y1);\n } else if (event.type == 1) {\n // Count intersections with vertical segment\n auto lower = activeSegments.lower_bound(event.y1);\n auto upper = activeSegments.upper_bound(event.y2);\n intersectionCount += distance(lower, upper);\n }\n }\n return intersectionCount;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 2つの円の交点の個数を返す\n int countCirclesIntersection(const Circle& c1, const Circle& c2) {\n Real d =\n sqrt((c1.center.x - c2.center.x) * (c1.center.x - c2.center.x) +\n (c1.center.y - c2.center.y) * (c1.center.y - c2.center.y));\n Real r1 = c1.r, r2 = c2.r;\n if (greaterThan(d, r1 + r2))\n return 4;\n else if (almostEqual(d, r1 + r2))\n return 3;\n else if (greaterThan(d, fabs(r1 - r2)))\n return 2;\n else if (almostEqual(d, fabs(r1 - r2)))\n return 1;\n else\n return 0;\n }\n\n /// @brief 内接円を求める\n Circle getInCircle(const Point& A, const Point& B, const Point& C) {\n Real a = (B - C).abs();\n Real b = (A - C).abs();\n Real c = (A - B).abs();\n Real s = (a + b + c) / 2;\n Real area = sqrt(s * (s - a) * (s - b) * (s - c));\n Real r = area / s;\n Real cx = (a * A.x + b * B.x + c * C.x) / (a + b + c);\n Real cy = (a * A.y + b * B.y + c * C.y) / (a + b + c);\n return Circle{Point(cx, cy), r};\n }\n\n /// @brief 外接円を求める\n Circle getCircumCircle(const Point& A, const Point& B, const Point& C) {\n Real D = 2 * (A.x * (B.y - C.y) + B.x * (C.y - A.y) + C.x * (A.y - B.y));\n Real Ux = ((A.x * A.x + A.y * A.y) * (B.y - C.y) + (B.x * B.x + B.y * B.y) * (C.y - A.y) + (C.x * C.x + C.y * C.y) * (A.y - B.y)) / D;\n Real Uy = ((A.x * A.x + A.y * A.y) * (C.x - B.x) + (B.x * B.x + B.y * B.y) * (A.x - C.x) + (C.x * C.x + C.y * C.y) * (B.x - A.x)) / D;\n Point center(Ux, Uy);\n Real radius = (center - A).abs();\n return Circle{center, radius};\n }\n\n /// @brief 円と直線の交点を求める\n vector<Point> getCircleLineIntersection(const Circle& c, Point p1, Point p2) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real dx = p2.x - p1.x;\n Real dy = p2.y - p1.y;\n Real a = dx * dx + dy * dy;\n Real b = 2 * (dx * (p1.x - cx) + dy * (p1.y - cy));\n Real c_const = (p1.x - cx) * (p1.x - cx) + (p1.y - cy) * (p1.y - cy) - r * r;\n Real discriminant = b * b - 4 * a * c_const;\n vector<Point> intersections;\n if (almostEqual(discriminant, 0)) {\n Real t = -b / (2 * a);\n Real ix = p1.x + t * dx;\n Real iy = p1.y + t * dy;\n intersections.emplace_back(ix, iy);\n intersections.emplace_back(ix, iy);\n } else if (discriminant > 0) {\n Real sqrt_discriminant = sqrt(discriminant);\n Real t1 = (-b + sqrt_discriminant) / (2 * a);\n Real t2 = (-b - sqrt_discriminant) / (2 * a);\n Real ix1 = p1.x + t1 * dx;\n Real iy1 = p1.y + t1 * dy;\n Real ix2 = p1.x + t2 * dx;\n Real iy2 = p1.y + t2 * dy;\n intersections.emplace_back(ix1, iy1);\n intersections.emplace_back(ix2, iy2);\n }\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 2つの円の交点を求める\n vector<Point> getCirclesIntersect(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real d = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n if (d > r1 + r2 || d < abs(r1 - r2)) return {}; // No intersection\n Real a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);\n Real h = sqrt(r1 * r1 - a * a);\n Real x0 = x1 + a * (x2 - x1) / d;\n Real y0 = y1 + a * (y2 - y1) / d;\n Real rx = -(y2 - y1) * (h / d);\n Real ry = (x2 - x1) * (h / d);\n Point p1(x0 + rx, y0 + ry);\n Point p2(x0 - rx, y0 - ry);\n vector<Point> intersections;\n intersections.push_back(p1);\n intersections.push_back(p2);\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 点から引ける円の接線の接点を求める\n vector<Point> getTangentLinesFromPoint(const Circle& c, const Point& p) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real px = p.x, py = p.y;\n Real dx = px - cx;\n Real dy = py - cy;\n Real d = (p - c.center).abs();\n if (lessThan(d, r))\n return {}; // No tangents if the point is inside the circle\n else if (almostEqual(d, r))\n return {p};\n Real a = r * r / d;\n Real h = sqrt(r * r - a * a);\n Real cx1 = cx + a * dx / d;\n Real cy1 = cy + a * dy / d;\n vector<Point> tangents;\n tangents.emplace_back(cx1 + h * dy / d, cy1 - h * dx / d);\n tangents.emplace_back(cx1 - h * dy / d, cy1 + h * dx / d);\n if (almostEqual(tangents[0].x, tangents[1].x)) {\n if (greaterThan(tangents[0].y, tangents[1].y)) swap(tangents[0], tangents[1]);\n } else if (greaterThan(tangents[0].x, tangents[1].x)) {\n swap(tangents[0], tangents[1]);\n }\n return tangents;\n }\n\n /// @brief 2つの円の共通接線を求める\n vector<Segment> getCommonTangentsLine(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real dx = x2 - x1;\n Real dy = y2 - y1;\n Real d = sqrt(dx * dx + dy * dy);\n vector<Segment> tangents;\n // Coincident circles(infinite tangents)\n if (almostEqual(d, 0) && almostEqual(r1, r2)) return tangents;\n // External tangents\n if (greaterThanOrEqual(d, r1 + r2)) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 + r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 + r2 * cos(a + sign * theta);\n Real cy2 = y2 + r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, r1 + r2)) break;\n }\n }\n // Internal tangents\n if (greaterThanOrEqual(d, fabs(r1 - r2))) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 - r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 - r2 * cos(a + sign * theta);\n Real cy2 = y2 - r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, fabs(r1 - r2))) break;\n }\n }\n sort(tangents.begin(), tangents.end(), [&](const Segment& s1, const Segment& s2) {\n if (almostEqual(s1.a.x, s2.a.x))\n return lessThan(s1.a.y, s2.a.y);\n else\n return lessThan(s1.a.x, s2.a.x);\n });\n return tangents;\n }\n}\n// --- End of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n\nusing namespace Geometry;\n\nvoid solve() {\n int n; cin >> n;\n vector<Point> P(n);\n rep(i, n) {\n Real x, y; cin >> x >> y;\n P[i] = {x, y};\n }\n auto H = convexHull(P, true);\n cout << H.size() << endl;\n for (auto [x, y] : H) {\n cout << x << \" \" << y << endl;\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout << fixed << setprecision(0);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 11252, "score_of_the_acc": -1.0625, "final_rank": 15 }, { "submission_id": "aoj_CGL_4_A_11043136", "code_snippet": "#line 1 \"convexHull.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\"\n#line 1 \"/home/zawatin/compro/bonsai-library/test/template.hpp\"\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep2(i, n) for (ll i = 0; i < (n); i++) \n#define rep3(i, a, b) for(ll i = a; i < (b); i++)\n#define overload(a, b, c, d, ...) d\n#define rep(...) overload(__VA_ARGS__, rep3, rep2)(__VA_ARGS__)\n#define all(a) begin(a), end(a)\n#define sz(a) ssize(a)\nbool chmin(auto& a, auto b) { return a > b ? a = b, 1 : 0; }\nbool chmax(auto& a, auto b) { return a < b ? a = b, 1 : 0; }\n\n#line 3 \"convexHull.test.cpp\"\n//#include \"../../src/geometry/geometryR2.hpp\"\nusing Z = long long;\nstruct Point {\n Z x, y;\n auto operator<=>(const Point&) const = default;\n};\nPoint operator-(const Point& p, const Point& q) {\n return {p.x-q.x, p.y-q.y};\n}\nbool Zero(Z v) {\n return v == 0;\n}\nbool Negative(Z v) {\n return v < 0;\n}\nbool Positive(Z v) {\n return v > 0;\n}\nbool Smaller(Z a, Z b) {\n return a < b;\n}\nZ Cross(Point p, Point q) {\n return p.x * q.y - p.y * q.x;\n}\nZ Dot(Point p, Point q) {\n return p.x * q.x + p.y * q.y;\n}\nZ NormSq(Point p) {\n return Dot(p, p);\n}\nenum RELATION {\n // p0 -> p1 -> p2\n ONLINE_FRONT = -2,\n CLOCKWISE,\n // p0 -> p2 -> p1\n ON_SEGMENT,\n COUNTER_CLOCKWISE,\n // p2 -> p0 -> p1 or p1 -> p0 -> p2\n ONLINE_BACK\n};\n// base point is p0\n// note: very slow!, gosa yabai! (Z2 ha gosanasi)\nRELATION Relation(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0, b = p2 - p0;\n if (!Zero(Cross(a, b)))\n return Positive(Cross(a, b)) ? COUNTER_CLOCKWISE : CLOCKWISE;\n return Negative(Dot(a, b)) ? ONLINE_BACK : (Smaller(NormSq(a), NormSq(b)) ? ONLINE_FRONT : ON_SEGMENT);\n}\n\n// You have to write Relation, Cross, Dot, and some operator override\n// Copy from geometryR2\nvector<Point> ConvexHull(vector<Point> p, bool strictly = true) {\n sort(p.begin(), p.end());\n p.erase(unique(p.begin(), p.end()), p.end());\n if (ssize(p) <= 2)\n return p;\n auto sweep = [&](auto first, auto last) {\n vector<Point> res;\n res.reserve(ssize(p));\n for (auto it = first ; it != last ; it++) {\n res.push_back(*it);\n while (ssize(res) >= 3) {\n auto rel = Relation(res[ssize(res)-3], res[ssize(res)-2], res[ssize(res)-1]);\n if (rel == COUNTER_CLOCKWISE)\n break;\n if (!strictly and rel == ONLINE_FRONT)\n break;\n swap(res[ssize(res)-2], res[ssize(res)-1]);\n res.pop_back();\n }\n }\n return res;\n };\n auto low = sweep(p.begin(), p.end()), up = sweep(p.rbegin(), p.rend());\n vector<Point> res;\n res.reserve(low.size()+up.size()-2);\n res.insert(res.end(), low.begin(), low.end());\n res.insert(res.end(), next(up.begin()), prev(up.end()));\n return res;\n}\nint main() {\n int n;\n cin >> n;\n vector<Point> P(n);\n for (Point& p : P)\n cin >> p.x >> p.y;\n auto ans = ConvexHull(P, false);\n ranges::rotate(ans, ranges::min_element(ans, [&](const auto& a, const auto& b) {\n return a.y != b.y ? a.y < b.y : a.x < b.x;\n }));\n cout << ssize(ans) << '\\n';\n for (auto p : ans)\n cout << p.x << ' ' << p.y << '\\n';\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8320, "score_of_the_acc": -0.3054, "final_rank": 4 }, { "submission_id": "aoj_CGL_4_A_11043100", "code_snippet": "#line 1 \"convexHull.test.cpp\"\n#define PROBLEM \"https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\"\n#line 1 \"/home/zawatin/compro/bonsai-library/test/template.hpp\"\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep2(i, n) for (ll i = 0; i < (n); i++) \n#define rep3(i, a, b) for(ll i = a; i < (b); i++)\n#define overload(a, b, c, d, ...) d\n#define rep(...) overload(__VA_ARGS__, rep3, rep2)(__VA_ARGS__)\n#define all(a) begin(a), end(a)\n#define sz(a) ssize(a)\nbool chmin(auto& a, auto b) { return a > b ? a = b, 1 : 0; }\nbool chmax(auto& a, auto b) { return a < b ? a = b, 1 : 0; }\n\n#line 1 \"/home/zawatin/compro/bonsai-library/src/geometry/geometryR2.hpp\"\n// Real \nusing R = long double;\n\n// CHECK THIS!!\nconst R EPS = 1e-12;\ninline bool Positive(R v) {\n return v > EPS;\n}\ninline bool Negative(R v) {\n return v < -EPS;\n}\ninline bool Zero(R v) {\n return !Positive(v) and !Negative(v);\n}\ninline bool Smaller(R l, R r) {\n return Negative(l - r);\n}\ninline bool Bigger(R l, R r) {\n return Positive(l - r);\n}\ninline bool Equal(R l, R r) {\n return Zero(l - r);\n}\n\ninline R Square(R v) {\n return Zero(v) ? v : v * v;\n}\ninline R Sqrt(R v) {\n // kyokutan ni tiisai toki dake dame to suru\n // ABC426-E Closest Moment\n assert(v > -0.1);\n return sqrtl(max<R>(0, v));\n}\ninline R Abs(R v) {\n return Negative(v) ? -v : v;\n}\n\n// Angle\n\nconst R PI = acosl(-1);\nconst R TAU = 2 * PI;\nR ArcToRad(R arc) {\n return (arc * PI) / 180.l;\n}\nR RadToArc(R rad) {\n return (rad * 180) / PI;\n}\n\n// Point\n\nstruct Point {\n R x, y;\n};\n\nPoint operator+(const Point& p, const Point& q) {\n return {p.x + q.x, p.y + q.y};\n}\nPoint operator-(const Point& p, const Point& q) {\n return {p.x - q.x, p.y - q.y};\n}\nPoint operator-(const Point& p) {\n return {-p.x, -p.y};\n}\nPoint operator*(const Point& p, R k) {\n return {p.x * k, p.y * k};\n}\nPoint operator/(const Point& p, R k) {\n return {p.x / k, p.y / k};\n}\nbool operator<(const Point& p, const Point& q) {\n if (!Equal(p.x, q.x))\n return Smaller(p.x, q.x);\n return Smaller(p.y, q.y);\n}\nbool operator==(const Point& p, const Point& q) {\n return Equal(p.x, q.x) and Equal(p.y, q.y);\n}\n\nostream& operator<<(ostream& os, const Point& p) {\n os << '(' << p.x << ',' << p.y << ')';\n return os; \n}\nistream& operator>>(istream& is, Point& p) {\n is >> p.x >> p.y;\n return is;\n}\n\nR NormSq(const Point& p) {\n return Square(p.x) + Square(p.y);\n}\nR Norm(const Point& p) {\n return Sqrt(Norm(p));\n}\nPoint Normalized(const Point& p) {\n return p / Sqrt(NormSq(p));\n}\nR DistSq(const Point& p, const Point& q) {\n return NormSq(p - q);\n}\nR Dist(const Point& p, const Point& q) {\n return Sqrt(DistSq(p, q));\n}\nR Dot(const Point& p, const Point& q) {\n return p.x * q.x + p.y * q.y;\n}\nR Cross(const Point& p, const Point& q) {\n return p.x * q.y - p.y * q.x;\n}\n\nPoint Rotated(const Point& p, R rad) {\n return {p.x * cosl(rad) - p.y * sinl(rad), p.x * sinl(rad) + p.y * cosl(rad)};\n}\nPoint Rot90(const Point& p) {\n return {-p.y, p.x};\n}\nR Argument(const Point& p) {\n return atan2l(p.y, p.x);\n}\n\nenum RELATION {\n // p0 -> p1 -> p2\n ONLINE_FRONT = -2,\n CLOCKWISE,\n // p0 -> p2 -> p1\n ON_SEGMENT,\n COUNTER_CLOCKWISE,\n // p2 -> p0 -> p1 or p1 -> p0 -> p2\n ONLINE_BACK\n};\n// base point is p0\n// note: very slow!, gosa yabai! (Z2 ha gosanasi)\nRELATION Relation(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0, b = p2 - p0;\n if (!Zero(Cross(a, b)))\n return Positive(Cross(a, b)) ? COUNTER_CLOCKWISE : CLOCKWISE;\n return Negative(Dot(a, b)) ? ONLINE_BACK : (Smaller(NormSq(a), NormSq(b)) ? ONLINE_FRONT : ON_SEGMENT);\n}\n\nenum ContainRest {\n INSIDE,\n ON,\n OUTSIDE\n};\n\n// Line\nstruct Line {\n Point a, b;\n};\n\nbool Parallel(const Line& a, const Line& b) {\n return Zero(Cross(a.b - a.a, b.b - b.a));\n}\nbool Orthogonal(const Line& a, const Line& b) {\n return Zero(Dot(a.b - a.a, b.b - b.a));\n}\n\n// Projection\nPoint Projection(const Point& p, const Line& l) {\n R coef = Dot(l.b - l.a, p - l.a) / DistSq(l.a, l.b);\n return l.b * coef + l.a * (1 - coef);\n}\nPoint Reflection(const Point& p, const Line& l) {\n return Projection(p, l) * 2 - p;\n}\n\n// Segment\nstruct Segment {\n Point a, b;\n R lenSq() const {\n return DistSq(a, b);\n }\n R len() const {\n return Dist(a, b);\n }\n Point ab() const {\n return b - a;\n }\n Point ba() const {\n return a - b;\n }\n};\n\nbool Straddle(const Segment& s, const Segment& t) {\n return Relation(s.a, s.b, t.a) * Relation(s.a, s.b, t.b) <= 0;\n}\n\nbool Intersect(Segment s, Segment t) {\n return Straddle(s, t) and Straddle(t, s);\n}\n\noptional<Point> CrossPoint(Segment s, Segment t) {\n if (!Intersect(s, t))\n return nullopt;\n if (Zero(Cross(s.ab(), t.ab()))) {\n // |{Cross Point}} != 1 case (return arbitry one)\n // This case is not verified...\n for (int i = 0 ; i < 2 ; i++) {\n if (Negative(Dot(s.ab(), t.a - s.a)))\n return s.a;\n if (Negative(Dot(s.ab(), t.b - s.a)))\n return s.a;\n if (Negative(Dot(s.ba(), t.a - s.b)))\n return s.b;\n if (Negative(Dot(s.ba(), t.b - s.b)))\n return s.b;\n swap(s, t);\n }\n assert(0);\n return Point{};\n }\n else {\n // This part is verified\n R norm = Sqrt(NormSq(s.ab()));\n R r1 = abs(Cross(s.ab(), t.a - s.a)) / norm;\n R r2 = abs(Cross(s.ab(), t.b - s.a)) / norm;\n return t.a + t.ab() * (r1 / (r1 + r2));\n }\n}\n\nR Dist(const Point& p, const Segment& s) {\n if (Negative(Dot(s.ab(), p - s.a)))\n return Dist(p, s.a);\n if (Negative(Dot(s.ba(), p - s.b)))\n return Dist(p, s.b);\n return Abs(Cross(s.ab(), p - s.a)) / s.len();\n}\n\nR Dist(Segment s, Segment t) {\n if (Intersect(s, t))\n return 0;\n else\n return min({Dist(s.a, t), Dist(s.b, t), Dist(t.a, s), Dist(t.b, s)});\n}\n\n// Polygon, PointCloud\n// note: ranges::sort, ranges::min_element, ... etc is not avaiable\nusing Poly = vector<Point>;\nusing PointCloud = vector<Point>;\n\nR Area(const Poly& p) {\n R res = 0;\n for (int i = 1 ; i < ssize(p) ; i++)\n res += Cross(p[i] - p[0], p[(i+1)%ssize(p)] - p[0]);\n return res / 2;\n}\n\nbool IsConvex(const Poly& p) {\n assert(ssize(p) >= 3);\n for (int i = 0 ; i < ssize(p) ; i++)\n if (Relation(p[i], p[(i+1)%ssize(p)], p[(i+2)%ssize(p)]) == CLOCKWISE)\n return false;\n return true;\n}\n\n// not have to convex\nContainRest Contain(const Poly& poly, const Point& p) {\n int odd = 0;\n int n = ssize(poly);\n for (int i = 0 ; i < n ; i++) {\n if (poly[i] == p)\n return ON;\n if (Relation(poly[i], poly[(i+1)%n], p) == ON_SEGMENT)\n return ON;\n Point a = poly[i] - p, b = poly[(i+1)%n] - p;\n if (Bigger(a.y, b.y))\n swap(a, b);\n odd ^= !Positive(a.y) and Positive(b.y) and Positive(Cross(a, b));\n }\n return odd ? INSIDE : OUTSIDE;\n}\n\nPoly ConvexHull(PointCloud p, bool strictly = true) {\n sort(p.begin(), p.end());\n p.erase(unique(p.begin(), p.end()), p.end());\n if (ssize(p) <= 2)\n return Poly{p};\n auto sweep = [&](auto first, auto last) -> PointCloud {\n PointCloud res;\n res.reserve(ssize(p));\n for (auto it = first ; it != last ; it++) {\n res.push_back(*it);\n while (ssize(res) >= 3) {\n auto rel = Relation(res[ssize(res)-3], res[ssize(res)-2], res[ssize(res)-1]);\n if (rel == COUNTER_CLOCKWISE)\n break;\n if (!strictly and rel == ONLINE_FRONT)\n break;\n swap(res[ssize(res)-2], res[ssize(res)-1]);\n res.pop_back();\n }\n }\n return res;\n };\n auto low = sweep(p.begin(), p.end()), up = sweep(p.rbegin(), p.rend());\n Poly res;\n res.reserve(low.size()+up.size()-2);\n res.insert(res.end(), low.begin(), low.end());\n res.insert(res.end(), next(up.begin()), prev(up.end()));\n return res;\n}\n\n// Circle\nstruct Circle {\n Point p;\n R r;\n};\n\noptional<Circle> CircumscribedCircle(Point p, Point q, Point r) {\n if (Zero(Cross(q - p, r - p)))\n return nullopt;\n auto bisec = [&](Point a, Point b) {\n Point m = (a + b) / 2, v = Rot90(b - a);\n return pair{m, m + v};\n };\n auto l0 = bisec(p, q), l1 = bisec(p, r);\n // This is CrossPointLine\n Point c = l0.first + (l0.second - l0.first) * \n (Cross(l1.first - l0.first, l1.second - l1.first) / Cross(l0.second - l0.first, l1.second - l1.first));\n R rad = Sqrt(DistSq(p, c));\n return Circle{c, rad};\n}\n\n//optional<Circle> InCircle(Point p, Point q, Point r) {\n// if (Zero(Cross(q - p, r - p)))\n// return nullopt;\n// auto bisec = [&](Point a, Point b, Point c) -> pair<Point, Point> {\n// Point ba = b - a, ca = c - a;\n// Point op = a + Rotated((Argument(ca) - Arugment(ba)) / 2);\n// return {a, op};\n// };\n// auto l0 = bisec(p, q, r), l1 = bisec(q, p, r);\n// Point c = l0.first + (l0.second - l0.first) * \n// (Cross(l1.first - l0.first, l1.second - l1.first) / Cross(l0.second - l0.first, l1.second - l1.first));\n//}\n\nint NumberCommonTangent(const Circle& a, const Circle& b) {\n R d = DistSq(a.p, b.p);\n R down = Square(abs(a.r - b.r));\n if (Smaller(d, down))\n return 0;\n if (Equal(d, down))\n return 1;\n R up = Square(a.r + b.r);\n if (Smaller(d, up))\n return 2;\n if (Equal(d, up))\n return 3;\n return 4;\n}\n\noptional<pair<Point, Point>> CrossPoint(Circle a, Circle b) {\n int n = NumberCommonTangent(a, b);\n if (n == 0 or n == 4)\n return nullopt;\n if (Bigger(a.r, b.r))\n swap(a, b);\n if (Zero(a.r))\n return pair{a.p, b.p};\n R d = Sqrt(DistSq(a.p, b.p));\n R cosin = (Square(a.r) + Square(d) - Square(b.r)) / (2*a.r*d);\n R rc = a.r*cosin, rs = Sqrt(Square(a.r) - Square(rc));\n Point lr = Normalized(b.p - a.p), h = a.p + lr * rc;\n Point p = h + Rot90(lr) * rs, q = h + Point{lr.y, -lr.x} * rs;\n return pair{p, q};\n}\n#line 4 \"convexHull.test.cpp\"\nint main() {\n int n;\n cin >> n;\n vector<Point> P(n);\n for (Point& p : P)\n cin >> p;\n auto ans = ConvexHull(P, false);\n ranges::rotate(ans, ranges::min_element(ans, [&](const auto& a, const auto& b) {\n if (!Equal(a.y, b.y))\n return Smaller(a.y, b.y);\n return Smaller(a.x, b.y);\n }));\n cout << ssize(ans) << '\\n';\n for (auto p : ans)\n cout << p.x << ' ' << p.y << '\\n';\n}", "accuracy": 0.9583333333333334, "time_ms": 70, "memory_kb": 13460, "score_of_the_acc": -1.1727, "final_rank": 20 }, { "submission_id": "aoj_CGL_4_A_11031586", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool to_left(pair<int, int> a, pair<int, int> b, pair<int, int> c) {\n\t// Cambiar a >= si se quiere incluir los puntos en los bordes también :v\n\treturn 1ll * (b.first - a.first) * (c.second - b.second) >= 1ll * (c.first - b.first) * (b.second - a.second);\n}\n\nvector<pair<int, int>> get_lower_hull(vector<pair<int, int>> P) {\n\tvector<pair<int, int>> CH;\n\tfor(auto e : P) {\n\t\twhile(CH.size() >= 2 and !to_left(CH[(int)CH.size() - 2], CH[(int)CH.size() - 1], e)) {\n\t\t\tCH.pop_back();\n\t\t}\n\t\tCH.emplace_back(e);\n\t}\n\treturn CH;\n}\n\nvector<pair<int, int>> convex_hull(vector<pair<int, int>> P) {\n\tsort(P.begin(), P.end());\n\tvector<pair<int, int>> lower = get_lower_hull(P);\n\treverse(P.begin(), P.end());\n\tvector<pair<int, int>> upper = get_lower_hull(P);\n\tfor(int i = 1; i + 1 < upper.size(); i++) {\n\t\tlower.emplace_back(upper[i]);\n\t}\n\treturn lower;\n}\n\nint main() {\n\tcin.tie(0) -> sync_with_stdio(false);\n\tint n;\n\tcin >> n;\n\tvector<pair<int, int>> P(n);\n\tfor(int i = 0; i < n; i++) cin >> P[i].first >> P[i].second;\n\tvector<pair<int, int>> CH = convex_hull(P);\n\tcout << CH.size() << '\\n';\n\tint at = 0;\n\tfor(int i = 1; i < CH.size(); i++) {\n\t\tif(CH[at].second > CH[i].second) {\n\t\t\tat = i;\n\t\t}\n\t\telse if(CH[at].second == CH[i].second and CH[at].first > CH[i].first) {\n\t\t\tat = i;\n\t\t}\n\t}\n\tfor(int i = 0; i < CH.size(); i++) {\n\t\tint to = (at + i) % CH.size();\n\t\tcout << CH[to].first << \" \" << CH[to].second << '\\n';\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6032, "score_of_the_acc": -0.1047, "final_rank": 3 }, { "submission_id": "aoj_CGL_4_A_11015372", "code_snippet": "// https://tubo28.me/compprog/algorithm/ より.\n\n#include <bits/stdc++.h>\n// #define int int64_t\n\n#define FOR(i, a, b) for (int i = (a); i < int(b); ++i)\n#define RFOR(i, a, b) for (int i = (b)-1; i >= int(a); --i)\n#define rep(i, n) FOR(i, 0, n)\n#define rep1(i, n) FOR(i, 1, int(n) + 1)\n#define rrep(i, n) RFOR(i, 0, n)\n#define rrep1(i, n) RFOR(i, 1, int(n) + 1)\n#define all(c) begin(c), end(c)\nnamespace io {\n#ifdef LOCAL\n#define dump(...) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #__VA_ARGS__ << \" = \"; \\\n io::print_to(os, \", \", \"\\n\", __VA_ARGS__); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dump_(cntnr) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #cntnr << \" = [\"; \\\n io::print_to_(os, \", \", \"]\\n\", all(cntnr)); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dumpf(fmt, ...) \\\n do { \\\n const int N = 4096; \\\n auto b = new char[N]; \\\n int l = snprintf(b, N, \"%d:\\t\", __LINE__); \\\n snprintf(b + l, N - l, fmt, ##__VA_ARGS__); \\\n std::cerr << io::highlight(b) << std::endl; \\\n delete[] b; \\\n } while (0)\n#else\n#define dump(...)\n#define dump_(...)\n#define dumpf(...)\n#endif\nstd::string highlight(std::string s) {\n#ifdef _MSC_VER\n return s;\n#else\n return \"\\033[33m\" + s + \"\\033[0m\";\n#endif\n}\ntemplate <typename T>\nvoid print_to(std::ostream &os, std::string, std::string tail, const T &first) {\n os << first << tail;\n}\ntemplate <typename F, typename... R>\nvoid print_to(std::ostream &os, std::string del, std::string tail, const F &first,\n const R &... rest) {\n os << first << del;\n print_to(os, del, tail, rest...);\n}\ntemplate <typename I>\nvoid print_to_(std::ostream &os, std::string del, std::string tail, I begin, I end) {\n for (I it = begin; it != end;) {\n os << *it;\n os << (++it != end ? del : tail);\n }\n}\ntemplate <typename F, typename... R>\nvoid println(const F &first, const R &... rest) {\n print_to(std::cout, \"\\n\", \"\\n\", first, rest...);\n}\ntemplate <typename F, typename... R>\nvoid print(const F &first, const R &... rest) {\n print_to(std::cout, \" \", \"\\n\", first, rest...);\n}\ntemplate <typename I>\nvoid println_(I begin, I end) {\n print_to_(std::cout, \"\\n\", \"\\n\", begin, end);\n}\ntemplate <typename I>\nvoid print_(I begin, I end) {\n print_to_(std::cout, \" \", \"\\n\", begin, end);\n}\ntemplate <typename C>\nvoid println_(const C &cntnr) {\n println_(std::begin(cntnr), std::end(cntnr));\n}\ntemplate <typename C>\nvoid print_(const C &cntnr) {\n print_(std::begin(cntnr), std::end(cntnr));\n}\nint _ = (\n#ifndef LOCAL\n std::cin.tie(nullptr), std::ios::sync_with_stdio(false),\n#endif\n std::cout.precision(10), std::cout.setf(std::ios::fixed));\n}\nusing io::print;\nusing io::println;\nusing io::println_;\nusing io::print_;\ntemplate <typename T>\nusing vec = std::vector<T>;\nusing vi = vec<int>;\nusing vvi = vec<vi>;\nusing pii = std::pair<int, int>;\nusing ll = long long;\nusing ld = long double;\nusing namespace std;\n// const int MOD = 1000000007;\n\n\n\n\nusing ld = long double;\nusing P = std::complex<ld>;\nusing G = std::vector<P>;\nconst ld pi = std::acos(-1);\nconst ld eps = 1e-10;\nconst ld inf = 1e12;\n\nld cross(const P &a, const P &b) { return a.real() * b.imag() - a.imag() * b.real(); }\nld dot(const P &a, const P &b) { return a.real() * b.real() + a.imag() * b.imag(); }\n\n/*\n CCW\n\n -- BEHIND -- [a -- ON -- b] --- FRONT --\n\n CW\n */\nenum CCW_RESULT { CCW = +1, CW = -1, BEHIND = +2, FRONT = -2, ON = 0 };\nint ccw(P a, P b, P c) {\n b -= a;\n c -= a;\n if (cross(b, c) > eps) return CCW; // counter clockwise\n if (cross(b, c) < -eps) return CW; // clockwise\n if (dot(b, c) < 0) return BEHIND; // c--a--b on line\n if (norm(b) < norm(c)) return FRONT; // a--b--c on line\n return ON;\n}\n\nnamespace std {\nbool operator<(const P &a, const P &b) {\n return std::abs(real(a) - real(b)) > eps ? real(a) < real(b) : imag(a) < imag(b);\n}\n}\n\nstruct L : public std::vector<P> {\n L(const P &a = P(), const P &b = P()) : std::vector<P>(2) {\n begin()[0] = a;\n begin()[1] = b;\n }\n\n // Ax + By + C = 0\n L(ld A, ld B, ld C) {\n if (std::abs(A) < eps && std::abs(B) < eps) {\n abort();\n } else if (std::abs(A) < eps) {\n *this = L(P(0, -C / B), P(1, -C / B));\n } else if (std::abs(B) < eps) {\n *this = L(P(-C / A, 0), P(-C / A, 1));\n } else {\n *this = L(P(0, -C / B), P(-C / A, 0));\n }\n }\n};\n\nstruct C {\n P p;\n ld r;\n C(const P &p = 0, ld r = 0) : p(p), r(r) {}\n};\n\n\n\n\nbool intersectLL(const L &l, const L &m) {\n return std::abs(cross(l[1] - l[0], m[1] - m[0])) > eps || // non-parallel\n std::abs(cross(l[1] - l[0], m[0] - l[0])) < eps; // same line\n}\nbool intersectLS(const L &l, const L &s) {\n return cross(l[1] - l[0], s[0] - l[0]) * // s[0] is left of l\n cross(l[1] - l[0], s[1] - l[0]) <\n eps; // s[1] is right of l\n}\nbool intersectLP(const L &l, const P &p) { return std::abs(cross(l[1] - p, l[0] - p)) < eps; }\nbool intersectSS(const L &s, const L &t) {\n return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 &&\n ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0;\n}\nbool intersectSP(const L &s, const P &p) {\n return std::abs(s[0] - p) + std::abs(s[1] - p) - std::abs(s[1] - s[0]) <\n eps; // triangle inequality\n}\n\nP projection(const L &l, const P &p) {\n ld t = dot(p - l[0], l[0] - l[1]) / norm(l[0] - l[1]);\n return l[0] + t * (l[0] - l[1]);\n}\nP reflection(const L &l, const P &p) { return p + (ld)2 * (projection(l, p) - p); }\nld distanceLP(const L &l, const P &p) { return std::abs(p - projection(l, p)); }\nld distanceLL(const L &l, const L &m) { return intersectLL(l, m) ? 0 : distanceLP(l, m[0]); }\nld distanceLS(const L &l, const L &s) {\n if (intersectLS(l, s)) return 0;\n return std::min(distanceLP(l, s[0]), distanceLP(l, s[1]));\n}\nld distanceSP(const L &s, const P &p) {\n const P r = projection(s, p);\n if (intersectSP(s, r)) return std::abs(r - p);\n return std::min(std::abs(s[0] - p), std::abs(s[1] - p));\n}\nld distanceSS(const L &s, const L &t) {\n if (intersectSS(s, t)) return 0;\n return std::min(std::min(distanceSP(s, t[0]), distanceSP(s, t[1])),\n std::min(distanceSP(t, s[0]), distanceSP(t, s[1])));\n}\nP crosspointLL(const L &l, const L &m) {\n ld A = cross(l[1] - l[0], m[1] - m[0]);\n ld B = cross(l[1] - l[0], l[1] - m[0]);\n if (std::abs(A) < eps && std::abs(B) < eps) return m[0]; // same line\n if (std::abs(A) < eps) assert(false); // !!!PRECONDITION NOT SATISFIED!!!\n return m[0] + B / A * (m[1] - m[0]);\n}\n\n\n// 符号付二倍面積 abs(area2(G pol))/2.0 で求められる.\n// polは頂点反時計回りで渡す\nld area2(const G& pol) {\n ld s = 0;\n int n = pol.size();\n for (int i = 0; i < n; ++i) s += cross(pol[i], pol[(i + 1) % n]);\n return s;\n}\n\n\n// 凸包\n// == CWを != CCWに置換すると 退化した角を除く.\nG andrewScan(G ps) {\n int N = ps.size(), k = 0;\n std::sort(ps.begin(), ps.end());\n G res(N * 2);\n for (int i = 0; i < N; i++) {\n while (k >= 2 && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n int t = k + 1;\n for (int i = N - 2; i >= 0; i--) {\n while (k >= t && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n res.resize(k - 1);\n return res;\n}\n\n// P:点 point x: .real() y: .imag()\n// L:直線 lineF\n// S:線分 section\n// G:多角形 vector<P>\n\nsigned main() {\n int N;\n cin >> N;\n G g(N);\n rep(i, N){\n int xi, yi;\n cin >> xi >> yi;\n g[i] = P(xi, yi);\n }\n g = andrewScan(g);\n cout << g.size() << endl;\n int startidx = 0;\n rep(i, g.size())if(g[startidx].imag()>g[i].imag()||(g[startidx].imag()==g[i].imag()&&g[startidx].real()>g[i].real())) startidx = i;\n rep(i, g.size())cout << (int)g[(i+startidx)%g.size()].real() << \" \" << (int)g[(i+startidx)%g.size()].imag() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 15452, "score_of_the_acc": -1.3474, "final_rank": 18 }, { "submission_id": "aoj_CGL_4_A_11008677", "code_snippet": "#include <bits/stdc++.h>\n#define T double\n\nconstexpr double eps = 1e-8, pi = std::acos(-1);\n\nstruct Point\n{\n\tT x, y;\n\tPoint(const T &X = {}, const T &Y = {}) : x(X), y(Y) {}\n};\nstruct Line\n{\n\tPoint x, y;\n\tLine(const Point &X = {}, const Point &Y = {}) : x(X), y(Y) {}\n};\n\ninline int dcmp(const T &a)\n{\n\treturn a < -eps ? -1 : a > eps;\n}\ninline bool operator==(const Point &a, const Point &b)\n{\n\treturn !dcmp(a.x - b.x) && !dcmp(a.y - b.y);\n}\ninline double len(const Point &a)\n{\n\treturn std::hypot(a.x, a.y);\n}\ninline std::istream &operator>>(std::istream &is, Point &a)\n{\n\treturn is >> a.x >> a.y;\n}\ninline std::ostream &operator<<(std::ostream &os, const Point &a)\n{\n\treturn os << a.x << \" \" << a.y;\n}\ninline Point operator+(const Point &a, const Point &b)\n{\n\treturn {a.x + b.x, a.y + b.y};\n}\ninline Point operator-(const Point &a, const Point &b)\n{\n\treturn {a.x - b.x, a.y - b.y};\n}\ninline Point operator*(const Point &a, const T &b)\n{\n\treturn {a.x * b, a.y * b};\n}\ninline Point operator/(const Point &a, const T &b)\n{\n\treturn {a.x / b, a.y / b};\n}\ninline T dot(const Point &a, const Point &b)\n{\n\treturn {a.x * b.x + a.y * b.y};\n}\ninline T cross(const Point &a, const Point &b)\n{\n\treturn {a.x * b.y - a.y * b.x};\n}\ninline Point ratate90(const Point &a)\n{\n\treturn {-a.y, a.x};\n}\ninline Point ratate(const Point &a, double b)\n{\n\treturn {a.x * std::cos(b) - a.y * std::sin(b), a.x * std::sin(b) + a.y * std::cos(b)};\n}\ndouble angle(const Point &a, const Point &b)\n{\n\treturn std::acos(dot(a, b) / len(a) / len(b));\n\treturn std::acos(dot(a, b) / len(a) / len(b)) / pi * 180;\n}\nPoint p_ver_l(const Point &p, const Line &l)\n{\n\treturn l.x + (l.y - l.x) * dot(l.y - l.x, p - l.x) / dot(l.y - l.x, l.y - l.x);\n}\nPoint l_inter_l(const Line &l1, const Line &l2)\n{\n\treturn l1.x + (l1.y - l1.x) * cross(l1.x - l2.x, l2.y - l2.x) / cross(l2.y - l2.x, l1.y - l1.x);\n}\nint p_rela_l(const Point &p, const Line &l)\n{\n\treturn dcmp(cross(l.y - l.x, p - l.x));\n}\nint l_rela_l(const Line &l1, const Line &l2)\n{\n\tif (dcmp(cross(l1.y - l1.x, l2.y - l2.x)) == 0) return p_rela_l(l1.x, l2) != 0;\n\treturn -1;\n}\nbool p_on_s(const Point &p, const Line &s)\n{\n\treturn p_rela_l(p, s) == 0 && dcmp(dot(s.y - p, s.x - p)) <= 0;\n}\nbool l_inter_s(const Line &l, const Line &s)\n{\n\treturn dcmp(cross(l.y - l.x, s.x - l.x)) * dcmp(cross(l.y - l.x, s.y - l.x)) <= 0;\n}\nbool s_inter_s(const Line &s1, const Line &s2)\n{\n\tif (p_on_s(s1.x, s2) || p_on_s(s1.y, s2) || p_on_s(s2.x, s1) || p_on_s(s2.y, s1)) return 1;\n\tif (dcmp(cross(s1.y - s1.x, s2.x - s1.x)) * dcmp(cross(s1.y - s1.x, s2.y - s1.x)) >= 0) return 0;\n\tif (dcmp(cross(s2.y - s2.x, s1.x - s2.x)) * dcmp(cross(s2.y - s2.x, s1.y - s2.x)) >= 0) return 0;\n\treturn 1;\n}\ndouble p_to_l(const Point &p, const Line &l)\n{\n\treturn std::abs(cross(l.y - l.x, p - l.x)) / len(l.y - l.x);\n}\ndouble p_to_s(const Point &p, const Line &s)\n{\n\tif (dcmp(dot(s.y - s.x, p - s.x)) <= 0) return len(p - s.x);\n\tif (dcmp(dot(s.x - s.y, p - s.y)) <= 0) return len(p - s.y);\n\treturn p_to_l(p, s);\n}\nT area(const std::vector<Point> &ps)\n{\n\tT ar = 0;\n\tfor (int i = 0, ie = ps.size(); i < ie; ++i)\n\t{\n\t\tar += cross(ps[i], ps[(i + 1) % ie]);\n\t}\n\treturn ar / 2;\n}\nbool Convex(const std::vector<Point> &ps, int pd)\n{\n\tfor (int i = 0, ie = ps.size(); i < ie; ++i)\n\t{\n\t\tif (dcmp(cross(ps[i] - ps[(i + 1) % ie], ps[(i + 1) % ie] - ps[(i + 2) % ie])) == pd) return 0;\n\t}\n\treturn 1;\n}\n\nstd::vector<Point> Andrew(std::vector<Point> ps)\n{\n\tint r = 0;\n\tstd::vector<Point> sp(ps.size() + 1);\n\tstd::sort(ps.begin(), ps.end(), [](Point &a, Point &b)\n\t{\n\t\treturn dcmp(a.y - b.y) ? dcmp(a.y - b.y) < 0 : dcmp(a.x - b.x) < 0;\n\t});\n\t\n\tfor (int i = 0, ie = ps.size(); i < ie; ++i)\n\t{\n\t\twhile (r > 1 && cross(sp[r - 1] - sp[r - 2], ps[i] - sp[r - 2]) < 0) --r;\n\t\tsp[r++] = ps[i];\n\t}\n\t\n\tfor (int i = ps.size() - 2, j = r; i >= 0; --i)\n\t{\n\t\twhile (r > j && cross(sp[r - 1] - sp[r - 2], ps[i] - sp[r - 2]) < 0) --r;\n\t\tsp[r++] = ps[i];\n\t}\n\t\n\tsp.resize(r - 1);\n\t\n\treturn sp;\n}\n\nvoid solve()\n{\n\tint n;\n\t\n\tstd::cin >> n;\n\tstd::vector<Point> ps(n);\n\t\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tstd::cin >> ps[i];\n\t}\n\t\n\tstd::vector<Point> chull = Andrew(ps);\n\t\n\tstd::cout << chull.size() << \"\\n\";\n\t\n//\tstd::sort(chull.begin(), chull.end(), [](Point &a, Point &b)\n//\t{\n//\t\treturn dcmp(a.y - b.y) ? dcmp(a.y - b.y) < 0 : dcmp(a.x - b.x) < 0;\n//\t});\n\n\n\tfor (int i = 0, ie = chull.size(); i < ie; ++i)\n\t{\n\t\tstd::cout << chull[i] << \"\\n\";\n\t}\n\n}\n\nsigned main()\n{\n\tstd::ios::sync_with_stdio(false);\n\tstd::cin.tie(nullptr);\n\tstd::cout << std::fixed << std::setprecision(0);\n\n\tint _ = 1;\n//\tstd::cin >> _;\n\n\twhile (_--)\n\t{\n\n\n\t\tsolve();\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 7860, "score_of_the_acc": -0.5984, "final_rank": 10 }, { "submission_id": "aoj_CGL_4_A_10994869", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define x real()\n#define y imag()\n\nusing ll = long long;\nusing pt = complex<ll>;\n\nll cross(pt a, pt b) { return imag(conj(a) * b); }\n\npt read() {\n int p,q;\n cin >> p >> q;\n return pt(p, q);\n}\n\nbool is_line(vector<pt> a) {\n const int n = a.size();\n pt p0 = a[0];\n for (int i = 1; i + 1 < n; i++) {\n if (cross(a[i] - p0, a[i + 1] - p0) != 0) return 0;\n }\n return 1;\n}\n\nvector<pt> convex_hull(vector<pt> a) { // include colinear\n const int n = a.size();\n if (n == 1) return a;\n int idx = 0;\n for (int i = 1; i < n; i++) {\n if (make_pair(a[i].y, a[i].x) < make_pair(a[idx].y, a[idx].x)) {\n idx = i;\n }\n }\n\n pt p0 = a[idx];\n \n a.erase(a.begin() + idx);\n sort(a.begin(), a.end(), [&](pt A, pt B) {\n int o = cross(A - p0, B - p0);\n if (o == 0) return norm(A - p0) < norm(B - p0);\n return o > 0;\n });\n a.insert(a.begin(), p0);\n\n if (is_line(a)) return a;\n\n // last line edge case\n int j = n - 2;\n while(j >= 0 and cross(a[n - 1] - p0, a[j] - p0) == 0) {\n j--;\n }\n reverse(a.begin() + j + 1, a.end());\n\n // building convex hull\n vector<pt> st = {a[0], a[1]};\n for (int i = 2; i < n; i++) {\n pt B = a[i];\n while(true) {\n pt A = st.back(); st.pop_back();\n pt C = st.back();\n if (cross(B - A, C - A) >= 0) {\n st.push_back(A);\n st.push_back(B);\n break;\n }\n }\n }\n\n return st;\n}\n\n\nvoid solve() {\n int n; cin >> n;\n vector<pt> a(n);\n for (int i = 0; i < n; i++) a[i] = read();\n vector<pt> ch = convex_hull(a);\n cout << ch.size() << '\\n';\n for (auto p : ch) {\n cout << p.x << \" \" << p.y << '\\n';\n }\n}\n\nint main() {\n cin.tie(0) -> sync_with_stdio(0);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8744, "score_of_the_acc": -0.3425, "final_rank": 5 }, { "submission_id": "aoj_CGL_4_A_10994863", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define x real()\n#define y imag()\n\nusing ll = long long;\nusing Point = complex<ll>;\n\nll cross(Point a, Point b) { return imag(conj(a) * b); }\n\nPoint read() {\n int p,q;\n cin >> p >> q;\n return Point(p, q);\n}\n\nvoid solve(int n) {\n vector<Point> a(n);\n int idx = -1;\n for (int i = 0; i < n; i++) {\n a[i] = read();\n if (idx == -1 or make_pair(a[i].y, a[i].x) < make_pair(a[idx].y, a[idx].x)) {\n idx = i;\n }\n }\n\n if (n == 1) {\n cout << a[0].x << \" \" << a[0].y << '\\n';\n return;\n }\n\n\n Point p0 = a[idx];\n a.erase(a.begin() + idx);\n sort(a.begin(), a.end(), [&](Point A, Point B) {\n if (cross(A - p0, B - p0) == 0) return norm(A - p0) < norm(B - p0);\n return cross(A - p0, B - p0) > 0;\n });\n a.insert(a.begin(), p0);\n\n \n {\n int j = n - 2;\n while(j >= 0 and cross(a[n - 1] - p0, a[j] - p0) == 0) {\n j--;\n }\n reverse(a.begin() + j + 1, a.end());\n }\n\n vector<Point> st = {a[0], a[1]};\n for (int i = 2; i < n; i++) {\n Point B = a[i];\n while(true) {\n Point A = st.back(); st.pop_back();\n Point C = st.back();\n if (cross(B - A, C - A) >= 0) {\n st.push_back(A);\n st.push_back(B);\n break;\n }\n }\n }\n\n cout << st.size() << '\\n';\n for (auto P : st) {\n cout << P.x << ' '<< P.y << '\\n';\n }\n\n}\n\nint main() {\n cin.tie(0) -> sync_with_stdio(0);\n int n;\n while(cin >> n) {\n solve(n);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6324, "score_of_the_acc": -0.047, "final_rank": 1 }, { "submission_id": "aoj_CGL_4_A_10937999", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i< (n); ++i)\n#define repi(i, a, b) for (int i = (a); i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define fore(i, a) for(auto &i:a)\nusing ll = long long;\nusing int64 = long long;\n#define DEBUG(x) cerr << #x << \": \"; for (auto _ : x) cerr << _ << \" \"; cerr << endl;\nconst int64 infll = (1LL << 62) - 1;\nconst int inf = (1 << 30) - 1;\n\nstruct IoSetup {\n\tIoSetup() {\n\t\tcin.tie(nullptr);\n\t\tios::sync_with_stdio(false);\n\t\tcout << fixed << setprecision(10);\n\t\tcerr << fixed << setprecision(10);\n\t}\n} iosetup;\n\ntemplate <typename T1, typename T2>\nostream& operator<<(ostream& os, const pair<T1, T2>& p) {\n\tos << p.first << \" \" << p.second;\n\treturn os;\n}\n\ntemplate <typename T1, typename T2>\nistream& operator>>(istream& is, pair<T1, T2>& p) {\n\tis >> p.first >> p.second;\n\treturn is;\n}\n\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n\tfor (int i = 0; i < (int)v.size(); i++) {\n\t\tos << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n\t}\n\treturn os;\n}\n\ntemplate <typename T>\nistream& operator>>(istream& is, vector<T>& v) {\n\tfor (T& in : v) is >> in;\n\treturn is;\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmax(T1& a, T2 b) {\n\treturn a < b && (a = b, true);\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmin(T1& a, T2 b) {\n\treturn a > b && (a = b, true);\n}\n\ntemplate <typename T = int64>\nvector<T> make_v(size_t a) {\n\treturn vector<T>(a);\n}\n\ntemplate <typename T, typename... Ts>\nauto make_v(size_t a, Ts... ts) {\n\treturn vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value == 0>::type fill_v(T& t, const V& v) {\n\tt = v;\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value != 0>::type fill_v(T& t, const V& v) {\n\tfor (auto& e : t) fill_v(e, v);\n}\n\ntemplate <typename F>\nstruct FixPoint : F {\n\texplicit FixPoint(F&& f) : F(std::forward<F>(f)) {}\n\n\ttemplate <typename... Args>\n\t\tdecltype(auto) operator()(Args&&... args) const {\n\t\t\treturn F::operator()(*this, std::forward<Args>(args)...);\n\t\t}\n};\n\ntemplate <typename F>\ninline decltype(auto) MFP(F&& f) {\n\treturn FixPoint<F>{std::forward<F>(f)};\n}\n//Geometry\nnamespace geometry {\nusing Real = double;\nconst Real EPS = 1e-15;\nconst Real PI = acos(static_cast<Real>(-1));\n\nenum { OUT, ON, IN };\n\ninline int sign(const Real& r) { return r <= -EPS ? -1 : r >= EPS ? 1 : 0; }\n\ninline bool equals(const Real& a, const Real& b) { return sign(a - b) == 0; }\n} // namespace geometry\n\nnamespace geometry {\nusing Point = complex<Real>;\n\nistream& operator>>(istream& is, Point& p) {\n Real a, b;\n is >> a >> b;\n p = Point(a, b);\n return is;\n}\n\nostream& operator<<(ostream& os, const Point& p) {\n return os << real(p) << \" \" << imag(p);\n}\n\nPoint operator*(const Point& p, const Real& d) {\n return Point(real(p) * d, imag(p) * d);\n}\n\n// rotate point p counterclockwise by theta rad\nPoint rotate(Real theta, const Point& p) {\n return Point(cos(theta) * real(p) - sin(theta) * imag(p),\n sin(theta) * real(p) + cos(theta) * imag(p));\n}\n\nReal cross(const Point& a, const Point& b) {\n return real(a) * imag(b) - imag(a) * real(b);\n}\n\nReal dot(const Point& a, const Point& b) {\n return real(a) * real(b) + imag(a) * imag(b);\n}\n\nbool compare_x(const Point& a, const Point& b) {\n return equals(real(a), real(b)) ? imag(a) < imag(b) : real(a) < real(b);\n}\n\nbool compare_y(const Point& a, const Point& b) {\n return equals(imag(a), imag(b)) ? real(a) < real(b) : imag(a) < imag(b);\n}\n\nusing Points = vector<Point>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Line {\n Point a, b;\n\n Line() = default;\n\n Line(const Point& a, const Point& b) : a(a), b(b) {}\n\n Line(const Real& A, const Real& B, const Real& C) { // Ax+By=C\n if (equals(A, 0)) {\n assert(!equals(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (equals(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (equals(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n friend ostream& operator<<(ostream& os, Line& l) {\n return os << l.a << \" to \" << l.b;\n }\n\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n};\n\nusing Lines = vector<Line>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Segment : Line {\n Segment() = default;\n\n using Line::Line;\n};\n\nusing Segments = vector<Segment>;\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A\nPoint projection(const Line& l, const Point& p) {\n auto t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);\n return l.a + (l.a - l.b) * t;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B\nPoint reflection(const Line& l, const Point& p) {\n return p + (projection(l, p) - p) * 2;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C\nconstexpr int COUNTER_CLOCKWISE = +1;\nconstexpr int CLOCKWISE = -1;\nconstexpr int ONLINE_BACK = +2; // c-a-b\nconstexpr int ONLINE_FRONT = -2; // a-b-c\nconstexpr int ON_SEGMENT = 0; // a-c-b\nint ccw(const Point& a, Point b, Point c) {\n b = b - a, c = c - a;\n if (sign(cross(b, c)) == +1) return COUNTER_CLOCKWISE;\n if (sign(cross(b, c)) == -1) return CLOCKWISE;\n if (sign(dot(b, c)) == -1) return ONLINE_BACK;\n if (norm(b) < norm(c)) return ONLINE_FRONT;\n return ON_SEGMENT;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_orthogonal(const Line& a, const Line& b) {\n return equals(dot(a.a - a.b, b.a - b.b), 0.0);\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_parallel(const Line& a, const Line& b) {\n return equals(cross(a.b - a.a, b.b - b.a), 0.0);\n}\n} // namespace geometry\n\nnamespace geometry {\nbool is_intersect_ss(const Segment& s, const Segment& t) {\n return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&\n ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;\n}\n} // namespace geometry\nnamespace geometry {\nbool is_intersect_sp(const Segment& s, const Point& p) {\n return ccw(s.a, s.b, p) == ON_SEGMENT;\n}\n} // namespace geometry\n\nnamespace geometry {\nPoint cross_point_ll(const Line& l, const Line& m) {\n Real A = cross(l.b - l.a, m.b - m.a);\n Real B = cross(l.b - l.a, l.b - m.a);\n if (equals(abs(A), 0) && equals(abs(B), 0)) return m.a;\n return m.a + (m.b - m.a) * B / A;\n}\n} // namespace geometry\nnamespace geometry {\nReal distance_sp(const Segment& s, const Point& p) {\n Point r = projection(s, p);\n if (is_intersect_sp(s, r)) return abs(r - p);\n return min(abs(s.a - p), abs(s.b - p));\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D\nReal distance_ss(const Segment& a, const Segment& b) {\n if (is_intersect_ss(a, b)) return 0;\n return min({distance_sp(a, b.a), distance_sp(a, b.b), distance_sp(b, a.a),\n distance_sp(b, a.b)});\n}\n} // namespace geometry\nnamespace geometry {\nusing Polygon = vector<Point>;\nusing Polygons = vector<Polygon>;\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A\nReal area(const Polygon& p) {\n int n = (int)p.size();\n Real A = 0;\n for (int i = 0; i < n; ++i) {\n A += cross(p[i], p[(i + 1) % n]);\n }\n return A * 0.5;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B\nbool is_convex_polygon(const Polygon& p) {\n int n = (int)p.size();\n for (int i = 0; i < n; i++) {\n if (ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == CLOCKWISE)\n return false;\n }\n return true;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C\nint contains(const Polygon& Q, const Point& p) {\n bool in = false;\n for (int i = 0; i < Q.size(); i++) {\n Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;\n if (imag(a) > imag(b)) swap(a, b);\n if (sign(imag(a)) <= 0 && 0 < sign(imag(b)) && sign(cross(a, b)) < 0)\n in = !in;\n if (equals(cross(a, b), 0) && sign(dot(a, b)) <= 0) return ON;\n }\n return in ? IN : OUT;\n}\n} // namespace geometry\nnamespace geometry {\nint convex_polygon_contains(const Polygon& Q, const Point& p) {\n int N = (int)Q.size();\n Point g = (Q[0] + Q[N / 3] + Q[N * 2 / 3]) / 3.0;\n if (equals(imag(g), imag(p)) && equals(real(g), real(p))) return IN;\n Point gp = p - g;\n int l = 0, r = N;\n while (r - l > 1) {\n int mid = (l + r) / 2;\n Point gl = Q[l] - g;\n Point gm = Q[mid] - g;\n if (cross(gl, gm) > 0) {\n if (cross(gl, gp) >= 0 && cross(gm, gp) <= 0)\n r = mid;\n else\n l = mid;\n } else {\n if (cross(gl, gp) <= 0 && cross(gm, gp) >= 0)\n l = mid;\n else\n r = mid;\n }\n }\n r %= N;\n Real v = cross(Q[l] - p, Q[r] - p);\n return sign(v) == 0 ? ON : sign(v) == -1 ? OUT : IN;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A\nPolygon convex_hull(Polygon& p, bool strict = true) {\n int n = (int)p.size(), k = 0;\n if (n <= 2) return p;\n sort(begin(p), end(p), compare_x);\n vector<Point> ch(2 * n);\n auto check = [&](int i) {\n return sign(cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1])) <= -1 + strict;\n };\n for (int i = 0; i < n; ch[k++] = p[i++]) {\n while (k >= 2 && check(i)) --k;\n }\n for (int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {\n while (k >= t && check(i)) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n} // namespace geometry\nusing namespace geometry;\nint main(){\n\tll n; cin >> n;\n\tPolygon a(n);\n\trep(i, n)cin >> a[i];\n auto ans = convex_hull(a, false);\n\tcout << ans.size() << endl;\n\tll idx = 0;\n\trep(i, n){\n\t\tif(compare_y(ans[i], ans[idx])){\n\t\t\tidx = i;\n\t\t}\n\t}\n\trep(i, ans.size())cout << fixed << setprecision(0)<< ans[(idx+i)%(int(ans.size()))] << endl;\n\n\t\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 7780, "score_of_the_acc": -1.008, "final_rank": 13 }, { "submission_id": "aoj_CGL_4_A_10914020", "code_snippet": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define rep(i, l, n) for(int i = int(l); i < int(n); i++)\n#define ll long long\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n\ntemplate<class T> bool chmin(T &a, T b) {if(a > b) {a = b; return true;} return false;}\ntemplate<class T> bool chmax(T &a, T b) {if(a < b) {a = b; return true;} return false;}\ntemplate<class T> using spq = priority_queue<T, vector<T>, greater<T>>;\n\n// bool -> Yes/No\nstring answer(bool b) {return b ? \"Yes\" : \"No\";}\n\nvoid fix(int k) {cout << fixed << setprecision(k);}\n\nconst int inf = 2e9;\nconst long long INF = 2e18;\nconst long double eps = 1e-12;\nconst long double pi = acos(-1);\nint dx[] = {0, -1, 0, 1, -1, -1, 1, 1}, dy[] = {1, 0, -1, 0, 1, -1, -1, 1};\n\nstruct Point {\n\n long double x, y;\n\n Point() : x(0.00), y(0.00) {}\n Point(long double x_, long double y_) : x(x_), y(y_) {}\n\n Point &operator+=(const Point &p) {\n x += p.x; y += p.y;\n return (*this);\n }\n\n Point &operator-=(const Point &p) {\n x -= p.x; y -= p.y;\n return (*this);\n }\n\n Point &operator*=(const long double &k) {\n x *= k; y *= k;\n return (*this);\n }\n\n Point &operator*=(const Point &p) {\n long double x_ = x * p.x - y * p.y;\n long double y_ = x * p.y + y * p.x;\n x = x_; y = y_;\n return (*this);\n }\n \n Point &operator/=(const long double &k) {\n x /= k; y /= k;\n return (*this);\n }\n\n bool operator==(const Point &p) {\n return std::abs(x - p.x) < eps && std::abs(y - p.y) < eps;\n }\n\n bool operator!=(const Point &p) {\n return std::abs(x - p.x) >= eps || std::abs(y - p.y) >= eps;\n }\n\n Point operator+(const Point &p) {return Point(*this) += p;}\n Point operator-(const Point &p) {return Point(*this) -= p;}\n Point operator*(const long double &k) {return Point(*this) *= k;}\n Point operator*(const Point &p) {return Point(*this) *= p;}\n Point operator/(const long double &k) {return Point(*this) /= k;}\n \n Point operator+() {\n return (*this);\n }\n\n Point operator-() {\n return (*this) * -1;\n }\n\n // 原点からの距離\n long double abs() {\n return std::hypotl(x, y);\n }\n\n // 原点からの距離の2乗\n long double norm() {\n return x * x + y * y;\n }\n\n // 原点中心にthetaラジアン回転\n Point rot(const long double &theta) {\n long double u = cos(theta), v = sin(theta);\n return (*this) * Point(u, v);\n }\n\n // 内積\n long double dot(const Point &p) {\n return x * p.x + y * p.y;\n }\n\n // 外積\n long double det(const Point &p) {\n return x * p.y - y * p.x;\n }\n\n // x軸の正の向きからの角度\n long double arg() {\n return atan2(y, x);\n }\n\n friend std::istream& operator>>(std::istream &is, Point &p) {\n is >> p.x >> p.y;\n return is;\n }\n\n friend std::ostream& operator<<(std::ostream &os, Point &p) {\n os << '(' << p.x << \",\" << p.y << ')';\n return os;\n }\n\n};\n\nbool operator<(const Point &a, const Point &b) {\n return std::abs(a.y - b.y) >= eps ? a.y < b.y : a.x < b.x;\n}\n\nstruct Line {\n \n Point a, b;\n\n Line() : a(), b() {}\n Line(Point a_, Point b_) : a(a_), b(b_) {}\n // 直線 sx + ty = c\n Line(long double s, long double t, long double c) {\n if(-eps < s < eps) a = Point(0, c / t), b = Point(1, c / t);\n else if(-eps < t < eps) a = Point(c / s, 0), b = Point(c / s, 1);\n else a = Point(0, c / t), b = Point(c / s, 0);\n }\n\n friend std::istream &operator>>(std::istream &is, Line &p) {\n is >> p.a >> p.b;\n return is;\n }\n\n friend std::ostream &operator<<(std::ostream &os, Line &p) {\n os << p.a << \" -> \" << p.b;\n return os;\n }\n\n};\n\nstruct Segment : Line {\n \n Segment() : Line() {}\n Segment(Point a, Point b) : Line(a, b) {}\n\n};\n\nstruct Circle {\n \n Point p;\n long double r;\n\n Circle() : p(), r(0.00) {}\n Circle(Point p_, long double r_) : p(p_), r(r_) {}\n\n};\n\nusing Polygon = std::vector<Point>;\n\n// a-b-cがなす角度のうち小さい方を返す\nlong double angle(Point a, Point b, Point c) {\n Point v = (a - b), u = (c - b);\n long double theta = std::abs(v.arg() - u.arg());\n return std::min<long double>(theta, 2.00 * pi - theta);\n}\n\n// 点の進行方向\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913642\nint ccw(Point a, Point b, Point c) {\n long double k = (b - a).det(c - a);\n if(k > eps) return 1;\n else if(k < -eps) return -1;\n if((b - a).dot(c - a) < -eps) return -2;\n if((a - b).dot(c - b) < -eps) return 2;\n return 0;\n}\n\n// 直線の平行判定\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913644\nbool parallel(Line a, Line b) {\n long double res = (a.b - a.a).det(b.b - b.a);\n return (-eps < res && res < eps);\n}\n\n// 直線の垂直判定\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913644\nbool vertical(Line a, Line b) {\n long double res = (a.a - a.b).dot(b.a - b.b);\n return (-eps < res && res < eps);\n}\n\n// 点pから直線lに引いた垂線の足\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913645\nPoint projection(Line l, Point p) {\n long double t = (p - l.a).dot(l.a - l.b) / (l.a - l.b).norm();\n return l.a + (l.a - l.b) * t;\n}\n\n// 点pから線分lに引いた垂線の足\nPoint projection(Segment s, Point p) {\n long double t = (p - s.a).dot(s.a - s.b) / (s.a - s.b).norm();\n return s.a + (s.a - s.b) * t;\n}\n\n// 直線lについて点pと線対称な位置にある点\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913652\nPoint reflection(Line l, Point p) {\n return p + (projection(l, p) - p) * 2.00;\n}\n\n// 直線と点の交差判定\nbool intersect(Line l, Point p) {\n return (std::abs(ccw(l.a, l.b, p)) != 1);\n}\n\n// 直線と直線の交差判定\nbool intersect(Line l, Line m) {\n if(std::abs((l.b - l.a).det(m.b - m.a)) > eps) return true;\n return (std::abs((l.b - l.a).det(m.b - l.a)) < eps);\n}\n\n// 線分と点の交差判定\nbool intersect(Segment s, Point p) {\n return (ccw(s.a, s.b, p) == 0);\n}\n\n// 線分と直線の交差判定\nbool intersect(Segment s, Line l) {\n return ((l.b - l.a).det(s.a - l.a) * (l.b - l.a).det(s.b - l.a) < eps);\n}\n\n// 線分と線分の交差判定\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913656\nbool intersect(Segment s, Segment t) {\n if(ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) > 0) return false;\n return (ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0);\n}\n\n// 円と点の交差判定\nbool intersect(Circle c, Point p) {\n return (std::abs((p - c.p).abs() - c.r) < eps);\n}\n\n// 円と直線の交差判定\nbool intersect(Circle c, Line l) {\n return ((c.p - projection(l, c.p)).abs() - c.r < eps);\n}\n\n// 円と線分の交差判定(交点の個数を返す)\nint intersect(Circle c, Segment s) {\n if((projection(s, c.p) - c.p).norm() - c.r * c.r > eps) return 0;\n long double d1 = (c.p - s.a).abs(), d2 = (c.p - s.b).abs();\n if(c.r - d1 > eps && c.r - d2 > eps) return 0;\n if((c.r - d1 > eps && d2 - c.r > eps) || (d1 - c.r > eps && c.r - d2 > eps)) return 1;\n Point h = projection(s, c.p);\n // hが線分上にあるとき...2点で交差\n if((s.a - h).dot(s.b - h) < 0) return 2;\n return 0;\n}\n\n// 円と円の交差判定\n// 外包(4), 外接(3), 2点で交わる(2), 内接(1), 内包(0)\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913658\nint intersect(Circle c, Circle d) {\n if(c.r < d.r) std::swap(c, d);\n long double dist = (c.p - d.p).abs();\n if(dist - c.r - d.r > eps) return 4;\n if(std::abs(dist - c.r - d.r) < eps) return 3;\n if(dist - c.r + d.r > eps) return 2;\n if(abs(dist - c.r + d.r) < eps) return 1;\n return 0;\n}\n\n// 点と点の距離\nlong double distance(Point a, Point b) {\n return (a - b).abs();\n}\n\n// 直線と点の距離\nlong double distance(Line l, Point p) {\n return (p - projection(l, p)).abs();\n}\n\n// 直線と直線の距離\nlong double distance(Line l, Line m) {\n return intersect(l, m) ? 0.00 : distance(l, m.a);\n}\n\n// 線分と点の距離\nlong double distance(Segment s, Point p) {\n Point h = projection(s, p);\n if(intersect(s, h)) return (h - p).abs();\n return std::min<long double>((s.a - p).abs(), (s.b - p).abs());\n}\n\n// 線分と直線の距離\nlong double distance(Segment s, Line l) {\n if(intersect(s, l)) return 0.00;\n return std::min<long double>(distance(l, s.a), distance(l, s.b));\n}\n\n// 線分と線分の距離\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913660\nlong double distance(Segment s, Segment t) {\n if(intersect(s, t)) return 0.00;\n return std::min<long double>({distance(s, t.a), distance(s, t.b), distance(t, s.a), distance(t, s.b)});\n}\n\n// 直線と直線の交点(交点を持つ前提)\nPoint crosspoint(Line l, Line m) {\n long double s = (l.b - l.a).det(m.b - m.a);\n long double t = (l.b - l.a).det(l.b - m.a);\n if(std::abs(s) < eps && std::abs(t) < eps) return m.a;\n return m.a + (m.b - m.a) * t / s;\n}\n\n// 線分と線分の交点(交点を持つ前提)\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913666\nPoint crosspoint(Segment s, Segment t) {\n return crosspoint(Line(s), Line(t));\n}\n\n// 円と直線の交点(交点を持つ前提)\n// 交点が一つの場合は、first == second == 交点\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913670\nstd::pair<Point, Point> crosspoint(Circle c, Line l) {\n Point h = projection(l, c.p), e = (l.b - l.a) / (l.b - l.a).abs();\n if(std::abs(distance(l, c.p) - c.r) < eps) return std::make_pair(h, h);\n long double d = std::sqrt(c.r * c.r - (h - c.p).norm());\n return std::make_pair(h - e * d, h + e * d);\n}\n\n// 円と線分の交点(交点を持つ前提)\n// 交点が一つの場合は、first == second == 交点\nstd::pair<Point, Point> crosspoint(Circle c, Segment s) {\n Line l = Line(s.a, s.b);\n if(intersect(c, s) == 2) return crosspoint(c, l);\n std::pair<Point, Point> ret = crosspoint(c, l);\n if((s.a - ret.first).dot(s.b - ret.first) < 0) ret.second = ret.first;\n else ret.first = ret.second;\n return ret;\n}\n\n// 円と円の交点(交点を持つ前提)\n// 交点が一つの場合は、first == second == 交点\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913672\nstd::pair<Point, Point> crosspoint(Circle c, Circle d) {\n long double dist = (c.p - d.p).abs();\n long double deg = std::acos((c.r * c.r + dist * dist - d.r * d.r) / (2.00 * c.r * dist));\n Point p = c.p + (d.p - c.p) * c.r / dist;\n Point p1 = c.p + (p - c.p).rot(deg);\n Point p2 = c.p + (p - c.p).rot(-deg);\n return std::make_pair(p1, p2);\n}\n\n// 点pを通る円の接線\n// verify : https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=10913675\nstd::pair<Line, Line> tangentline(Circle c, Point p) {\n std::pair<Point, Point> res = crosspoint(c, Circle(p, std::sqrt((c.p - p).norm() - c.r * c.r)));\n return std::make_pair(Line(res.first, p), Line(res.second, p));\n}\n\n// 円の共通接線\nstd::vector<Line> tangentline(Circle c, Circle d) {\n std::vector<Line> ret;\n if(c.r < d.r) std::swap(c, d);\n long double dist = (c.p - d.p).norm();\n if(std::abs(dist) < eps) return ret;\n Point u = (d.p - c.p) / std::sqrt(dist);\n Point v = u.rot(pi * 0.50);\n for(int s = -1; s <= 1; s += 2) {\n long double h = (c.r + s * d.r) / std::sqrt(dist);\n if(std::abs(1.00 - h * h) < eps) ret.emplace_back(c.p + u * c.r, c.p + (u + v) * c.r);\n else if(1.00 - h * h > eps) {\n Point u_ = u * h, v_ = v * std::sqrt(1 - h * h);\n ret.emplace_back(c.p + (u_ + v_) * c.r, d.p - (u_ + v_) * d.r * s);\n ret.emplace_back(c.p + (u_ - v_) * c.r, d.p - (u_ - v_) * d.r * s);\n }\n }\n return ret;\n}\n\n// 多角形の凸性判定\nbool is_convex(Polygon p) {\n int n = int(p.size());\n for(int i = 0; i < n; i++) {\n if(ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == -1) return false;\n }\n return true;\n}\n\n// 凸包(反時計回り)\nPolygon convex_hull(Polygon p) {\n int n = int(p.size()), k = 0;\n if(n <= 2) return p;\n std::sort(p.begin(), p.end());\n std::vector<Point> ret;\n for(int i = 0; i < n; i++) {\n while(k > 1 && ccw(ret[k - 2], ret[k - 1], p[i]) < 0) {\n k--; ret.pop_back();\n }\n ret.emplace_back(p[i]); k++;\n }\n for(int i = n - 2, t = k; i >= 0; i--) {\n while(k > t && ccw(ret[k - 2], ret[k - 1], p[i]) < 0) {\n k--; ret.pop_back();\n }\n ret.emplace_back(p[i]); k++;\n }\n ret.pop_back(); k--;\n return ret;\n}\n\nvoid main_program() {\n int n; cin >> n;\n Polygon q;\n rep(i, 0, n) {\n Point p; cin >> p;\n q.emplace_back(p);\n }\n Polygon ans = convex_hull(q);\n cout << ans.size() << \"\\n\";\n for(Point p : ans) cout << p.x << \" \" << p.y << \"\\n\";\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int T = 1;\n //cin >> T;\n while(T--) {\n main_program();\n }\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 17192, "score_of_the_acc": -1.5, "final_rank": 19 }, { "submission_id": "aoj_CGL_4_A_10912965", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#include <iostream>\ntemplate <typename T, typename U>\nostream& operator<<(ostream& os, const pair<T, U>& p) {return os<<'(' <<p.first<<\", \"<<p.second<<')';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {os<<'[';for(auto it=v.begin();it!=v.end();++it){os<<*it; if(next(it)!=v.end()){os<<\", \";}}return os<<']';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<vector<T>>& vv) {os<<\"[\\n\";for(auto it=vv.begin();it!=vv.end();++it){os<<\" \"<<*it;if(next(it)!=vv.end()){os<<\",\\n\";}else{os<<\"\\n\";}}return os<<\"]\";}\n#define dump(x) cerr << #x << \" = \" << (x) << '\\n'\n#else\n#define dump(x) (void)0\n#endif\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\ntemplate<class T> using pq = priority_queue<T>;\ntemplate<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>;\n#define out(x) cout<<x<<'\\n'\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define OVERLOAD_REP(_1,_2,_3,name,...) name\n#define REP1(i,n) for (auto i = std::decay_t<decltype(n)>{}; (i) < (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) < (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\ntemplate<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};\ntemplate<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};\nconst ll INF=(1LL<<60);\nconst ll mod=998244353;\nusing Graph = vector<vector<ll>>;\nusing Network = vector<vector<pair<ll,ll>>>;\nusing Grid = vector<string>;\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int dx2[8] = {1, 1, 1, 0, 0, -1, -1, -1};\nconst int dy2[8] = {1, 0, -1, 1, -1, 1, 0, -1};\n\n// #include \"../geo.hpp\"\n\n#pragma once\n\nusing D = long double;\nconst D EPS = 1e-12L;\nconst D PI = acosl(-1.0L);\nusing P2 = complex<D>;\nstruct L2{P2 a, b;};\nstruct S2{P2 a, b;};\nusing G2 = vector<P2>;\n\nint sgn(D x){return (x>EPS)-(x<-EPS);}\nint cmp(D a, D b){return sgn(a-b);}\nbool eq(D a, D b){return cmp(a, b)==0;}\nbool lt(D a, D b){return cmp(a, b)<0;}\nbool le(D a, D b){return cmp(a, b)<=0;}\nbool gt(D a, D b){return cmp(a, b)>0;}\nbool ge(D a, D b){return cmp(a, b)>=0;}\nbool eqP2(P2 a, P2 b){return eq(real(a), real(b)) && eq(imag(a), imag(b));}\nbool ltP2(P2 a, P2 b) {\n return lt(real(a), real(b)) || (eq(real(a), real(b)) && lt(imag(a), imag(b)));\n}\n\nD dot(P2 a, P2 b) {return real(conj(a)*b);}\nD cross(P2 a, P2 b) {return imag(conj(a)*b);}\nint ccw(P2 a, P2 b, P2 c) {\n b-=a; c-=a;\n auto cr=cross(b, c), dt=dot(b, c);\n if (cr > EPS) return +1; // counter clockwise\n if (cr < -EPS) return -1; // clockwise\n if (dt < -EPS) return +2; // c--a--b\n if (lt(norm(b), norm(c))) return -2; // a--b--c\n return 0; // a--c--b\n}\nint turn(P2 a, P2 b, P2 c) { return sgn(cross(b - a, c - a)); }\n\nP2 rot(P2 a, D th) { return a*polar<D>(1, th); }\nP2 rot90(P2 a) { return P2(-imag(a), real(a)); }\nbool ltP2Arg(P2 a, P2 b) {\n auto up = [](P2 p) { return (imag(p) > 0 || (eq(imag(p), 0) && ge(real(p), 0))); };\n if (up(a) != up(b)) return up(a);\n if (!eq(cross(a, b), 0)) return cross(a, b) > 0;\n return lt(norm(a), norm(b));\n}\n\ninline void rd(P2& p) {D x, y; cin>>x>>y; p = P2(x, y);}\n#define setp(n) cout<<setprecision(n)<<fixed\ninline void pr(const P2& p) {setp(0); cout<<real(p)<<' '<<imag(p)<<'\\n';}\n\n// ----------------------------------------------------------------------------------\n\nP2 proj(L2 l, P2 p) { P2 a=p-l.a, b=l.b-l.a; return l.a+b*dot(a, b)/norm(b);}\nP2 refl(L2 l, P2 p) { return proj(l, p)*2.0L - p; }\nbool isParallel(L2 l, L2 m){ return eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isPerp(L2 l, L2 m){ return eq(dot(l.a-l.b, m.a-m.b), 0); }\n\nbool isLL(L2 l, L2 m){ return !eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isLS(L2 l, S2 s){ return turn(l.a, l.b, s.a)*turn(l.a, l.b, s.b)<=0; }\nbool isSS(S2 s, S2 t) {\n return\n ccw(s.a,s.b,t.a)*ccw(s.a,s.b,t.b) <= 0 &&\n ccw(t.a,t.b,s.a)*ccw(t.a,t.b,s.b) <= 0;\n}\n\nP2 cpLL(L2 l, L2 m) {\n P2 a=l.b-l.a, b=m.b-m.a;\n D d=cross(a, b);\n if (eq(d, 0)) return P2(INF, INF); // parallel\n return l.a + a*cross(m.b-l.a,b)/d;\n}\n\nD distLP(L2 l, P2 p) { return abs(cross(l.b-l.a, p-l.a))/abs(l.b-l.a); }\nD distSP(S2 s, P2 p) {\n P2 a=s.a, b=s.b;\n if (lt(dot(b-a, p-a), 0)) return abs(p-a);\n if (lt(dot(a-b, p-b), 0)) return abs(p-b);\n return distLP({a,b}, p);\n}\nD distSS(S2 s, S2 t) {\n if (isSS(s, t)) return 0;\n return min({distSP(s, t.a), distSP(s, t.b), distSP(t, s.a), distSP(t, s.b)});\n}\n\nD area(G2 g) {\n D s=0;\n int n=g.size();\n rep(i, n) s+=cross(g[i], g[(i+1)%n]);\n return s/2.0L;\n}\n\nbool isConvex(G2 g) {\n int n=g.size();\n if (n < 3) return false;\n int dir = 0;\n rep(i,n){\n int s = turn(g[i], g[(i+1)%n], g[(i+2)%n]);\n if (s == 0) return false; // -> continue : allows three points on a line\n if (dir == 0) dir = s;\n else if (dir*s < 0) return false;\n }\n return true;\n}\n\nint inG(G2 g, P2 p) {\n bool in=false;\n int n=g.size();\n rep(i, n) {\n P2 a=g[i], b=g[(i+1)%n];\n if (ccw(a, b, p) == 0) return 1; // on boundary\n if (a.imag() > b.imag()) swap(a, b);\n if (le(a.imag(), p.imag()) && lt(p.imag(), b.imag()) && turn(a, b, p) > 0) in=!in;\n }\n return in ? 2 : 0; // inside : outside\n}\n\nG2 hull(G2 g) {\n sort(all(g), ltP2);\n g.erase(unique(all(g), eqP2), g.end());\n if (g.size()<=1) return g;\n G2 lo, up;\n for (auto &p:g) {\n while (lo.size()>=2 && turn(lo[lo.size()-2], lo.back(), p)<0) lo.pop_back(); //-> turn()<0 : allow three points on a line\n lo.push_back(p);\n }\n reverse(all(g));\n for (auto &p:g) {\n while (up.size()>=2 && turn(up[up.size()-2], up.back(), p)<0) up.pop_back(); // -> turn()<0 : allow three points on a line\n up.push_back(p);\n }\n lo.pop_back(); up.pop_back();\n lo.insert(lo.end(), all(up));\n return lo;\n}\n\npair<P2, P2> diameter(const G2& h) {\n int n=h.size();\n if(n==0) return {P2(0,0), P2(0,0)};\n if(n==1) return {h[0], h[0]};\n auto area2=[&](int i, int j, int k) {return abs(cross(h[j]-h[i], h[k]-h[i]));};\n D maxd=0;\n pair<P2, P2> res={h[0], h[0]};\n int j=1;\n rep(i, n) {\n int ni=(i+1)%n;\n while (gt(area2(i, ni, (j+1)%n), area2(i, ni, j))) j=(j+1)%n;\n if (gt(abs(h[i]-h[j]), maxd)) maxd=abs(h[i]-h[j]), res={h[i], h[j]};\n if (gt(abs(h[ni]-h[j]), maxd)) maxd=abs(h[ni]-h[j]), res={h[ni], h[j]};\n }\n return res;\n}\n\n// int inConvex(G2 h, P2 p) {\n// int n=h.size();\n// if (n==0) return 0;\n// if (n==1) return eqP2(h[0], p) ? 2 : 0;\n// if (n==2) return ccw(h[0], h[1], p)==0 && le(abs(h[0]-p)+abs(h[1]-p), abs(h[0]-h[1])) ? 2 : 0;\n// int left=1, right=n-1;\n// while (right-left>1) {\n// int mid=(left+right)/2;\n// if (turn(h[0], h[mid], p)<0) right=mid;\n// else left=mid;\n// }\n// if (turn(h[0], h[left], p)<0) return 0;\n// if (turn(h[left], h[right%n], p)<0) return 0;\n// if (turn(h[right%n], h[0], p)<0) return 0;\n// if (turn(h[0], h[left], p)==0 || turn(h[left], h[right%n], p)==0 || turn(h[right%n], h[0], p)==0) return 2;\n// return 1;\n// }\n\nG2 cutConvex(G2 h, L2 l) {\n int n=h.size();\n G2 res;\n if (n==0) return res;\n auto inside=[&](P2 p){ return turn(l.a, l.b, p) >= 0; };\n rep(i, n) {\n P2 a=h[i], b=h[(i+1)%n];\n bool ina=inside(a), inb=inside(b);\n if (ina&&inb) res.push_back(b);\n else if (ina&&!inb) {\n res.push_back(proj({a,b}, l.a));\n }\n else if (!ina&&inb) {\n res.push_back(proj({a,b}, l.a));\n res.push_back(b);\n }\n }\n return res;\n}\n\n\npair<P2, P2> closestPair(G2 g) {\n auto ps = g;\n int n=ps.size();\n if (n < 2) return {P2(0,0), P2(0,0)};\n sort(all(ps), ltP2);\n D mind = norm(ps[0]-ps[1]);\n pair<P2, P2> res = {ps[0], ps[1]};\n set<pair<D,int>> box;\n int j=0;\n rep(i, n) {\n D xi=real(ps[i]), yi=imag(ps[i]);\n D rad = sqrtl(mind);\n while (j<i && gt(xi - real(ps[j]), rad)) {\n box.erase({imag(ps[j]), j});\n j++;\n }\n auto it = box.lower_bound({yi - rad, -1});\n for (; it != box.end() && le(it->first, yi + rad); ++it) {\n int k = it->second;\n D d = norm(ps[i]-ps[k]);\n if (lt(d, mind)) mind=d, res={ps[i], ps[k]}, rad = sqrtl(mind);\n }\n box.insert({yi, i});\n }\n return res;\n}\n\n\nstruct C2 { P2 o; D r; };\n\nC2 makeC2(P2 a, P2 b) {\n return C2{(a+b)/D(2), abs(a-b)/D(2)};\n}\nC2 makeC2(P2 a, P2 b, P2 c) {\n P2 B=b-a, C=c-a;\n D d=2*cross(B, C);\n if (eq(d, 0)) {\n D ab=norm(B), bc=norm(b-c), ca=norm(c-a);\n if (le(ab, bc) && le(ab, ca)) return makeC2(a, b);\n if (le(bc, ca)) return makeC2(b, c);\n return makeC2(c, a);\n }\n P2 o=a+(rot90(B)*norm(C)-rot90(C)*norm(B))/d;\n return C2{o, abs(o-a)};\n}\n\nC2 incircle(P2 a, P2 b, P2 c) {\n D ab=abs(b-a), bc=abs(c-b), ca=abs(a-c);\n P2 o=(a*bc+b*ca+c*ab)/(ab+bc+ca);\n D r=abs(cross(b-a, o-a))/abs(b-a);\n return C2{o, r};\n}\n\nvector<P2> cpCL(L2 l, C2 c) {\n vector<P2> res;\n P2 a=l.a-c.o, d=l.b-l.a;\n D A=norm(d), B=2*dot(a, d), C=norm(a)-c.r*c.r;\n D Dlt=B*B-4*A*C;\n if (lt(Dlt, 0)) return res;\n D s = le(Dlt, 0) ? 0 : sqrtl(max<D>(0, Dlt));\n D t1 = (-B - s)/(2*A), t2 = (-B + s)/(2*A);\n res.push_back(c.o + a + d*t1);\n if (gt(Dlt, 0)) res.push_back(c.o + a + d*t2);\n return res;\n}\n\nvector<P2> cpCC(C2 c1, C2 c2) {\n vector<P2> res;\n P2 d=c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n D a=(c1.r*c1.r-c2.r*c2.r+L*L)/(2*L), h2=c1.r*c1.r-a*a;\n if (lt(h2, 0)) return res;\n P2 m=c1.o+d*(a/L), n=rot90(d)*( (lt(h2, 0) ? 0 : sqrtl(max<D>(0, h2))/L) );\n res.push_back(m-n);\n if (gt(h2, 0)) res.push_back(m+n);\n return res;\n}\n\nD isaCC(C2 c1, C2 c2) {\n D d=abs(c1.o-c2.o), r1=c1.r, r2=c2.r;\n if (ge(d, r1+r2)) return 0;\n if (le(d, abs(r1-r2))) {\n D r=min(r1, r2);\n return PI*r*r;\n }\n auto f = [&] (D z) { return max<D>(-1, min<D>(1, z)); };\n D a = 2*acosl(f((d*d+r1*r1-r2*r2)/(2*d*r1)));\n D b = 2*acosl(f((d*d+r2*r2-r1*r1)/(2*d*r2)));\n return 0.5L*(r1*r1*(a-sinl(a)) + r2*r2*(b-sinl(b)));\n}\n\nvector<L2> tangCP(C2 c, P2 p) {\n vector<L2> res;\n P2 v = p - c.o;\n D d2 = norm(v), r2 = c.r*c.r;\n if (lt(d2, r2)) return res;\n if (eq(d2, r2)) {\n res.push_back({c.o+v*(r2/d2), p});\n return res;\n }\n D h = c.r*sqrtl(max<D>(0, d2 - r2));\n P2 n1 = (v*r2 - rot90(v)*h)/d2;\n P2 n2 = (v*r2 + rot90(v)*h)/d2;\n res.push_back({c.o+n1, p});\n res.push_back({c.o+n2, p});\n return res;\n}\n\nvector<L2> tangCC(C2 c1, C2 c2) {\n vector<L2> res;\n P2 d = c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n P2 e = d/L;\n auto add = [&] (int s) {\n D c=(s*c2.r - c1.r)/L;\n if (gt(c*c, 1)) return;\n D s2 = max<D>(0, 1 - c*c);\n if (eq(s2, 0)) {\n P2 n = e*c;\n res.push_back({c1.o-n*c1.r, c2.o-n*c2.r});\n } else {\n D s = sqrtl(s2);\n P2 n1 = e*c + rot90(e)*s;\n P2 n2 = e*c - rot90(e)*s;\n res.push_back({c1.o-n1*c1.r, c2.o-n1*c2.r});\n res.push_back({c1.o-n2*c1.r, c2.o-n2*c2.r});\n }\n };\n add(+1); // external\n add(-1); // internal\n return res;\n}\n\nC2 mec(G2 ps) {\n auto inC2=[&](C2 c, P2 p){ return le(abs(c.o - p), c.r); };\n mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n shuffle(all(ps), rng);\n int n=ps.size();\n if(n==0) return C2{P2(0,0), 0};\n C2 c{ps[0], 0};\n rep(i, n) {\n if (inC2(c, ps[i])) continue;\n c={ps[i], 0};\n rep(j, i) {\n if (inC2(c, ps[j])) continue;\n c=makeC2(ps[i], ps[j]);\n rep(k, j) {\n if (inC2(c, ps[k])) continue;\n c=makeC2(ps[i], ps[j], ps[k]);\n }\n }\n }\n return c;\n}\n\nvector<P2> cpSegs(vector<S2> ss) {\n struct E { D x; int t; D y, y1, y2; }; // t: 0=add(H), 1=query(V), 2=remove(H)\n vector<E> es; es.reserve(ss.size()*2);\n\n for(auto s: ss) {\n if (eq(s.a.imag(), s.b.imag())) {\n if (gt(s.a.real(), s.b.real())) swap(s.a, s.b);\n es.push_back({s.a.real(), 0, s.a.imag(), 0, 0});\n es.push_back({s.b.real(), 2, s.a.imag(), 0, 0});\n } else {\n if (gt(s.a.imag(), s.b.imag())) swap(s.a, s.b);\n es.push_back({s.a.real(), 1, 0, s.a.imag(), s.b.imag()});\n }\n }\n\n sort(all(es), [](E a, E b) {\n if (!eq(a.x, b.x)) return lt(a.x, b.x);\n return a.t < b.t;\n });\n\n multiset<D> active;\n vector<P2> res; res.reserve(ss.size());\n for (auto e : es) {\n if (e.t == 0) { // add\n active.insert(e.y);\n } else if (e.t == 2) { // remove\n auto it = active.find(e.y);\n if (it != active.end()) active.erase(it);\n } else { // query\n for (auto it = active.lower_bound(e.y1); it != active.end() && le(*it, e.y2); ++it) {\n res.push_back(P2(e.x, *it));\n }\n }\n }\n\n sort(all(res), ltP2);\n res.erase(unique(all(res), eqP2), res.end());\n return res;\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_A\nvoid Projection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(proj(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_B\nvoid Reflection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(refl(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_C\nvoid CounterClockwise() {\n P2 p0, p1;\n rd(p0); rd(p1);\n ll q; cin>>q;\n while(q--) {\n P2 p; rd(p);\n int res = ccw(p0, p1, p);\n if (res == +1) out(\"COUNTER_CLOCKWISE\");\n else if (res == -1) out(\"CLOCKWISE\");\n else if (res == +2) out(\"ONLINE_BACK\");\n else if (res == -2) out(\"ONLINE_FRONT\");\n else out(\"ON_SEGMENT\");\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_2_A\nvoid ParallelOrthogonal() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n if (isParallel({p1, p2}, {p3, p4})) out(2);\n else if(isPerp({p1, p2}, {p3, p4})) out(1);\n else out(0);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_B\nvoid IntersectionSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n out(isSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_C\nvoid CrossPointSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n L2 s1 = {p1, p2}, s2 = {p3, p4};\n pr(cpLL(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_D\nvoid DistanceSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n setp(12);\n out(distSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_A\nvoid Area() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n setp(1);\n out(area(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_B\nvoid IsConvex() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n out(isConvex(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_C\nvoid PolygonPointContainment() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n out(inG(g, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\nvoid ConvexHull() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n G2 h = hull(g);\n out(h.size());\n ll sx = INF, sy = INF;\n ll id = -1;\n rep(i, h.size()) {\n if (lt(imag(h[i]), sy)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n else if (eq(imag(h[i]), sy) && lt(real(h[i]), sx)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n }\n rep(i, h.size()) {\n ll ni = (id + i) % h.size();\n pr(h[ni]);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_B\nvoid DiameterOfConvexPolygon() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = diameter(g);\n setp(12);\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_C\nvoid ConvexCut() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n G2 h = cutConvex(g, l);\n setp(12);\n out(area(h));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_A\nvoid ClosestPair() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = closestPair(g);\n setp(12);\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_B\nvoid MinimumEnclosingCircle() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [c, r] = mec(g);\n pr(c);\n setp(12);\n out(r);\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/6/CGL_6_A\nvoid SegmentIntersections() {\n ll n;cin>>n;\n vector<S2> seg(n);\n rep(i, n) {\n P2 a, b; rd(a); rd(b);\n seg[i] = {a, b};\n }\n out(cpSegs(seg).size());\n}\n\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_A\nvoid IntersectionOfCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n out(tangCC(c1, c2).size());\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_B\nvoid IncircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [ic, ir] = incircle(a, b, c);\n pr(ic);\n setp(12);\n out(ir);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_C\nvoid CircumscribedCircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [cc, cr] = makeC2(a, b, c);\n pr(cc);\n setp(12);\n out(cr);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_D\nvoid CrossPointsCL() {\n P2 c; D r;\n rd(c); cin>>r;\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n auto ps = cpCL(l, {c, r});\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n }\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_E\nvoid CrossPointsCC() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ps = cpCC(c1, c2);\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_F\nvoid TangentToCircle() {\n P2 p, c; D r;\n rd(p);\n rd(c); cin>>r;\n C2 c1={c, r};\n auto ls = tangCP(c1, p);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_G\nvoid CommonTangent() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ls = tangCC(c1, c2);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_H\n// void IntersectionCP() {\n// ll n;cin>>n;\n// D r; cin>>r;\n// C2 c = {P2(0, 0), r};\n// G2 g(n);\n// rep(i, n) rd(g[i]);\n// out(isaCP(c, g));\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_I\nvoid AreaOfIntersectionBetweenTwoCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n setp(12);\n out(isaCC(c1, c2));\n}\n\nint main() {\n cin.tie(0);\n ios_base::sync_with_stdio(false);\n\n // Projection();\n // Reflection();\n // CounterClockwise();\n\n // ParallelOrthogonal();\n // IntersectionSS();\n // CrossPointSS();\n // DistanceSS();\n\n // Area();\n // IsConvex();\n // PolygonPointContainment();\n\n ConvexHull();\n // DiameterOfConvexPolygon();\n // ConvexCut();\n\n // ClosestPair();\n // MinimumEnclosingCircle();\n\n // SegmentIntersections();\n\n // IntersectionOfCircles();\n // IncircleOfTriangle();\n // CircumscribedCircleOfTriangle();\n // CrossPointsCL();\n // CrossPointsCC();\n // TangentToCircle();\n // CommonTangent();\n // IntersectionCP();\n // AreaOfIntersectionBetweenTwoCircles();\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 13248, "score_of_the_acc": -1.3208, "final_rank": 17 }, { "submission_id": "aoj_CGL_4_A_10903843", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <climits>\n#include <unordered_map>\n#include <queue>\n#include <deque>\n#include <math.h>\n#include <bits/stdc++.h>\n#define ll long long\n#define Lt Line<T>\n#define Pt Point<T>\nusing i64 = long long;\nusing namespace std;\n\nconst ll N=1e6+10,MOD=998244353;\n\ntypedef std::pair<ll,ll> pii;\ntypedef std::pair<ll,pii> piii;\n//i64 n,m,k;\n\nusing ld = long double;\nconst ld PI = acos(-1);\nconst ld EPS = 1e-7;\nconst ld INF = numeric_limits<ld>::max();\n#define cc(x) cout << fixed << setprecision(x);\n\nld fgcd(ld x, ld y) { // 实数域gcd\n return abs(y) < EPS ? abs(x) : fgcd(y, fmod(x, y));\n}\ntemplate<class T, class S> bool equal(T x, S y) {\n return -EPS < x - y && x - y < EPS;\n}\ntemplate<class T> int sign(T x) {\n if (-EPS < x && x < EPS) return 0;\n return x < 0 ? -1 : 1;\n}\n\ntemplate<class T> struct Point { // 在C++17下使用 emplace_back 绑定可能会导致CE!\n T x, y;\n Point(T x_ = 0, T y_ = 0) : x(x_), y(y_) {} // 初始化\n template<class U> operator Point<U>() { // 自动类型匹配\n return Point<U>(U(x), U(y));\n }\n Point &operator+=(Point p) & { return x += p.x, y += p.y, *this; }\n Point &operator+=(T t) & { return x += t, y += t, *this; }\n Point &operator-=(Point p) & { return x -= p.x, y -= p.y, *this; }\n Point &operator-=(T t) & { return x -= t, y -= t, *this; }\n Point &operator*=(T t) & { return x *= t, y *= t, *this; }\n Point &operator/=(T t) & { return x /= t, y /= t, *this; }\n Point operator-() const { return Point(-x, -y); }\n friend Point operator+(Point a, Point b) { return a += b; }\n friend Point operator+(Point a, T b) { return a += b; }\n friend Point operator-(Point a, Point b) { return a -= b; }\n friend Point operator-(Point a, T b) { return a -= b; }\n friend Point operator*(Point a, T b) { return a *= b; }\n friend Point operator*(T a, Point b) { return b *= a; }\n friend Point operator/(Point a, T b) { return a /= b; }\n friend bool operator<(Point a, Point b) {\n return equal(a.x, b.x) ? a.y < b.y - EPS : a.x < b.x - EPS;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return !(a < b) && !(b < a); }\n friend bool operator!=(Point a, Point b) { return a < b || b < a; }\n friend auto &operator>>(istream &is, Point &p) {\n return is >> p.x >> p.y;\n }\n friend auto &operator<<(ostream &os, Point p) {\n return os << \"(\" << p.x << \", \" << p.y << \")\";\n }\n};\ntemplate<class T> struct Line {\n Point<T> a, b;\n Line(Point<T> a_ = Point<T>(), Point<T> b_ = Point<T>()) : a(a_), b(b_) {}\n template<class U> operator Line<U>() { // 自动类型匹配\n return Line<U>(Point<U>(a), Point<U>(b));\n }\n friend auto &operator<<(ostream &os, Line l) {\n return os << \"<\" << l.a << \", \" << l.b << \">\";\n }\n};\n\nusing Pd = Point<ld>;\nusing Ld = Line<ld>;\n\n\ntemplate<class T> T cross(Point<T> a, Point<T> b) { // 叉乘\n return a.x * b.y - a.y * b.x;\n}\ntemplate<class T> T cross(Point<T> p1, Point<T> p2, Point<T> p0) { // 叉乘 (p1 - p0) x (p2 - p0);\n return cross(p1 - p0, p2 - p0);\n}\n\n\ntemplate<class T> T dot(Point<T> a, Point<T> b) { // 点乘\n return a.x * b.x + a.y * b.y;\n}\ntemplate<class T> T dot(Point<T> p1, Point<T> p2, Point<T> p0) { // 点乘 (p1 - p0) * (p2 - p0);\n return dot(p1 - p0, p2 - p0);\n}\n\ntemplate <class T> ld dis(T x1, T y1, T x2, T y2) {\n ld val = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n return sqrt(val);\n}\ntemplate <class T> ld dis(Point<T> a, Point<T> b) {\n return dis(a.x, a.y, b.x, b.y);\n}\n\ntemplate<class T> Point<T> rotate(Point<T> p1, Point<T> p2) { // 旋转\n Point<T> vec = p1 - p2;\n return {-vec.y, vec.x};\n}\n\nld toDeg(ld x) { // 弧度转角度\n return x * 180 / PI;\n}\nld toArc(ld x) { // 角度转弧度\n return PI / 180 * x;\n}\n\nPoint<ld> rotate(Point<ld> p, ld rad) {\n return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)};\n}\n\nPoint<ld> rotate(Point<ld> a, Point<ld> b, ld rad) {\n ld x = (a.x - b.x) * cos(rad) + (a.y - b.y) * sin(rad) + b.x;\n ld y = (b.x - a.x) * sin(rad) + (a.y - b.y) * cos(rad) + b.y;\n return {x, y};\n}\n\ntemplate<class T> bool onLine(Point<T> a, Point<T> b, Point<T> c) {\n return sign(cross(b, a, c)) == 0;\n}\ntemplate<class T> bool onLine(Point<T> p, Line<T> l) {\n return onLine(p, l.a, l.b);\n}\n\ntemplate<class T> bool pointOnLineLeft(Pt p, Lt l) {\n return cross(l.b, p, l.a) > 0;\n}\n\ntemplate<class T> bool pointOnLineSide(Pt p1, Pt p2, Lt vec) {\n T val = cross(p1, vec.a, vec.b) * cross(p2, vec.a, vec.b);\n return sign(val) == 1;\n}\ntemplate<class T> bool pointNotOnLineSide(Pt p1, Pt p2, Lt vec) {\n T val = cross(p1, vec.a, vec.b) * cross(p2, vec.a, vec.b);\n return sign(val) == -1;\n}\n\nPd lineIntersection(Ld l1, Ld l2) {\n ld val = cross(l2.b - l2.a, l1.a - l2.a) / cross(l2.b - l2.a, l1.a - l1.b);\n return l1.a + (l1.b - l1.a) * val;\n}\n\ntemplate<class T> bool lineParallel(Lt p1, Lt p2) {\n return sign(cross(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool lineVertical(Lt p1, Lt p2) {\n return sign(dot(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool same(Line<T> l1, Line<T> l2) {\n return lineParallel(Line{l1.a, l2.b}, {l1.b, l2.a}) &&\n lineParallel(Line{l1.a, l2.a}, {l1.b, l2.b}) && lineParallel(l1, l2);\n}\n\npair<Pd, ld> pointToLine(Pd p, Ld l) {\n Pd ans = lineIntersection({p, p + rotate(l.a, l.b)}, l);\n return {ans, dis(p, ans)};\n}\n\ntemplate<class T> ld disPointToLine(Pt p, Lt l) {\n ld ans = cross(p, l.a, l.b);\n return abs(ans) / dis(l.a, l.b); // 面积除以底边长\n}\n\ntemplate<class T> bool pointOnSegment(Pt p, Lt l) { // 端点也算作在直线上\n return sign(cross(p, l.a, l.b)) == 0 && min(l.a.x, l.b.x) <= p.x && p.x <= max(l.a.x, l.b.x) &&\n min(l.a.y, l.b.y) <= p.y && p.y <= max(l.a.y, l.b.y);\n}\n\npair<Pd, ld> pointToSegment(Pd p, Ld l) {\n if (sign(dot(p, l.b, l.a)) == -1) { // 特判到两端点的距离\n return {l.a, dis(p, l.a)};\n } else if (sign(dot(p, l.a, l.b)) == -1) {\n return {l.b, dis(p, l.b)};\n }\n return pointToLine(p, l);\n}\n\ntemplate<class T> bool segmentIntersection(Lt l1, Lt l2) {\n auto [s1, e1] = l1;\n auto [s2, e2] = l2;\n auto A = max(s1.x, e1.x), AA = min(s1.x, e1.x);\n auto B = max(s1.y, e1.y), BB = min(s1.y, e1.y);\n auto C = max(s2.x, e2.x), CC = min(s2.x, e2.x);\n auto D = max(s2.y, e2.y), DD = min(s2.y, e2.y);\n return A >= CC && B >= DD && C >= AA && D >= BB &&\n sign(cross(s1, s2, e1) * cross(s1, e1, e2)) == 1 &&\n sign(cross(s2, s1, e2) * cross(s2, e2, e1)) == 1;\n}\n\ntemplate<class T> int pointInPolygon(Point<T> a, vector<Point<T>> p) {\n int n = p.size();\n for (int i = 0; i < n; i++) {\n if (pointOnSegment(a, Line{p[i], p[(i + 1) % n]})) {\n return 2;\n }\n }\n int t = 0;\n for (int i = 0; i < n; i++) {\n auto u = p[i], v = p[(i + 1) % n];\n if (u.x < a.x && v.x >= a.x && pointOnLineLeft(a, Line{v, u})) {\n t ^= 1;\n }\n if (u.x >= a.x && v.x < a.x && pointOnLineLeft(a, Line{u, v})) {\n t ^= 1;\n }\n }\n return t == 1;\n}\n\ntemplate<class T> bool cmp1(Point<T> &a,Point<T> &b)\n{\n Point<T> a1(a.y,a.x);\n Point<T> b1(b.y,b.x);\n return a1<b1;\n}\n\ntemplate<class T> vector<Point<T>> staticConvexHull(vector<Point<T>> A, int flag = 1) {\n int n = A.size();\n if (n <= 2) { // 特判\n return A;\n }\n vector<Point<T>> ans(n * 2);\n sort(A.begin(), A.end());\n int now = -1;\n \n for (int i = 0; i < n; i++) { // 维护下凸包\n while (now > 0 && cross(A[i], ans[now], ans[now - 1]) < 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n int pre = now;\n for (int i = n - 2; i >= 0; i--) { // 维护上凸包\n while (now > pre && cross(A[i], ans[now], ans[now - 1]) < 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n ans.resize(now);\n return ans;\n}\n\n\nint main() {\n \n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n\n int n; cin>>n;\n vector<Point<ll>> P(n);\n for(auto &t:P) cin>>t;\n auto res=staticConvexHull(P);\n \n //sort(res.begin(),res.end(),cmp1<ll>);\n //res.erase(unique(res.begin(),res.end()),res.end());\n // cout<<res.size()<<'\\n';\n\n // for(auto tee:res) cout<<tee.x<<' '<<tee.y<<'\\n';\n\n vector<Point<ll>> res1; Point<ll> tem(INT_MAX,INT_MAX);\n int w;\n for(int i=0;i<res.size();i++) \n {\n if(cmp1(res[i],tem))\n {\n tem=res[i];\n w=i;\n }\n }\n\n for(int i=w;i>=0;i--)\n {\n res1.push_back(res[i]);\n }\n for(int i=res.size()-1;i>w;i--) res1.push_back(res[i]);\n cout<<res1.size()<<'\\n';\n for(auto re:res1) cout<<re.x<<' '<<re.y<<'\\n';\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10384, "score_of_the_acc": -0.403, "final_rank": 6 }, { "submission_id": "aoj_CGL_4_A_10896314", "code_snippet": "#line 1 \"a.cpp\"\n#define PROBLEM \\\n \"https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\"\n#line 2 \"/workspaces/cp-container/libraries/template.hpp\"\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing vll = vector<ll>;\nusing vvll = vector<vll>;\n\ntemplate <typename T>\nbool chmax(T& a, const T& b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\n\ntemplate <typename T>\nbool chmin(T& a, const T& b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n#line 3 \"/workspaces/cp-container/libraries/geometry/core.hpp\"\n\nusing Point = complex<double>;\n\nstruct Line {\n Point a, b;\n Line() = default;\n Line(const Point& _a, const Point& _b) : a(_a), b(_b) {}\n};\n\nconstexpr double eps = 1.0e-9;\n\ndouble dot(const Point& a, const Point& b) { return (conj(a) * b).real(); }\ndouble cross(const Point& a, const Point& b) { return (conj(a) * b).imag(); }\n\nPoint projection(const Point& p0, const Point& p1, const Point& p) {\n Point base = p1 - p0, hyp = p - p0;\n double t = dot(base, hyp) / norm(base);\n return p0 + t * base;\n}\n\nPoint reflection(const Point& p0, const Point& p1, const Point& p) {\n return 2.0 * projection(p0, p1, p) - p;\n}\n\nconstexpr int COUNTER_CLOCKWISE = 1, CLOCKWISE = -1, ONLINE_BACK = 2,\n ONLINE_FRONT = -2, ON_SEGMENT = 0;\n\nint ccw(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0, b = p2 - p0;\n if (eps < cross(a, b)) return COUNTER_CLOCKWISE;\n if (cross(a, b) < -eps) return CLOCKWISE;\n if (dot(a, b) < -eps) return ONLINE_BACK;\n if (norm(a) < norm(b)) return ONLINE_FRONT;\n return ON_SEGMENT;\n}\n\nbool is_parallel(const Line& l0, const Line& l1) {\n return abs(cross(l0.b - l0.a, l1.b - l1.a)) < eps;\n}\n\nbool is_orthogonal(const Line& l0, const Line& l1) {\n return abs(dot(l0.b - l0.a, l1.b - l1.a)) < eps;\n}\n\nbool has_intersection(Line s0, Line s1) {\n return ccw(s0.a, s0.b, s1.a) * ccw(s0.a, s0.b, s1.b) <= 0 &&\n ccw(s1.a, s1.b, s0.a) * ccw(s1.a, s1.b, s0.b) <= 0;\n}\n\nPoint cross_point(const Line& l0, const Line& l1) {\n double d0 = cross(l0.b - l0.a, l1.b - l1.a),\n d1 = cross(l0.b - l0.a, l0.b - l1.a);\n if (abs(d0) < eps && abs(d1) < eps) return l1.a;\n return l1.a + d1 / d0 * (l1.b - l1.a);\n}\n\ndouble distance_between_point_and_segment(const Point& p, const Line& s) {\n if (dot(s.b - s.a, p - s.a) < eps) return abs(p - s.a);\n if (dot(s.a - s.b, p - s.b) < eps) return abs(p - s.b);\n return abs(cross(s.b - s.a, p - s.a)) / abs(s.b - s.a);\n}\n\ndouble distance_between_segments(const Line& s0, const Line& s1) {\n if (has_intersection(s0, s1)) return 0.0;\n double ret = numeric_limits<double>::max();\n chmin(ret, distance_between_point_and_segment(s0.a, s1));\n chmin(ret, distance_between_point_and_segment(s0.b, s1));\n chmin(ret, distance_between_point_and_segment(s1.a, s0));\n chmin(ret, distance_between_point_and_segment(s1.b, s0));\n return ret;\n}\n\nusing Polygon = vector<Point>;\n\ndouble area(const Polygon& g) {\n int n = g.size();\n double ret = 0.0;\n rep(i, n) ret += cross(g[i], g[(i + 1) % n]);\n ret /= 2.0;\n return ret;\n}\n\nbool is_convex(const Polygon& g) {\n int n = g.size();\n rep(i, n) {\n if (ccw(g[(i - 1 + n) % n], g[i], g[(i + 1) % n]) == CLOCKWISE)\n return false;\n }\n return true;\n}\n\nint polygon_point_containment(const Polygon& g, const Point& p) {\n bool is_contained = false;\n int n = g.size();\n rep(i, n) {\n Point a = g[i] - p, b = g[(i + 1) % n] - p;\n if (a.imag() > b.imag()) swap(a, b);\n if (a.imag() < eps && eps < b.imag() && cross(a, b) < -eps)\n is_contained = !is_contained;\n if (abs(cross(a, b)) < eps && dot(a, b) < eps) return 1;\n }\n return is_contained ? 2 : 0;\n}\n\nvi convex_hull(const Polygon& g) {\n int n = g.size();\n if (n == 0) return {};\n vi p_idx(n);\n iota(p_idx.begin(), p_idx.end(), 0);\n ranges::sort(p_idx, [&](int a, int b) {\n if (eps < abs(g[a].real() - g[b].real())) return g[a].real() < g[b].real();\n return g[a].imag() < g[b].imag() - eps;\n });\n vvi hull(2);\n rep(i, 2) {\n for (int idx : p_idx) {\n while (2 <= (int)hull[i].size() &&\n ccw(g[hull[i][(int)hull[i].size() - 2]], g[hull[i].back()],\n g[idx]) == CLOCKWISE) {\n hull[i].pop_back();\n }\n hull[i].emplace_back(idx);\n }\n hull[i].pop_back();\n ranges::reverse(p_idx);\n }\n ranges::copy(hull[1], back_inserter(hull[0]));\n return hull[0];\n}\n#line 5 \"a.cpp\"\nsigned main() {\n cin.tie(nullptr)->sync_with_stdio(false);\n int n;\n cin >> n;\n vi x(n), y(n);\n Polygon g(n);\n rep(i, n) {\n cin >> x[i] >> y[i];\n g[i] = Point(x[i], y[i]);\n }\n vi res = convex_hull(g);\n pair<int, int> mn = {1 << 30, 1 << 30};\n int mni = -1, siz = res.size();\n rep(i, siz) {\n if (chmin(mn, make_pair(y[res[i]], x[res[i]]))) mni = i;\n }\n cout << siz << endl;\n rep(i, siz) cout << x[res[(mni + i) % siz]] << ' ' << y[res[(mni + i) % siz]]\n << '\\n';\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 6432, "score_of_the_acc": -0.0565, "final_rank": 2 }, { "submission_id": "aoj_CGL_4_A_10893565", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n\n#define maxn 100010\n\n\nstruct Point{\n double x,y;\n bool operator <(Point p){\n if(x!=p.x)return x<p.x;\n return y<p.y;\n }\n};\n\ndouble det(Point a1,Point a2,Point b1,Point b2){\n return (a2.x-a1.x)*(b2.y-b1.y)-(b2.x-b1.x)*(a2.y-a1.y);\n}\ndouble dis(Point a,Point b){\n return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));\n}\n\ndouble tot;\nint n;\nPoint point[maxn];\nint s[maxn],top;\nvector<int>f;\nsigned main(){\n cin>>n;\n for(int i =1;i<=n;i++)cin>>point[i].x>>point[i].y;\n sort(point+1,point+1+n);\n \n s[++top]=1;\n for(int i = 2;i<=n;i++){\n while(top>1&&det(point[s[top-1]],point[s[top]],point[s[top]],point[i])<0){\n s[top--]=0;\n }\n s[++top]=i;\n }\n for(int i =1;i<top;i++){\n tot+=dis(point[s[i]],point[s[i+1]]);\n f.push_back(s[i]);\n }\n \n top=0;\n s[++top]=n;\n for(int i = n-1;i>=1;i--){\n while(top>1&&det(point[s[top-1]],point[s[top]],point[s[top]],point[i])<0){\n s[top--]=0;\n }\n s[++top]=i;\n }\n for(int i =1;i<top;i++){\n tot+=dis(point[s[i]],point[s[i+1]]);\n f.push_back(s[i]);\n }\n // printf(\"%.2lf\\n\",tot);\n cout<<f.size()<<endl;\n int pos =0;\n double miy = 1e18;\n for(int it = 0;it<f.size();it++){\n if(miy>point[f[it]].y){\n miy = point[f[it]].y;\n pos = it;\n }\n }\n // cout<<pos<<endl;\n //for(auto it:f)cout<<point[it].x<<' '<<point[it].y<<endl;\n for(int i = pos;i<f.size();i++){\n //cout<<i<<endl;\n cout<<point[f[i]].x<<' '<<point[f[i]].y<<endl;\n }\n for(int i = 0;i<pos;i++){\n cout<<point[f[i]].x<<' '<<point[f[i]].y<<endl;\n }\n\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5788, "score_of_the_acc": -0.5833, "final_rank": 9 }, { "submission_id": "aoj_CGL_4_A_10853526", "code_snippet": "#include<bits/stdc++.h>\n#define siz(x) int((x).size())\n#define all(x) std::begin(x),std::end(x)\n#define fi first\n#define se second\nusing namespace std;\nusing unt=unsigned;\nusing loli=long long;\nusing lolu=unsigned long long;\nusing pii=pair<int,int>;\nmt19937_64 rng(random_device{}());\nconstexpr double eps=1e-8;\ntemplate<typename any>inline any sqr(const any &x){return x*x;}\ninline int get_op(double x){if(fabs(x)<eps)return 0;return x>0?1:-1;}\ndouble det(array<double,3>a0,array<double,3>a1,array<double,3>a2){\n\tdouble sum=0;\n\tsum+=a0[0]*a1[1]*a2[2];\n\tsum+=a1[0]*a2[1]*a0[2];\n\tsum+=a2[0]*a0[1]*a1[2];\n\tsum-=a0[2]*a1[1]*a2[0];\n\tsum-=a0[1]*a1[0]*a2[2];\n\tsum-=a0[0]*a1[2]*a2[1];\n\treturn sum;\n}\nstruct bector{\n\tdouble x,y;\n\tbool operator<(const bector&t)const{return fabs(x-t.x)<eps?y<t.y:x<t.x;}\n\tbool operator==(const bector&t)const{return fabs(x-t.x)<eps&&fabs(y-t.y)<eps;}\n\tbector(double a=0,double b=0):x(a),y(b){}\n\tdouble operator~()const{return sqrt(x*x+y*y);}\n\tdouble operator*()const{return x*x+y*y;}\n\tfriend istream&operator>>(istream&a,bector&b){return a>>b.x>>b.y;}\n\tfriend ostream&operator<<(ostream&a,const bector&b){return a<<b.x<<' '<<b.y;}\n\tfriend bector operator+(const bector&a,const bector&b){return {a.x+b.x,a.y+b.y};}\n\tbector&operator+=(const bector&t){x+=t.x,y+=t.y;return *this;}\n\tfriend bector operator-(const bector&a,const bector&b){return {a.x-b.x,a.y-b.y};}\n\tbector&operator-=(const bector&t){x-=t.x,y-=t.y;return *this;}\n\tfriend bector operator*(const bector&a,double b){return {a.x*b,a.y*b};}\n\tfriend bector operator*(double b,const bector&a){return {a.x*b,a.y*b};}\n\tbector&operator*=(double t){x*=t,y*=t;return *this;}\n\tfriend bector operator/(const bector&a,double b){return {a.x/b,a.y/b};}\n\tbector&operator/=(double t){x/=t,y/=t;return *this;}\n\tfriend double operator*(const bector&a,const bector&b){return a.x*b.x+a.y*b.y;}\n\tfriend double operator/(const bector&a,const bector&b){return a.x*b.y-a.y*b.x;}\n\tbool frontis(const bector&t)const{auto r=*this*t;return get_op(r)>0;}\n\tbool backis(const bector&t)const{auto r=*this*t;return get_op(r)<0;}\n\tbool leftis(const bector&t)const{auto r=*this/t;return get_op(r)>0;}\n\tbool rightis(const bector&t)const{auto r=*this/t;return get_op(r)<0;}\n\tfriend double dis(const bector&a,const bector&b){return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}\n\tbector rot90()const{return {-y,x};}\n\tdouble arg()const{return atan2(y,x);}\n\tbector rotate(const bector&a,double r){\n\t\tauto u=a-*this;\n\t\treturn *this+bector{u.x*cos(r)-u.y*sin(r),u.x*sin(r)+u.y*cos(r)};\n\t}\n\tfriend double c0s(const bector&x,const bector&y){\n\t\t// 求 cos<x,y>\n\t\treturn x*y/~x/~y;\n\t}\n\tbector unit()const{\n\t\treturn (*this)/~(*this);\n\t}\n\tfriend bool operator&(const bector&a,const bector&b){return !get_op(a*b);}\n\tfriend bool operator|(const bector&a,const bector&b){return !get_op(a/b);}\n};\nbector polar(double p,double r){return {cos(r)*p,sin(r)*p};}\nstruct segment{\n\tbector p1,p2;\n\tsegment(const bector&a={0,0},const bector&b={0,0}):p1(a),p2(b){};\n\tfriend istream&operator>>(istream&a,segment &b){return a>>b.p1>>b.p2;}\n\tfriend ostream&operator<<(ostream&a,const segment&b){return a<<b.p1<<' '<<b.p2;}\n\tfriend bool operator&(const segment&a,const segment&b){return !get_op((a.p2-a.p1)*(b.p2-b.p1));}\n\tfriend bool operator|(const segment&a,const segment&b){return !get_op((a.p2-a.p1)/(b.p2-b.p1));}\n\tfriend bool banana(const segment&a,const segment&b){\n\t\t// 判断是否相交\n\t\tif(min(a.p1.x,a.p2.x)>max(b.p1.x,b.p2.x)||min(b.p1.x,b.p2.x)>max(a.p1.x,a.p2.x)||min(a.p1.y,a.p2.y)>max(b.p1.y,b.p2.y)||min(b.p1.y,b.p2.y)>max(a.p1.y,a.p2.y))return false;\n\t\treturn get_op(((a.p2-a.p1)/(b.p1-a.p1))*((a.p2-a.p1)/(b.p2-a.p1)))<=0&&get_op(((b.p2-b.p1)/(a.p1-b.p1))*((b.p2-b.p1)/(a.p2-b.p1)))<=0;\n\t}\n\tfriend bector focus(const segment&a,const segment&b){\n\t\t// 输入必须保证有交,输出交点\n\t\tbector v=a.p2-a.p1,w=b.p2-b.p1,u=a.p1-b.p1;\n\t\treturn a.p1+v*((w/u)/(v/w));\n\t}\n\tfriend double dis(const segment&a,const bector&b){\n\t\tif(a.p1==a.p2)return ~(b-a.p1);\n\t\tauto v1=a.p2-a.p1,v2=b-a.p1,v3=b-a.p2;\n\t\tif(v1.backis(v2))return ~v2;\n\t\tif(v1.frontis(v3))return ~v3;\n\t\treturn fabs(v1/v2)/~v1;\n\t}\n\tfriend double dis(const segment&a,const segment&b){\n\t\t// 求线段间最短距离\n\t\tif(banana(a,b))return 0;\n\t\treturn min({dis(a,b.p1),dis(a,b.p2),dis(b,a.p1),dis(b,a.p2)});\n\t}\n\tbector project(const bector&a)const{\n\t\t// 求点 a 在当前线段上的投影点坐标\n\t\tif(a==p1||a==p2)return a;\n\t\tauto u=p2-p1,v=a-p1;\n\t\treturn c0s(u,v)*(~v)*u.unit()+p1;\n\t}\n\tbector reflect(const bector&a)const{\n\t\t// 求点 a 在当前线段上的对称点\n\t\treturn 2*project(a)-a;\n\t}\n\tsegment&sort(){if(p2<p1)std::swap(p1,p2);return *this;}\n};\nstruct circle{\n\tbector p;double r;\n\tcircle(const bector&a={0,0},double b=0):p(a),r(b){}\n\tcircle(bector p1,bector p2){\n\t\tp=(p1+p2)/2;\n\t\tr=dis(p1,p2)/2;\n\t}\n\tcircle(bector p1,bector p2,bector p3){\n\t\tp.x=det({*p1,p1.y,1},{*p2,p2.y,1},{*p3,p3.y,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tp.y=-det({*p1,p1.x,1},{*p2,p2.x,1},{*p3,p3.x,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tr=dis(p,p1);\n\t}\n\tfriend istream&operator>>(istream&a,circle &b){return a>>b.p>>b.r;}\n\tfriend ostream&operator<<(ostream&a,const circle &b){return a<<b.p<<' '<<b.r;}\n\tbool check(bector t){\n\t\treturn dis(p,t)-r<=eps;\n\t}\n\tfriend segment focus(const circle &a,const segment&b){\n\t\tauto d=b.project(a.p),u=b.p2-b.p1,e=u/~u;\n\t\tauto t=sqrt(a.r*a.r-sqr(dis(d,a.p)));\n\t\treturn segment{d+e*t,d-e*t}.sort();\n\t}\n\tfriend segment focus(const circle &a,const circle &b){\n\t\tauto d=dis(a.p,b.p),l=acos((sqr(a.r)+sqr(d)-sqr(b.r))/(2*a.r*d)),t=(b.p-a.p).arg();\n\t\treturn segment{a.p+polar(a.r,t+l),a.p+polar(a.r,t-l)}.sort();\n\t}\n\tsegment tangent(const bector&a){\n\t\tauto u=a-p;\n\t\tauto l=acos(r/~u);\n\t\tu=u*r/~u;\n\t\treturn segment{p.rotate(p+u,+l),p.rotate(p+u,-l)}.sort();\n\t}\n};\nstruct points:vector<bector>{\n#define p (*this)\n\tpoints&read(istream&t,int n=-1){\n\t\tif(n==-1)cin>>n;\n\t\tp.resize(n);\n\t\tfor(int i=0;i<n;i++)t>>p[i];\n\t\treturn *this;\n\t}\n\tdouble area()const{\n\t\t// 无需满足多边形是凸的\n\t\tdouble ans=0;\n\t\tfor(int i=1;i<siz(p)-1;i++)ans+=(p[i]-p[0])/(p[i+1]-p[0]);\n\t\treturn ans/2;\n\t}\n\tpoints tobag(){\n\t\tsort(all(p));\n\t\tpoints b1,b2;\n\t\tb1.push_back(p[0]),b1.push_back(p[1]);\n\t\tfor(int i=2;i<siz(p);i++){\n\t\t\tfor(int j=siz(b1)-1;j>=1&&(b1[j]-b1[j-1]).leftis(p[i]-b1[j-1]);j--)\n\t\t\t\tb1.pop_back();\n\t\t\tb1.push_back(p[i]);\n\t\t}\n\t\tb2.push_back(p.back()),b2.push_back(p[siz(p)-2]);\n\t\tfor(int i=siz(p)-3;~i;i--){\n\t\t\tfor(int j=siz(b2)-1;j>=1&&(b2[j]-b2[j-1]).leftis(p[i]-b2[j-1]);j--)\n\t\t\t\tb2.pop_back();\n\t\t\tb2.push_back(p[i]);\n\t\t}\n\t\treverse(all(b2));\n\t\tfor(int i=siz(b1)-2;i;i--)\n\t\t\tb2.push_back(b1[i]);\n\t\tif(siz(p)<=3)for(int i=0;i<siz(b2)-1;i++)\n\t\t\tif(b2[i]==b2.back()){\n\t\t\t\tb2.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\t\treturn b2;\n\t}\n\tdouble xzqk(){\n\t\tdouble ans=0;\n\t\tfor(size_t i=0,j=1;i<p.size();i++){\n\t\t\twhile((p[(i+1)%p.size()]-p[i])/(p[j]-p[i])<(p[(i+1)%p.size()]-p[i])/(p[(j+1)%p.size()]-p[i]))(++j)%=p.size();\n\t\t\tans=max({ans,dis(p[i],p[j]),dis(p[(i+1)%p.size()],p[j])});\n\t\t}\n\t\treturn ans;\n\t}\n\tcircle incircle(){\n\t\tassert(p.size()==3);\n\t\tauto u=p[1]-p[0],v=p[2]-p[0];u=u/~u*~v;\n\t\tsegment l1{p[0],p[0]+u+v};\n\t\tu=p[2]-p[1],v=p[0]-p[1];u=u/~u*~v;\n\t\tsegment l2{p[1],p[1]+u+v};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(segment{p[0],p[1]},pp)};\n\t}\n\tcircle outcirce(){\n\t\tassert(p.size()==3);\n\t\tauto u=p[1]-p[0],mid=(p[0]+p[1])/2;\n\t\tsegment l1{mid,mid+u.rot90()};\n\t\tu=p[2]-p[0],mid=(p[0]+p[2])/2;\n\t\tsegment l2{mid,mid+u.rot90()};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(p[0],pp)};\n\t}\n\tint contains(bector t){\n\t\t// 无需满足多边形是凸的\n\t\t// 2表示包含,1表示在边上,0表示在外面\n\t\tbool res=false;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tauto a=p[i]-t,b=p[(i+1)%siz(p)]-t;\n\t\t\tif(!a.leftis(b)&&!a.rightis(b)&&!a.frontis(b))return 1;\n\t\t\tif(a.y>b.y)std::swap(a,b);\n\t\t\tif(a.y<eps&&eps<b.y&&a.leftis(b))res=!res;\n\t\t}\n\t\treturn res?2:0;\n\t}\n#undef p\n};\ncircle mingenshin(points b){\n\tshuffle(all(b),rng);\n\tcircle ans;\n\tfor(int i=0;i<siz(b);i++)if(!ans.check(b[i])){\n\t\tans={b[i],0};\n\t\tfor(int j=0;j<i;j++)if(!ans.check(b[j])){\n\t\t\tans=circle(b[i],b[j]);\n\t\t\tfor(int k=0;k<j;k++)if(!ans.check(b[k])){\n\t\t\t\tans=circle(b[i],b[j],b[k]);\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\npoints a;\nsigned main(){\n//\tfreopen(\".in\",\"r\",stdin);\n//\tfreopen(\".out\",\"w\",stdout);\n\tstd::ios::sync_with_stdio(false);cin.tie(nullptr);\n\tcout<<std::setiosflags(std::ios::fixed)<<std::setprecision(0);\n\tauto b=a.read(cin).tobag();\n\tcout<<siz(b)<<'\\n';\n\tfor(int i=0;;i++)if(b[i%siz(b)].y<=b[(i+1)%siz(b)].y){\n\t\tfor(int j=i%siz(b);j<siz(b);j++)cout<<b[j]<<'\\n';\n\t\tfor(int j=0;j<i%siz(b);j++)cout<<b[j]<<'\\n';\n\t\tbreak;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 7076, "score_of_the_acc": -0.6129, "final_rank": 12 }, { "submission_id": "aoj_CGL_4_A_10853522", "code_snippet": "#include<bits/stdc++.h>\n#define siz(x) int((x).size())\n#define all(x) std::begin(x),std::end(x)\n#define fi first\n#define se second\nusing namespace std;\nusing unt=unsigned;\nusing loli=long long;\nusing lolu=unsigned long long;\nusing pii=pair<int,int>;\nmt19937_64 rng(random_device{}());\nconstexpr double eps=1e-8;\ntemplate<typename any>inline any sqr(const any &x){return x*x;}\ninline int get_op(double x){if(fabs(x)<eps)return 0;return x>0?1:-1;}\ndouble det(array<double,3>a0,array<double,3>a1,array<double,3>a2){\n\tdouble sum=0;\n\tsum+=a0[0]*a1[1]*a2[2];\n\tsum+=a1[0]*a2[1]*a0[2];\n\tsum+=a2[0]*a0[1]*a1[2];\n\tsum-=a0[2]*a1[1]*a2[0];\n\tsum-=a0[1]*a1[0]*a2[2];\n\tsum-=a0[0]*a1[2]*a2[1];\n\treturn sum;\n}\nstruct bector{\n\tdouble x,y;\n\tbool operator<(const bector&t)const{return fabs(x-t.x)<eps?y<t.y:x<t.x;}\n\tbool operator==(const bector&t)const{return fabs(x-t.x)<eps&&fabs(y-t.y)<eps;}\n\tbector(double a=0,double b=0):x(a),y(b){}\n\tdouble operator~()const{return sqrt(x*x+y*y);}\n\tdouble operator*()const{return x*x+y*y;}\n\tfriend istream&operator>>(istream&a,bector&b){return a>>b.x>>b.y;}\n\tfriend ostream&operator<<(ostream&a,const bector&b){return a<<b.x<<' '<<b.y;}\n\tfriend bector operator+(const bector&a,const bector&b){return {a.x+b.x,a.y+b.y};}\n\tbector&operator+=(const bector&t){x+=t.x,y+=t.y;return *this;}\n\tfriend bector operator-(const bector&a,const bector&b){return {a.x-b.x,a.y-b.y};}\n\tbector&operator-=(const bector&t){x-=t.x,y-=t.y;return *this;}\n\tfriend bector operator*(const bector&a,double b){return {a.x*b,a.y*b};}\n\tfriend bector operator*(double b,const bector&a){return {a.x*b,a.y*b};}\n\tbector&operator*=(double t){x*=t,y*=t;return *this;}\n\tfriend bector operator/(const bector&a,double b){return {a.x/b,a.y/b};}\n\tbector&operator/=(double t){x/=t,y/=t;return *this;}\n\tfriend double operator*(const bector&a,const bector&b){return a.x*b.x+a.y*b.y;}\n\tfriend double operator/(const bector&a,const bector&b){return a.x*b.y-a.y*b.x;}\n\tbool frontis(const bector&t)const{auto r=*this*t;return get_op(r)>0;}\n\tbool backis(const bector&t)const{auto r=*this*t;return get_op(r)<0;}\n\tbool leftis(const bector&t)const{auto r=*this/t;return get_op(r)>0;}\n\tbool rightis(const bector&t)const{auto r=*this/t;return get_op(r)<0;}\n\tfriend double dis(const bector&a,const bector&b){return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}\n\tbector rot90()const{return {-y,x};}\n\tdouble arg()const{return atan2(y,x);}\n\tbector rotate(const bector&a,double r){\n\t\tauto u=a-*this;\n\t\treturn *this+bector{u.x*cos(r)-u.y*sin(r),u.x*sin(r)+u.y*cos(r)};\n\t}\n\tfriend double c0s(const bector&x,const bector&y){\n\t\t// 求 cos<x,y>\n\t\treturn x*y/~x/~y;\n\t}\n\tbector unit()const{\n\t\treturn (*this)/~(*this);\n\t}\n\tfriend bool operator&(const bector&a,const bector&b){return !get_op(a*b);}\n\tfriend bool operator|(const bector&a,const bector&b){return !get_op(a/b);}\n};\nbector polar(double p,double r){return {cos(r)*p,sin(r)*p};}\nstruct segment{\n\tbector p1,p2;\n\tsegment(const bector&a={0,0},const bector&b={0,0}):p1(a),p2(b){};\n\tfriend istream&operator>>(istream&a,segment &b){return a>>b.p1>>b.p2;}\n\tfriend ostream&operator<<(ostream&a,const segment&b){return a<<b.p1<<' '<<b.p2;}\n\tfriend bool operator&(const segment&a,const segment&b){return !get_op((a.p2-a.p1)*(b.p2-b.p1));}\n\tfriend bool operator|(const segment&a,const segment&b){return !get_op((a.p2-a.p1)/(b.p2-b.p1));}\n\tfriend bool banana(const segment&a,const segment&b){\n\t\t// 判断是否相交\n\t\tif(min(a.p1.x,a.p2.x)>max(b.p1.x,b.p2.x)||min(b.p1.x,b.p2.x)>max(a.p1.x,a.p2.x)||min(a.p1.y,a.p2.y)>max(b.p1.y,b.p2.y)||min(b.p1.y,b.p2.y)>max(a.p1.y,a.p2.y))return false;\n\t\treturn get_op(((a.p2-a.p1)/(b.p1-a.p1))*((a.p2-a.p1)/(b.p2-a.p1)))<=0&&get_op(((b.p2-b.p1)/(a.p1-b.p1))*((b.p2-b.p1)/(a.p2-b.p1)))<=0;\n\t}\n\tfriend bector focus(const segment&a,const segment&b){\n\t\t// 输入必须保证有交,输出交点\n\t\tbector v=a.p2-a.p1,w=b.p2-b.p1,u=a.p1-b.p1;\n\t\treturn a.p1+v*((w/u)/(v/w));\n\t}\n\tfriend double dis(const segment&a,const bector&b){\n\t\tif(a.p1==a.p2)return ~(b-a.p1);\n\t\tauto v1=a.p2-a.p1,v2=b-a.p1,v3=b-a.p2;\n\t\tif(v1.backis(v2))return ~v2;\n\t\tif(v1.frontis(v3))return ~v3;\n\t\treturn fabs(v1/v2)/~v1;\n\t}\n\tfriend double dis(const segment&a,const segment&b){\n\t\t// 求线段间最短距离\n\t\tif(banana(a,b))return 0;\n\t\treturn min({dis(a,b.p1),dis(a,b.p2),dis(b,a.p1),dis(b,a.p2)});\n\t}\n\tbector project(const bector&a)const{\n\t\t// 求点 a 在当前线段上的投影点坐标\n\t\tif(a==p1||a==p2)return a;\n\t\tauto u=p2-p1,v=a-p1;\n\t\treturn c0s(u,v)*(~v)*u.unit()+p1;\n\t}\n\tbector reflect(const bector&a)const{\n\t\t// 求点 a 在当前线段上的对称点\n\t\treturn 2*project(a)-a;\n\t}\n\tsegment&sort(){if(p2<p1)std::swap(p1,p2);return *this;}\n};\nstruct circle{\n\tbector p;double r;\n\tcircle(const bector&a={0,0},double b=0):p(a),r(b){}\n\tcircle(bector p1,bector p2){\n\t\tp=(p1+p2)/2;\n\t\tr=dis(p1,p2)/2;\n\t}\n\tcircle(bector p1,bector p2,bector p3){\n\t\tp.x=det({*p1,p1.y,1},{*p2,p2.y,1},{*p3,p3.y,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tp.y=-det({*p1,p1.x,1},{*p2,p2.x,1},{*p3,p3.x,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tr=dis(p,p1);\n\t}\n\tfriend istream&operator>>(istream&a,circle &b){return a>>b.p>>b.r;}\n\tfriend ostream&operator<<(ostream&a,const circle &b){return a<<b.p<<' '<<b.r;}\n\tbool check(bector t){\n\t\treturn dis(p,t)-r<=eps;\n\t}\n\tfriend segment focus(const circle &a,const segment&b){\n\t\tauto d=b.project(a.p),u=b.p2-b.p1,e=u/~u;\n\t\tauto t=sqrt(a.r*a.r-sqr(dis(d,a.p)));\n\t\treturn segment{d+e*t,d-e*t}.sort();\n\t}\n\tfriend segment focus(const circle &a,const circle &b){\n\t\tauto d=dis(a.p,b.p),l=acos((sqr(a.r)+sqr(d)-sqr(b.r))/(2*a.r*d)),t=(b.p-a.p).arg();\n\t\treturn segment{a.p+polar(a.r,t+l),a.p+polar(a.r,t-l)}.sort();\n\t}\n\tsegment tangent(const bector&a){\n\t\tauto u=a-p;\n\t\tauto l=acos(r/~u);\n\t\tu=u*r/~u;\n\t\treturn segment{p.rotate(p+u,+l),p.rotate(p+u,-l)}.sort();\n\t}\n};\nstruct points:vector<bector>{\n#define p (*this)\n\tpoints&read(istream&t,int n=-1){\n\t\tif(n==-1)cin>>n;\n\t\tp.resize(n);\n\t\tfor(int i=0;i<n;i++)t>>p[i];\n\t\treturn *this;\n\t}\n\tdouble area()const{\n\t\t// 无需满足多边形是凸的\n\t\tdouble ans=0;\n\t\tfor(int i=1;i<siz(p)-1;i++)ans+=(p[i]-p[0])/(p[i+1]-p[0]);\n\t\treturn ans/2;\n\t}\n\tpoints tobag(){\n\t\tsort(all(p));\n\t\tpoints b1,b2;\n\t\tb1.push_back(p[0]),b1.push_back(p[1]);\n\t\tfor(int i=2;i<siz(p);i++){\n\t\t\tfor(int j=siz(b1)-1;j>=1&&(b1[j]-b1[j-1]).leftis(p[i]-b1[j-1]);j--)\n\t\t\t\tb1.pop_back();\n\t\t\tb1.push_back(p[i]);\n\t\t}\n\t\tb2.push_back(p.back()),b2.push_back(p[siz(p)-2]);\n\t\tfor(int i=siz(p)-3;~i;i--){\n\t\t\tfor(int j=siz(b2)-1;j>=1&&(b2[j]-b2[j-1]).leftis(p[i]-b2[j-1]);j--)\n\t\t\t\tb2.pop_back();\n\t\t\tb2.push_back(p[i]);\n\t\t}\n\t\treverse(all(b2));\n\t\tfor(int i=siz(b1)-2;i;i--)\n\t\t\tb2.push_back(b1[i]);\n\t\tfor(int i=0;i<siz(b2)-1;i++)\n\t\t\tif(b2[i]==b2.back()){\n\t\t\t\tb2.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\t\treturn b2;\n\t}\n\tdouble xzqk(){\n\t\tdouble ans=0;\n\t\tfor(size_t i=0,j=1;i<p.size();i++){\n\t\t\twhile((p[(i+1)%p.size()]-p[i])/(p[j]-p[i])<(p[(i+1)%p.size()]-p[i])/(p[(j+1)%p.size()]-p[i]))(++j)%=p.size();\n\t\t\tans=max({ans,dis(p[i],p[j]),dis(p[(i+1)%p.size()],p[j])});\n\t\t}\n\t\treturn ans;\n\t}\n\tcircle incircle(){\n\t\tassert(p.size()==3);\n\t\tauto u=p[1]-p[0],v=p[2]-p[0];u=u/~u*~v;\n\t\tsegment l1{p[0],p[0]+u+v};\n\t\tu=p[2]-p[1],v=p[0]-p[1];u=u/~u*~v;\n\t\tsegment l2{p[1],p[1]+u+v};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(segment{p[0],p[1]},pp)};\n\t}\n\tcircle outcirce(){\n\t\tassert(p.size()==3);\n\t\tauto u=p[1]-p[0],mid=(p[0]+p[1])/2;\n\t\tsegment l1{mid,mid+u.rot90()};\n\t\tu=p[2]-p[0],mid=(p[0]+p[2])/2;\n\t\tsegment l2{mid,mid+u.rot90()};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(p[0],pp)};\n\t}\n\tint contains(bector t){\n\t\t// 无需满足多边形是凸的\n\t\t// 2表示包含,1表示在边上,0表示在外面\n\t\tbool res=false;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tauto a=p[i]-t,b=p[(i+1)%siz(p)]-t;\n\t\t\tif(!a.leftis(b)&&!a.rightis(b)&&!a.frontis(b))return 1;\n\t\t\tif(a.y>b.y)std::swap(a,b);\n\t\t\tif(a.y<eps&&eps<b.y&&a.leftis(b))res=!res;\n\t\t}\n\t\treturn res?2:0;\n\t}\n#undef p\n};\ncircle mingenshin(points b){\n\tshuffle(all(b),rng);\n\tcircle ans;\n\tfor(int i=0;i<siz(b);i++)if(!ans.check(b[i])){\n\t\tans={b[i],0};\n\t\tfor(int j=0;j<i;j++)if(!ans.check(b[j])){\n\t\t\tans=circle(b[i],b[j]);\n\t\t\tfor(int k=0;k<j;k++)if(!ans.check(b[k])){\n\t\t\t\tans=circle(b[i],b[j],b[k]);\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\npoints a;\nsigned main(){\n//\tfreopen(\".in\",\"r\",stdin);\n//\tfreopen(\".out\",\"w\",stdout);\n\tstd::ios::sync_with_stdio(false);cin.tie(nullptr);\n\tcout<<std::setiosflags(std::ios::fixed)<<std::setprecision(0);\n\tauto b=a.read(cin).tobag();\n\tcout<<siz(b)<<'\\n';\n\tfor(int i=0;;i++)if(b[i%siz(b)].y<=b[(i+1)%siz(b)].y){\n\t\tfor(int j=i%siz(b);j<siz(b);j++)cout<<b[j]<<'\\n';\n\t\tfor(int j=0;j<i%siz(b);j++)cout<<b[j]<<'\\n';\n\t\tbreak;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 6992, "score_of_the_acc": -0.6056, "final_rank": 11 }, { "submission_id": "aoj_CGL_4_A_10853451", "code_snippet": "#include<bits/stdc++.h>\n#define siz(x) int((x).size())\n#define all(x) std::begin(x),std::end(x)\n#define fi first\n#define se second\nusing namespace std;\nusing unt=unsigned;\nusing loli=long long;\nusing lolu=unsigned long long;\nusing pii=pair<int,int>;\nmt19937_64 rng(random_device{}());\nconstexpr double eps=1e-8;\ntemplate<typename any>inline any sqr(const any &x){return x*x;}\ninline int get_op(double x){if(fabs(x)<eps)return 0;return x>0?1:-1;}\ndouble det(array<double,3>a0,array<double,3>a1,array<double,3>a2){\n\tdouble sum=0;\n\tsum+=a0[0]*a1[1]*a2[2];\n\tsum+=a1[0]*a2[1]*a0[2];\n\tsum+=a2[0]*a0[1]*a1[2];\n\tsum-=a0[2]*a1[1]*a2[0];\n\tsum-=a0[1]*a1[0]*a2[2];\n\tsum-=a0[0]*a1[2]*a2[1];\n\treturn sum;\n}\nstruct bector{\n\tdouble x,y;\n\tbool operator<(const bector&t)const{return fabs(x-t.x)<eps?y<t.y:x<t.x;}\n\tbool operator==(const bector&t)const{return fabs(x-t.x)<eps&&fabs(y-t.y)<eps;}\n\tbector(double a=0,double b=0):x(a),y(b){}\n\tdouble operator~()const{return sqrt(x*x+y*y);}\n\tdouble operator*()const{return x*x+y*y;}\n\tfriend istream&operator>>(istream&a,bector&b){return a>>b.x>>b.y;}\n\tfriend ostream&operator<<(ostream&a,const bector&b){return a<<b.x<<' '<<b.y;}\n\tfriend bector operator+(const bector&a,const bector&b){return {a.x+b.x,a.y+b.y};}\n\tbector&operator+=(const bector&t){x+=t.x,y+=t.y;return *this;}\n\tfriend bector operator-(const bector&a,const bector&b){return {a.x-b.x,a.y-b.y};}\n\tbector&operator-=(const bector&t){x-=t.x,y-=t.y;return *this;}\n\tfriend bector operator*(const bector&a,double b){return {a.x*b,a.y*b};}\n\tfriend bector operator*(double b,const bector&a){return {a.x*b,a.y*b};}\n\tbector&operator*=(double t){x*=t,y*=t;return *this;}\n\tfriend bector operator/(const bector&a,double b){return {a.x/b,a.y/b};}\n\tbector&operator/=(double t){x/=t,y/=t;return *this;}\n\tfriend double operator*(const bector&a,const bector&b){return a.x*b.x+a.y*b.y;}\n\tfriend double operator/(const bector&a,const bector&b){return a.x*b.y-a.y*b.x;}\n\tbool frontis(const bector&t)const{auto r=*this*t;return get_op(r)>0;}\n\tbool backis(const bector&t)const{auto r=*this*t;return get_op(r)<0;}\n\tbool leftis(const bector&t)const{auto r=*this/t;return get_op(r)>0;}\n\tbool rightis(const bector&t)const{auto r=*this/t;return get_op(r)<0;}\n\tfriend double dis(const bector&a,const bector&b){return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}\n\tbector rot90()const{return {-y,x};}\n\tdouble arg()const{return atan2(y,x);}\n\tbector rotate(const bector&a,double r){\n\t\tauto u=a-*this;\n\t\treturn *this+bector{u.x*cos(r)-u.y*sin(r),u.x*sin(r)+u.y*cos(r)};\n\t}\n\tfriend double c0s(const bector&x,const bector&y){\n\t\t// 求 cos<x,y>\n\t\treturn x*y/~x/~y;\n\t}\n\tbector unit()const{\n\t\treturn (*this)/~(*this);\n\t}\n\tfriend bool operator&(const bector&a,const bector&b){return !get_op(a*b);}\n\tfriend bool operator|(const bector&a,const bector&b){return !get_op(a/b);}\n};\nbector polar(double p,double r){return {cos(r)*p,sin(r)*p};}\nstruct segment{\n\tbector p1,p2;\n\tsegment(const bector&a={0,0},const bector&b={0,0}):p1(a),p2(b){};\n\tfriend istream&operator>>(istream&a,segment &b){return a>>b.p1>>b.p2;}\n\tfriend ostream&operator<<(ostream&a,const segment&b){return a<<b.p1<<' '<<b.p2;}\n\tfriend bool operator&(const segment&a,const segment&b){return !get_op((a.p2-a.p1)*(b.p2-b.p1));}\n\tfriend bool operator|(const segment&a,const segment&b){return !get_op((a.p2-a.p1)/(b.p2-b.p1));}\n\tfriend bool banana(const segment&a,const segment&b){\n\t\t// 判断是否相交\n\t\tif(min(a.p1.x,a.p2.x)>max(b.p1.x,b.p2.x)||min(b.p1.x,b.p2.x)>max(a.p1.x,a.p2.x)||min(a.p1.y,a.p2.y)>max(b.p1.y,b.p2.y)||min(b.p1.y,b.p2.y)>max(a.p1.y,a.p2.y))return false;\n\t\treturn get_op(((a.p2-a.p1)/(b.p1-a.p1))*((a.p2-a.p1)/(b.p2-a.p1)))<=0&&get_op(((b.p2-b.p1)/(a.p1-b.p1))*((b.p2-b.p1)/(a.p2-b.p1)))<=0;\n\t}\n\tfriend bector focus(const segment&a,const segment&b){\n\t\t// 输入必须保证有交,输出交点\n\t\tbector v=a.p2-a.p1,w=b.p2-b.p1,u=a.p1-b.p1;\n\t\treturn a.p1+v*((w/u)/(v/w));\n\t}\n\tfriend double dis(const segment&a,const bector&b){\n\t\tif(a.p1==a.p2)return ~(b-a.p1);\n\t\tauto v1=a.p2-a.p1,v2=b-a.p1,v3=b-a.p2;\n\t\tif(v1.backis(v2))return ~v2;\n\t\tif(v1.frontis(v3))return ~v3;\n\t\treturn fabs(v1/v2)/~v1;\n\t}\n\tfriend double dis(const segment&a,const segment&b){\n\t\t// 求线段间最短距离\n\t\tif(banana(a,b))return 0;\n\t\treturn min({dis(a,b.p1),dis(a,b.p2),dis(b,a.p1),dis(b,a.p2)});\n\t}\n\tbector project(const bector&a)const{\n\t\t// 求点 a 在当前线段上的投影点坐标\n\t\tif(a==p1||a==p2)return a;\n\t\tauto u=p2-p1,v=a-p1;\n\t\treturn c0s(u,v)*(~v)*u.unit()+p1;\n\t}\n\tbector reflect(const bector&a)const{\n\t\t// 求点 a 在当前线段上的对称点\n\t\treturn 2*project(a)-a;\n\t}\n\tsegment&sort(){if(p2<p1)std::swap(p1,p2);return *this;}\n};\nstruct circle{\n\tbector p;double r;\n\tcircle(const bector&a={0,0},double b=0):p(a),r(b){}\n\tcircle(bector p1,bector p2){\n\t\tp=(p1+p2)/2;\n\t\tr=dis(p1,p2)/2;\n\t}\n\tcircle(bector p1,bector p2,bector p3){\n\t\tp.x=det({*p1,p1.y,1},{*p2,p2.y,1},{*p3,p3.y,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tp.y=-det({*p1,p1.x,1},{*p2,p2.x,1},{*p3,p3.x,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tr=dis(p,p1);\n\t}\n\tfriend istream&operator>>(istream&a,circle &b){return a>>b.p>>b.r;}\n\tfriend ostream&operator<<(ostream&a,const circle &b){return a<<b.p<<' '<<b.r;}\n\tbool check(bector t){\n\t\treturn dis(p,t)-r<=eps;\n\t}\n\tfriend segment focus(const circle &a,const segment&b){\n\t\tauto d=b.project(a.p),u=b.p2-b.p1,e=u/~u;\n\t\tauto t=sqrt(a.r*a.r-sqr(dis(d,a.p)));\n\t\treturn segment{d+e*t,d-e*t}.sort();\n\t}\n\tfriend segment focus(const circle &a,const circle &b){\n\t\tauto d=dis(a.p,b.p),l=acos((sqr(a.r)+sqr(d)-sqr(b.r))/(2*a.r*d)),t=(b.p-a.p).arg();\n\t\treturn segment{a.p+polar(a.r,t+l),a.p+polar(a.r,t-l)}.sort();\n\t}\n\tsegment tangent(const bector&a){\n\t\tauto u=a-p;\n\t\tauto l=acos(r/~u);\n\t\tu=u*r/~u;\n\t\treturn segment{p.rotate(p+u,+l),p.rotate(p+u,-l)}.sort();\n\t}\n};\nstruct points:vector<bector>{\n#define p (*this)\n\tpoints&read(istream&t,int n=-1){\n\t\tif(n==-1)cin>>n;\n\t\tp.resize(n);\n\t\tfor(int i=0;i<n;i++)t>>p[i];\n\t\treturn *this;\n\t}\n\tdouble area()const{\n\t\t// 无需满足多边形是凸的\n\t\tdouble ans=0;\n\t\tfor(int i=1;i<siz(p)-1;i++)ans+=(p[i]-p[0])/(p[i+1]-p[0]);\n\t\treturn ans/2;\n\t}\n\tpoints tobag(){\n\t\tsort(all(p));\n\t\tpoints b1,b2;\n\t\tb1.push_back(p[0]),b1.push_back(p[1]);\n\t\tfor(int i=2;i<siz(p);i++){\n\t\t\tauto u=b1.back()-b1[siz(b1)-2],v=p[i]-b1.back();\n\t\t\twhile(u.leftis(v)){\n\t\t\t\tif(siz(b1)==1)break;\n\t\t\t\tb1.pop_back();\n\t\t\t\tu=b1.back()-b1[siz(b1)-2],v=p[i]-b1.back();\n\t\t\t}\n\t\t\tb1.push_back(p[i]);\n\t\t}\n\t\tb2.push_back(p.back()),b2.push_back(p[siz(p)-2]);\n\t\tfor(int i=siz(p)-3;~i;i--){\n\t\t\tauto u=b2.back()-b2[siz(b2)-2],v=p[i]-b2.back();\n\t\t\twhile(u.leftis(v)){\n\t\t\t\tif(siz(b2)==1)break;\n\t\t\t\tb2.pop_back();\n\t\t\t\tu=b2.back()-b2[siz(b2)-2],v=p[i]-b2.back();\n\t\t\t}\n\t\t\tb2.push_back(p[i]);\n\t\t}\n\t\treverse(all(b2));\n\t\tfor(int i=siz(b1)-2;i;i--)\n\t\t\tb2.push_back(b1[i]);\n\t\treturn b2;\n\t}\n\tdouble xzqk(){\n\t\tdouble ans=0;\n\t\tfor(size_t i=0,j=1;i<p.size();i++){\n\t\t\twhile((p[(i+1)%p.size()]-p[i])/(p[j]-p[i])<(p[(i+1)%p.size()]-p[i])/(p[(j+1)%p.size()]-p[i]))(++j)%=p.size();\n\t\t\tans=max({ans,dis(p[i],p[j]),dis(p[(i+1)%p.size()],p[j])});\n\t\t}\n\t\treturn ans;\n\t}\n\tcircle incircle(){\n\t\tassert(p.size()==3);\n\t\tauto u=p[1]-p[0],v=p[2]-p[0];u=u/~u*~v;\n\t\tsegment l1{p[0],p[0]+u+v};\n\t\tu=p[2]-p[1],v=p[0]-p[1];u=u/~u*~v;\n\t\tsegment l2{p[1],p[1]+u+v};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(segment{p[0],p[1]},pp)};\n\t}\n\tcircle outcirce(){\n\t\tassert(p.size()==3);\n\t\tauto u=p[1]-p[0],mid=(p[0]+p[1])/2;\n\t\tsegment l1{mid,mid+u.rot90()};\n\t\tu=p[2]-p[0],mid=(p[0]+p[2])/2;\n\t\tsegment l2{mid,mid+u.rot90()};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(p[0],pp)};\n\t}\n\tint contains(bector t){\n\t\t// 无需满足多边形是凸的\n\t\t// 2表示包含,1表示在边上,0表示在外面\n\t\tbool res=false;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tauto a=p[i]-t,b=p[(i+1)%siz(p)]-t;\n\t\t\tif(!a.leftis(b)&&!a.rightis(b)&&!a.frontis(b))return 1;\n\t\t\tif(a.y>b.y)std::swap(a,b);\n\t\t\tif(a.y<eps&&eps<b.y&&a.leftis(b))res=!res;\n\t\t}\n\t\treturn res?2:0;\n\t}\n#undef p\n};\ncircle mingenshin(points b){\n\tshuffle(all(b),rng);\n\tcircle ans;\n\tfor(int i=0;i<siz(b);i++)if(!ans.check(b[i])){\n\t\tans={b[i],0};\n\t\tfor(int j=0;j<i;j++)if(!ans.check(b[j])){\n\t\t\tans=circle(b[i],b[j]);\n\t\t\tfor(int k=0;k<j;k++)if(!ans.check(b[k])){\n\t\t\t\tans=circle(b[i],b[j],b[k]);\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\npoints a;\nsigned main(){\n//\tfreopen(\".in\",\"r\",stdin);\n//\tfreopen(\".out\",\"w\",stdout);\n\tstd::ios::sync_with_stdio(false);cin.tie(nullptr);\n\tcout<<std::setiosflags(std::ios::fixed)<<std::setprecision(0);\n\tauto b=a.read(cin).tobag();\n\tcout<<siz(b)<<'\\n';\n\tfor(int i=0;;i++)if(b[i%siz(b)].y<=b[(i+1)%siz(b)].y){\n\t\tfor(int j=i%siz(b);j<siz(b);j++)cout<<b[j]<<'\\n';\n\t\tfor(int j=0;j<i%siz(b);j++)cout<<b[j]<<'\\n';\n\t\tbreak;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 7056, "score_of_the_acc": -0.5279, "final_rank": 8 }, { "submission_id": "aoj_CGL_4_A_10851335", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nconst double eps = 5e-8;\n#define eq(a,b) (fabs((a)-(b))<eps)\nconst double pi = acos(-1);\nclass point {\n public:\n double x,y;\n point(double x=0,double y=0):x(x),y(y){}\n \n point operator+(point b)const{return point(x+b.x,y+b.y);}\n point operator-(point b)const{return point(x-b.x,y-b.y);}\n point operator*(double b)const{return point(x*b,y*b);}\n point operator/(double b)const{return point(x/b,y/b);}\n //重载输入\n friend istream& operator>>(istream &in,point& a){in>>a.x>>a.y;return in;}\n friend ostream& operator<<(ostream &out,point a){out<<a.x<<\" \"<<a.y;return out;}\n double operator*(point b)const{return x*b.x+y*b.y;}//dot product\n double operator^(point b)const{return x*b.y-y*b.x;}//cross product\n bool operator==(point b)const{return eq(x,b.x)&&eq(y,b.y);}\n bool operator<(point b)const{return eq(x,b.x)?y<b.y:x<b.x;}\n double norm(){return x*x+y*y;}\n double abs(){return sqrt(norm());}\n};\ndouble norm(point a){return a.norm();}\ndouble abs(point a){return a.abs();}\n\ntypedef vector<point> poly;\nint contain(const poly &g,point p){//作平行x轴射线,交奇数次在内\n bool in = 0;\n int n = g.size();\n for(int i = 0;i < n;i++){\n point a = g[i] - p,b = g[(i + 1) % n] - p;\n if(fabs(a ^ b) < eps && (a * b) < eps)return 1;//on edge\n if(a.y > b.y)swap(a,b);//a under b\n if(a.y < eps && eps < b.y && (a ^ b) > eps)in ^= 1;//注意端点相交\n }return in ? 2 : 0;//in or out\n}\n\ninline double arg(point p){return atan2(p.y,p.x);}\npoint polar(double r,double theta){return point(r*cos(theta),r*sin(theta));}\n\nstruct seg{\n point p1,p2;\n point base(){return p2 - p1;}\n friend istream& operator>>(istream&in,seg&s){in>>s.p1>>s.p2;return in;}\n};\ntypedef seg line;\n\nbool isort(point a,point b){return eq(a * b,0);}//orthogonal\nbool ispara(point a,point b){return eq(a ^ b,0);}//parallel\n\npoint project(seg s,point p){//点p在直线s上的投影\n point base = s.base();\n double r = (p - s.p1) * base / base.norm();//t / base / base\n return s.p1 + base * r;\n}\npoint reflect(seg s,point p){\n return project(s,p) * 2 - p;//p + 2 * (project(s,p) - p);\n}\ndouble dislp(line l,point p){\n point base = l.base();\n return abs((base ^ p - l.p1) / abs(base));\n}\ndouble dis(seg s,point p){\n if((s.p2 - s.p1) * (p - s.p1) < eps)return abs(p - s.p1);\n if((s.p1 - s.p2) * (p - s.p2) < eps)return abs(p - s.p2);\n return dislp(s,p);\n}\nint ccw(point p0,point p1,point p2){\n point a = p1 - p0,b = p2 - p0;\n if((a ^ b) > eps)return 1;//counter clockwise\n if((a ^ b) < -eps)return -1;//clockwise\n if((a * b) < -eps)return 2;//p2--p0--p1\n if(a.norm() < b.norm())return -2;//p0--p1--p2\n return 0;//p0--p2--p1\n}\npoly andrew(poly s){\n const int n = s.size();\n if(s.size() < 3)return s;\n sort(s.begin(),s.end());\n poly u({s[0],s[1]}),l({s[n - 1],s[n - 2]});\n for(int i = 2;i < n;i++){\n for(int top = u.size();top >= 2 && 1 == ccw(u[top - 2],u[top - 1],s[i]);top--)u.pop_back();\n u.emplace_back(s[i]);\n }\n for(int i = n - 3;i >= 0;i--){\n for(int top = l.size();top >= 2 && 1 == ccw(l[top - 2],l[top - 1],s[i]);top--)l.pop_back();\n l.emplace_back(s[i]);\n }//clockwise\n reverse(l.begin(),l.end());\n for(int i = u.size() - 2;i >= 1;i--)l.emplace_back(u[i]);\n return l;\n}\nbool intersect(point p1,point p2,point p3,point p4){\n return ccw(p1,p2,p3) * ccw(p1,p2,p4) <= 0 && ccw(p3,p4,p1) * ccw(p3,p4,p2) <= 0;\n}\nbool intersect(seg s1,seg s2){\n return intersect(s1.p1,s1.p2,s2.p1,s2.p2);\n}\ndouble dis(seg s1,seg s2){\n if(intersect(s1,s2))return 0.0;\n return min({dis(s1,s2.p1),dis(s1,s2.p2),dis(s2,s1.p1),dis(s2,s1.p2)});\n}\npoint getcross(seg s1,seg s2){\n assert(intersect(s1,s2));\n point base = s2.base();\n double d1 = abs(base ^ (s1.p1 - s2.p1));\n double d2 = abs(base ^ (s1.p2 - s2.p1));\n double t = d1 / (d1 + d2);\n return s1.p1 + s1.base() * t;\n}\n\nclass circle{\npublic:\n point o; double r;\n circle(point o=point(),double r=0):o(o),r(r){}\n friend istream& operator>>(istream&in,circle&c){in>>c.o>>c.r;return in;}\n bool intersect(line l){\n return dislp(l,o) < r + eps;\n }\n bool intersect(circle c){\n vector<double> d = {abs(o - c.o),r,c.r};\n sort(d.begin(),d.end());\n return d[0] + d[1] > d[2] - eps;\n }\n pair<point,point> getcross(line l){\n assert(intersect(l));\n point pr = project(l,o);\n point e = l.base() / abs(l.base());\n double d = sqrt(r*r - (pr - o).norm());\n return {pr - e * d,pr + e * d};\n }\n pair<point,point> getcross(circle c){\n assert(intersect(c));\n double d = abs(o - c.o);\n double t = arg(c.o - o);\n double a = acos((r*r + d*d - c.r*c.r) / (2 * r * d));\n return {o + polar(r,t - a),o + polar(r,t + a)};\n }\n};\n\nint main(){\n int n;cin >> n;vector<point> g(n);\n for(auto& i : g)cin >> i;\n auto ans = andrew(g);cout << ans.size() << endl;\n rotate(ans.begin(),min_element(ans.begin(),ans.end(),[](point a,point b){\n return a.y < b.y || (eq(a.y,b.y) && a.x < b.x);\n }),ans.end());\n for(auto i : ans)cout << i << endl; \n}", "accuracy": 1, "time_ms": 130, "memory_kb": 8360, "score_of_the_acc": -1.2255, "final_rank": 16 } ]
aoj_NTL_1_B_cpp
Power For given integers m and n , compute m n (mod 1,000,000,007). Here, A (mod M ) is the remainder when A is divided by M . Input m n Two integers m and n are given in a line. Output Print m n (mod 1,000,000,007) in a line. Constraints 1 ≤ m ≤ 100 1 ≤ n ≤ 10 9 Sample Input 1 2 3 Sample Output 1 8 Sample Input 2 5 8 Sample Output 2 390625
[ { "submission_id": "aoj_NTL_1_B_10672756", "code_snippet": "// This is free and unencumbered software released into the public domain.\n\n// Anyone is free to copy, modify, publish, use, compile, sell, or\n// distribute this software, either in source code form or as a compiled\n// binary, for any purpose, commercial or non-commercial, and by any\n// means.\n\n// In jurisdictions that recognize copyright laws, the author or authors\n// of this software dedicate any and all copyright interest in the\n// software to the public domain. We make this dedication for the benefit\n// of the public at large and to the detriment of our heirs and\n// successors. We intend this dedication to be an overt act of\n// relinquishment in perpetuity of all present and future rights to this\n// software under copyright law.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n// OTHER DEALINGS IN THE SOFTWARE.\n\n// For more information, please refer to <http://unlicense.org>\n\n/****************/\n/* template.hpp */\n/****************/\n\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <sstream>\n\nusing namespace std;\n\n\ntemplate <typename T> string debug_v_(T x) {\n stringstream ss;\n ss << \"[\";\n bool first = true;\n for (const auto &itr : x) {\n if (!first) {\n ss << \", \";\n }\n ss << itr;\n first = false;\n }\n ss << \"]\";\n return ss.str();\n}\n\n\nstruct Initializer {\n Initializer() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout << fixed << setprecision(15) << boolalpha;\n }\n} initializer;\n\ntemplate <typename T, typename S> bool chmin(T &a, const S &b) {\n return a > b ? a = b, true : false;\n}\n\ntemplate <typename T, typename S> bool chmax(T &a, const S &b) {\n return a < b ? a = b, true : false;\n}\n\ntemplate <typename T> constexpr T inf() {\n return numeric_limits<T>::max() / 2 - 1;\n}\n\n/********************/\n/* math/inverse.hpp */\n/********************/\n\n#include <vector>\n\nclass Inverse {\nprivate:\n int64_t mod;\n vector<int64_t> inv;\n\npublic:\n Inverse() {}\n\n Inverse(int64_t mod, int64_t n = 1000000) : mod(mod), inv(n, 1) {\n for (int i = 2; i < n; ++i) {\n inv[i] = inv[mod % i] * (mod - mod / i) % mod;\n }\n }\n\n int64_t operator()(int64_t a) const {\n if (a < int(inv.size())) {\n return inv[a];\n }\n int64_t b = mod, x = 1, y = 0;\n while (b) {\n int64_t t = a / b;\n swap(a -= t * b, b);\n swap(x -= t * y, y);\n }\n return x < 0 ? x + mod : x;\n }\n};\n\nint64_t inverse(int64_t n, int64_t mod) {\n Inverse inv(mod, 0);\n return inv(n);\n}\n\n/*****************/\n/* math/mint.hpp */\n/*****************/\n\nclass Mint {\nprivate:\n static int64_t mod;\n static Inverse inverse;\n int64_t val;\n\npublic:\n Mint() : val(0) {}\n\n Mint(const int64_t &val) {\n this->val = val % mod;\n if (this->val < 0) {\n this->val += mod;\n }\n }\n\n static void setMod(const int64_t &m) {\n mod = m;\n inverse = Inverse(m);\n }\n\n Mint operator-() const { return Mint(val ? mod - val : 0); }\n\n Mint &operator+=(const Mint &m) {\n val += m.val;\n if (val >= mod) {\n val -= mod;\n }\n return *this;\n }\n\n Mint operator+(const Mint &m) const {\n int64_t ret = val + m.val;\n if (ret >= mod) {\n ret -= mod;\n }\n return ret;\n }\n\n Mint &operator-=(const Mint &m) {\n val -= m.val;\n if (val < 0) {\n val += mod;\n }\n return *this;\n }\n\n Mint operator-(const Mint &m) const {\n int64_t ret = val - m.val;\n if (ret < 0) {\n ret += mod;\n }\n return ret;\n }\n\n Mint &operator*=(const Mint &m) {\n val *= m.val;\n val %= mod;\n return *this;\n }\n\n Mint operator*(const Mint &m) const {\n return val * m.val % mod;\n }\n\n Mint &operator/=(const Mint &m) {\n val *= inverse(m.val);\n val %= mod;\n return *this;\n }\n\n Mint operator/(const Mint &m) const {\n return val * inverse(m.val) % mod;\n }\n\n bool operator==(const Mint &m) const { return val == m.val; }\n\n Mint &operator++() { return *this += 1; }\n\n Mint &operator--() { return *this -= 1; }\n\n explicit operator char() const { return val; }\n\n explicit operator int() const { return val; }\n\n explicit operator int64_t() const { return val; }\n\n static Mint identity() { return 1; }\n\n friend istream& operator>>(istream& is, Mint& m) {\n is >> m.val;\n return is;\n }\n};\n\nint64_t Mint::mod = 998244353;\nInverse Mint::inverse(998244353);\n\nstd::ostream &operator<<(std::ostream &os, Mint a) {\n os << int64_t(a);\n return os;\n}\n\nMint operator+(const int &n, const Mint &m) { return m + n; }\n\nMint operator-(const int &n, const Mint &m) { return -m + n; }\n\nMint operator*(const int &n, const Mint &m) { return m * n; }\n\nMint operator/(const int &n, const Mint &m) { return Mint(n) / m; }\n\nMint operator+(const int64_t &n, const Mint &m) { return m + n; }\n\nMint operator-(const int64_t &n, const Mint &m) { return -m + n; }\n\nMint operator*(const int64_t &n, const Mint &m) { return m * n; }\n\nMint operator/(const int64_t &n, const Mint &m) { return Mint(n) / m; }\n/****************/\n/* math/pow.hpp */\n/****************/\n\ntemplate<typename, typename = std::void_t<>> struct has_identity : std::false_type {};\ntemplate<typename T> struct has_identity<T, std::void_t<decltype(std::declval<T>().identity())>> : std::true_type {};\ntemplate<typename, typename = std::void_t<>> struct has_identity_with_size : std::false_type {};\ntemplate<typename T> struct has_identity_with_size<T, std::void_t<decltype(std::declval<T>().identity(0))>> : std::true_type {};\n\ntemplate <typename T> T identity_element(const T &m) {\n if constexpr (has_identity<T>::value) {\n return T::identity();\n } else if constexpr (has_identity_with_size<T>::value) {\n return T::identity(m.size());\n } else {\n return 1;\n }\n}\n\ntemplate <typename T> T pow(const T &m, int64_t n) {\n if (n == 0) {\n return identity_element<T>(m);\n } else if (n < 0) {\n return identity_element<T>(m) / pow(m, -n);\n }\n T mm = pow(m, n / 2);\n mm *= mm;\n if (n % 2) {\n mm *= m;\n }\n return mm;\n}\n\n/************/\n/* main.cpp */\n/************/\n\nint main() {\n Mint::setMod(1000000007);\n Mint m;\n int n;\n cin >> m >> n;\n cout << pow(m, n) << endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 18808, "score_of_the_acc": -1, "final_rank": 1 }, { "submission_id": "aoj_NTL_1_B_10367430", "code_snippet": "/*****************************************************************//*!\nFunction\n2つの整数 m, nについて、m^nを1,000,000,007で割った余りを求めてください。\n\n入力\n2つの整数 m, n が1つの空白区切りで1行に与えられます。\n\n出力\nm^nを1,000,000,007で割った余りを1行に出力します。\n*//*****************************************************************/\n\n#define _USE_MATH_DEFINES // for C++\n#include<iostream>\n#include<vector>\n#include<sstream>\n#include<cmath>\n#include<iomanip>\n#include<stdexcept>\n#include<map>\n#include<cctype>\n\nint main(void)\n{\n int den = 1000000007; //割る数(denominator(分母))\n long long m, n; //m: 底、 n: 指数 \n std::cin >> m >> n;\n\n /******アルゴリズム******//*!\n 1. m^(count) > den を満たすまで冪乗を行う。(count <= n)\n 2. m^(count) % den = d とすると、{(m^(count))^b} % den = d^bとなる。 (b: (b*count) < n を満たす最大のb)\n また、冪乗されていない残りの指数を s とする。\n 式で表すと、(n = count * b + s)、(m^n = (d^b) * (m^s))となる。\n これを計算するためのd, b, sを求める。\n 3. 数値のオーバーフロー防止のため、パワー関数ではなくfor文で乗算し、逐次 den による余剰を求める。\n */\n\n int count = 0; //現在何乗されたか\n long long ans = 1; //冪乗の途中経過\n bool flag = false; //m^nがdenより大きいか否か\n\n //lより乗算が大きくなるまで回す\n do\n {\n count++;\n ans *= m;\n if (ans > den)\n {\n flag = true;\n break;\n }\n } while (count < n);\n\n //denよりansが大きくなった場合、その余りを求めて計算効率を上げる(小さい場合ansがそのまま余りになる)\n int d; //ans%denを格納\n int b; //dの冪(べき)\n int s; //残りの冪\n if (flag)\n {\n d = ans % den;\n b = n / count;\n s = n % count;\n\n ans = d;\n\n //std::cout << \"count:\" << count << \"\\td:\" << d << \"\\t\" << \"b:\" << b << \"\\t\" << \"s:\" << s << \"\\n\";\n\n //アルゴリズム 3.の計算\n for (int i = 1; i < b; i++)\n {\n ans *= d;\n ans %= den;\n }\n\n for (int j = 0; j < s; j++)\n {\n ans *= m;\n ans %= den;\n }\n }\n\n std::cout << ans%den << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 640, "memory_kb": 3440, "score_of_the_acc": -1.0047, "final_rank": 3 }, { "submission_id": "aoj_NTL_1_B_10367335", "code_snippet": "#define _USE_MATH_DEFINES // for C++\n#include<iostream>\n#include<vector>\n#include<sstream>\n#include<cmath>\n#include<iomanip>\n#include<stdexcept>\n#include<map>\n#include<cctype>\n\nint main(void)\n{\n long long m, n; //m: 底、 n: 指数 \n std::cin >> m >> n;\n\n int count = 0; //現在何乗されたか\n long ans = 1; //乗算の途中結果\n int l = 1000000007; //割る数\n bool flag = false; //左項がlより大きいか否か\n\n //lより乗算が大きくなるまで回す\n do\n {\n count++;\n ans *= m;\n if (ans > l)\n {\n flag = true;\n break;\n }\n } while (count < n);\n\n //lよりansが大きくなった場合、その余りを求めて計算効率を上げる(小さい場合ansがそのまま余りになる)\n int d; //ans%lを格納\n int b; //dの冪(べき)\n int s; //残りの冪\n if (flag)\n {\n d = ans % l;\n b = n / count;\n s = n % count;\n\n ans = d;\n for (int i = 1; i < b; i++)\n {\n ans *= d;\n ans %= l;\n }\n\n\n for (int j = 0; j < s; j++)\n {\n ans *= m;\n ans %= l;\n }\n }\n\n std::cout << ans%l << std::endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 640, "memory_kb": 3368, "score_of_the_acc": -1, "final_rank": 1 } ]
aoj_CGL_4_B_cpp
Diameter of a Convex Polygon Find the diameter of a convex polygon g . In other words, find a pair of points that have maximum distance between them. Input n x 1 y 1 x 2 y 2 : x n y n The first integer n is the number of points in g . In the following lines, the coordinate of the i -th point p i is given by two real numbers x i and y i . The coordinates of points are given in the order of counter-clockwise visit of them. Each value is a real number with at most 6 digits after the decimal point. Output Print the diameter of g in a line. The output values should be in a decimal fraction with an error less than 0.000001. Constraints 3 ≤ n ≤ 80000 -100 ≤ x i , y i ≤ 100 No point in the g will occur more than once. Sample Input 1 3 0.0 0.0 4.0 0.0 2.0 2.0 Sample Output 1 4.00 Sample Input 2 4 0.0 0.0 1.0 0.0 1.0 1.0 0.0 1.0 Sample Output 2 1.414213562373
[ { "submission_id": "aoj_CGL_4_B_11065558", "code_snippet": "#include <bits/stdc++.h>\n\n#define debug(a) cout << #a << \" = \" << (a) << ' '\n\nusing namespace std;\n\n#define db long double\n// #define db long long\n\nconst db EPS = 1e-9;\n\n#define cross(p1, p2, p3) (p2 - p1).det(p3 - p1)\n#define crossop(p1, p2, p3) sign(cross(p1, p2, p3))\n\nint sign(db a) { return a < -EPS ? -1 : a > EPS; }\nint cmp(db a, db b) { return sign(a - b); }\n\nstruct P {\n db x, y;\n P() {}\n P(db _x, db _y) : x(_x), y(_y) {}\n\n P operator +(P p) { return {x + p.x, y + p.y}; }\n P operator -(P p) { return {x - p.x, y - p.y}; }\n P operator *(db d) { return {x * d, y * d}; }\n P operator /(db d) { return {x / d, y / d}; }\n\n bool operator < (P p) const {\n int c = cmp(x, p.x);\n if (c) return c == -1;\n return cmp(y, p.y) == -1;\n }\n\n bool operator == (P p) const {\n return ! cmp(x, p.x) && ! cmp(y, p.y);\n }\n\n db abs2() { return x * x + y * y; }\n db abs() { return sqrt(x * x + y * y); }\n db distTo(P p) { return (*this - p).abs(); }\n db alpha() { return atan2(y, x); }\n db dot(P p) { return x * p.x + y * p.y; }\n db det(P p) { return x * p.y - y * p.x; }\n\n int quadY() const { return sign(x) == 1 || (sign(x) == 0 && sign(y) >= 0); }\n int quadX() const { return sign(y) == 1 || (sign(y) == 0 && sign(x) >= 0); }\n\n P rot90() { return P(-y, x); }\n P rot(db alpha) { return { x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha)}; }\n P unit() { return *this / abs(); }\n};\n\nostream & operator << (ostream &out, const P &A) {\n out << A.x << \" \" << A.y;\n return out;\n}\n\n// ------------------------------------\n// 线段 / 线段\n\nbool checkPll(P p1, P p2, P q1, P q2) {\n // 判断平行\n db a1 = cross(q1, q2, p1), a2 = - cross(q1, q2, p2);\n return sign(a1 + a2) == 0;\n}\n\nP isLL(P p1, P p2, P q1, P q2) {\n // 返回交点\n db a1 = cross(q1, q2, p1), a2 = - cross(q1, q2, p2);\n return (p1 * a2 + p2 * a1) / (a1 + a2);\n}\n\nbool intersect(db l1, db r1, db l2, db r2) {\n if (l1 > r1) swap(l1, r1);\n if (l2 > r2) swap(l2, r2);\n return cmp(r1, l2) >= 0 && cmp(r2, l1) >= 0;\n}\n\nbool isSS(P p1, P p2, P q1, P q2) {\n // 线段是否 不严格 相交\n // 1 : SS\n // 0 : unSS\n return intersect(p1.x, p2.x, q1.x, q2.x) &&\n intersect(p1.y, p2.y, q1.y, q2.y) && \n crossop(p1, p2, q1) * crossop(p1, p2, q2) <= 0 && \n crossop(q1, q2, p1) * crossop(q1, q2, p2) <= 0;\n}\n\nbool isSS_strict(P p1, P p2, P q1, P q2) {\n // 线段是否 严格 相交\n // 1 : SS\n // 0 : unSS\n return crossop(p1, p2, q1) * crossop(p1, p2, q2) < 0 && \n crossop(q1, q2, p1) * crossop(q1, q2, p2) < 0;\n}\n\nbool isMiddle(db a, db m, db b) {\n return sign(a - m) == 0 || sign(b - m) == 0 || ((a < m) != (b < m));\n}\n\nbool isMiddle(P a, P m, P b) {\n return isMiddle(a.x, m.x, b.x) && isMiddle(a.y, m.y, b.y);\n}\n\nbool onSeg(P p1, P p2, P q) {\n // 是否在线段上 不严格\n return crossop(p1, p2, q) == 0 && isMiddle(p1, q, p2);\n}\n\nbool onSeg_strict(P p1, P p2, P q) {\n // 是否在线段上 严格\n return crossop(p1, p2, q) == 0 && \n sign((q - p1).dot(p1 - p2)) * \n sign((q - p2).dot(p1 - p2)) < 0;\n}\n\nP proj(P p1, P p2, P q) {\n // 求 q 到 p1 p2 的投影\n P dir = p2 - p1;\n return p1 + (p2 - p1) * (dir.dot(q - p1) / (dir).abs2());\n}\n\nP reflect(P p1, P p2, P q) {\n // 求 q 到 p1 p2 的反射点\n return proj(p1, p2, q) * 2 - q;\n}\n\ndb nearest(P p1, P p2, P q) {\n // 求 q 到 p1 p2(线段)的最近点\n if (p1 == p2) return p1.distTo(q);\n P h = proj(p1, p2, q);\n if (isMiddle(p1, h, p2))\n return q.distTo(h);\n return min(p1.distTo(q), p2.distTo(q));\n}\n\ndb disSS(P p1, P p2, P q1, P q2) {\n // 求线段 p1p2 和 线段 q1q2 的距离\n if (isSS(p1, p2, q1, q2)) return 0;\n db val1 = min(nearest(p1, p2, q1), nearest(p1, p2, q2));\n db val2 = min(nearest(q1, q2, p1), nearest(q1, q2, p2));\n return min(val1, val2);\n}\n\ndb rad(P p1, P p2) {\n // 求向量 p1 p2 的角度(逆时针为正,顺时针为负,范围 (- pi, pi])\n return atan2l(p1.det(p2), p1.dot(p2));\n}\n\n// ---------------------------------------------\n// 多边形\n\ndb area(vector < P > ps) {\n // 求多边形面积(逆时针顺序给出点 -> 面积为正)\n db ret = 0; if (ps.size() == 0) return 0;\n for (int i = 0; i < (int)ps.size(); ++ i) {\n ret += ps[i].det(ps[(i + 1) % ps.size()]);\n }\n return ret / 2;\n}\n\nint contain(vector < P > ps, P p) {\n // 0 : outside\n // 1 : on_seg\n // 2 : inside\n\n // ps 是多边形,判断 p 在多边形 内部 / 线段上 / 外部\n int n = ps.size(), ret = 0;\n for (int i = 0; i < n; ++ i) {\n P u = ps[i], v = ps[(i + 1) % n];\n if (onSeg(u, v, p)) return 1;\n if (cmp(u.y, v.y) <= 0) swap(u, v);\n if (cmp(p.y, u.y) > 0 || cmp(p.y, v.y) <= 0)\n continue;\n ret ^= crossop(p, u, v) > 0;\n }\n return ret * 2;\n}\n\nvector < P > convexHull(vector < P > ps) {\n // 求凸包\n int n = ps.size();\n if (n <= 1) return ps;\n sort(ps.begin(), ps.end());\n vector < P > qs(n * 2);\n int k = 0;\n for (int i = 0; i < n; qs[k ++] = ps[i ++])\n while (k > 1 && crossop(qs[k - 2], qs[k - 1], ps[i]) <= 0)\n -- k;\n for (int i = n - 2, t = k; i >= 0; qs[k ++] = ps[i --])\n while (k > t && crossop(qs[k - 2], qs[k - 1], ps[i]) <= 0)\n -- k;\n qs.resize(k - 1);\n return qs;\n}\n\n\nvector < P > convexHullNonStrict(vector < P > ps) {\n // 求凸包(边界上的点也在凸包内)\n sort(ps.begin(), ps.end());\n ps.erase(unique(ps.begin(), ps.end()), ps.end());\n int n = ps.size();\n if (n <= 1) return ps;\n vector < P > qs(n * 2);\n int k = 0;\n for (int i = 0; i < n; qs[k ++] = ps[i ++])\n while (k > 1 && crossop(qs[k - 2], qs[k - 1], ps[i]) < 0)\n -- k;\n for (int i = n - 2, t = k; i >= 0; qs[k ++] = ps[i --])\n while (k > t && crossop(qs[k - 2], qs[k - 1], ps[i]) < 0)\n -- k;\n qs.resize(k - 1);\n return qs;\n}\n\nbool checkConvexHull(vector < P > p) {\n // 判断 p 多边形是否是凸包\n // 注意:不可通过再跑一次凸包判断点数是否相同\n // 因为点数相同 不能代表是凸包的连接方式\n int n = p.size();\n for (int i = 0; i < n; ++ i) {\n int pre = i - 1;\n int suf = i + 1;\n if (pre == -1) pre = n - 1;\n if (suf == n) suf = 0;\n if (crossop(p[i], p[suf], p[pre]) < 0)\n return 0;\n }\n return 1;\n}\n\ndb convexDiameter(vector < P > ps) {\n int n = ps.size();\n if (n <= 1) return 0;\n int is = 0, js = 0;\n for (int k = 1; k < n; ++ k)\n is = ps[k] < ps[is] ? k : is,\n js = ps[js] < ps[k] ? k : js;\n int i = is, j = js;\n db ret = ps[i].distTo(ps[j]);\n do {\n if ((ps[(i + 1) % n] - ps[i]).det(ps[(j + 1) % n] - ps[j]) >= 0)\n (++ j) %= n;\n else (++ i) %= n;\n ret = max(ret, ps[i].distTo(ps[j]));\n } while (i != is || j != js);\n return ret;\n}\n\nbool polar_cmpX(P a, P b) {\n // 极角排序 X 轴正半轴(包含)开始逆时针转\n if (a.quadX() != b.quadX()) \n return a.quadX() > b.quadX();\n return sign(a.det(b)) > 0;\n}\n\nbool polar_cmpY(P a, P b) {\n // 极角排序 Y 轴负半轴(不包含)开始逆时针转\n if (a.quadY() != b.quadY()) \n return a.quadY() > b.quadY();\n return sign(a.det(b)) > 0;\n}\n\nvector < P > MincowskySum(vector < P > p, vector < P > q) {\n // p, q 为两个凸包(顺序同方向),求这两个凸包的 闵可夫斯基和\n // 得保证 p, q 的第一个点 是排序后的\n // 即 尽可能在 convexHull 后再传入 p, q \n if (p.size() == 0) return q;\n if (q.size() == 0) return p;\n vector < P > qs; qs.push_back(p[0] + q[0]);\n P p0 = p[0], q0 = q[0];\n for (int i = 0; i + 1 < (int)p.size(); ++ i)\n p[i] = p[i + 1] - p[i];\n for (int i = 0; i + 1 < (int)q.size(); ++ i)\n q[i] = q[i + 1] - q[i];\n p[p.size() - 1] = p0 - p[p.size() - 1];\n q[q.size() - 1] = q0 - q[q.size() - 1];\n qs.resize(p.size() + q.size() + 1);\n merge(p.begin(), p.end(), q.begin(), q.end(), qs.begin() + 1, polar_cmpY);\n for (int i = 1; i < (int)qs.size(); ++ i)\n qs[i] = qs[i] + qs[i - 1];\n qs.pop_back();\n return qs;\n}\n\nvoid solve() {\n int n; cin >> n;\n vector < P > p(n);\n for (int i = 0; i < n; ++ i) {\n cin >> p[i].x >> p[i].y;\n }\n cout << fixed << setprecision(10) << convexDiameter(p) << '\\n';\n}\n\n\nint main() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n int t = 1;\n while (t --) {\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8104, "score_of_the_acc": -0.489, "final_rank": 8 }, { "submission_id": "aoj_CGL_4_B_11065238", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define pii pair<int, int>\n#define pll pair<ll, ll>\n#define vi vector<int>\n#define vl vector<ll>\n#define ov4(a, b, c, d, name, ...) name\n#define rep3(i, a, b, c) for(ll i = (a); i < (b); i += (c))\n#define rep2(i, a, b) rep3(i, a, b, 1)\n#define rep1(i, n) rep2(i, 0, n)\n#define rep0(n) rep1(aaaaa, n)\n#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)\n#define per(i, a, b) for(ll i = (a)-1; i >= (b); i--)\n#define fore(e, v) for(auto&& e : v)\n#define all(a) begin(a), end(a)\n#define si(a) (int)(size(a))\n#define lb(v, x) (lower_bound(all(v), x) - begin(v))\n#define eb emplace_back\n\ntemplate<typename T, typename S> bool chmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; }\ntemplate<typename T, typename S> bool chmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; }\n\nconst int INF = 1e9 + 100;\nconst ll INFL = 3e18 + 100;\n\n#define i128 __int128_t\n\nstruct _ {\n _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }\n} __;\n\ntemplate<class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n typedef Point P;\n T x, y;\n explicit Point(T x=0, T y=0) : x(x), y(y) {}\n bool operator<(P p) const { return tie(x, y) < tie(p.x, p.y); }\n bool operator==(P p) const { return tie(x, y) == tie(p.x, p.y); }\n P operator-(P p) const { return P(x - p.x, y - p.y); }\n P operator*(T d) const { return P(x * d, y * d); }\n P operator/(T d) const { return P(x / d, y / d); }\n T dot(P p) const { return x * p.x + y * p.y; }\n T cross(P p) const { return x * p.y - y * p.x; }\n T cross(P a, P b) const { return (a - *this).cross(b - *this); }\n T dist2() const { return x*x + y*y; }\n double dist() const { return sqrt((double)dist2()); }\n P perp() const { return P(-y, x); }\n};\n\ntemplate<class P>\nP lineProj(P a, P b, P p, bool refl=false) {\n P v = b - a;\n return p - v.perp() * (1 + refl) * v.cross(p - a) / v.dist2();\n}\n\ntemplate<class P>\nbool onSegment(P s, P e, P p) {\n return p.cross(s, e) == 0 and (s - p).dot(e - p) <= 0;\n}\n\ntemplate<class P>\nvector<P> segInter(P a, P b, P c, P d) {\n auto oa = c.cross(d, a), ob = c.cross(d, b),\n oc = a.cross(b, c), od = a.cross(b, d);\n if (sgn(oa) * sgn(ob) < 0 and sgn(oc) * sgn(od) < 0) {\n return {(a * ob - b * oa) / (ob - oa)};\n }\n set<P> s;\n if (onSegment(c, d, a)) s.insert(a);\n if (onSegment(c, d, b)) s.insert(b);\n if (onSegment(a, b, c)) s.insert(c);\n if (onSegment(a, b, d)) s.insert(d);\n return {all(s)};\n}\n\ntemplate<class P>\ndouble segDist(P s, P e, P p) {\n if (s == e) return (p - s).dist();\n auto d = (s - e).dist2(), t = min(d, max(.0, (p - s).dot(e - s)));\n return ((p - s) * d - (e - s) * t).dist() / d;\n}\n\ntemplate<class P>\ndouble segDist(P s1, P e1, P s2, P e2) {\n if (!segInter(s1, e1, s2, e2).empty()) return 0;\n auto a = min(segDist(s1, e1, s2), segDist(s1, e1, e2));\n auto b = min(segDist(s2, e2, s1), segDist(s2, e2, e1));\n return min(a, b);\n}\n\ntemplate<class P>\npair<int, P> lineInter(P s1, P e1, P s2, P e2) {\n auto d = (e1 - s2).cross(e2 - s2);\n if(d == 0) {\n return {-(s1.cross(e1, s2) == 0), P(0, 0)};\n }\n auto p = s2.cross(e1, e2), q = s2.cross(e2, s1);\n return {1, (s1 * p + e1 * q) / d};\n}\n\ntemplate<class T>\nT polygonArea2(vector<Point<T>> &v) {\n T a = v.back().cross(v[0]);\n rep(i, si(v) - 1) a += v[i].cross(v[i + 1]);\n return a;\n}\n\n// speed star library\ntypedef Point<long double> P;\nvector<P> convex_hull(vector<P> pts) {\n int n = si(pts), k = 0;\n if (n <= 2) return pts;\n sort(all(pts));\n vector<P> ch(2 * n);\n for(int i = 0; i < n; ch[k++] = pts[i++]) {\n while(k >= 2 and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) <= -1.0e-14) --k;\n }\n for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = pts[i--]) {\n while(k >= t and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) <= -1.0e-14) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n\narray<P, 2> hullDiameter(vector<P> S) {\n int n = si(S), j = n < 2 ? 0 : 1;\n pair<long double, array<P, 2>> res({0, {S[0], S[0]}});\n rep(i, j) {\n for (;; j = (j + 1) % n) {\n res = max(res, {(S[i] - S[j]).dist2(), {S[i], S[j]}});\n if ((S[(j + 1) % n] - S[j]).cross(S[i + 1] - S[i]) >= 1.0e-14) break;\n }\n }\n return res.second;\n}\n#undef P\n\ntemplate<class P>\nbool inPolygon(vector<P> &p, P a, bool strict = true) {\n int cnt = 0, n = si(p);\n rep(i, n) {\n P q = p[(i + 1) % n];\n if (onSegment(p[i], q, a)) return !strict;\n cnt ^= ((a.y < p[i].y) - (a.y < q.y)) * a.cross(p[i], q) > 0;\n }\n return cnt;\n}\n\nusing P = Point<long double>;\n\nint main() {\n int n;\n cin >> n;\n vector<P> v;\n rep(i, n) {\n double x, y;\n cin >> x >> y;\n v.push_back(P(x, y));\n }\n\n auto cv = convex_hull(v);\n auto res = hullDiameter(cv);\n cout << setprecision(15);\n cout << (res[0] - res[1]).dist() << endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 13780, "score_of_the_acc": -0.7193, "final_rank": 13 }, { "submission_id": "aoj_CGL_4_B_11047886", "code_snippet": "// --- Start of include: ./../../akakoi_lib/template/template.cpp ---\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i,n) for(ll i=0;i<(ll)(n);++i)\nbool chmin(auto& a, auto b) {return a>b?a=b,1:0;}\nbool chmax(auto& a, auto b) {return a<b?a=b,1:0;}\n// int main() {\n// ios::sync_with_stdio(false);\n// cin.tie(0);\n// }\n// --- End of include: ./../../akakoi_lib/template/template.cpp ---\n// --- Start of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n/// @brief 幾何ライブラリ\nnamespace Geometry {\n using Real = long double;\n const Real EPS = 1e-9;\n\n bool almostEqual(Real a, Real b) { return abs(a - b) < EPS; }\n bool lessThan(Real a, Real b) { return a < b && !almostEqual(a, b); }\n bool greaterThan(Real a, Real b) { return a > b && !almostEqual(a, b); }\n bool lessThanOrEqual(Real a, Real b) { return a < b || almostEqual(a, b); }\n bool greaterThanOrEqual(Real a, Real b) { return a > b || almostEqual(a, b); }\n\n /// @brief 2次元平面上の位置ベクトル\n struct Point {\n Real x, y;\n Point() = default;\n Point(Real x, Real y) : x(x), y(y) {}\n\n Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); }\n Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); }\n Point operator*(Real k) const { return Point(x * k, y * k); }\n Point operator/(Real k) const { return Point(x / k, y / k); }\n\n /// @brief p との内積を返す\n Real dot(const Point& p) const { return x * p.x + y * p.y; }\n\n /// @brief p との外積を返す\n Real cross(const Point& p) const { return x * p.y - y * p.x; }\n\n /// @brief p1 と p2 を端点とするベクトルとの外積を返す\n Real cross(const Point& p1, const Point& p2) const { return (p1.x - x) * (p2.y - y) - (p1.y - y) * (p2.x - x); }\n\n /// @brief 2乗ノルムを返す\n Real norm() const { return x * x + y * y; }\n\n /// @brief ユークリッドノルムを返す\n Real abs() const { return sqrt(norm()); }\n\n /// @brief 偏角を返す\n Real arg() const { return atan2(y, x); }\n\n bool operator==(const Point& p) const { return almostEqual(x, p.x) && almostEqual(y, p.y); }\n friend istream& operator>>(istream& is, Point& p) { return is >> p.x >> p.y; }\n };\n\n /// @brief 直線\n struct Line {\n Point a, b;\n Line() = default;\n Line(const Point& _a, const Point& _b) : a(_a), b(_b) {}\n\n /// @brief 直線 Ax+By=C を定義する\n Line(const Real& A, const Real& B, const Real& C) {\n if (almostEqual(A, 0)) {\n assert(!almostEqual(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (almostEqual(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (almostEqual(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n bool operator==(const Line& l) const { return a == l.a && b == l.b; }\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n };\n\n /// @brief 線分\n struct Segment : Line {\n Segment() = default;\n using Line::Line;\n };\n\n /// @brief 円\n struct Circle {\n Point center; ///< 中心\n Real r; ///< 半径\n\n Circle() = default;\n Circle(Real x, Real y, Real r) : center(x, y), r(r) {}\n Circle(Point _center, Real r) : center(_center), r(r) {}\n\n bool operator==(const Circle& C) const { return center == C.center && r == C.r; }\n friend istream& operator>>(istream& is, Circle& C) { return is >> C.center >> C.r; }\n };\n\n //-----------------------------------------------------------\n\n /// @brief 3点の進行方向\n enum Orientation {\n COUNTER_CLOCKWISE, ///< 反時計回り\n CLOCKWISE, ///< 時計回り\n ONLINE_BACK,\n ONLINE_FRONT,\n ON_SEGMENT\n };\n\n /// @brief 3点 p0, p1, p2 の進行方向を返す\n Orientation ccw(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0;\n Point b = p2 - p0;\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) return COUNTER_CLOCKWISE;\n if (lessThan(cross_product, 0)) return CLOCKWISE;\n if (lessThan(a.dot(b), 0)) return ONLINE_BACK;\n if (lessThan(a.norm(), b.norm())) return ONLINE_FRONT;\n return ON_SEGMENT;\n }\n\n string orientationToString(Orientation o) {\n switch (o) {\n case COUNTER_CLOCKWISE:\n return \"COUNTER_CLOCKWISE\";\n case CLOCKWISE:\n return \"CLOCKWISE\";\n case ONLINE_BACK:\n return \"ONLINE_BACK\";\n case ONLINE_FRONT:\n return \"ONLINE_FRONT\";\n case ON_SEGMENT:\n return \"ON_SEGMENT\";\n default:\n return \"UNKNOWN\";\n }\n }\n\n /// @brief ベクトル p の直線 p1, p2 への正射影ベクトルを返す\n Point projection(const Point& p1, const Point& p2, const Point& p) {\n Point base = p2 - p1;\n Real r = (p - p1).dot(base) / base.norm();\n return p1 + base * r;\n }\n\n /// @brief ベクトル p の直線 l への正射影ベクトルを返す\n Point projection(const Line& l, const Point& p) {\n Point base = l.b - l.a;\n Real r = (p - l.a).dot(base) / base.norm();\n return l.a + base * r;\n }\n\n /// @brief ベクトル p の直線 p1, p2 に対する鏡像ベクトルを返す\n Point reflection(const Point& p1, const Point& p2, const Point& p) {\n Point proj = projection(p1, p2, p);\n return proj * 2 - p;\n }\n\n /// @brief ベクトル p の直線 l に対する鏡像ベクトルを返す\n Point reflection(const Line& l, const Point& p) {\n Point proj = projection(l, p);\n return proj * 2 - p;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 直線の平行判定\n bool isParallel(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線の直交判定\n bool isOrthogonal(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分の平行判定\n bool isParallel(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分の直交判定\n bool isOrthogonal(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 直線と線分の平行判定\n bool isParallel(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線と線分の直交判定\n bool isOrthogonal(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分と直線の平行判定\n bool isParallel(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分と直線の直交判定\n bool isOrthogonal(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 点が直線上にあるか判定\n bool isPointOnLine(const Point& p, const Line& l) { return almostEqual((l.b - l.a).cross(p - l.a), 0.0); }\n\n /// @brief 点が線分上にあるか判定\n bool isPointOnSegment(const Point& p, const Segment& s) {\n return lessThanOrEqual(min(s.a.x, s.b.x), p.x) &&\n lessThanOrEqual(p.x, max(s.a.x, s.b.x)) &&\n lessThanOrEqual(min(s.a.y, s.b.y), p.y) &&\n lessThanOrEqual(p.y, max(s.a.y, s.b.y)) &&\n almostEqual((s.b - s.a).cross(p - s.a), 0.0);\n }\n\n /// @brief 直線の交差判定\n bool isIntersecting(const Segment& s1, const Segment& s2) {\n Point p0p1 = s1.b - s1.a, p0p2 = s2.a - s1.a, p0p3 = s2.b - s1.a, p2p3 = s2.b - s2.a, p2p0 = s1.a - s2.a, p2p1 = s1.b - s2.a;\n Real d1 = p0p1.cross(p0p2), d2 = p0p1.cross(p0p3), d3 = p2p3.cross(p2p0), d4 = p2p3.cross(p2p1);\n if (lessThan(d1 * d2, 0) && lessThan(d3 * d4, 0)) return true;\n if (almostEqual(d1, 0.0) && isPointOnSegment(s2.a, s1)) return true;\n if (almostEqual(d2, 0.0) && isPointOnSegment(s2.b, s1)) return true;\n if (almostEqual(d3, 0.0) && isPointOnSegment(s1.a, s2)) return true;\n if (almostEqual(d4, 0.0) && isPointOnSegment(s1.b, s2)) return true;\n return false;\n }\n\n /// @brief 線分の交点を返す\n Point getIntersection(const Segment& s1, const Segment& s2) {\n assert(isIntersecting(s1, s2));\n auto cross = [](Point p, Point q) { return p.x * q.y - p.y * q.x; };\n Point base = s2.b - s2.a;\n Real d1 = abs(cross(base, s1.a - s2.a));\n Real d2 = abs(cross(base, s1.b - s2.a));\n Real t = d1 / (d1 + d2);\n return s1.a + (s1.b - s1.a) * t;\n }\n\n /// @brief 点と線分の距離を返す\n Real distancePointToSegment(const Point& p, const Segment& s) {\n Point proj = projection(s.a, s.b, p);\n if (isPointOnSegment(proj, s))\n return (p - proj).abs();\n else\n return min((p - s.a).abs(), (p - s.b).abs());\n }\n\n /// @brief 線分と線分の距離を返す\n Real distanceSegmentToSegment(const Segment& s1, const Segment& s2) {\n if (isIntersecting(s1, s2)) return 0.0;\n return min({distancePointToSegment(s1.a, s2),\n distancePointToSegment(s1.b, s2),\n distancePointToSegment(s2.a, s1),\n distancePointToSegment(s2.b, s1)});\n }\n\n //-----------------------------------------------------------\n\n /// @brief 多角形の面積を返す\n Real getPolygonArea(const vector<Point>& points) {\n int n = points.size();\n Real area = 0.0;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n area += points[i].x * points[j].y;\n area -= points[i].y * points[j].x;\n }\n return abs(area) / 2.0;\n }\n\n /// @brief 多角形が凸か判定\n bool isConvex(const vector<Point>& points) {\n int n = points.size();\n bool has_positive = false, has_negative = false;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n int k = (i + 2) % n;\n Point a = points[j] - points[i];\n Point b = points[k] - points[j];\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) has_positive = true;\n if (lessThan(cross_product, 0)) has_negative = true;\n }\n return !(has_positive && has_negative);\n }\n\n /// @brief 点が凸多角形の辺上に存在するか判定\n bool isPointOnPolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n Segment s(a, b);\n if (isPointOnSegment(p, s)) return true;\n }\n return false;\n }\n\n /// @brief 点が多角形の内部に存在するか判定(辺上は含まない)\n bool isPointInsidePolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n bool inPolygon = false;\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n if (greaterThan(a.y, b.y)) swap(a, b);\n if (lessThanOrEqual(a.y, p.y) && lessThan(p.y, b.y) && greaterThan((b - a).cross(p - a), 0)) inPolygon = !inPolygon;\n }\n return inPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 凸包を求める\n vector<Point> convexHull(vector<Point>& points, bool include_collinear = false) {\n int n = points.size();\n if (n <= 1) return points;\n sort(points.begin(), points.end(), [](const Point& l, const Point& r) -> bool {\n if (almostEqual(l.y, r.y)) return lessThan(l.x, r.x);\n return lessThan(l.y, r.y);\n });\n if (n == 2) return points;\n vector<Point> upper = {points[0], points[1]}, lower = {points[0], points[1]};\n for (int i = 2; i < n; i++) {\n while (upper.size() >= 2 && ccw(upper.end()[-2], upper.end()[-1], points[i]) != CLOCKWISE) {\n if (ccw(upper.end()[-2], upper.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n upper.pop_back();\n }\n upper.push_back(points[i]);\n while (lower.size() >= 2 && ccw(lower.end()[-2], lower.end()[-1], points[i]) != COUNTER_CLOCKWISE) {\n if (ccw(lower.end()[-2], lower.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n lower.pop_back();\n }\n lower.push_back(points[i]);\n }\n reverse(upper.begin(), upper.end());\n upper.pop_back();\n lower.pop_back();\n lower.insert(lower.end(), upper.begin(), upper.end());\n return lower;\n }\n\n /// @brief 凸包の直径を求める\n Real convexHullDiameter(const vector<Point>& hull) {\n int n = hull.size();\n if (n == 1) return 0;\n int k = 1;\n Real max_dist = 0;\n for (int i = 0; i < n; i++) {\n while (true) {\n int j = (k + 1) % n;\n Point dist1 = hull[i] - hull[j], dist2 = hull[i] - hull[k];\n max_dist = max(max_dist, dist1.abs());\n max_dist = max(max_dist, dist2.abs());\n if (dist1.abs() > dist2.abs())\n k = j;\n else\n break;\n }\n Point dist = hull[i] - hull[k];\n max_dist = max(max_dist, dist.abs());\n }\n return max_dist;\n }\n\n /// @brief 凸包を直線で切断して左側を返す\n vector<Point> cutPolygon(const vector<Point>& g, const Line& l) {\n auto isLeft = [](const Point& p1, const Point& p2, const Point& p) -> bool { return (p2 - p1).cross(p - p1) > 0; };\n vector<Point> newPolygon;\n int n = g.size();\n for (int i = 0; i < n; i++) {\n const Point& cur = g[i];\n const Point& next = g[(i + 1) % n];\n if (isLeft(l.a, l.b, cur)) newPolygon.push_back(cur);\n if ((isLeft(l.a, l.b, cur) && !isLeft(l.a, l.b, next)) || (!isLeft(l.a, l.b, cur) && isLeft(l.a, l.b, next))) {\n Real A1 = (next - cur).cross(l.a - cur);\n Real A2 = (next - cur).cross(l.b - cur);\n Point intersection = l.a + (l.b - l.a) * (A1 / (A1 - A2));\n newPolygon.push_back(intersection);\n }\n }\n return newPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 最近点対の距離を求める\n /// @note points は x 座標でソートされている必要がある\n Real closestPair(vector<Point>& points, int l, int r) {\n if (r - l <= 1) return numeric_limits<Real>::max();\n int mid = (l + r) >> 1;\n Real x = points[mid].x;\n Real d = min(closestPair(points, l, mid), closestPair(points, mid, r));\n auto iti = points.begin(), itl = iti + l, itm = iti + mid, itr = iti + r;\n inplace_merge(itl, itm, itr, [](const Point& lhs, const Point& rhs) -> bool {\n return lessThan(lhs.y, rhs.y);\n });\n vector<Point> nearLine;\n for (int i = l; i < r; i++) {\n if (greaterThanOrEqual(fabs(points[i].x - x), d)) continue;\n int sz = nearLine.size();\n for (int j = sz - 1; j >= 0; j--) {\n Point dv = points[i] - nearLine[j];\n if (dv.y >= d) break;\n d = min(d, dv.abs());\n }\n nearLine.push_back(points[i]);\n }\n return d;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 線分の交差数を数える\n int countIntersections(vector<Segment> segments) {\n struct Event {\n Real x;\n int type; // 0:horizontal start,1:vertical,2:horizontal end\n Real y1, y2;\n Event(Real x, int type, Real y1, Real y2) : x(x), type(type), y1(y1), y2(y2) {}\n bool operator<(const Event& other) const {\n if (x == other.x) return type < other.type;\n return x < other.x;\n }\n };\n vector<Event> events;\n sort(segments.begin(), segments.end(), [](const Segment& lhs, const Segment& rhs) -> bool {\n return lessThan(min(lhs.a.x, lhs.b.x), min(rhs.a.x, rhs.b.x));\n });\n for (const auto& seg : segments) {\n if (seg.a.y == seg.b.y) {\n // Horizontal segment\n Real y = seg.a.y;\n Real x1 = min(seg.a.x, seg.b.x);\n Real x2 = max(seg.a.x, seg.b.x);\n events.emplace_back(x1, 0, y, y);\n events.emplace_back(x2, 2, y, y);\n } else {\n // Vertical segment\n Real x = seg.a.x;\n Real y1 = min(seg.a.y, seg.b.y);\n Real y2 = max(seg.a.y, seg.b.y);\n events.emplace_back(x, 1, y1, y2);\n }\n }\n sort(events.begin(), events.end());\n set<Real> activeSegments;\n int intersectionCount = 0;\n for (const auto& event : events) {\n if (event.type == 0) {\n // Add horizontal segment to active set\n activeSegments.insert(event.y1);\n } else if (event.type == 2) {\n // Remove horizontal segment from active set\n activeSegments.erase(event.y1);\n } else if (event.type == 1) {\n // Count intersections with vertical segment\n auto lower = activeSegments.lower_bound(event.y1);\n auto upper = activeSegments.upper_bound(event.y2);\n intersectionCount += distance(lower, upper);\n }\n }\n return intersectionCount;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 2つの円の交点の個数を返す\n int countCirclesIntersection(const Circle& c1, const Circle& c2) {\n Real d =\n sqrt((c1.center.x - c2.center.x) * (c1.center.x - c2.center.x) +\n (c1.center.y - c2.center.y) * (c1.center.y - c2.center.y));\n Real r1 = c1.r, r2 = c2.r;\n if (greaterThan(d, r1 + r2))\n return 4;\n else if (almostEqual(d, r1 + r2))\n return 3;\n else if (greaterThan(d, fabs(r1 - r2)))\n return 2;\n else if (almostEqual(d, fabs(r1 - r2)))\n return 1;\n else\n return 0;\n }\n\n /// @brief 内接円を求める\n Circle getInCircle(const Point& A, const Point& B, const Point& C) {\n Real a = (B - C).abs();\n Real b = (A - C).abs();\n Real c = (A - B).abs();\n Real s = (a + b + c) / 2;\n Real area = sqrt(s * (s - a) * (s - b) * (s - c));\n Real r = area / s;\n Real cx = (a * A.x + b * B.x + c * C.x) / (a + b + c);\n Real cy = (a * A.y + b * B.y + c * C.y) / (a + b + c);\n return Circle{Point(cx, cy), r};\n }\n\n /// @brief 外接円を求める\n Circle getCircumCircle(const Point& A, const Point& B, const Point& C) {\n Real D = 2 * (A.x * (B.y - C.y) + B.x * (C.y - A.y) + C.x * (A.y - B.y));\n Real Ux = ((A.x * A.x + A.y * A.y) * (B.y - C.y) + (B.x * B.x + B.y * B.y) * (C.y - A.y) + (C.x * C.x + C.y * C.y) * (A.y - B.y)) / D;\n Real Uy = ((A.x * A.x + A.y * A.y) * (C.x - B.x) + (B.x * B.x + B.y * B.y) * (A.x - C.x) + (C.x * C.x + C.y * C.y) * (B.x - A.x)) / D;\n Point center(Ux, Uy);\n Real radius = (center - A).abs();\n return Circle{center, radius};\n }\n\n /// @brief 円と直線の交点を求める\n vector<Point> getCircleLineIntersection(const Circle& c, Point p1, Point p2) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real dx = p2.x - p1.x;\n Real dy = p2.y - p1.y;\n Real a = dx * dx + dy * dy;\n Real b = 2 * (dx * (p1.x - cx) + dy * (p1.y - cy));\n Real c_const = (p1.x - cx) * (p1.x - cx) + (p1.y - cy) * (p1.y - cy) - r * r;\n Real discriminant = b * b - 4 * a * c_const;\n vector<Point> intersections;\n if (almostEqual(discriminant, 0)) {\n Real t = -b / (2 * a);\n Real ix = p1.x + t * dx;\n Real iy = p1.y + t * dy;\n intersections.emplace_back(ix, iy);\n intersections.emplace_back(ix, iy);\n } else if (discriminant > 0) {\n Real sqrt_discriminant = sqrt(discriminant);\n Real t1 = (-b + sqrt_discriminant) / (2 * a);\n Real t2 = (-b - sqrt_discriminant) / (2 * a);\n Real ix1 = p1.x + t1 * dx;\n Real iy1 = p1.y + t1 * dy;\n Real ix2 = p1.x + t2 * dx;\n Real iy2 = p1.y + t2 * dy;\n intersections.emplace_back(ix1, iy1);\n intersections.emplace_back(ix2, iy2);\n }\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 2つの円の交点を求める\n vector<Point> getCirclesIntersect(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real d = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n if (d > r1 + r2 || d < abs(r1 - r2)) return {}; // No intersection\n Real a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);\n Real h = sqrt(r1 * r1 - a * a);\n Real x0 = x1 + a * (x2 - x1) / d;\n Real y0 = y1 + a * (y2 - y1) / d;\n Real rx = -(y2 - y1) * (h / d);\n Real ry = (x2 - x1) * (h / d);\n Point p1(x0 + rx, y0 + ry);\n Point p2(x0 - rx, y0 - ry);\n vector<Point> intersections;\n intersections.push_back(p1);\n intersections.push_back(p2);\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 点から引ける円の接線の接点を求める\n vector<Point> getTangentLinesFromPoint(const Circle& c, const Point& p) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real px = p.x, py = p.y;\n Real dx = px - cx;\n Real dy = py - cy;\n Real d = (p - c.center).abs();\n if (lessThan(d, r))\n return {}; // No tangents if the point is inside the circle\n else if (almostEqual(d, r))\n return {p};\n Real a = r * r / d;\n Real h = sqrt(r * r - a * a);\n Real cx1 = cx + a * dx / d;\n Real cy1 = cy + a * dy / d;\n vector<Point> tangents;\n tangents.emplace_back(cx1 + h * dy / d, cy1 - h * dx / d);\n tangents.emplace_back(cx1 - h * dy / d, cy1 + h * dx / d);\n if (almostEqual(tangents[0].x, tangents[1].x)) {\n if (greaterThan(tangents[0].y, tangents[1].y)) swap(tangents[0], tangents[1]);\n } else if (greaterThan(tangents[0].x, tangents[1].x)) {\n swap(tangents[0], tangents[1]);\n }\n return tangents;\n }\n\n /// @brief 2つの円の共通接線を求める\n vector<Segment> getCommonTangentsLine(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real dx = x2 - x1;\n Real dy = y2 - y1;\n Real d = sqrt(dx * dx + dy * dy);\n vector<Segment> tangents;\n // Coincident circles(infinite tangents)\n if (almostEqual(d, 0) && almostEqual(r1, r2)) return tangents;\n // External tangents\n if (greaterThanOrEqual(d, r1 + r2)) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 + r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 + r2 * cos(a + sign * theta);\n Real cy2 = y2 + r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, r1 + r2)) break;\n }\n }\n // Internal tangents\n if (greaterThanOrEqual(d, fabs(r1 - r2))) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 - r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 - r2 * cos(a + sign * theta);\n Real cy2 = y2 - r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, fabs(r1 - r2))) break;\n }\n }\n sort(tangents.begin(), tangents.end(), [&](const Segment& s1, const Segment& s2) {\n if (almostEqual(s1.a.x, s2.a.x))\n return lessThan(s1.a.y, s2.a.y);\n else\n return lessThan(s1.a.x, s2.a.x);\n });\n return tangents;\n }\n}\n// --- End of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n\nusing namespace Geometry;\n\nvoid solve() {\n int n; cin >> n;\n vector<Point> P(n);\n rep(i, n) {\n Real x, y; cin >> x >> y;\n P[i] = {x, y};\n }\n P = convexHull(P);\n cout << convexHullDiameter(P) << endl;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout << fixed << setprecision(10);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6188, "score_of_the_acc": -0.2446, "final_rank": 3 }, { "submission_id": "aoj_CGL_4_B_11019141", "code_snippet": "// https://tubo28.me/compprog/algorithm/ より.\n\n#include <bits/stdc++.h>\n// #define int int64_t\n\n#define FOR(i, a, b) for (int i = (a); i < int(b); ++i)\n#define RFOR(i, a, b) for (int i = (b)-1; i >= int(a); --i)\n#define rep(i, n) FOR(i, 0, n)\n#define rep1(i, n) FOR(i, 1, int(n) + 1)\n#define rrep(i, n) RFOR(i, 0, n)\n#define rrep1(i, n) RFOR(i, 1, int(n) + 1)\n#define all(c) begin(c), end(c)\nnamespace io {\n#ifdef LOCAL\n#define dump(...) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #__VA_ARGS__ << \" = \"; \\\n io::print_to(os, \", \", \"\\n\", __VA_ARGS__); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dump_(cntnr) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #cntnr << \" = [\"; \\\n io::print_to_(os, \", \", \"]\\n\", all(cntnr)); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dumpf(fmt, ...) \\\n do { \\\n const int N = 4096; \\\n auto b = new char[N]; \\\n int l = snprintf(b, N, \"%d:\\t\", __LINE__); \\\n snprintf(b + l, N - l, fmt, ##__VA_ARGS__); \\\n std::cerr << io::highlight(b) << std::endl; \\\n delete[] b; \\\n } while (0)\n#else\n#define dump(...)\n#define dump_(...)\n#define dumpf(...)\n#endif\nstd::string highlight(std::string s) {\n#ifdef _MSC_VER\n return s;\n#else\n return \"\\033[33m\" + s + \"\\033[0m\";\n#endif\n}\ntemplate <typename T>\nvoid print_to(std::ostream &os, std::string, std::string tail, const T &first) {\n os << first << tail;\n}\ntemplate <typename F, typename... R>\nvoid print_to(std::ostream &os, std::string del, std::string tail, const F &first,\n const R &... rest) {\n os << first << del;\n print_to(os, del, tail, rest...);\n}\ntemplate <typename I>\nvoid print_to_(std::ostream &os, std::string del, std::string tail, I begin, I end) {\n for (I it = begin; it != end;) {\n os << *it;\n os << (++it != end ? del : tail);\n }\n}\ntemplate <typename F, typename... R>\nvoid println(const F &first, const R &... rest) {\n print_to(std::cout, \"\\n\", \"\\n\", first, rest...);\n}\ntemplate <typename F, typename... R>\nvoid print(const F &first, const R &... rest) {\n print_to(std::cout, \" \", \"\\n\", first, rest...);\n}\ntemplate <typename I>\nvoid println_(I begin, I end) {\n print_to_(std::cout, \"\\n\", \"\\n\", begin, end);\n}\ntemplate <typename I>\nvoid print_(I begin, I end) {\n print_to_(std::cout, \" \", \"\\n\", begin, end);\n}\ntemplate <typename C>\nvoid println_(const C &cntnr) {\n println_(std::begin(cntnr), std::end(cntnr));\n}\ntemplate <typename C>\nvoid print_(const C &cntnr) {\n print_(std::begin(cntnr), std::end(cntnr));\n}\nint _ = (\n#ifndef LOCAL\n std::cin.tie(nullptr), std::ios::sync_with_stdio(false),\n#endif\n std::cout.precision(10), std::cout.setf(std::ios::fixed));\n}\nusing io::print;\nusing io::println;\nusing io::println_;\nusing io::print_;\ntemplate <typename T>\nusing vec = std::vector<T>;\nusing vi = vec<int>;\nusing vvi = vec<vi>;\nusing pii = std::pair<int, int>;\nusing ll = long long;\nusing ld = long double;\nusing namespace std;\n// const int MOD = 1000000007;\n\n\n\n\nusing ld = long double;\nusing P = std::complex<ld>;\nusing G = std::vector<P>;\nconst ld pi = std::acos(-1);\nconst ld eps = 1e-10;\nconst ld inf = 1e12;\n\nld cross(const P &a, const P &b) { return a.real() * b.imag() - a.imag() * b.real(); }\nld dot(const P &a, const P &b) { return a.real() * b.real() + a.imag() * b.imag(); }\n\n/*\n CCW\n\n -- BEHIND -- [a -- ON -- b] --- FRONT --\n\n CW\n */\nenum CCW_RESULT { CCW = +1, CW = -1, BEHIND = +2, FRONT = -2, ON = 0 };\nint ccw(P a, P b, P c) {\n b -= a;\n c -= a;\n if (cross(b, c) > eps) return CCW; // counter clockwise\n if (cross(b, c) < -eps) return CW; // clockwise\n if (dot(b, c) < 0) return BEHIND; // c--a--b on line\n if (norm(b) < norm(c)) return FRONT; // a--b--c on line\n return ON;\n}\n\nnamespace std {\nbool operator<(const P &a, const P &b) {\n return std::abs(real(a) - real(b)) > eps ? real(a) < real(b) : imag(a) < imag(b);\n}\n}\n\nstruct L : public std::vector<P> {\n L(const P &a = P(), const P &b = P()) : std::vector<P>(2) {\n begin()[0] = a;\n begin()[1] = b;\n }\n\n // Ax + By + C = 0\n L(ld A, ld B, ld C) {\n if (std::abs(A) < eps && std::abs(B) < eps) {\n abort();\n } else if (std::abs(A) < eps) {\n *this = L(P(0, -C / B), P(1, -C / B));\n } else if (std::abs(B) < eps) {\n *this = L(P(-C / A, 0), P(-C / A, 1));\n } else {\n *this = L(P(0, -C / B), P(-C / A, 0));\n }\n }\n};\n\nstruct C {\n P p;\n ld r;\n C(const P &p = 0, ld r = 0) : p(p), r(r) {}\n};\n\n\n\n\nbool intersectLL(const L &l, const L &m) {\n return std::abs(cross(l[1] - l[0], m[1] - m[0])) > eps || // non-parallel\n std::abs(cross(l[1] - l[0], m[0] - l[0])) < eps; // same line\n}\nbool intersectLS(const L &l, const L &s) {\n return cross(l[1] - l[0], s[0] - l[0]) * // s[0] is left of l\n cross(l[1] - l[0], s[1] - l[0]) <\n eps; // s[1] is right of l\n}\nbool intersectLP(const L &l, const P &p) { return std::abs(cross(l[1] - p, l[0] - p)) < eps; }\nbool intersectSS(const L &s, const L &t) {\n return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 &&\n ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0;\n}\nbool intersectSP(const L &s, const P &p) {\n return std::abs(s[0] - p) + std::abs(s[1] - p) - std::abs(s[1] - s[0]) <\n eps; // triangle inequality\n}\n\nP projection(const L &l, const P &p) {\n ld t = dot(p - l[0], l[0] - l[1]) / norm(l[0] - l[1]);\n return l[0] + t * (l[0] - l[1]);\n}\nP reflection(const L &l, const P &p) { return p + (ld)2 * (projection(l, p) - p); }\nld distanceLP(const L &l, const P &p) { return std::abs(p - projection(l, p)); }\nld distanceLL(const L &l, const L &m) { return intersectLL(l, m) ? 0 : distanceLP(l, m[0]); }\nld distanceLS(const L &l, const L &s) {\n if (intersectLS(l, s)) return 0;\n return std::min(distanceLP(l, s[0]), distanceLP(l, s[1]));\n}\nld distanceSP(const L &s, const P &p) {\n const P r = projection(s, p);\n if (intersectSP(s, r)) return std::abs(r - p);\n return std::min(std::abs(s[0] - p), std::abs(s[1] - p));\n}\nld distanceSS(const L &s, const L &t) {\n if (intersectSS(s, t)) return 0;\n return std::min(std::min(distanceSP(s, t[0]), distanceSP(s, t[1])),\n std::min(distanceSP(t, s[0]), distanceSP(t, s[1])));\n}\nP crosspointLL(const L &l, const L &m) {\n ld A = cross(l[1] - l[0], m[1] - m[0]);\n ld B = cross(l[1] - l[0], l[1] - m[0]);\n if (std::abs(A) < eps && std::abs(B) < eps) return m[0]; // same line\n if (std::abs(A) < eps) assert(false); // !!!PRECONDITION NOT SATISFIED!!!\n return m[0] + B / A * (m[1] - m[0]);\n}\n\n\n// 符号付二倍面積 abs(area2(G pol))/2.0 で求められる.\n// polは頂点反時計回りで渡す\nld area2(const G& pol) {\n ld s = 0;\n int n = pol.size();\n for (int i = 0; i < n; ++i) s += cross(pol[i], pol[(i + 1) % n]);\n return s;\n}\n\n\n// 凸包\n// == CWを != CCWに置換すると 退化した角を除く.\nG andrewScan(G ps) {\n int N = ps.size(), k = 0;\n std::sort(ps.begin(), ps.end());\n G res(N * 2);\n for (int i = 0; i < N; i++) {\n while (k >= 2 && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n int t = k + 1;\n for (int i = N - 2; i >= 0; i--) {\n while (k >= t && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n res.resize(k - 1);\n return res;\n}\n\n\n// 凸多角形の直径\n#define curr(P, i) P[i]\n#define next(P, i) P[(i + 1) % P.size()]\n#define diff(P, i) (next(P, i) - curr(P, i))\nld convex_diameter(const G &pt) {\n const int n = pt.size();\n int is = 0, js = 0;\n for (int i = 1; i < n; ++i) {\n if (imag(pt[i]) > imag(pt[is])) is = i;\n if (imag(pt[i]) < imag(pt[js])) js = i;\n }\n ld maxd = norm(pt[is] - pt[js]);\n int i, maxi, j, maxj;\n i = maxi = is;\n j = maxj = js;\n do {\n if (cross(diff(pt, i), diff(pt, j)) >= 0)\n j = (j + 1) % n;\n else\n i = (i + 1) % n;\n if (norm(pt[i] - pt[j]) > maxd) {\n maxd = norm(pt[i] - pt[j]);\n maxi = i;\n maxj = j;\n }\n } while (i != is || j != js);\n return maxd; /* farthest pair is (maxi, maxj). */\n}\n//凸多角形の直径終.\n\n\n// P:点 point x: .real() y: .imag()\n// L:直線 lineF\n// S:線分 section\n// G:多角形 vector<P>\n\nsigned main() {\n int N;\n cin >> N;\n G g(N);\n rep(i, N){\n ld xi, yi;\n cin >> xi >> yi;\n g[i] = P(xi, yi);\n }\n cout << fixed << setprecision(15) << sqrt(convex_diameter(g)) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 5548, "score_of_the_acc": -0.3853, "final_rank": 6 }, { "submission_id": "aoj_CGL_4_B_11008035", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n#define print(s) cout << s;\n#define println(s) cout << s << endl;\n#define eps (1e-10)\n#define bigint 2000000000\n#define biglong 2000000000000000000L\n#define rep(i,s,n) for(int i=s;i<(int)(n);i++)\n#define sz(x) (int)(x).size()\n#define all(x) (x).begin(), (x).end()//いるらしい\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n\n\n//ーーー入出力\ntemplate<typename T>\nT next() {T a; cin >> a; return a;}\n\ntemplate<typename T>\nvector<T> arrayInput(int n) {\n vector<T> a(n);\n for (int i = 0; i < n; i++) cin >> a[i];\n return a;\n}\n\ntemplate<typename T>\nvector<vector<T>> arrayInput(int h, int w) {\n vector<vector<T>> a(h, vector<T>(w));\n for (int i = 0; i < h; i++)\n for (int j = 0; j < w; j++)\n cin >> a[i][j];\n return a;\n}\n\n\ntemplate <typename T>\nvoid arrayPrint(const vector<T>& vec, bool blank = true) {\n int n = vec.size();\n for (int i = 0; i < n; ++i) {\n cout << vec[i];\n if (blank && i != n - 1) cout << ' ';\n }\n cout << '\\n';\n}\nvoid arrayPrint(const vector<string>& vec, bool blank = false) {\n int n = vec.size();\n for (int i = 0; i < n; ++i) {\n cout << vec[i];\n if (blank && i != n - 1) cout << ' ';\n }\n cout << '\\n';\n}\nvoid arrayPrint(const vector<bool>& vec, bool blank = true) {\n int n = vec.size();\n for (int i = 0; i < n; ++i) {\n cout << (vec[i] ? 'T' : 'F');\n if (blank && i != n - 1) cout << ' ';\n }\n cout << '\\n';\n}\n\ntemplate <typename T>\nvoid arrayPrint(const vector<vector<T>>& mat, bool blank = true) {\n for (const auto& row : mat) {\n arrayPrint(row, blank);\n }\n}\nvoid arrayPrint(const vector<vector<string>>& mat, bool blank = false) {\n for (const auto& row : mat) {\n arrayPrint(row, blank);\n }\n}\n\nvoid arrayPrint(const vector<vector<bool>>& mat, bool blank = true) {\n for (const auto& row : mat) {\n arrayPrint(row, blank);\n }\n}\n\ntemplate <class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n typedef Point P;\n T x, y;\n explicit Point(T x=0, T y=0) : x(x), y(y) {}\n bool operator<(P p) const { return tie(x,y) < tie(p.x,p.y); }\n bool operator==(P p) const { return tie(x,y)==tie(p.x,p.y); }\n P operator+(P p) const { return P(x+p.x, y+p.y); }\n P operator-(P p) const { return P(x-p.x, y-p.y); }\n P operator*(T d) const { return P(x*d, y*d); }\n P operator/(T d) const { return P(x/d, y/d); }\n T dot(P p) const { return x*p.x + y*p.y; }\n T cross(P p) const { return x*p.y - y*p.x; }\n T cross(P a, P b) const { return (a-*this).cross(b-*this); }\n T dist2() const { return x*x + y*y; }\n double dist() const { return sqrt((double)dist2()); }\n // angle to x-axis in interval [-pi, pi]\n double angle() const { return atan2(y, x); }\n P unit() const { return *this/dist(); } // makes dist()=1\n P perp() const { return P(-y, x); } // rotates +90 degrees\n P normal() const { return perp().unit(); }\n // returns point rotated 'a' radians ccw around the origin\n P rotate(double a) const {\n return P(x*cos(a)-y*sin(a),x*sin(a)+y*cos(a)); }\n friend ostream& operator<<(ostream& os, P p) {\n return os << \"(\" << p.x << \",\" << p.y << \")\"; }\n};\n\ntemplate<class P>\npair<int, P> lineInter(P s1, P e1, P s2, P e2) {\n auto d = (e1 - s1).cross(e2 - s2);\n if (d == 0) // if parallel\n return {-(s1.cross(e1, s2) == 0), P(0, 0)};\n auto p = s2.cross(e1, e2), q = s2.cross(e2, s1);\n return {1, (s1 * p + e1 * q) / d};\n}\ntypedef Point<ld> P;\nvector<P> convexHull(vector<P> pts) {\n if (sz(pts) <= 1) return pts;\n sort(all(pts));\n vector<P> h(sz(pts)+1);\n int s = 0, t = 0;\n for (int it = 2; it--; s = --t, reverse(all(pts)))\n for (P p : pts) {\n while (t >= s + 2 && h[t-2].cross(h[t-1], p) <= 0) t--;\n h[t++] = p;\n }\n return {h.begin(), h.begin() + t - (t == 2 && h[0] == h[1])};\n}\n\ntypedef Point<ld> P;\narray<P, 2> hullDiameter(vector<P> S) {\n int n = sz(S), j = n < 2 ? 0 : 1;\n pair<ld, array<P, 2>> res({0.0, {S[0], S[0]}});\n rep(i,0,j)\n for (;; j = (j + 1) % n) {\n res = max(res, {(S[i] - S[j]).dist2(), {S[i], S[j]}});\n if ((S[(j + 1) % n] - S[j]).cross(S[i + 1] - S[i]) >= 0)\n break;\n }\n return res.second;\n}\n\nint main() {\n cin.tie(0) -> sync_with_stdio(0);\n cin.exceptions(cin.failbit);\n cout << fixed << setprecision(10) << endl;\n int n; cin >> n;\n vector<Point<ld>> points(n);\n for (int i = 0; i < n; ++i) {\n ld x, y;\n cin >> x >> y;\n points[i] = Point<ld>(x, y);\n }\n auto conv = convexHull(points);\n auto dia = hullDiameter(conv);\n cout << (dia[1]-dia[0]).dist() << endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 10696, "score_of_the_acc": -0.5942, "final_rank": 9 }, { "submission_id": "aoj_CGL_4_B_10996392", "code_snippet": "#include <bits/stdc++.h>\n\ntypedef long long int64;\n\ntypedef long double db;\n \nconst db eps=1e-8L,pi=std::acos(-1.0L);\n\nstruct point{\n \n db x,y;\n \n point():x(),y(){}\n point(db _x,db _y):x(_x),y(_y){}\n\n db &operator[](int p){return p?y:x;}\n const db &operator[](int p)const{return p?y:x;}\n\n friend point operator+(const point &a,const point &b){return point(a.x+b.x,a.y+b.y);}\n friend point operator-(const point &a,const point &b){return point(a.x-b.x,a.y-b.y);}\n friend point operator*(const point &a,const db &b){return point(a.x*b,a.y*b);}\n friend point operator*(const db &b,const point &a){return point(a.x*b,a.y*b);}\n friend point operator/(const point &a,const db &b){return point(a.x/b,a.y/b);}\n \n friend db operator*(const point &a,const point &b){return a.x*b.x+a.y*b.y;}\n friend db operator%(const point &a,const point &b){return a.x*b.y-a.y*b.x;}\n \n friend bool operator==(const point &a,const point &b){return std::abs(a.x-b.x)<=eps&&std::abs(a.y-b.y)<=eps;}\n friend bool operator!=(const point &a,const point &b){return std::abs(a.x-b.x)>eps||std::abs(a.y-b.y)>eps;}\n \n db mod2()const{return x*x+y*y;}\n db mod()const{return std::sqrt(x*x+y*y);}\n db dis2(const point &a)const{return (*this-a).mod2();}\n db dis(const point &a)const{return (*this-a).mod();}\n point unit()const{return *this/mod();}\n\n db ang()const{return std::atan2(y,x);}\n db ang(const point &a)const{return std::atan2(*this%a,*this*a);}\n point norm()const{return point(-y,x);}\n point rot(const db &th)const{db s=std::sin(th),c=std::cos(th);return point(x*c-y*s,x*s+y*c);}\n\n // 象限,x 轴正半轴开始逆时针旋转1 2 -2 -1,左闭右开,原点返回 0\n int quad()const{\n if (std::abs(x)<=eps&&std::abs(y)<=eps) return 0;\n if (x>eps&&y>=-eps) return 1;\n if (x<=eps&&y>eps) return 2;\n if (x<-eps&&y<=eps) return -2;\n if (x>=-eps&&y<-eps) return -1;\n assert(0);\n }\n\n};\n\n// 保证只有 o 半边有点的极角排序\nstruct HalfPolarAngleCmp{\n point o;\n HalfPolarAngleCmp(const point &_o):o(_o){}\n bool operator()(const point &a,const point &b)const{\n db t=(a-o)%(b-o);\n return std::abs(t)<=eps?(a-o).mod2()<(b-o).mod2():t>eps;\n }\n};\n\n// 完整的极角排序,行为应与使用 std::atan2 相同\nstruct PolarAngleCmp{\n point o;\n PolarAngleCmp(const point &_o):o(_o){}\n bool operator()(point a,point b)const{\n a=a-o;b=b-o;\n if (a.quad()!=b.quad()) return a.quad()<b.quad();\n db t=a%b;\n return std::abs(t)<=eps?a.mod2()<b.mod2():t>eps;\n }\n};\n\nstruct XFirstCmp{\n bool operator()(const point &a,const point &b)const{\n return std::abs(a.x-b.x)<=eps?a.y<b.y:a.x<b.x;\n }\n};\n\nstruct YFirstCmp{\n bool operator()(const point &a,const point &b)const{\n return std::abs(a.y-b.y)<=eps?a.x<b.x:a.y<b.y;\n }\n};\n\nstruct line{\n \n point s,t;\n \n line():s(),t(){}\n line(point _s,point _t):s(_s),t(_t){}\n \n // todo\n // 一般式 ax+by+c=0 转两点\n // line(db a,db b,db c){\n // if (!a){\n // s=point();\n // }else if (!b){\n\n // }else{\n\n // }\n // }\n \n point &operator[](int p){return p?t:s;}\n const point &operator[](int p)const{return p?t:s;}\n\n db x(db y)const{return s.x+(y-s.y)/(t.y-s.y)*(t.x-s.x);}\n db y(db x)const{return s.y+(x-s.x)/(t.x-s.x)*(t.y-s.y);}\n \n point vec()const{return t-s;}\n db len2()const{return (t-s).mod2();}\n db len()const{return (t-s).mod();}\n\n point pro(const point &a)const{return s+(t-s)*((a-s)*(t-s)/(t-s).mod2());}\n point ref(const point &a)const{return 2*pro(a)-a;}\n db dis2(const point &a)const{return (pro(a)-a).mod2();}\n db dis(const point &a)const{return (pro(a)-a).mod();}\n\n // seg_in 不包括端点 seg_on 包括端点\n bool on(const point &a)const{return std::abs((a-s)%(a-t))<=eps;}\n bool seg_in(const point &a)const{return on(a)&&((a-s)*(a-t)<-eps);}\n bool seg_on(const point &a)const{return seg_in(a)||a==s||a==t;}\n\n // -1 重合 0 相交 1 平行\n int para(const line &b)const{\n const line &a=*this;\n return std::abs(a.vec()%b.vec())>eps?0:on(b.s)?-1:1;\n }\n\n // 包括端点\n int seg_cross(const line &b)const{\n const line &a=*this;\n if (std::min(b.s.x,b.t.x)-std::max(a.s.x,a.t.x)>eps) return 0;\n if (std::min(b.s.y,b.t.y)-std::max(a.s.y,a.t.y)>eps) return 0;\n if (std::min(a.s.x,a.t.x)-std::max(b.s.x,b.t.x)>eps) return 0;\n if (std::min(a.s.y,a.t.y)-std::max(b.s.y,b.t.y)>eps) return 0;\n auto sgn=[&](db x){return std::abs(x)<=eps?0:(x>0?1:-1);};\n if (sgn((a.s-b.s)%b.vec())*sgn((a.t-b.s)%b.vec())>0) return 0;\n if (sgn((b.s-a.s)%a.vec())*sgn((b.t-a.s)%a.vec())>0) return 0;\n return 1;\n }\n\n point cross(const line &b)const{\n const line &a=*this;\n point u=a.s-b.s,v=a.vec(),w=b.vec();\n return a.s+(w%u)/(v%w)*v;\n }\n \n};\n\ntypedef std::vector<point> polygon;\n\n// 1 在多边形内 0 不在多边形内 -1 在多边形边界上\nint InPolygon(const polygon &a,const point &b){\n int res=0;\n for (int i=0;i<(int)a.size();++i){\n point u=a[i],v=a[(i+1)%(int)a.size()];\n if (line(u,v).seg_on(b)) return -1;\n if (std::abs(u.y-v.y)<=eps) continue;\n if (u.y>v.y) std::swap(u,v);\n if ((b-u)%(v-u)>eps) continue;\n if (b.y-u.y>eps&&b.y-v.y<=eps) res^=1;\n }\n return res&1;\n}\n\n// 1 在多边形内 0 不在多边形内 -1 在多边形边界上\nint InConvex(const polygon &a,const point &b){\n if (b==a[0]) return -1;\n if ((a.back()-a[0])%(b-a[0])>eps) return 0;\n if (line(a.back(),a[0]).seg_on(b)) return -1;\n const point &o=a[0];\n int p=std::lower_bound(a.begin(),a.end()-1,b,HalfPolarAngleCmp(o))-a.begin();\n if (line(a[p-1],a[p]).seg_on(b)) return -1;\n return (a[p]-a[p-1])%(b-a[p-1])>=-eps;\n}\n\npolygon ConvexHull(polygon a){\n point o=*std::min_element(a.begin(),a.end(),YFirstCmp());\n std::sort(a.begin(),a.end(),HalfPolarAngleCmp(o));\n polygon res({a.front()});\n for (int i=1;i<(int)a.size();++i){\n for (;res.size()>=2&&(res.back()-res.end()[-2])%(a[i]-res.back())<=eps;res.pop_back());\n res.push_back(a[i]);\n }\n return res;\n}\n\n// tag\ndb Diameter(polygon a){\n db res=0;\n int n=a.size();\n a.push_back(a[0]);\n for (int i=0,j=1;i<n;++i){\n for (;(a[i+1]-a[i])%(a[j+1]-a[i])-(a[i+1]-a[i])%(a[j]-a[i])>eps;j=(j+1)%n);\n res=std::max({res,(a[j]-a[i]).mod2(),(a[j]-a[i+1]).mod2()});\n }\n return std::sqrt(res);\n}\n\npolygon Minkowski(polygon a,polygon b){\n int n=a.size(),m=b.size();\n polygon res({a[0]+b[0]});\n a.push_back(a[0]);b.push_back(b[0]);\n for (int i=0,j=0;;){\n (a[i+1]-a[i])%(b[j+1]-b[j])>eps?i=(i+1)%n:j=(j+1)%m;\n point t=a[i]+b[j];\n if (res.size()>=2&&std::abs((t-res.back())%(res.back()-res.end()[-2]))<=eps)\n res.pop_back();\n res.push_back(t);\n if (!i&&!j) break;\n }\n res.pop_back();\n return res;\n}\n\n// 半平面在直线逆时针方向\npolygon HalfPlaneIntersection(std::vector<line> a){ // 半平面在直线逆时针方向\n const db inf=1e20L;\n a.emplace_back(point(-inf,-inf),point(inf,-inf));\n a.emplace_back(point(inf,-inf),point(inf,inf));\n a.emplace_back(point(inf,inf),point(-inf,inf));\n a.emplace_back(point(-inf,inf),point(-inf,-inf));\n std::sort(a.begin(),a.end(),[&](const line &a,const line &b){\n point u=a.vec(),v=b.vec();\n if (u.quad()!=v.quad()) return u.quad()<v.quad();\n db t=u%v;\n if (std::abs(t)>eps) return t>eps;\n return (a[0]-b[0])%b.vec()<-eps;\n });\n std::deque<point> qc;\n std::deque<line> ql;\n ql.emplace_back(a[0]);\n auto popback=[&](const line &a){\n for (;!qc.empty()&&(qc.back()-a.s)%a.vec()>=-eps;)\n qc.pop_back(),ql.pop_back();\n };\n auto popfront=[&](const line &a){\n for (;!qc.empty()&&(qc.front()-a.s)%a.vec()>=-eps;)\n qc.pop_front(),ql.pop_front();\n };\n for (int i=1;i<(int)a.size();++i){\n if (a[i].vec()*a[i-1].vec()>=eps&&std::abs(a[i].vec()%a[i-1].vec())<=eps) continue;\n popback(a[i]);popfront(a[i]);\n if (!ql.empty()){\n if (std::abs(a[i].vec()%ql.back().vec())<=eps) return {};\n qc.push_back(a[i].cross(ql.back()));\n }\n ql.push_back(a[i]);\n }\n popback(ql.front());popfront(ql.back());\n qc.push_back(ql.front().cross(ql.back()));\n if (qc.size()<=2) return {};\n polygon res;\n for (auto t:qc) res.push_back(t);\n return res;\n}\n\nstruct circle{\n\n point o;\n db r;\n\n circle():o(),r(){}\n circle(point _o,db _r):o(_o),r(_r){}\n\n point operator()(db th)const{return o+r*point(std::cos(th),std::sin(th));}\n\n // tag\n // 1 在圆内 -1 在圆上 0 在圆外\n int in(const point &a)const{\n db d2=(o-a).mod2();\n return std::abs(d2-r*r)<=eps?-1:r*r-d2>eps;\n }\n\n std::vector<point> cross(const line &b)const{\n const circle &a=*this;\n point t=b.pro(a.o);\n db d2=(t-a.o).mod2();\n if (d2-a.r*a.r>eps) return {};\n if (std::abs(d2-a.r*a.r)<=eps) return {t};\n point v=b.vec().unit()*std::sqrt(a.r*a.r-d2);\n return {t+v,t-v};\n }\n\n // tag\n std::vector<point> cross(const circle &b)const{\n const circle &a=*this;\n db d2=(a.o-b.o).mod2(),d=std::sqrt(d2);\n if (a.r+b.r-d<-eps||std::abs(a.r-b.r)-d>eps) return {};\n if (std::abs(a.r+b.r-d)<=eps||std::abs(std::abs(a.r-b.r)-d)<=eps)\n return {a.o+(b.o-a.o).unit()*a.r};\n db c=(d2+a.r*a.r-b.r*b.r)/(2*d2);\n point t=a.o+c*(b.o-a.o);\n point v=(b.o-a.o).norm().unit()*std::sqrt(a.r*a.r-(t-a.o).mod2());\n return {t+v,t-v};\n }\n\n};\n\n// 外接圆,共线时是三点的最小圆覆盖\ncircle CircumCircle(point a,point b,point c){\n if (std::abs((a-b)%(b-c))<=eps){\n if (YFirstCmp()(a,b)) std::swap(a,b);\n if (YFirstCmp()(a,c)) std::swap(a,c);\n if (YFirstCmp()(b,c)) std::swap(b,c);\n return circle((a+c)/2,(c-a).mod()/2);\n }\n point u=(a+b)/2,v=(a+c)/2;\n line p(u,u+(b-a).norm()),q(v,v+(c-a).norm());\n point o=p.cross(q);\n return circle(o,(o-a).mod());\n}\n\n// 内切圆,共线时可能出错\ncircle InCircle(const point &a,const point &b,const point &c){\n line p(a,a+(b-a).unit()+(c-a).unit());\n line q(b,b+(a-b).unit()+(c-b).unit());\n point o=p.cross(q);\n return circle(o,line(a,b).dis(o));\n}\n\ncircle MinimumEnclosingCircle(polygon a){\n std::shuffle(a.begin(),a.end(),std::mt19937(time(0)));\n circle res(a[0],0);\n for (int i=1;i<(int)a.size();++i){\n if (res.in(a[i])) continue;\n res=circle(a[i],0);\n for (int j=0;j<i;++j){\n if (res.in(a[j])) continue;\n res=circle((a[i]+a[j])/2,(a[i]-a[j]).mod()/2);\n for (int k=0;k<j;++k){\n if (res.in(a[k])) continue;\n res=CircumCircle(a[i],a[j],a[k]);\n }\n }\n }\n return res;\n}\n\n\n\n\n\ndb Area(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=a[i]%a[(i+1)%(int)a.size()];\n assert(std::abs(res)>=-eps);\n return res/2;\n}\n\ndb Length(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=(a[i]-a[(i+1)%(int)a.size()]).mod();\n return res;\n}\n\nvoid work(){\n // circle a,b;\n // std::cin>>a.o.x>>a.o.y>>a.r;\n // std::cin>>b.o.x>>b.o.y>>b.r;\n // auto ans=a.cross(b);\n // if (ans.size()==1) ans.push_back(ans.front());\n // std::sort(ans.begin(),ans.end(),XFirstCmp());\n // std::cout<<ans[0][0]<<' '<<ans[0][1]<<' '<<ans[1][0]<<' '<<ans[1][1]<<'\\n';\n int n;\n std::cin>>n;\n polygon a(n);\n for (auto &[x,y]:a) std::cin>>x>>y;\n std::cout<<Diameter(ConvexHull(a))<<'\\n';\n // int q;\n // std::cin>>q;\n // for (;q--;){\n // point p;\n // std::cin>>p.x>>p.y;\n // int ans=InPolygon(a,p);\n // std::cout<<(ans?ans==1?2:1:0)<<'\\n';\n // }\n}\n\nint main(){\n std::ios::sync_with_stdio(0);\n std::cin.tie(0);\n std::cout<<std::fixed<<std::setprecision(12);\n std::cerr<<std::fixed<<std::setprecision(2);\n int T=1;\n // std::cin>>T;\n for (;T--;) work();\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8188, "score_of_the_acc": -0.6591, "final_rank": 12 }, { "submission_id": "aoj_CGL_4_B_10993737", "code_snippet": "#include <bits/stdc++.h>\n\ntypedef long long int64;\n\ntypedef long double db;\n \nconst db eps=1e-8L,pi=std::acos(-1.0L);\n\nstruct point{\n \n db x,y;\n \n point():x(),y(){}\n point(db _x,db _y):x(_x),y(_y){}\n\n db &operator[](int p){return p?y:x;}\n const db &operator[](int p)const{return p?y:x;}\n\n friend point operator+(const point &a,const point &b){return point(a.x+b.x,a.y+b.y);}\n friend point operator-(const point &a,const point &b){return point(a.x-b.x,a.y-b.y);}\n friend point operator*(const point &a,const db &b){return point(a.x*b,a.y*b);}\n friend point operator*(const db &b,const point &a){return point(a.x*b,a.y*b);}\n friend point operator/(const point &a,const db &b){return point(a.x/b,a.y/b);}\n \n friend db operator*(const point &a,const point &b){return a.x*b.x+a.y*b.y;}\n friend db operator%(const point &a,const point &b){return a.x*b.y-a.y*b.x;}\n \n friend bool operator==(const point &a,const point &b){return std::abs(a.x-b.x)<=eps&&std::abs(a.y-b.y)<=eps;}\n friend bool operator!=(const point &a,const point &b){return std::abs(a.x-b.x)>eps||std::abs(a.y-b.y)>eps;}\n \n db mod2()const{return x*x+y*y;}\n db mod()const{return std::sqrt(x*x+y*y);}\n db dis2(const point &a)const{return (*this-a).mod2();}\n db dis(const point &a)const{return (*this-a).mod();}\n point unit()const{return *this/mod();}\n\n db ang()const{return std::atan2(y,x);}\n db ang(const point &a)const{return std::atan2(*this%a,*this*a);}\n point norm()const{return point(-y,x);}\n point rot(const db &th)const{db s=std::sin(th),c=std::cos(th);return point(x*c-y*s,x*s+y*c);}\n\n};\n \nstruct line{\n \n point s,t;\n \n line():s(),t(){}\n line(point _s,point _t):s(_s),t(_t){}\n \n point &operator[](int p){return p?t:s;}\n const point &operator[](int p)const{return p?t:s;}\n\n db x(db y)const{return s.x+(y-s.y)/(t.y-s.y)*(t.x-s.x);}\n db y(db x)const{return s.y+(x-s.x)/(t.x-s.x)*(t.y-s.y);}\n \n point vec()const{return t-s;}\n db len2()const{return (t-s).mod2();}\n db len()const{return (t-s).mod();}\n\n point pro(const point &a)const{return s+(t-s)*((a-s)*(t-s)/(t-s).mod2());}\n point ref(const point &a)const{return 2*pro(a)-a;}\n db dis2(const point &a)const{return (pro(a)-a).mod2();}\n db dis(const point &a)const{return (pro(a)-a).mod();}\n\n // seg_in 不包括端点 seg_on 包括端点\n bool on(const point &a)const{return std::abs((a-s)%(a-t))<=eps;}\n bool seg_in(const point &a)const{return on(a)&&((a-s)*(a-t)<-eps);}\n bool seg_on(const point &a)const{return seg_in(a)||a==s||a==t;}\n\n // -1 重合 0 相交 1 平行\n int para(const line &b)const{\n const line &a=*this;\n return std::abs(a.vec()%b.vec())>eps?0:on(b.s)?-1:1;\n }\n\n // 包括端点\n int seg_cross(const line &b)const{\n const line &a=*this;\n if (std::max(a.s.x,a.t.x)+eps<std::min(b.s.x,b.t.x)) return 0;\n if (std::max(b.s.x,b.t.x)+eps<std::min(a.s.x,a.t.x)) return 0;\n if (std::max(a.s.y,a.t.y)+eps<std::min(b.s.y,b.t.y)) return 0;\n if (std::max(b.s.y,b.t.y)+eps<std::min(a.s.y,a.t.y)) return 0;\n auto sgn=[&](db x){return std::abs(x)<=eps?0:(x>0?1:-1);};\n if (sgn((a.s-b.s)%b.vec())*sgn((a.t-b.s)%b.vec())>0) return 0;\n if (sgn((b.s-a.s)%a.vec())*sgn((b.t-a.s)%a.vec())>0) return 0;\n return 1;\n }\n\n point cross(const line &b)const{\n const line &a=*this;\n point u=a.s-b.s,v=a.vec(),w=b.vec();\n return a.s+(w%u)/(v%w)*v;\n }\n \n};\n\ntypedef std::vector<point> polygon;\n\npolygon ConvexHull(polygon a){\n auto o=*std::min_element(a.begin(),a.end(),[&](const point &a,const point &b){\n return a.y==b.y?a.x<b.x:a.y<b.y;\n });\n std::sort(a.begin(),a.end(),[&](const point &a,const point &b){\n int64 t=(a-o)%(b-o);\n return t==0?(a-o).mod2()<(b-o).mod2():t>0;\n });\n polygon res({a.front()});\n for (int i=1;i<(int)a.size();++i){\n for (;res.size()>=2&&(res.back()-res.end()[-2])%(a[i]-res.back())<=eps;res.pop_back());\n res.push_back(a[i]);\n }\n return res;\n}\n\ndb Area(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=a[i]%a[(i+1)%(int)a.size()];\n assert(std::abs(res)>=-eps);\n return res/2;\n}\n\ndb Length(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=(a[i]-a[(i+1)%(int)a.size()]).mod();\n return res;\n}\n\ndb Diameter(polygon a){\n db res=0;\n int n=a.size();\n a.push_back(a[0]);\n for (int i=0,j=1;i<n;++i){\n for (;(a[i+1]-a[i])%(a[j]-a[i])<(a[i+1]-a[i])%(a[j+1]-a[i])-eps;j=(j+1)%n);\n res=std::max({res,(a[j]-a[i]).mod2(),(a[j]-a[i+1]).mod2()});\n }\n return std::sqrt(res);\n}\n\n// struct circle{\n\n// point o;\n// db r;\n\n// circle():o(),r(){}\n// circle(point _o,db _r):o(_o),r(_r){}\n\n// circle()\n\n// };\n\nvoid work(){\n int n;\n std::cin>>n;\n polygon a(n);\n for (auto &[x,y]:a)\n std::cin>>x>>y;\n // auto sqr=[&](db x){return x*x;};\n std::cout<<Diameter(ConvexHull(a))+eps<<'\\n';\n}\n\nint main(){\n std::ios::sync_with_stdio(0);\n std::cin.tie(0);\n std::cout<<std::fixed<<std::setprecision(10);\n std::cerr<<std::fixed<<std::setprecision(2);\n int T=1;\n // std::cin>>T;\n for (;T--;) work();\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8164, "score_of_the_acc": -0.6581, "final_rank": 10 }, { "submission_id": "aoj_CGL_4_B_10938015", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i< (n); ++i)\n#define repi(i, a, b) for (int i = (a); i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define fore(i, a) for(auto &i:a)\nusing ll = long long;\nusing int64 = long long;\n#define DEBUG(x) cerr << #x << \": \"; for (auto _ : x) cerr << _ << \" \"; cerr << endl;\nconst int64 infll = (1LL << 62) - 1;\nconst int inf = (1 << 30) - 1;\n\nstruct IoSetup {\n\tIoSetup() {\n\t\tcin.tie(nullptr);\n\t\tios::sync_with_stdio(false);\n\t\tcout << fixed << setprecision(10);\n\t\tcerr << fixed << setprecision(10);\n\t}\n} iosetup;\n\ntemplate <typename T1, typename T2>\nostream& operator<<(ostream& os, const pair<T1, T2>& p) {\n\tos << p.first << \" \" << p.second;\n\treturn os;\n}\n\ntemplate <typename T1, typename T2>\nistream& operator>>(istream& is, pair<T1, T2>& p) {\n\tis >> p.first >> p.second;\n\treturn is;\n}\n\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n\tfor (int i = 0; i < (int)v.size(); i++) {\n\t\tos << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n\t}\n\treturn os;\n}\n\ntemplate <typename T>\nistream& operator>>(istream& is, vector<T>& v) {\n\tfor (T& in : v) is >> in;\n\treturn is;\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmax(T1& a, T2 b) {\n\treturn a < b && (a = b, true);\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmin(T1& a, T2 b) {\n\treturn a > b && (a = b, true);\n}\n\ntemplate <typename T = int64>\nvector<T> make_v(size_t a) {\n\treturn vector<T>(a);\n}\n\ntemplate <typename T, typename... Ts>\nauto make_v(size_t a, Ts... ts) {\n\treturn vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value == 0>::type fill_v(T& t, const V& v) {\n\tt = v;\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value != 0>::type fill_v(T& t, const V& v) {\n\tfor (auto& e : t) fill_v(e, v);\n}\n\ntemplate <typename F>\nstruct FixPoint : F {\n\texplicit FixPoint(F&& f) : F(std::forward<F>(f)) {}\n\n\ttemplate <typename... Args>\n\t\tdecltype(auto) operator()(Args&&... args) const {\n\t\t\treturn F::operator()(*this, std::forward<Args>(args)...);\n\t\t}\n};\n\ntemplate <typename F>\ninline decltype(auto) MFP(F&& f) {\n\treturn FixPoint<F>{std::forward<F>(f)};\n}\n//Geometry\nnamespace geometry {\nusing Real = double;\nconst Real EPS = 1e-15;\nconst Real PI = acos(static_cast<Real>(-1));\n\nenum { OUT, ON, IN };\n\ninline int sign(const Real& r) { return r <= -EPS ? -1 : r >= EPS ? 1 : 0; }\n\ninline bool equals(const Real& a, const Real& b) { return sign(a - b) == 0; }\n} // namespace geometry\n\nnamespace geometry {\nusing Point = complex<Real>;\n\nistream& operator>>(istream& is, Point& p) {\n Real a, b;\n is >> a >> b;\n p = Point(a, b);\n return is;\n}\n\nostream& operator<<(ostream& os, const Point& p) {\n return os << real(p) << \" \" << imag(p);\n}\n\nPoint operator*(const Point& p, const Real& d) {\n return Point(real(p) * d, imag(p) * d);\n}\n\n// rotate point p counterclockwise by theta rad\nPoint rotate(Real theta, const Point& p) {\n return Point(cos(theta) * real(p) - sin(theta) * imag(p),\n sin(theta) * real(p) + cos(theta) * imag(p));\n}\n\nReal cross(const Point& a, const Point& b) {\n return real(a) * imag(b) - imag(a) * real(b);\n}\n\nReal dot(const Point& a, const Point& b) {\n return real(a) * real(b) + imag(a) * imag(b);\n}\n\nbool compare_x(const Point& a, const Point& b) {\n return equals(real(a), real(b)) ? imag(a) < imag(b) : real(a) < real(b);\n}\n\nbool compare_y(const Point& a, const Point& b) {\n return equals(imag(a), imag(b)) ? real(a) < real(b) : imag(a) < imag(b);\n}\n\nusing Points = vector<Point>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Line {\n Point a, b;\n\n Line() = default;\n\n Line(const Point& a, const Point& b) : a(a), b(b) {}\n\n Line(const Real& A, const Real& B, const Real& C) { // Ax+By=C\n if (equals(A, 0)) {\n assert(!equals(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (equals(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (equals(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n friend ostream& operator<<(ostream& os, Line& l) {\n return os << l.a << \" to \" << l.b;\n }\n\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n};\n\nusing Lines = vector<Line>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Segment : Line {\n Segment() = default;\n\n using Line::Line;\n};\n\nusing Segments = vector<Segment>;\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A\nPoint projection(const Line& l, const Point& p) {\n auto t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);\n return l.a + (l.a - l.b) * t;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B\nPoint reflection(const Line& l, const Point& p) {\n return p + (projection(l, p) - p) * 2;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C\nconstexpr int COUNTER_CLOCKWISE = +1;\nconstexpr int CLOCKWISE = -1;\nconstexpr int ONLINE_BACK = +2; // c-a-b\nconstexpr int ONLINE_FRONT = -2; // a-b-c\nconstexpr int ON_SEGMENT = 0; // a-c-b\nint ccw(const Point& a, Point b, Point c) {\n b = b - a, c = c - a;\n if (sign(cross(b, c)) == +1) return COUNTER_CLOCKWISE;\n if (sign(cross(b, c)) == -1) return CLOCKWISE;\n if (sign(dot(b, c)) == -1) return ONLINE_BACK;\n if (norm(b) < norm(c)) return ONLINE_FRONT;\n return ON_SEGMENT;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_orthogonal(const Line& a, const Line& b) {\n return equals(dot(a.a - a.b, b.a - b.b), 0.0);\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_parallel(const Line& a, const Line& b) {\n return equals(cross(a.b - a.a, b.b - b.a), 0.0);\n}\n} // namespace geometry\n\nnamespace geometry {\nbool is_intersect_ss(const Segment& s, const Segment& t) {\n return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&\n ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;\n}\n} // namespace geometry\nnamespace geometry {\nbool is_intersect_sp(const Segment& s, const Point& p) {\n return ccw(s.a, s.b, p) == ON_SEGMENT;\n}\n} // namespace geometry\n\nnamespace geometry {\nPoint cross_point_ll(const Line& l, const Line& m) {\n Real A = cross(l.b - l.a, m.b - m.a);\n Real B = cross(l.b - l.a, l.b - m.a);\n if (equals(abs(A), 0) && equals(abs(B), 0)) return m.a;\n return m.a + (m.b - m.a) * B / A;\n}\n} // namespace geometry\nnamespace geometry {\nReal distance_sp(const Segment& s, const Point& p) {\n Point r = projection(s, p);\n if (is_intersect_sp(s, r)) return abs(r - p);\n return min(abs(s.a - p), abs(s.b - p));\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D\nReal distance_ss(const Segment& a, const Segment& b) {\n if (is_intersect_ss(a, b)) return 0;\n return min({distance_sp(a, b.a), distance_sp(a, b.b), distance_sp(b, a.a),\n distance_sp(b, a.b)});\n}\n} // namespace geometry\nnamespace geometry {\nusing Polygon = vector<Point>;\nusing Polygons = vector<Polygon>;\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A\nReal area(const Polygon& p) {\n int n = (int)p.size();\n Real A = 0;\n for (int i = 0; i < n; ++i) {\n A += cross(p[i], p[(i + 1) % n]);\n }\n return A * 0.5;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B\nbool is_convex_polygon(const Polygon& p) {\n int n = (int)p.size();\n for (int i = 0; i < n; i++) {\n if (ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == CLOCKWISE)\n return false;\n }\n return true;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C\nint contains(const Polygon& Q, const Point& p) {\n bool in = false;\n for (int i = 0; i < Q.size(); i++) {\n Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;\n if (imag(a) > imag(b)) swap(a, b);\n if (sign(imag(a)) <= 0 && 0 < sign(imag(b)) && sign(cross(a, b)) < 0)\n in = !in;\n if (equals(cross(a, b), 0) && sign(dot(a, b)) <= 0) return ON;\n }\n return in ? IN : OUT;\n}\n} // namespace geometry\nnamespace geometry {\nint convex_polygon_contains(const Polygon& Q, const Point& p) {\n int N = (int)Q.size();\n Point g = (Q[0] + Q[N / 3] + Q[N * 2 / 3]) / 3.0;\n if (equals(imag(g), imag(p)) && equals(real(g), real(p))) return IN;\n Point gp = p - g;\n int l = 0, r = N;\n while (r - l > 1) {\n int mid = (l + r) / 2;\n Point gl = Q[l] - g;\n Point gm = Q[mid] - g;\n if (cross(gl, gm) > 0) {\n if (cross(gl, gp) >= 0 && cross(gm, gp) <= 0)\n r = mid;\n else\n l = mid;\n } else {\n if (cross(gl, gp) <= 0 && cross(gm, gp) >= 0)\n l = mid;\n else\n r = mid;\n }\n }\n r %= N;\n Real v = cross(Q[l] - p, Q[r] - p);\n return sign(v) == 0 ? ON : sign(v) == -1 ? OUT : IN;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A\nPolygon convex_hull(Polygon& p, bool strict = true) {\n int n = (int)p.size(), k = 0;\n if (n <= 2) return p;\n sort(begin(p), end(p), compare_x);\n vector<Point> ch(2 * n);\n auto check = [&](int i) {\n return sign(cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1])) <= -1 + strict;\n };\n for (int i = 0; i < n; ch[k++] = p[i++]) {\n while (k >= 2 && check(i)) --k;\n }\n for (int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {\n while (k >= t && check(i)) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B\npair<int, int> convex_polygon_diameter(const Polygon& p) {\n int N = (int)p.size();\n int is = 0, js = 0;\n for (int i = 1; i < N; i++) {\n if (imag(p[i]) > imag(p[is])) is = i;\n if (imag(p[i]) < imag(p[js])) js = i;\n }\n Real maxdis = norm(p[is] - p[js]);\n\n int maxi, maxj, i, j;\n i = maxi = is;\n j = maxj = js;\n do {\n if (cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {\n j = (j + 1) % N;\n } else {\n i = (i + 1) % N;\n }\n if (norm(p[i] - p[j]) > maxdis) {\n maxdis = norm(p[i] - p[j]);\n maxi = i;\n maxj = j;\n }\n } while (i != is || j != js);\n return minmax(maxi, maxj);\n}\n} // namespace geometry\nusing namespace geometry;\nint main(){\n\tll n; cin >> n;\n\tPolygon a(n);\n\trep(i, n)cin >> a[i];\n\tauto[p, q] = convex_polygon_diameter(a);\n\tcout << abs(a[p]-a[q]) << endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 4396, "score_of_the_acc": -0.3385, "final_rank": 5 }, { "submission_id": "aoj_CGL_4_B_10913243", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#include <iostream>\ntemplate <typename T, typename U>\nostream& operator<<(ostream& os, const pair<T, U>& p) {return os<<'(' <<p.first<<\", \"<<p.second<<')';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {os<<'[';for(auto it=v.begin();it!=v.end();++it){os<<*it; if(next(it)!=v.end()){os<<\", \";}}return os<<']';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<vector<T>>& vv) {os<<\"[\\n\";for(auto it=vv.begin();it!=vv.end();++it){os<<\" \"<<*it;if(next(it)!=vv.end()){os<<\",\\n\";}else{os<<\"\\n\";}}return os<<\"]\";}\n#define dump(x) cerr << #x << \" = \" << (x) << '\\n'\n#else\n#define dump(x) (void)0\n#endif\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\ntemplate<class T> using pq = priority_queue<T>;\ntemplate<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>;\n#define out(x) cout<<x<<'\\n'\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define OVERLOAD_REP(_1,_2,_3,name,...) name\n#define REP1(i,n) for (auto i = std::decay_t<decltype(n)>{}; (i) < (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) < (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\ntemplate<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};\ntemplate<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};\nconst ll INF=(1LL<<60);\nconst ll mod=998244353;\nusing Graph = vector<vector<ll>>;\nusing Network = vector<vector<pair<ll,ll>>>;\nusing Grid = vector<string>;\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int dx2[8] = {1, 1, 1, 0, 0, -1, -1, -1};\nconst int dy2[8] = {1, 0, -1, 1, -1, 1, 0, -1};\n\n// #include \"../geo.hpp\"\n\nusing D = long double;\nconst D EPS = 1e-12L;\nconst D PI = acosl(-1.0L);\nusing P2 = complex<D>;\nstruct L2{P2 a, b;};\nstruct S2{P2 a, b;};\nusing G2 = vector<P2>;\n\nint sgn(D x){return (x>EPS)-(x<-EPS);}\nint cmp(D a, D b){return sgn(a-b);}\nbool eq(D a, D b){return cmp(a, b)==0;}\nbool lt(D a, D b){return cmp(a, b)<0;}\nbool le(D a, D b){return cmp(a, b)<=0;}\nbool gt(D a, D b){return cmp(a, b)>0;}\nbool ge(D a, D b){return cmp(a, b)>=0;}\nbool eqP2(P2 a, P2 b){return eq(real(a), real(b)) && eq(imag(a), imag(b));}\nbool ltP2(P2 a, P2 b) {\n return lt(real(a), real(b)) || (eq(real(a), real(b)) && lt(imag(a), imag(b)));\n}\n\nD dot(P2 a, P2 b) {return real(conj(a)*b);}\nD cross(P2 a, P2 b) {return imag(conj(a)*b);}\nint ccw(P2 a, P2 b, P2 c) {\n b-=a; c-=a;\n auto cr=cross(b, c), dt=dot(b, c);\n if (cr > EPS) return +1; // counter clockwise\n if (cr < -EPS) return -1; // clockwise\n if (dt < -EPS) return +2; // c--a--b\n if (lt(norm(b), norm(c))) return -2; // a--b--c\n return 0; // a--c--b\n}\nint turn(P2 a, P2 b, P2 c) { return sgn(cross(b - a, c - a)); }\n\nP2 rot(P2 a, D th) { return a*polar<D>(1, th); }\nP2 rot90(P2 a) { return P2(-imag(a), real(a)); }\nbool ltP2Arg(P2 a, P2 b) {\n auto up = [](P2 p) { return (imag(p) > 0 || (eq(imag(p), 0) && ge(real(p), 0))); };\n if (up(a) != up(b)) return up(a);\n if (!eq(cross(a, b), 0)) return cross(a, b) > 0;\n return lt(norm(a), norm(b));\n}\n\ninline void rd(P2& p) {D x, y; cin>>x>>y; p = P2(x, y);}\n#define setp(n) cout<<setprecision(n)<<fixed\ninline void pr(const P2& p) {setp(12); cout<<real(p)<<' '<<imag(p)<<'\\n';}\n\n// ----------------------------------------------------------------------------------\n\nP2 proj(L2 l, P2 p) { P2 a=p-l.a, b=l.b-l.a; return l.a+b*dot(a, b)/norm(b);}\nP2 refl(L2 l, P2 p) { return proj(l, p)*2.0L - p; }\nbool isParallel(L2 l, L2 m){ return eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isPerp(L2 l, L2 m){ return eq(dot(l.a-l.b, m.a-m.b), 0); }\n\nbool isLL(L2 l, L2 m){ return !eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isLS(L2 l, S2 s){ return turn(l.a, l.b, s.a)*turn(l.a, l.b, s.b)<=0; }\nbool isSS(S2 s, S2 t) {\n return\n ccw(s.a,s.b,t.a)*ccw(s.a,s.b,t.b) <= 0 &&\n ccw(t.a,t.b,s.a)*ccw(t.a,t.b,s.b) <= 0;\n}\n\nP2 cpLL(L2 l, L2 m) {\n P2 a=l.b-l.a, b=m.b-m.a;\n D d=cross(a, b);\n if (eq(d, 0)) return P2(INF, INF); // parallel\n return l.a + a*cross(m.b-l.a,b)/d;\n}\n\nD distLP(L2 l, P2 p) { return abs(cross(l.b-l.a, p-l.a))/abs(l.b-l.a); }\nD distSP(S2 s, P2 p) {\n P2 a=s.a, b=s.b;\n if (lt(dot(b-a, p-a), 0)) return abs(p-a);\n if (lt(dot(a-b, p-b), 0)) return abs(p-b);\n return distLP({a,b}, p);\n}\nD distSS(S2 s, S2 t) {\n if (isSS(s, t)) return 0;\n return min({distSP(s, t.a), distSP(s, t.b), distSP(t, s.a), distSP(t, s.b)});\n}\n\nD area(G2 g) {\n D s=0;\n int n=g.size();\n rep(i, n) s+=cross(g[i], g[(i+1)%n]);\n return s/2.0L;\n}\n\nbool isConvex(G2 g) {\n int n=g.size();\n if (n < 3) return false;\n int dir = 0;\n rep(i,n){\n int s = turn(g[i], g[(i+1)%n], g[(i+2)%n]);\n if (s == 0) return false; // -> continue : allows three points on a line\n if (dir == 0) dir = s;\n else if (dir*s < 0) return false;\n }\n return true;\n}\n\nint inG(G2 g, P2 p) {\n bool in=false;\n int n=g.size();\n rep(i, n) {\n P2 a=g[i], b=g[(i+1)%n];\n if (ccw(a, b, p) == 0) return 1; // on boundary\n if (a.imag() > b.imag()) swap(a, b);\n if (le(a.imag(), p.imag()) && lt(p.imag(), b.imag()) && turn(a, b, p) > 0) in=!in;\n }\n return in ? 2 : 0; // inside : outside\n}\n\nG2 hull(G2 g) {\n sort(all(g), ltP2);\n g.erase(unique(all(g), eqP2), g.end());\n if (g.size()<=1) return g;\n G2 lo, up;\n for (auto &p:g) {\n while (lo.size()>=2 && turn(lo[lo.size()-2], lo.back(), p)<=0) lo.pop_back(); //-> turn()<0 : allow three points on a line\n lo.push_back(p);\n }\n reverse(all(g));\n for (auto &p:g) {\n while (up.size()>=2 && turn(up[up.size()-2], up.back(), p)<=0) up.pop_back(); // -> turn()<0 : allow three points on a line\n up.push_back(p);\n }\n lo.pop_back(); up.pop_back();\n lo.insert(lo.end(), all(up));\n return lo;\n}\n\npair<P2, P2> diameter(G2 g) {\n auto h = hull(g);\n int n=h.size();\n if(n==0) return {P2(0,0), P2(0,0)};\n if(n==1) return {h[0], h[0]};\n auto area2=[&](int i, int j, int k) {return abs(cross(h[j]-h[i], h[k]-h[i]));};\n D maxd=0;\n pair<P2, P2> res={h[0], h[0]};\n int j=1;\n rep(i, n) {\n int ni=(i+1)%n;\n while (gt(area2(i, ni, (j+1)%n), area2(i, ni, j))) j=(j+1)%n;\n if (gt(abs(h[i]-h[j]), maxd)) maxd=abs(h[i]-h[j]), res={h[i], h[j]};\n if (gt(abs(h[ni]-h[j]), maxd)) maxd=abs(h[ni]-h[j]), res={h[ni], h[j]};\n }\n return res;\n}\n\n// int inConvex(G2 h, P2 p) {\n// int n=h.size();\n// if (n==0) return 0;\n// if (n==1) return eqP2(h[0], p) ? 2 : 0;\n// if (n==2) return ccw(h[0], h[1], p)==0 && le(abs(h[0]-p)+abs(h[1]-p), abs(h[0]-h[1])) ? 2 : 0;\n// int left=1, right=n-1;\n// while (right-left>1) {\n// int mid=(left+right)/2;\n// if (turn(h[0], h[mid], p)<0) right=mid;\n// else left=mid;\n// }\n// if (turn(h[0], h[left], p)<0) return 0;\n// if (turn(h[left], h[right%n], p)<0) return 0;\n// if (turn(h[right%n], h[0], p)<0) return 0;\n// if (turn(h[0], h[left], p)==0 || turn(h[left], h[right%n], p)==0 || turn(h[right%n], h[0], p)==0) return 2;\n// return 1;\n// }\n\nG2 cutConvex(G2 h, L2 l) {\n int n=h.size();\n G2 res;\n if (n==0) return res;\n auto inside=[&](P2 p){ return turn(l.a, l.b, p) >= 0; };\n rep(i, n) {\n P2 a=h[i], b=h[(i+1)%n];\n bool ina=inside(a), inb=inside(b);\n if (ina&&inb) res.push_back(b);\n else if (ina&&!inb) {\n res.push_back(cpLL({a,b}, l));\n }\n else if (!ina&&inb) {\n res.push_back(cpLL({a,b}, l));\n res.push_back(b);\n }\n }\n return res;\n}\n\n\npair<P2, P2> closestPair(G2 g) {\n auto ps = g;\n int n=ps.size();\n if (n < 2) return {P2(0,0), P2(0,0)};\n sort(all(ps), ltP2);\n D mind = norm(ps[0]-ps[1]);\n pair<P2, P2> res = {ps[0], ps[1]};\n set<pair<D,int>> box;\n int j=0;\n rep(i, n) {\n D xi=real(ps[i]), yi=imag(ps[i]);\n D rad = sqrtl(mind);\n while (j<i && gt(xi - real(ps[j]), rad)) {\n box.erase({imag(ps[j]), j});\n j++;\n }\n auto it = box.lower_bound({yi - rad, -1});\n for (; it != box.end() && le(it->first, yi + rad); ++it) {\n int k = it->second;\n D d = norm(ps[i]-ps[k]);\n if (lt(d, mind)) mind=d, res={ps[i], ps[k]}, rad = sqrtl(mind);\n }\n box.insert({yi, i});\n }\n return res;\n}\n\n\nstruct C2 { P2 o; D r; };\n\nC2 makeC2(P2 a, P2 b) {\n return C2{(a+b)/D(2), abs(a-b)/D(2)};\n}\nC2 makeC2(P2 a, P2 b, P2 c) {\n P2 B=b-a, C=c-a;\n D d=2*cross(B, C);\n if (eq(d, 0)) {\n D ab=norm(B), bc=norm(b-c), ca=norm(c-a);\n if (le(ab, bc) && le(ab, ca)) return makeC2(a, b);\n if (le(bc, ca)) return makeC2(b, c);\n return makeC2(c, a);\n }\n P2 o=a+(rot90(B)*norm(C)-rot90(C)*norm(B))/d;\n return C2{o, abs(o-a)};\n}\n\nC2 incircle(P2 a, P2 b, P2 c) {\n D ab=abs(b-a), bc=abs(c-b), ca=abs(a-c);\n P2 o=(a*bc+b*ca+c*ab)/(ab+bc+ca);\n D r=abs(cross(b-a, o-a))/abs(b-a);\n return C2{o, r};\n}\n\nvector<P2> cpCL(L2 l, C2 c) {\n vector<P2> res;\n P2 a=l.a-c.o, d=l.b-l.a;\n D A=norm(d), B=2*dot(a, d), C=norm(a)-c.r*c.r;\n if (le(A, 0)) {\n if (eq(abs(a), c.r)) res.push_back(l.a);\n return res;\n }\n D Dlt=B*B-4*A*C;\n if (lt(Dlt, 0)) return res;\n D s = le(Dlt, 0) ? 0 : sqrtl(max<D>(0, Dlt));\n D t1 = (-B - s)/(2*A), t2 = (-B + s)/(2*A);\n res.push_back(c.o + a + d*t1);\n if (gt(Dlt, 0)) res.push_back(c.o + a + d*t2);\n return res;\n}\n\nvector<P2> cpCC(C2 c1, C2 c2) {\n vector<P2> res;\n P2 d=c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n D a=(c1.r*c1.r-c2.r*c2.r+L*L)/(2*L), h2=c1.r*c1.r-a*a;\n if (lt(h2, 0)) return res;\n P2 m=c1.o+d*(a/L), n=rot90(d)*( (lt(h2, 0) ? 0 : sqrtl(max<D>(0, h2))/L) );\n res.push_back(m-n);\n if (gt(h2, 0)) res.push_back(m+n);\n return res;\n}\n\nD isaCC(C2 c1, C2 c2) {\n D d=abs(c1.o-c2.o), r1=c1.r, r2=c2.r;\n if (ge(d, r1+r2)) return 0;\n if (le(d, abs(r1-r2))) {\n D r=min(r1, r2);\n return PI*r*r;\n }\n auto f = [&] (D z) { return max<D>(-1, min<D>(1, z)); };\n D a = 2*acosl(f((d*d+r1*r1-r2*r2)/(2*d*r1)));\n D b = 2*acosl(f((d*d+r2*r2-r1*r1)/(2*d*r2)));\n return 0.5L*(r1*r1*(a-sinl(a)) + r2*r2*(b-sinl(b)));\n}\n\nvector<L2> tangCP(C2 c, P2 p) {\n vector<L2> res;\n P2 v = p - c.o;\n D d2 = norm(v), r2 = c.r*c.r;\n if (lt(d2, r2)) return res;\n if (eq(d2, r2)) {\n res.push_back({c.o+v*(r2/d2), p});\n return res;\n }\n D h = c.r*sqrtl(max<D>(0, d2 - r2));\n P2 n1 = (v*r2 - rot90(v)*h)/d2;\n P2 n2 = (v*r2 + rot90(v)*h)/d2;\n res.push_back({c.o+n1, p});\n res.push_back({c.o+n2, p});\n return res;\n}\n\nvector<L2> tangCC(C2 c1, C2 c2) {\n vector<L2> res;\n P2 d = c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n P2 e = d/L;\n auto add = [&] (int s) {\n D c=(s*c2.r - c1.r)/L;\n if (gt(c*c, 1)) return;\n D s2 = max<D>(0, 1 - c*c);\n if (eq(s2, 0)) {\n P2 n = e*c;\n res.push_back({c1.o-n*c1.r, c2.o-n*c2.r});\n } else {\n D s = sqrtl(s2);\n P2 n1 = e*c + rot90(e)*s;\n P2 n2 = e*c - rot90(e)*s;\n res.push_back({c1.o-n1*c1.r, c2.o-n1*c2.r});\n res.push_back({c1.o-n2*c1.r, c2.o-n2*c2.r});\n }\n };\n add(+1); // external\n add(-1); // internal\n return res;\n}\n\nC2 mec(G2 ps) {\n auto inC2=[&](C2 c, P2 p){ return le(abs(c.o - p), c.r); };\n mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n shuffle(all(ps), rng);\n int n=ps.size();\n if(n==0) return C2{P2(0,0), 0};\n C2 c{ps[0], 0};\n rep(i, n) {\n if (inC2(c, ps[i])) continue;\n c={ps[i], 0};\n rep(j, i) {\n if (inC2(c, ps[j])) continue;\n c=makeC2(ps[i], ps[j]);\n rep(k, j) {\n if (inC2(c, ps[k])) continue;\n c=makeC2(ps[i], ps[j], ps[k]);\n }\n }\n }\n return c;\n}\n\nvector<P2> cpSegs(vector<S2> ss) {\n struct E { D x; int t; D y, y1, y2; }; // t: 0=add(H), 1=query(V), 2=remove(H)\n vector<E> es; es.reserve(ss.size()*2);\n\n for(auto s: ss) {\n if (eq(s.a.imag(), s.b.imag())) {\n if (gt(s.a.real(), s.b.real())) swap(s.a, s.b);\n es.push_back({s.a.real(), 0, s.a.imag(), 0, 0});\n es.push_back({s.b.real(), 2, s.a.imag(), 0, 0});\n } else {\n if (gt(s.a.imag(), s.b.imag())) swap(s.a, s.b);\n es.push_back({s.a.real(), 1, 0, s.a.imag(), s.b.imag()});\n }\n }\n\n sort(all(es), [](E a, E b) {\n if (!eq(a.x, b.x)) return lt(a.x, b.x);\n return a.t < b.t;\n });\n\n multiset<D> active;\n vector<P2> res; res.reserve(ss.size());\n for (auto e : es) {\n if (e.t == 0) { // add\n active.insert(e.y);\n } else if (e.t == 2) { // remove\n auto it = active.find(e.y);\n if (it != active.end()) active.erase(it);\n } else { // query\n for (auto it = active.lower_bound(e.y1); it != active.end() && le(*it, e.y2); ++it) {\n res.push_back(P2(e.x, *it));\n }\n }\n }\n\n sort(all(res), ltP2);\n res.erase(unique(all(res), eqP2), res.end());\n return res;\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_A\nvoid Projection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(proj(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_B\nvoid Reflection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(refl(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_C\nvoid CounterClockwise() {\n P2 p0, p1;\n rd(p0); rd(p1);\n ll q; cin>>q;\n while(q--) {\n P2 p; rd(p);\n int res = ccw(p0, p1, p);\n if (res == +1) out(\"COUNTER_CLOCKWISE\");\n else if (res == -1) out(\"CLOCKWISE\");\n else if (res == +2) out(\"ONLINE_BACK\");\n else if (res == -2) out(\"ONLINE_FRONT\");\n else out(\"ON_SEGMENT\");\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_2_A\nvoid ParallelOrthogonal() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n if (isParallel({p1, p2}, {p3, p4})) out(2);\n else if(isPerp({p1, p2}, {p3, p4})) out(1);\n else out(0);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_B\nvoid IntersectionSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n out(isSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_C\nvoid CrossPointSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n L2 s1 = {p1, p2}, s2 = {p3, p4};\n pr(cpLL(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_D\nvoid DistanceSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n setp(12);\n out(distSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_A\nvoid Area() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n setp(1);\n out(area(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_B\nvoid IsConvex() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n out(isConvex(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_C\nvoid PolygonPointContainment() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n out(inG(g, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\nvoid ConvexHull() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n G2 h = hull(g);\n out(h.size());\n ll sx = INF, sy = INF;\n ll id = -1;\n rep(i, h.size()) {\n if (lt(imag(h[i]), sy)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n else if (eq(imag(h[i]), sy) && lt(real(h[i]), sx)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n }\n rep(i, h.size()) {\n ll ni = (id + i) % h.size();\n pr(h[ni]);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_B\nvoid DiameterOfConvexPolygon() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = diameter(g);\n setp(12);\n out(abs(p1 - p2));\n // todo\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_C\nvoid ConvexCut() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n G2 h = cutConvex(g, l);\n setp(12);\n out(area(h));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_A\nvoid ClosestPair() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = closestPair(g);\n setp(12);\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_B\nvoid MinimumEnclosingCircle() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [c, r] = mec(g);\n pr(c);\n setp(12);\n out(r);\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/6/CGL_6_A\nvoid SegmentIntersections() {\n ll n;cin>>n;\n vector<S2> seg(n);\n rep(i, n) {\n P2 a, b; rd(a); rd(b);\n seg[i] = {a, b};\n }\n out(cpSegs(seg).size());\n}\n\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_A\nvoid IntersectionOfCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n out(tangCC(c1, c2).size());\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_B\nvoid IncircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [ic, ir] = incircle(a, b, c);\n pr(ic);\n setp(12);\n out(ir);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_C\nvoid CircumscribedCircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [cc, cr] = makeC2(a, b, c);\n pr(cc);\n setp(12);\n out(cr);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_D\nvoid CrossPointsCL() {\n P2 c; D r;\n rd(c); cin>>r;\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n auto ps = cpCL(l, {c, r});\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n }\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_E\nvoid CrossPointsCC() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ps = cpCC(c1, c2);\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_F\nvoid TangentToCircle() {\n P2 p, c; D r;\n rd(p);\n rd(c); cin>>r;\n C2 c1={c, r};\n auto ls = tangCP(c1, p);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_G\nvoid CommonTangent() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ls = tangCC(c1, c2);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_H\n// void IntersectionCP() {\n// ll n;cin>>n;\n// D r; cin>>r;\n// C2 c = {P2(0, 0), r};\n// G2 g(n);\n// rep(i, n) rd(g[i]);\n// out(isaCP(c, g));\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_I\nvoid AreaOfIntersectionBetweenTwoCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n setp(12);\n out(isaCC(c1, c2));\n}\n\nint main() {\n cin.tie(0);\n ios_base::sync_with_stdio(false);\n\n // Projection();\n // Reflection();\n // CounterClockwise();\n\n // ParallelOrthogonal();\n // IntersectionSS();\n // CrossPointSS();\n // DistanceSS();\n\n // Area();\n // IsConvex();\n // PolygonPointContainment();\n\n // ConvexHull();\n DiameterOfConvexPolygon();\n // ConvexCut();\n\n // ClosestPair();\n // MinimumEnclosingCircle();\n\n // SegmentIntersections();\n\n // IntersectionOfCircles();\n // IncircleOfTriangle();\n // CircumscribedCircleOfTriangle();\n // CrossPointsCL();\n // CrossPointsCC();\n // TangentToCircle();\n // CommonTangent();\n // IntersectionCP();\n // AreaOfIntersectionBetweenTwoCircles();\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 10684, "score_of_the_acc": -0.927, "final_rank": 16 }, { "submission_id": "aoj_CGL_4_B_10904211", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <climits>\n#include <unordered_map>\n#include <queue>\n#include <deque>\n#include <math.h>\n#include <bits/stdc++.h>\n#define ll long long\n#define Lt Line<T>\n#define Pt Point<T>\nusing i64 = long long;\nusing namespace std;\n\nconst ll N=1e6+10,MOD=998244353;\n\ntypedef std::pair<ll,ll> pii;\ntypedef std::pair<ll,pii> piii;\n//i64 n,m,k;\n\nusing ld = long double;\nconst ld PI = acos(-1);\nconst ld EPS = 1e-7;\nconst ld INF = numeric_limits<ld>::max();\n#define cc(x) cout << fixed << setprecision(x);\n\nld fgcd(ld x, ld y) { // 实数域gcd\n return abs(y) < EPS ? abs(x) : fgcd(y, fmod(x, y));\n}\ntemplate<class T, class S> bool equal(T x, S y) {\n return -EPS < x - y && x - y < EPS;\n}\ntemplate<class T> int sign(T x) {\n if (-EPS < x && x < EPS) return 0;\n return x < 0 ? -1 : 1;\n}\n\ntemplate<class T> struct Point { // 在C++17下使用 emplace_back 绑定可能会导致CE!\n T x, y;\n Point(T x_ = 0, T y_ = 0) : x(x_), y(y_) {} // 初始化\n template<class U> operator Point<U>() { // 自动类型匹配\n return Point<U>(U(x), U(y));\n }\n Point &operator+=(Point p) & { return x += p.x, y += p.y, *this; }\n Point &operator+=(T t) & { return x += t, y += t, *this; }\n Point &operator-=(Point p) & { return x -= p.x, y -= p.y, *this; }\n Point &operator-=(T t) & { return x -= t, y -= t, *this; }\n Point &operator*=(T t) & { return x *= t, y *= t, *this; }\n Point &operator/=(T t) & { return x /= t, y /= t, *this; }\n Point operator-() const { return Point(-x, -y); }\n friend Point operator+(Point a, Point b) { return a += b; }\n friend Point operator+(Point a, T b) { return a += b; }\n friend Point operator-(Point a, Point b) { return a -= b; }\n friend Point operator-(Point a, T b) { return a -= b; }\n friend Point operator*(Point a, T b) { return a *= b; }\n friend Point operator*(T a, Point b) { return b *= a; }\n friend Point operator/(Point a, T b) { return a /= b; }\n friend bool operator<(Point a, Point b) {\n return equal(a.x, b.x) ? a.y < b.y - EPS : a.x < b.x - EPS;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return !(a < b) && !(b < a); }\n friend bool operator!=(Point a, Point b) { return a < b || b < a; }\n friend auto &operator>>(istream &is, Point &p) {\n return is >> p.x >> p.y;\n }\n friend auto &operator<<(ostream &os, Point p) {\n return os << \"(\" << p.x << \", \" << p.y << \")\";\n }\n};\ntemplate<class T> struct Line {\n Point<T> a, b;\n Line(Point<T> a_ = Point<T>(), Point<T> b_ = Point<T>()) : a(a_), b(b_) {}\n template<class U> operator Line<U>() { // 自动类型匹配\n return Line<U>(Point<U>(a), Point<U>(b));\n }\n friend auto &operator<<(ostream &os, Line l) {\n return os << \"<\" << l.a << \", \" << l.b << \">\";\n }\n};\n\nusing Pd = Point<ld>;\nusing Ld = Line<ld>;\n\n\ntemplate<class T> T cross(Point<T> a, Point<T> b) { // 叉乘\n return a.x * b.y - a.y * b.x;\n}\ntemplate<class T> T cross(Point<T> p1, Point<T> p2, Point<T> p0) { // 叉乘 (p1 - p0) x (p2 - p0);\n return cross(p1 - p0, p2 - p0);\n}\n\n\ntemplate<class T> T dot(Point<T> a, Point<T> b) { // 点乘\n return a.x * b.x + a.y * b.y;\n}\ntemplate<class T> T dot(Point<T> p1, Point<T> p2, Point<T> p0) { // 点乘 (p1 - p0) * (p2 - p0);\n return dot(p1 - p0, p2 - p0);\n}\n\ntemplate <class T> ld dis(T x1, T y1, T x2, T y2) {\n ld val = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n return sqrt(val);\n}\ntemplate <class T> ld dis(Point<T> a, Point<T> b) {\n return dis(a.x, a.y, b.x, b.y);\n}\n\ntemplate<class T> Point<T> rotate(Point<T> p1, Point<T> p2) { // 旋转\n Point<T> vec = p1 - p2;\n return {-vec.y, vec.x};\n}\n\nld toDeg(ld x) { // 弧度转角度\n return x * 180 / PI;\n}\nld toArc(ld x) { // 角度转弧度\n return PI / 180 * x;\n}\n\nPoint<ld> rotate(Point<ld> p, ld rad) {\n return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)};\n}\n\nPoint<ld> rotate(Point<ld> a, Point<ld> b, ld rad) {\n ld x = (a.x - b.x) * cos(rad) + (a.y - b.y) * sin(rad) + b.x;\n ld y = (b.x - a.x) * sin(rad) + (a.y - b.y) * cos(rad) + b.y;\n return {x, y};\n}\n\ntemplate<class T> bool onLine(Point<T> a, Point<T> b, Point<T> c) {\n return sign(cross(b, a, c)) == 0;\n}\ntemplate<class T> bool onLine(Point<T> p, Line<T> l) {\n return onLine(p, l.a, l.b);\n}\n\ntemplate<class T> bool pointOnLineLeft(Pt p, Lt l) {\n return cross(l.b, p, l.a) > 0;\n}\n\ntemplate<class T> bool pointOnLineSide(Pt p1, Pt p2, Lt vec) {\n T val = cross(p1, vec.a, vec.b) * cross(p2, vec.a, vec.b);\n return sign(val) == 1;\n}\ntemplate<class T> bool pointNotOnLineSide(Pt p1, Pt p2, Lt vec) {\n T val = cross(p1, vec.a, vec.b) * cross(p2, vec.a, vec.b);\n return sign(val) == -1;\n}\n\nPd lineIntersection(Ld l1, Ld l2) {\n ld val = cross(l2.b - l2.a, l1.a - l2.a) / cross(l2.b - l2.a, l1.a - l1.b);\n return l1.a + (l1.b - l1.a) * val;\n}\n\ntemplate<class T> bool lineParallel(Lt p1, Lt p2) {\n return sign(cross(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool lineVertical(Lt p1, Lt p2) {\n return sign(dot(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool same(Line<T> l1, Line<T> l2) {\n return lineParallel(Line{l1.a, l2.b}, {l1.b, l2.a}) &&\n lineParallel(Line{l1.a, l2.a}, {l1.b, l2.b}) && lineParallel(l1, l2);\n}\n\npair<Pd, ld> pointToLine(Pd p, Ld l) {\n Pd ans = lineIntersection({p, p + rotate(l.a, l.b)}, l);\n return {ans, dis(p, ans)};\n}\n\ntemplate<class T> ld disPointToLine(Pt p, Lt l) {\n ld ans = cross(p, l.a, l.b);\n return abs(ans) / dis(l.a, l.b); // 面积除以底边长\n}\n\ntemplate<class T> bool pointOnSegment(Pt p, Lt l) { // 端点也算作在直线上\n return sign(cross(p, l.a, l.b)) == 0 && min(l.a.x, l.b.x) <= p.x && p.x <= max(l.a.x, l.b.x) &&\n min(l.a.y, l.b.y) <= p.y && p.y <= max(l.a.y, l.b.y);\n}\n\npair<Pd, ld> pointToSegment(Pd p, Ld l) {\n if (sign(dot(p, l.b, l.a)) == -1) { // 特判到两端点的距离\n return {l.a, dis(p, l.a)};\n } else if (sign(dot(p, l.a, l.b)) == -1) {\n return {l.b, dis(p, l.b)};\n }\n return pointToLine(p, l);\n}\n\ntemplate<class T> bool segmentIntersection(Lt l1, Lt l2) {\n auto [s1, e1] = l1;\n auto [s2, e2] = l2;\n auto A = max(s1.x, e1.x), AA = min(s1.x, e1.x);\n auto B = max(s1.y, e1.y), BB = min(s1.y, e1.y);\n auto C = max(s2.x, e2.x), CC = min(s2.x, e2.x);\n auto D = max(s2.y, e2.y), DD = min(s2.y, e2.y);\n return A >= CC && B >= DD && C >= AA && D >= BB &&\n sign(cross(s1, s2, e1) * cross(s1, e1, e2)) == 1 &&\n sign(cross(s2, s1, e2) * cross(s2, e2, e1)) == 1;\n}\n\ntemplate<class T> int pointInPolygon(Point<T> a, vector<Point<T>> p) {\n int n = p.size();\n for (int i = 0; i < n; i++) {\n if (pointOnSegment(a, Line{p[i], p[(i + 1) % n]})) {\n return 2;\n }\n }\n int t = 0;\n for (int i = 0; i < n; i++) {\n auto u = p[i], v = p[(i + 1) % n];\n if (u.x < a.x && v.x >= a.x && pointOnLineLeft(a, Line{v, u})) {\n t ^= 1;\n }\n if (u.x >= a.x && v.x < a.x && pointOnLineLeft(a, Line{u, v})) {\n t ^= 1;\n }\n }\n return t == 1;\n}\n\ntemplate<class T> bool cmp1(Point<T> &a,Point<T> &b)\n{\n Point<T> a1(a.y,a.x);\n Point<T> b1(b.y,b.x);\n return a1<b1;\n}\n\ntemplate<class T> vector<Point<T>> staticConvexHull(vector<Point<T>> A, int flag = 1) {\n int n = A.size();\n if (n <= 2) { // 特判\n return A;\n }\n vector<Point<T>> ans(n * 2);\n sort(A.begin(), A.end());\n int now = -1;\n \n for (int i = 0; i < n; i++) { // 维护下凸包\n while (now > 0 && cross(A[i], ans[now], ans[now - 1]) <= 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n int pre = now;\n for (int i = n - 2; i >= 0; i--) { // 维护上凸包\n while (now > pre && cross(A[i], ans[now], ans[now - 1]) <= 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n ans.resize(now);\n return ans;\n}\n\ntemplate<class T>T GetConvexHullDis(vector<Pt> A)\n{\n int w=0; \n T ans=max(dis(A[w],A[0]),dis(A[w],A[1]));\n for(int i=0;i<A.size();i++)\n {\n int j=(i+1)%A.size();\n int ne=(w+1)%A.size();\n while(cross(A[ne],A[i],A[j])>=cross(A[w],A[i],A[j])) w=ne,ne=(w+1)%A.size();\n ans=max(max(dis(A[w],A[i]),dis(A[w],A[j])),ans);\n }\n return ans;\n}\n\n\nint main() {\n \n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n\n int n; cin>>n;\n vector<Pd> z(n);\n for(auto &t:z) cin>>t;\n\n cc(12);\n cout<<GetConvexHullDis(z);\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 8616, "score_of_the_acc": -0.1764, "final_rank": 1 }, { "submission_id": "aoj_CGL_4_B_10898110", "code_snippet": "#line 1 \"a.cpp\"\n#define PROBLEM \\\n \"https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_B\"\n#define ERROR 0.000001\n#line 2 \"/workspaces/cp-container/libraries/template.hpp\"\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i, n) for (int i = 0; i < (int)(n); ++i)\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing vll = vector<ll>;\nusing vvll = vector<vll>;\n\ntemplate <typename T>\nbool chmax(T& a, const T& b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\n\ntemplate <typename T>\nbool chmin(T& a, const T& b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n#line 3 \"/workspaces/cp-container/libraries/geometry/core.hpp\"\n\nusing Point = complex<double>;\n\nstruct Line {\n Point a, b;\n Line() = default;\n Line(const Point& _a, const Point& _b) : a(_a), b(_b) {}\n};\n\nconstexpr double eps = 1.0e-9;\n\ndouble dot(const Point& a, const Point& b) { return (conj(a) * b).real(); }\ndouble cross(const Point& a, const Point& b) { return (conj(a) * b).imag(); }\n\nPoint projection(const Point& p0, const Point& p1, const Point& p) {\n Point base = p1 - p0, hyp = p - p0;\n double t = dot(base, hyp) / norm(base);\n return p0 + t * base;\n}\n\nPoint reflection(const Point& p0, const Point& p1, const Point& p) {\n return 2.0 * projection(p0, p1, p) - p;\n}\n\nconstexpr int COUNTER_CLOCKWISE = 1, CLOCKWISE = -1, ONLINE_BACK = 2,\n ONLINE_FRONT = -2, ON_SEGMENT = 0;\n\nint ccw(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0, b = p2 - p0;\n if (eps < cross(a, b)) return COUNTER_CLOCKWISE;\n if (cross(a, b) < -eps) return CLOCKWISE;\n if (dot(a, b) < -eps) return ONLINE_BACK;\n if (norm(a) < norm(b)) return ONLINE_FRONT;\n return ON_SEGMENT;\n}\n\nbool is_parallel(const Line& l0, const Line& l1) {\n return abs(cross(l0.b - l0.a, l1.b - l1.a)) < eps;\n}\n\nbool is_orthogonal(const Line& l0, const Line& l1) {\n return abs(dot(l0.b - l0.a, l1.b - l1.a)) < eps;\n}\n\nbool has_intersection(Line s0, Line s1) {\n return ccw(s0.a, s0.b, s1.a) * ccw(s0.a, s0.b, s1.b) <= 0 &&\n ccw(s1.a, s1.b, s0.a) * ccw(s1.a, s1.b, s0.b) <= 0;\n}\n\nPoint cross_point(const Line& l0, const Line& l1) {\n double d0 = cross(l0.b - l0.a, l1.b - l1.a),\n d1 = cross(l0.b - l0.a, l0.b - l1.a);\n if (abs(d0) < eps && abs(d1) < eps) return l1.a;\n return l1.a + d1 / d0 * (l1.b - l1.a);\n}\n\ndouble distance_between_point_and_segment(const Point& p, const Line& s) {\n if (dot(s.b - s.a, p - s.a) < eps) return abs(p - s.a);\n if (dot(s.a - s.b, p - s.b) < eps) return abs(p - s.b);\n return abs(cross(s.b - s.a, p - s.a)) / abs(s.b - s.a);\n}\n\ndouble distance_between_segments(const Line& s0, const Line& s1) {\n if (has_intersection(s0, s1)) return 0.0;\n double ret = numeric_limits<double>::max();\n chmin(ret, distance_between_point_and_segment(s0.a, s1));\n chmin(ret, distance_between_point_and_segment(s0.b, s1));\n chmin(ret, distance_between_point_and_segment(s1.a, s0));\n chmin(ret, distance_between_point_and_segment(s1.b, s0));\n return ret;\n}\n\nusing Polygon = vector<Point>;\n\ndouble area(const Polygon& g) {\n int n = g.size();\n double ret = 0.0;\n rep(i, n) ret += cross(g[i], g[(i + 1) % n]);\n ret /= 2.0;\n return ret;\n}\n\nbool is_convex(const Polygon& g) {\n int n = g.size();\n rep(i, n) {\n if (ccw(g[(i - 1 + n) % n], g[i], g[(i + 1) % n]) == CLOCKWISE)\n return false;\n }\n return true;\n}\n\nint polygon_point_containment(const Polygon& g, const Point& p) {\n bool is_contained = false;\n int n = g.size();\n rep(i, n) {\n Point a = g[i] - p, b = g[(i + 1) % n] - p;\n if (a.imag() > b.imag()) swap(a, b);\n if (a.imag() < eps && eps < b.imag() && cross(a, b) < -eps)\n is_contained = !is_contained;\n if (abs(cross(a, b)) < eps && dot(a, b) < eps) return 1;\n }\n return is_contained ? 2 : 0;\n}\n\nvi convex_hull(const Polygon& g) {\n int n = g.size();\n if (n == 0) return {};\n vi p_idx(n);\n iota(p_idx.begin(), p_idx.end(), 0);\n ranges::sort(p_idx, [&](int a, int b) {\n if (eps < abs(g[a].real() - g[b].real())) return g[a].real() < g[b].real();\n return g[a].imag() < g[b].imag() - eps;\n });\n vvi hull(2);\n rep(i, 2) {\n for (int idx : p_idx) {\n while (2 <= (int)hull[i].size() &&\n ccw(g[hull[i][(int)hull[i].size() - 2]], g[hull[i].back()],\n g[idx]) == CLOCKWISE) {\n hull[i].pop_back();\n }\n hull[i].emplace_back(idx);\n }\n hull[i].pop_back();\n ranges::reverse(p_idx);\n }\n ranges::copy(hull[1], back_inserter(hull[0]));\n return hull[0];\n}\n\ndouble convex_diameter(const Polygon& g) {\n int n = g.size();\n if (n <= 2) return 0.0;\n if (n == 2) return abs(g[0] - g[1]);\n int i = 0, j = 0;\n rep(k, n) {\n if (g[k].imag() < g[i].imag()) i = k;\n if (g[j].imag() < g[k].imag()) j = k;\n }\n double ret = 0.0;\n int i0 = i, j0 = j;\n do {\n chmax(ret, abs(g[i] - g[j]));\n if (cross(g[(i + 1) % n] - g[i], g[(j + 1) % n] - g[j]) < -eps)\n i = (i + 1) % n;\n else\n j = (j + 1) % n;\n } while (i != i0 || j != j0);\n return ret;\n}\n#line 6 \"a.cpp\"\nsigned main() {\n cin.tie(nullptr)->sync_with_stdio(false);\n int n;\n cin >> n;\n Polygon g(n);\n rep(i, n) {\n double x, y;\n cin >> x >> y;\n g[i] = Point(x, y);\n }\n cout << fixed << setprecision(20) << convex_diameter(g) << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4992, "score_of_the_acc": -0.196, "final_rank": 2 }, { "submission_id": "aoj_CGL_4_B_10894980", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n\n#define maxn 100010\n\n\nstruct Point{\n double x,y;\n bool operator <(Point p){\n if(x!=p.x)return x<p.x;\n return y<p.y;\n }\n};\ndouble tot;\nint n,k;\nPoint point[maxn];\nint s[maxn],top;\nvector<Point>p;\ndouble det(Point a1,Point a2,Point b1,Point b2){\n return (a2.x-a1.x)*(b2.y-b1.y)-(b2.x-b1.x)*(a2.y-a1.y);\n}\ndouble dis(Point a,Point b){\n return ((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));\n}\n\ndouble find(){\n if(k<2)return 0;\n else if(k<=2)return sqrt(dis(p[0],p[1]));\n p.push_back(p[0]);\n\n int j = 1;\n double maxd = 0.0;\n for(int i = 0;i<k;i++){\n while(det(p[i],p[i+1],p[i],p[j])<det(p[i],p[i+1],p[i],p[j+1])){\n j = (j+1)%k;\n }\n maxd = max({maxd,dis(p[i],p[j]),dis(p[i+1],p[j])});\n }\n return sqrt(maxd);\n}\n\n\nsigned main(){\n cin>>n;\n for(int i =1;i<=n;i++)cin>>point[i].x>>point[i].y;\n sort(point+1,point+1+n);\n \n s[++top]=1;\n for(int i = 2;i<=n;i++){\n while(top>1&&det(point[s[top-1]],point[s[top]],point[s[top]],point[i])<=0){\n s[top--]=0;\n }\n s[++top]=i;\n }\n for(int i =1;i<top;i++){\n tot+=dis(point[s[i]],point[s[i+1]]);\n p.push_back(point[s[i]]);\n }\n\n top=0;\n s[++top]=n;\n for(int i = n-1;i>=1;i--){\n while(top>1&&det(point[s[top-1]],point[s[top]],point[s[top]],point[i])<=0){\n s[top--]=0;\n }\n s[++top]=i;\n }\n for(int i =1;i<top;i++){\n tot+=dis(point[s[i]],point[s[i+1]]);\n p.push_back(point[s[i]]);\n }\n k=p.size();\n double ans = find();\n printf(\"%.10lf\\n\",ans);\n\n\n // printf(\"%.2lf\\n\",tot);\n\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4720, "score_of_the_acc": -0.8517, "final_rank": 15 }, { "submission_id": "aoj_CGL_4_B_10894977", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n\n#define maxn 100010\n\n\nstruct Point{\n double x,y;\n bool operator <(Point p){\n if(x!=p.x)return x<p.x;\n return y<p.y;\n }\n};\ndouble tot;\nint n,k;\nPoint point[maxn];\nint s[maxn],top;\nvector<Point>p;\ndouble det(Point a1,Point a2,Point b1,Point b2){\n return (a2.x-a1.x)*(b2.y-b1.y)-(b2.x-b1.x)*(a2.y-a1.y);\n}\ndouble dis(Point a,Point b){\n return ((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));\n}\n\ndouble find(){\n if(k<2)return 0;\n else if(k<=2)return sqrt(dis(p[0],p[1]));\n p.push_back(p[0]);\n\n int j = 1;\n double maxd = 0.0;\n for(int i = 0;i<k;i++){\n while(det(p[i],p[i+1],p[i],p[j])<det(p[i],p[i+1],p[i],p[j+1])){\n j = (j+1)%k;\n }\n maxd = max(maxd,dis(p[i],p[j]));\n maxd = max(maxd,dis(p[i+1],p[j]));\n }\n return sqrt(maxd);\n}\n\n\nsigned main(){\n cin>>n;\n for(int i =1;i<=n;i++)cin>>point[i].x>>point[i].y;\n sort(point+1,point+1+n);\n \n s[++top]=1;\n for(int i = 2;i<=n;i++){\n while(top>1&&det(point[s[top-1]],point[s[top]],point[s[top]],point[i])<=0){\n s[top--]=0;\n }\n s[++top]=i;\n }\n for(int i =1;i<top;i++){\n tot+=dis(point[s[i]],point[s[i+1]]);\n p.push_back(point[s[i]]);\n }\n\n top=0;\n s[++top]=n;\n for(int i = n-1;i>=1;i--){\n while(top>1&&det(point[s[top-1]],point[s[top]],point[s[top]],point[i])<=0){\n s[top--]=0;\n }\n s[++top]=i;\n }\n for(int i =1;i<top;i++){\n tot+=dis(point[s[i]],point[s[i+1]]);\n p.push_back(point[s[i]]);\n }\n k=p.size();\n double ans = find();\n printf(\"%.10lf\\n\",ans);\n\n\n // printf(\"%.2lf\\n\",tot);\n\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4708, "score_of_the_acc": -0.8512, "final_rank": 14 }, { "submission_id": "aoj_CGL_4_B_10854084", "code_snippet": "#include<bits/stdc++.h>\n#define siz(x) int((x).size())\n#define all(x) std::begin(x),std::end(x)\n#define fi first\n#define se second\nusing namespace std;\nusing unt=unsigned;\nusing loli=long long;\nusing lolu=unsigned long long;\nusing pii=pair<int,int>;\nmt19937_64 rng(random_device{}());\nconstexpr double eps=1e-8;\ntemplate<typename any>inline any sqr(const any &x){return x*x;}\ninline int get_op(double x){if(fabs(x)<eps)return 0;return x>0?1:-1;}\ndouble det(array<double,3>a0,array<double,3>a1,array<double,3>a2){\n\tdouble sum=0;\n\tsum+=a0[0]*a1[1]*a2[2];\n\tsum+=a1[0]*a2[1]*a0[2];\n\tsum+=a2[0]*a0[1]*a1[2];\n\tsum-=a0[2]*a1[1]*a2[0];\n\tsum-=a0[1]*a1[0]*a2[2];\n\tsum-=a0[0]*a1[2]*a2[1];\n\treturn sum;\n}\nstruct bector{\n\tdouble x,y;\n\tbool operator<(const bector&t)const{return fabs(x-t.x)<eps?y<t.y:x<t.x;}\n\tbool operator==(const bector&t)const{return fabs(x-t.x)<eps&&fabs(y-t.y)<eps;}\n\tbector(double a=0,double b=0):x(a),y(b){}\n\tdouble operator~()const{return sqrt(x*x+y*y);}\n\tdouble operator*()const{return x*x+y*y;}\n\tfriend istream&operator>>(istream&a,bector&b){return a>>b.x>>b.y;}\n\tfriend ostream&operator<<(ostream&a,const bector&b){return a<<b.x<<' '<<b.y;}\n\tfriend bector operator+(const bector&a,const bector&b){return {a.x+b.x,a.y+b.y};}\n\tbector&operator+=(const bector&t){x+=t.x,y+=t.y;return *this;}\n\tfriend bector operator-(const bector&a,const bector&b){return {a.x-b.x,a.y-b.y};}\n\tbector&operator-=(const bector&t){x-=t.x,y-=t.y;return *this;}\n\tfriend bector operator*(const bector&a,double b){return {a.x*b,a.y*b};}\n\tfriend bector operator*(double b,const bector&a){return {a.x*b,a.y*b};}\n\tbector&operator*=(double t){x*=t,y*=t;return *this;}\n\tfriend bector operator/(const bector&a,double b){return {a.x/b,a.y/b};}\n\tbector&operator/=(double t){x/=t,y/=t;return *this;}\n\tfriend double operator*(const bector&a,const bector&b){return a.x*b.x+a.y*b.y;}\n\tfriend double operator/(const bector&a,const bector&b){return a.x*b.y-a.y*b.x;}\n\tbool frontis(const bector&t)const{auto r=*this*t;return get_op(r)>0;}\n\tbool backis(const bector&t)const{auto r=*this*t;return get_op(r)<0;}\n\tbool leftis(const bector&t)const{auto r=*this/t;return get_op(r)>0;}\n\tbool rightis(const bector&t)const{auto r=*this/t;return get_op(r)<0;}\n\tfriend double dis(const bector&a,const bector&b){return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}\n\tbector rot90()const{return {-y,x};}\n\tdouble arg()const{return atan2(y,x);}\n\tbector rotate(const bector&a,double r){\n\t\tauto u=a-*this;\n\t\treturn *this+bector{u.x*cos(r)-u.y*sin(r),u.x*sin(r)+u.y*cos(r)};\n\t}\n\tfriend double c0s(const bector&x,const bector&y){\n\t\t// 求 cos<x,y>\n\t\treturn x*y/~x/~y;\n\t}\n\tbector unit()const{\n\t\treturn (*this)/~(*this);\n\t}\n\tfriend bool operator&(const bector&a,const bector&b){return !get_op(a*b);}\n\tfriend bool operator|(const bector&a,const bector&b){return !get_op(a/b);}\n\tfriend double triarea(const bector&x,const bector&y,const bector&z){\n\t\treturn (y-x)/(z-x)/2;\n\t}\n};\nbector polar(double p,double r){return {cos(r)*p,sin(r)*p};}\nstruct segment{\n\tbector p1,p2;\n\tsegment(const bector&a={0,0},const bector&b={0,0}):p1(a),p2(b){};\n\tfriend istream&operator>>(istream&a,segment &b){return a>>b.p1>>b.p2;}\n\tfriend ostream&operator<<(ostream&a,const segment&b){return a<<b.p1<<' '<<b.p2;}\n\tfriend bool operator&(const segment&a,const segment&b){return !get_op((a.p2-a.p1)*(b.p2-b.p1));}\n\tfriend bool operator|(const segment&a,const segment&b){return !get_op((a.p2-a.p1)/(b.p2-b.p1));}\n\tfriend bool banana(const segment&a,const segment&b){\n\t\t// 判断是否相交\n\t\tif(min(a.p1.x,a.p2.x)>max(b.p1.x,b.p2.x)||min(b.p1.x,b.p2.x)>max(a.p1.x,a.p2.x)||min(a.p1.y,a.p2.y)>max(b.p1.y,b.p2.y)||min(b.p1.y,b.p2.y)>max(a.p1.y,a.p2.y))return false;\n\t\treturn get_op(((a.p2-a.p1)/(b.p1-a.p1))*((a.p2-a.p1)/(b.p2-a.p1)))<=0&&get_op(((b.p2-b.p1)/(a.p1-b.p1))*((b.p2-b.p1)/(a.p2-b.p1)))<=0;\n\t}\n\tfriend bector focus(const segment&a,const segment&b){\n\t\t// 输入必须保证有交,输出交点\n\t\tbector v=a.p2-a.p1,w=b.p2-b.p1,u=a.p1-b.p1;\n\t\treturn a.p1+v*((w/u)/(v/w));\n\t}\n\tfriend double dis(const segment&a,const bector&b){\n\t\tif(a.p1==a.p2)return ~(b-a.p1);\n\t\tauto v1=a.p2-a.p1,v2=b-a.p1,v3=b-a.p2;\n\t\tif(v1.backis(v2))return ~v2;\n\t\tif(v1.frontis(v3))return ~v3;\n\t\treturn fabs(v1/v2)/~v1;\n\t}\n\tfriend double dis(const segment&a,const segment&b){\n\t\t// 求线段间最短距离\n\t\tif(banana(a,b))return 0;\n\t\treturn min({dis(a,b.p1),dis(a,b.p2),dis(b,a.p1),dis(b,a.p2)});\n\t}\n\tbector project(const bector&a)const{\n\t\t// 求点 a 在当前线段上的投影点坐标\n\t\tif(a==p1||a==p2)return a;\n\t\tauto u=p2-p1,v=a-p1;\n\t\treturn c0s(u,v)*(~v)*u.unit()+p1;\n\t}\n\tdouble pr0ject(const bector&a)const{\n\t\treturn dis(a,project(a));\n\t}\n\tbector reflect(const bector&a)const{\n\t\t// 求点 a 在当前线段上的对称点\n\t\treturn 2*project(a)-a;\n\t}\n\tsegment&sort(){if(p2<p1)std::swap(p1,p2);return *this;}\n};\nstruct circle{\n\tbector p;double r;\n\tcircle(const bector&a={0,0},double b=0):p(a),r(b){}\n\tcircle(bector p1,bector p2){\n\t\tp=(p1+p2)/2;\n\t\tr=dis(p1,p2)/2;\n\t}\n\tcircle(bector p1,bector p2,bector p3){\n\t\tp.x=det({*p1,p1.y,1},{*p2,p2.y,1},{*p3,p3.y,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tp.y=-det({*p1,p1.x,1},{*p2,p2.x,1},{*p3,p3.x,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tr=dis(p,p1);\n\t}\n\tfriend istream&operator>>(istream&a,circle &b){return a>>b.p>>b.r;}\n\tfriend ostream&operator<<(ostream&a,const circle &b){return a<<b.p<<' '<<b.r;}\n\tbool check(bector t){\n\t\treturn dis(p,t)-r<=eps;\n\t}\n\tfriend segment focus(const circle &a,const segment&b){\n\t\tauto d=b.project(a.p),u=b.p2-b.p1,e=u/~u;\n\t\tauto t=sqrt(a.r*a.r-sqr(dis(d,a.p)));\n\t\treturn segment{d+e*t,d-e*t}.sort();\n\t}\n\tfriend segment focus(const circle &a,const circle &b){\n\t\tauto d=dis(a.p,b.p),l=acos((sqr(a.r)+sqr(d)-sqr(b.r))/(2*a.r*d)),t=(b.p-a.p).arg();\n\t\treturn segment{a.p+polar(a.r,t+l),a.p+polar(a.r,t-l)}.sort();\n\t}\n\tsegment tangent(const bector&a){\n\t\tauto u=a-p;\n\t\tauto l=acos(r/~u);\n\t\tu=u*r/~u;\n\t\treturn segment{p.rotate(p+u,+l),p.rotate(p+u,-l)}.sort();\n\t}\n};\nstruct points:vector<bector>{\n#define p (*this)\n\tpoints&read(istream&t,int n=-1){\n\t\tif(n==-1)cin>>n;\n\t\tp.resize(n);\n\t\tfor(int i=0;i<n;i++)t>>p[i];\n\t\treturn *this;\n\t}\n\tdouble area()const{\n\t\t// 无需满足多边形是凸的\n\t\tdouble ans=0;\n\t\tfor(int i=1;i<siz(p)-1;i++)ans+=(p[i]-p[0])/(p[i+1]-p[0]);\n\t\treturn ans/2;\n\t}\n\tpoints tobag(){\n\t\tsort(all(p));\n\t\terase(unique(all(p)),end());\n\t\tpoints b;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\twhile(siz(b)>1&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<=0)\n\t\t\t// while(siz(b)>1&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<0)\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(p[i]);\n\t\t}\n\t\tint o=siz(b);\n\t\tfor(int i=siz(p)-2;~i;i--){\n\t\t\twhile(siz(b)>o&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<=0)\n\t\t\t// while(siz(b)>o&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<0)\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(p[i]);\n\t\t}\n\t\t// if(siz(p)>1)b.pop_back();\n\t\treturn b;\n\t}\n\tdouble xzqk()const{\n\t\tif(siz(p)==1)return 0;\n\t\tif(siz(p)==2)return dis(p[0],p[1]);\n\t\tif(siz(p)==3)return max({dis(p[0],p[1]),dis(p[0],p[2]),dis(p[1],p[2])});\n\t\tdouble ans=0;\n\t\tfor(int i=1,j=2;i<siz(p);i++){\n\t\t\twhile(get_op(triarea(p[i-1],p[i],p[j])-triarea(p[i-1],p[i],p[(j+1)%siz(p)]))<=0)\n\t\t\t\t(++j)%=siz(p);\n\t\t\tans=max({ans,dis(p[i-1],p[j]),dis(p[i],p[j])});\n\t\t}\n\t\treturn ans;\n\t}\n\t// double xzqk(){\n\t// \tdouble ans=0;\n\t// \tfor(size_t i=0,j=1;i<p.size();i++){\n\t// \t\twhile((p[(i+1)%p.size()]-p[i])/(p[j]-p[i])<(p[(i+1)%p.size()]-p[i])/(p[(j+1)%p.size()]-p[i]))(++j)%=p.size();\n\t// \t\tans=std::max({ans,dis(p[i],p[j]),dis(p[(i+1)%p.size()],p[j])});\n\t// \t}\n\t// \treturn ans;\n\t// }\n\t// double xzqk()const{\n\t// \tif(p.size()==2)\n\t// \t\treturn ~(p[0]-p[1]);\n\t// \tdouble ans=0;\n\t// \tfor(int i=1,j=2;i<(int)p.size();i++){\n\t// \t\twhile((triarea(p[i-1],p[i],p[j])<=\n\t// \t\t\ttriarea(p[i-1],p[i],p[(j+1)%siz(p)])))\n\t// \t\t\tj=(j+1)%siz(p);\n\t// \t\tans=max(ans,max(~(p[i-1]-p[j]),\n\t// \t\t\t~(p[i]-p[j])));\n\t// \t}\n\t// \treturn ans;\n\t// }\n\tcircle incircle(){\n\t\tassert(siz(p)==3);\n\t\tauto u=p[1]-p[0],v=p[2]-p[0];u=u/~u*~v;\n\t\tsegment l1{p[0],p[0]+u+v};\n\t\tu=p[2]-p[1],v=p[0]-p[1];u=u/~u*~v;\n\t\tsegment l2{p[1],p[1]+u+v};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(segment{p[0],p[1]},pp)};\n\t}\n\tcircle outcirce(){\n\t\tassert(siz(p)==3);\n\t\tauto u=p[1]-p[0],mid=(p[0]+p[1])/2;\n\t\tsegment l1{mid,mid+u.rot90()};\n\t\tu=p[2]-p[0],mid=(p[0]+p[2])/2;\n\t\tsegment l2{mid,mid+u.rot90()};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(p[0],pp)};\n\t}\n\tint contains(bector t){\n\t\t// 无需满足多边形是凸的\n\t\t// 2表示包含,1表示在边上,0表示在外面\n\t\tbool res=false;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tauto a=p[i]-t,b=p[(i+1)%siz(p)]-t;\n\t\t\tif(!a.leftis(b)&&!a.rightis(b)&&!a.frontis(b))return 1;\n\t\t\tif(a.y>b.y)std::swap(a,b);\n\t\t\tif(a.y<eps&&eps<b.y&&a.leftis(b))res=!res;\n\t\t}\n\t\treturn res?2:0;\n\t}\n#undef p\n};\ncircle mingenshin(points b){\n\tshuffle(all(b),rng);\n\tcircle ans;\n\tfor(int i=0;i<siz(b);i++)if(!ans.check(b[i])){\n\t\tans={b[i],0};\n\t\tfor(int j=0;j<i;j++)if(!ans.check(b[j])){\n\t\t\tans=circle(b[i],b[j]);\n\t\t\tfor(int k=0;k<j;k++)if(!ans.check(b[k])){\n\t\t\t\tans=circle(b[i],b[j],b[k]);\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\npoints a,b;\nsigned main(){\n//\tfreopen(\".in\",\"r\",stdin);\n//\tfreopen(\".out\",\"w\",stdout);\n\tstd::ios::sync_with_stdio(false);cin.tie(nullptr);\n\tcout<<std::setiosflags(std::ios::fixed)<<std::setprecision(10);\n\ta.read(cin);\n\tcout<<a.tobag().xzqk();\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 4268, "score_of_the_acc": -0.3333, "final_rank": 4 }, { "submission_id": "aoj_CGL_4_B_10850955", "code_snippet": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <iomanip>\n\n#define EPS 1e-10\n#define N 80001\n\nusing namespace std;\n\ntypedef double T;\n\nint n;\n\nclass POS{\npublic:\n\tT x, y;\n\tPOS(const T& x = 0, const T& y = 0) : x(x), y(y){}\n\tPOS(const POS& x) : x(x.x), y(x.y){}\n\t\n\tbool operator==(const POS& rhs) const{\n\t\treturn x == rhs.x && y == rhs.y;\n\t}\n\t\n\tT dist(const POS& rhs) const{\n\t\tT tmp_x = x - rhs.x, tmp_y = y - rhs.y;\n\t\treturn sqrt(tmp_x*tmp_x + tmp_y*tmp_y);\n\t}\n} p[N], h[N], EX[N << 1];\n\nbool cmp_convex(const POS& lhs, const POS& rhs){\n\treturn (lhs.x < rhs.x) || ((lhs.x == rhs.x)&&(lhs.y < rhs.y));\n}\n\nT cross(const POS& o, const POS& a, const POS& b){\n\tT value = (a.x - o.x)*(b.y - o.y) - (a.y - o.y)*(b.x - o.x);\n\tif(fabs(value) < EPS) return 0;\n\treturn value;\n}\n\nvoid convex_hull(POS* points, POS* need, int& n){\n\tsort(points, points + n, cmp_convex);\n\tint idx = 0;\n\tfor(int i = 0; i < n; i++){\n\t\twhile(idx >= 2 && cross(need[idx - 2], need[idx - 1], points[i]) <= 0)\n\t\t\tidx--;\n\t\tneed[idx++] = points[i];\n\t}\n\tint half_point = idx + 1;\n\tfor(int i = n - 2; i >= 0; i--){\n\t\twhile(idx >= half_point && cross(need[idx - 2], need[idx - 1], points[i]) <= 0)\n\t\t\tidx--;\n\t\tneed[idx++] = points[i];\n\t}\n\t\t\t\n\tn = idx;\n}\n\nint main(){\n\t\n\tT x, y, ans = 0;\n\t\n\tcin >> n;\n\t\n\tfor(int i = 0; i < n; i++){\n\t\tcin >> x >> y;\n\t\tp[i] = POS(x, y);\n\t}\n\t\n\tconvex_hull(p, h, n);\n\t\n\tfor(int i = 0; i < n; i++)\n\t\tEX[i] = h[i];\n\t\n\tfor(int i = 0; i < n ; i++){\n\t\tint L = i + 1, R = i + n;\n\t\twhile(L < R){\n\t\t\tint mid = (L + R) / 2;\n\t\t\tif(EX[i].dist(EX[mid]) > EX[i].dist(EX[mid + 1]))\n\t\t\t\tR = mid;\n\t\t\telse\n\t\t\t\tL = mid + 1;\n\t\t}\n\t\tans = max(ans, EX[i].dist(EX[L]));\n\t\tEX[n + i] = EX[i];\n\t}\n\t\t\n\tcout << fixed << setprecision(7) << ans << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 8516, "score_of_the_acc": -1.0057, "final_rank": 17 }, { "submission_id": "aoj_CGL_4_B_10847970", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vv<vec<T>>;\ntemplate <class T> using minpq = priority_queue<T, vector<T>, greater<T>>;\n#define rep(i, r) for(ll i = 0; i < (r); i++)\n#define reps(i, l, r) for(ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for(ll i = (r) - 1; i >= l; i--)\ntemplate <class T> void uniq(T &a) { sort(all(a)); erase(unique(all(a)), a.end()); }\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\nconst ll INF = numeric_limits<ll>::max() / 4;\nconst ld inf = numeric_limits<ld>::max() / 2;\nconst ll mod1 = 1000000007;\nconst ll mod2 = 998244353;\nconst ld pi = 3.141592653589793238;\ntemplate <class T> void rev(T &a) { reverse(all(a)); }\nll popcnt(ll a) { return __builtin_popcountll(a); }\ntemplate<typename T>\nbool chmax(T &a, const T& b) { return a < b ? a = b, true : false; }\ntemplate<typename T>\nbool chmin(T &a, const T& b) { return a > b ? a = b, true : false; }\nconst ll mod = mod1;\nstruct mint {\n\tll x;\n\tmint(ll y = 0) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}\n\tmint &operator+=(const mint &p) {\n\t\tif ((x += p.x) >= mod) x -= mod;\n\t\treturn *this;\n\t}\n\tmint &operator-=(const mint &p) {\n\t\tif ((x += mod - p.x) >= mod) x -= mod;\n\t\treturn *this;\n\t}\n\tmint &operator*=(const mint &p) {\n\t\tx = (ll)(1ll * x * p.x % mod);\n\t\treturn *this;\n\t}\n\tmint &operator/=(const mint &p) {\n\t\t*this *= p.inv();\n\t\treturn *this;\n\t}\n\tmint operator-() const { return mint(-x); }\n\tmint operator+(const mint &p) const { return mint(*this) += p; }\n\tmint operator-(const mint &p) const { return mint(*this) -= p; }\n\tmint operator*(const mint &p) const { return mint(*this) *= p; }\n\tmint operator/(const mint &p) const { return mint(*this) /= p; }\n\tbool operator==(const mint &p) const { return x == p.x; }\n\tbool operator!=(const mint &p) const { return x != p.x; }\n\tfriend ostream &operator<<(ostream &os, const mint &p) { return os << p.x; }\n\tfriend istream &operator>>(istream &is, mint &a) {\n\t\tll t; is >> t; a = mint(t); return (is);\n\t}\n\tmint inv() const { return pow(mod - 2); }\n\tmint pow(ll n) const {\n\t\tmint ret(1), mul(x);\n\t\twhile (n > 0) {\n\t\t\tif (n & 1) ret *= mul;\n\t\t\tmul *= mul;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn ret;\n\t}\n};\nvoid YesNo(bool t) {\n\tcout << (t ? \"Yes\" : \"No\") << endl;\n}\n#define EPS (1e-10)\n#define eq(a, b) (fabs((a) - (b)) < EPS)\nll sign(ld x) { return (x >= EPS) - (x <= -EPS); }\nclass Point {\n\ttypedef Point P;\npublic:\n\tld x, y;\n\n\tPoint(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}\n\n\tP operator+(Point p) const { return P(x + p.x, y + p.y); }\n\tP operator-(Point p) const { return P(x - p.x, y - p.y); }\n\tP operator*(ld a) const { return P(a * x, a * y); }\n\tP operator/(ld a) const { return P(x / a, y / a); }\n\n\tld abs() const { return sqrtl(norm()); }\n\tld norm() const { return x * x + y * y; }\n\n\tbool operator<(const P& p) const { return tie(x, y) < tie(p.x, p.y); }\n\tbool operator==(const P& p) const { return eq(x, p.x) && eq(y, p.y); }\n\tld dot(P p) const { return x * p.x + y * p.y; }\n\tld cross(P p) const { return x * p.y - y * p.x; }\n\tld cross(P a, P b) const { return (a-*this).cross(b-*this); }\n\tld angle() const { return atan2(y, x); }\n\tP unit() const { return *this / abs(); }\n\tP perp() const { return P(-y, x); }\n\tP normal() const { return perp()/abs(); }\n\tP rotate(ld theta) const {\n\t\treturn P(x*cosl(theta)-y*sinl(theta), x*sinl(theta)+y*cosl(theta));\n\t}\n\tP rotate(ld theta, Point &p) const {\n\t\treturn (*this - p).rotate(theta) + p;\n\t}\n};\ntypedef Point Vector;\nstruct Segment {\n\tPoint s;\n\tPoint e;\n};\ntypedef Segment Line;\nclass Circle {\npublic:\n\tPoint c;\n\tld r;\n\tCircle(Point c = Point(), ld r = 0.0) : c(c), r(r) {}\n};\ntypedef vector<Point> Polygon;\nPolygon convex_hull(Polygon &p, bool strict = true) {\n\tsort(all(p));\n\tp.erase(unique(all(p)), p.end());\n\tll n = sz(p), k = 0;\n\tif (n <= 2) return p;\n\tvec<Point> ch(2 * n);\n\tauto check = [&](ll i) {\n\t\tPoint a = ch[k - 1] - ch[k - 2], b = p[i] - ch[k - 1];\n\t\tif (strict) {\n\t\t\treturn a.cross(b) <= EPS;\n\t\t}\n\t\telse {\n\t\t\treturn a.cross(b) <= -EPS;\n\t\t}\n\t};\n\tfor (ll i = 0; i < n; ch[k++] = p[i++]) {\n\t\twhile (k >= 2 && check(i)) --k;\n\t}\n\tfor (ll i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {\n\t\twhile (k >= t && check(i)) --k;\n\t}\n\tch.resize(k - 1);\n\treturn ch;\n}\npair<Point, Point> Diameter(Polygon S) {\n\tPolygon Q = convex_hull(S);\n\tll n = sz(Q), j = n < 2 ? 0 : 1;\n\tpair<ld, pair<Point, Point>> ans({(ld)0, {Q[0], Q[0]}});\n\trep(i, j) {\n\t\tfor (;; j = (j + 1) % n) {\n\t\t\tans = max(ans, {(Q[i] - Q[j]).abs(), {Q[i], Q[j]}});\n\t\t\tif ((Q[(j + 1) % n] - Q[j]).cross(Q[i + 1] - Q[i]) > -EPS) break;\n\t\t}\n\t}\n\treturn ans.second;\n}\nvoid solve() {\n\tll n; cin >> n;\n\tPolygon g(n);\n\trep(i, n) cin >> g[i].x >> g[i].y;\n\tauto res = Diameter(g);\n\tcout << fixed << setprecision(12) << (res.second - res.first).abs() << endl;\n}\nint main() {\n\tll T = 1;\n\t// cin >> T;\n\twhile (T--) solve();\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 13272, "score_of_the_acc": -1.3654, "final_rank": 19 }, { "submission_id": "aoj_CGL_4_B_10847966", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vv<vec<T>>;\ntemplate <class T> using minpq = priority_queue<T, vector<T>, greater<T>>;\n#define rep(i, r) for(ll i = 0; i < (r); i++)\n#define reps(i, l, r) for(ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for(ll i = (r) - 1; i >= l; i--)\ntemplate <class T> void uniq(T &a) { sort(all(a)); erase(unique(all(a)), a.end()); }\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\nconst ll INF = numeric_limits<ll>::max() / 4;\nconst ld inf = numeric_limits<ld>::max() / 2;\nconst ll mod1 = 1000000007;\nconst ll mod2 = 998244353;\nconst ld pi = 3.141592653589793238;\ntemplate <class T> void rev(T &a) { reverse(all(a)); }\nll popcnt(ll a) { return __builtin_popcountll(a); }\ntemplate<typename T>\nbool chmax(T &a, const T& b) { return a < b ? a = b, true : false; }\ntemplate<typename T>\nbool chmin(T &a, const T& b) { return a > b ? a = b, true : false; }\nconst ll mod = mod1;\nstruct mint {\n\tll x;\n\tmint(ll y = 0) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}\n\tmint &operator+=(const mint &p) {\n\t\tif ((x += p.x) >= mod) x -= mod;\n\t\treturn *this;\n\t}\n\tmint &operator-=(const mint &p) {\n\t\tif ((x += mod - p.x) >= mod) x -= mod;\n\t\treturn *this;\n\t}\n\tmint &operator*=(const mint &p) {\n\t\tx = (ll)(1ll * x * p.x % mod);\n\t\treturn *this;\n\t}\n\tmint &operator/=(const mint &p) {\n\t\t*this *= p.inv();\n\t\treturn *this;\n\t}\n\tmint operator-() const { return mint(-x); }\n\tmint operator+(const mint &p) const { return mint(*this) += p; }\n\tmint operator-(const mint &p) const { return mint(*this) -= p; }\n\tmint operator*(const mint &p) const { return mint(*this) *= p; }\n\tmint operator/(const mint &p) const { return mint(*this) /= p; }\n\tbool operator==(const mint &p) const { return x == p.x; }\n\tbool operator!=(const mint &p) const { return x != p.x; }\n\tfriend ostream &operator<<(ostream &os, const mint &p) { return os << p.x; }\n\tfriend istream &operator>>(istream &is, mint &a) {\n\t\tll t; is >> t; a = mint(t); return (is);\n\t}\n\tmint inv() const { return pow(mod - 2); }\n\tmint pow(ll n) const {\n\t\tmint ret(1), mul(x);\n\t\twhile (n > 0) {\n\t\t\tif (n & 1) ret *= mul;\n\t\t\tmul *= mul;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn ret;\n\t}\n};\nvoid YesNo(bool t) {\n\tcout << (t ? \"Yes\" : \"No\") << endl;\n}\n#define EPS (1e-10)\n#define eq(a, b) (fabs((a) - (b)) < EPS)\nll sign(ld x) { return (x >= EPS) - (x <= -EPS); }\nclass Point {\n\ttypedef Point P;\npublic:\n\tld x, y;\n\n\tPoint(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}\n\n\tP operator+(Point p) const { return P(x + p.x, y + p.y); }\n\tP operator-(Point p) const { return P(x - p.x, y - p.y); }\n\tP operator*(ld a) const { return P(a * x, a * y); }\n\tP operator/(ld a) const { return P(x / a, y / a); }\n\n\tld abs() const { return sqrtl(norm()); }\n\tld norm() const { return x * x + y * y; }\n\n\tbool operator<(const P& p) const { return tie(x, y) < tie(p.x, p.y); }\n\tbool operator==(const P& p) const { return eq(x, p.x) && eq(y, p.y); }\n\tld dot(P p) const { return x * p.x + y * p.y; }\n\tld cross(P p) const { return x * p.y - y * p.x; }\n\tld cross(P a, P b) const { return (a-*this).cross(b-*this); }\n\tld angle() const { return atan2(y, x); }\n\tP unit() const { return *this / abs(); }\n\tP perp() const { return P(-y, x); }\n\tP normal() const { return perp()/abs(); }\n\tP rotate(ld theta) const {\n\t\treturn P(x*cosl(theta)-y*sinl(theta), x*sinl(theta)+y*cosl(theta));\n\t}\n\tP rotate(ld theta, Point &p) const {\n\t\treturn (*this - p).rotate(theta) + p;\n\t}\n};\ntypedef Point Vector;\nstruct Segment {\n\tPoint s;\n\tPoint e;\n};\ntypedef Segment Line;\nclass Circle {\npublic:\n\tPoint c;\n\tld r;\n\tCircle(Point c = Point(), ld r = 0.0) : c(c), r(r) {}\n};\ntypedef vector<Point> Polygon;\nPolygon convex_hull(Polygon &p, bool strict = true) {\n\tsort(all(p));\n\tp.erase(unique(all(p)), p.end());\n\tll n = sz(p), k = 0;\n\tif (n <= 2) return p;\n\tvec<Point> ch(2 * n);\n\tauto check = [&](ll i) {\n\t\tPoint a = ch[k - 1] - ch[k - 2], b = p[i] - ch[k - 1];\n\t\tif (strict) {\n\t\t\treturn a.cross(b) <= EPS;\n\t\t}\n\t\telse {\n\t\t\treturn a.cross(b) <= -EPS;\n\t\t}\n\t};\n\tfor (ll i = 0; i < n; ch[k++] = p[i++]) {\n\t\twhile (k >= 2 && check(i)) --k;\n\t}\n\tfor (ll i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {\n\t\twhile (k >= t && check(i)) --k;\n\t}\n\tch.resize(k - 1);\n\treturn ch;\n}\npair<ld, pair<Point, Point>> Diameter(Polygon S) {\n\tPolygon Q = convex_hull(S, false);\n\tll n = sz(Q), j = n < 2 ? 0 : 1;\n\tpair<ld, pair<Point, Point>> ans({(ld)0, {Q[0], Q[0]}});\n\trep(i, j) {\n\t\tfor (;; j = (j + 1) % n) {\n\t\t\tans = max(ans, {(Q[i] - Q[j]).abs(), {Q[i], Q[j]}});\n\t\t\tif ((Q[(j + 1) % n] - Q[j]).cross(Q[i + 1] - Q[i]) > -EPS) break;\n\t\t}\n\t}\n\treturn ans;\n}\nvoid solve() {\n\tll n; cin >> n;\n\tPolygon g(n);\n\trep(i, n) cin >> g[i].x >> g[i].y;\n\tauto res = Diameter(g);\n\tcout << fixed << setprecision(10) << res.first << endl;\n}\nint main() {\n\tll T = 1;\n\t// cin >> T;\n\twhile (T--) solve();\n}", "accuracy": 0.7916666666666666, "time_ms": 10, "memory_kb": 4372, "score_of_the_acc": -0.0042, "final_rank": 20 }, { "submission_id": "aoj_CGL_4_B_10847751", "code_snippet": "#include<bits/stdc++.h>\n#include<unordered_set>\n#include<unordered_map>\n#include<array>\n#define int long long\n#define lowbit(x) (x&(-x))\n#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n#define endl '\\n'\nusing namespace std;\ntypedef pair<int, int>PII;\ntypedef long long ll;\nusing ull = unsigned long long;\nconst double EPS = 1e-9;\nconst int N = 2e5 + 5;\n//a.erase(unique(a.begin() + 1, a.end()), a.end()); 去重a(从1开始)\n//2^20=1048576(1e6),2^30=1073741824(1e9)\n// a / b % mod == a * [ b ^ (mod-2) ]\nstruct Point { double x;double y; }p[N];\nvector<Point>s(N + 1);\nint n; int cnt = 1;\ndouble dis(Point a, Point b) {//计算a,b两点间距离\n return sqrt(1.0 * (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\ndouble cross(Point a, Point b, Point c) {//如果 c 在 a->b 左边返回 >0,右边返回 <0,三点共线返回 0。\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\n}\ndouble check(Point a1, Point a2, Point b1, Point b2) {\n return (a2.x - a1.x) * (b2.y - b1.y) - (b2.x - b1.x) * (a2.y - a1.y);\n}\nbool cmp(Point p1, Point p2) {\n double t = check(p[1], p1, p[1], p2);\n if (t > EPS) return true;\n if (fabs(t) <= EPS) return dis(p[1], p1) < dis(p[1], p2);\n return false;\n}\ndouble rorating_calipers() {\n double res = 0;\n for (int i = 1, j = 2;i <= cnt;i++) {\n while (cross(s[i], s[i + 1], s[j]) < cross(s[i], s[i + 1], s[j + 1]))j = j % cnt + 1;\n res = max(res, max(dis(s[i], s[j]), dis(s[i + 1], s[j])));\n }\n return res;\n}\nvoid solve() {\n cin >> n;\n double temp;\n for (int i = 1;i <= n;i++) {\n cin >> p[i].x >> p[i].y;\n if (i != 1 && (p[i].y < p[1].y || (fabs(p[i].y - p[1].y) <= EPS && p[i].x < p[1].x))) {\n swap(p[i], p[1]);\n }\n }\n sort(p + 2, p + 1 + n, cmp);\n s[1] = p[1];\n for (int i = 2;i <= n;i++) {\n while (cnt > 1 && check(s[cnt - 1], s[cnt], s[cnt], p[i]) <= EPS) {\n cnt--;\n }\n cnt++;\n s[cnt] = p[i];\n }\n s[cnt + 1] = p[1];\n double ans2 = rorating_calipers();\n //cout << ans2 << endl;\n cout << fixed << setprecision(12) << ans2 << endl;\n}\nsigned main() {\n IOS;\n int t;\n //cin >> t;\n t = 1;\n while (t--) {\n solve();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 7524, "score_of_the_acc": -0.4655, "final_rank": 7 }, { "submission_id": "aoj_CGL_4_B_10842984", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nnamespace DBG\n{\n template <class T>\n void _dbg(const char *f, T t) { cerr << f << '=' << t << '\\n'; }\n template <class A, class... B>\n void _dbg(const char *f, A a, B... b)\n {\n while (*f != ',')\n cerr << *f++;\n cerr << '=' << a << \",\";\n _dbg(f + 1, b...);\n }\n template <typename Container>\n void _print(const char *f, const Container &v)\n {\n cerr << f << \" = [ \";\n for (const auto &x : v)\n cerr << x << \", \";\n cerr << \"]\\n\";\n }\n#define bug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n#define bugv(container) _print(#container, container)\n}\nusing namespace DBG;\n\nvoid _();\nint main()\n{\n ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n cout << fixed << setprecision(10);\n int T = 1;\n // cin >> T;\n while (T--)\n _();\n return 0;\n}\n\n#define int long long\n\nusing ld = long double;\nconst ld eps = 1e-9;\nconst ld PI = acos(-1);\n#define Pt Point<T>\n#define Pd Point<ld>\n#define Lt Line<T>\n#define Ld Line<ld>\n\nint sign(ld x) // 判符号\n{\n if (fabsl(x) < eps)\n return 0;\n else\n return x < 0 ? -1 : 1;\n}\nbool equal(ld x, ld y) { return !sign(x - y); } // 近似\nbool big(ld has, ld tar) { return sign(has - tar) > 0; }\n\n//////////////////////////////////////////////////////////////////////////// 点类\n\n// 点与向量\ntemplate <class T>\nstruct Point\n{\n T x, y;\n\n Point(T x = 0, T y = 0) : x(x), y(y) {} // 带参构造\n\n // 运算符重载\n Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }\n Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }\n Point operator*(T k) const { return Point(x * k, y * k); }\n Point operator/(T k) const { return Point(x / k, y / k); }\n\n friend bool operator<(Point a, Point b)\n {\n if (!equal(a.x, b.x))\n return a.x < b.x;\n return a.y < b.y;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return equal(a.x, b.x) && equal(a.y, b.y); } // 近似\n friend bool operator!=(Point a, Point b) { return !(a == b); }\n friend auto &operator>>(istream &is, Point &p) { return is >> p.x >> p.y; }\n friend auto &operator<<(ostream &os, Point p) { return os << \"(\" << p.x << \", \" << p.y << \")\"; }\n};\n\nld len(Point<ld> a) { return sqrtl(a.x * a.x + a.y * a.y); }; // 模长\nld dis(Point<ld> a, Point<ld> b) { return len(a - b); } // 两点距离\n\nld cross(Point<ld> a, Point<ld> b) { return a.x * b.y - a.y * b.x; } // 叉积 ab*sin 两点与原点三角形面积 判两点位置关系两侧\nld cross(Point<ld> p0, Point<ld> p1, Point<ld> p2) { return cross(p1 - p0, p2 - p0); }\nld dot(Point<ld> a, Point<ld> b) { return a.x * b.x + a.y * b.y; } // 点积 ab*cos 结合判两点象限位置关系\nld dot(Point<ld> p0, Point<ld> p1, Point<ld> p2) { return dot(p1 - p0, p2 - p0); }\nld angle(Point<ld> a, Point<ld> b) { return atan2(cross(a, b), dot(a, b)); } // 向量夹角[-pi, pi] 非负fabsl\n\nPoint<ld> standardize(Point<ld> h) // 转换为单位向量\n{\n ld l = len(h);\n if (sign(l) == 0)\n return {0, 0}; // 防止除零\n return h / l;\n}\nPd rotate(Pd p, ld rad) { return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)}; } // 向量旋转任意角度\n\nPd rotate90(Pd a) { return Point<ld>{-a.y, a.x}; } // 旋转90° 垂直向量\nld toDeg(ld x) { return x * 180 / PI; } // 弧度转角度\nld toArc(ld x) { return PI / 180 * x; } // 角度转弧度\nld angle(ld a, ld b, ld c) { return acos((a * a + b * b - c * c) / (2.0 * a * b)); } // 余弦定理 三边求角C弧度\n\n//////////////////////////////////////////////////////////////////////// 直线与线段\n\n// 直线\ntemplate <class T>\nstruct Line\n{\n Point<T> a, b;\n Line(Pt a_ = {}, Pt b_ = {}) : a(a_), b(b_) {}\n friend auto &operator<<(ostream &os, Line l) { return os << \"<\" << l.a << \", \" << l.b << \">\"; }\n};\nbool pointOnLineLeft(Pd p, Ld l) { return cross(l.b - l.a, p - l.a) > 0; } // 点在直线左侧\nbool onLine(Pd a, Pd b, Pd c) { return sign(cross(a - b, c - b)) == 0; } // 点是否在直线上(三点是否共线)ok\nbool onLine(Pd p, Ld l) { return onLine(p, l.a, l.b); }\n// 线段:点是否在线段上 ok\nbool pointOnSegment(Pd p, Ld l) { return fabsl(cross(l.a - p, l.b - p)) < eps && dot(l.a - p, l.b - p) <= 0; }\nbool Parallel(Pd p1, Pd p2) { return equal(0, cross(p1, p2)); } // 平行 ok\nbool Orthogonal(Pd p1, Pd p2) { return equal(0, dot(p1, p2)); } // 垂直 ok\nLd midSegment(Ld l) { return {(l.a + l.b) / 2, (l.a + l.b) / 2 + rotate90(l.a - l.b)}; } // 线段的中垂线\n\nld disPointToLine(Pd p, Ld l, bool isSegment = false) // 点到直线/线段的最近距离 ok\n{\n ld len_ab = dis(l.a, l.b);\n if (sign(len_ab) == 0)\n return dis(p, l.a);\n if (!isSegment)\n {\n ld ans = cross(p, l.a, l.b);\n return fabsl(ans) / dis(l.a, l.b); // 面积除以底边长\n }\n else\n {\n if (dot(p - l.a, l.b - l.a) <= 0)\n return dis(p, l.a);\n if (dot(p - l.b, l.a - l.b) <= 0)\n return dis(p, l.b);\n ld ans = cross(p, l.a, l.b);\n return fabsl(ans) / dis(l.a, l.b);\n }\n}\n\nPd lineIntersection(Ld l1, Ld l2, bool seg1 = false, bool seg2 = false) // 两直线/线段相交交点 ok\n{\n ld det = cross(l1.b - l1.a, l2.b - l2.a);\n if (sign(det) == 0) // 1. 平行或共线\n {\n if (sign(cross(l2.a - l1.a, l1.b - l1.a)) != 0) // 如果不共线 -> 平行\n return Pd(1e18, 1e18);\n\n if (pointOnSegment(l1.a, l2)) // 共线情况:检查端点是否重合/相连\n return l1.a;\n if (pointOnSegment(l1.b, l2))\n return l1.b;\n if (pointOnSegment(l2.a, l1))\n return l2.a;\n if (pointOnSegment(l2.b, l1))\n return l2.b;\n return Pd(1e18, 1e18); // 完全不相交\n }\n\n ld t = cross(l2.a - l1.a, l2.b - l2.a) / det; // 2. 一般情况,唯一交点 ✅\n Pd inter = l1.a + (l1.b - l1.a) * t;\n\n if ((seg1 && !pointOnSegment(inter, l1)) || (seg2 && !pointOnSegment(inter, l2)))\n return Pd(1e18, 1e18); // 不在线段上\n\n return inter;\n}\n\nPd project(Pd p, Ld l, bool isSegment = false) // 点在直线/线段上的投影点(垂足)ok\n{\n Pd h = l.b - l.a;\n ld r = dot(h, p - l.a) / (h.x * h.x + h.y * h.y);\n Pd pro = l.a + h * r;\n if (isSegment)\n {\n if (dot(pro - l.a, l.b - l.a) < 0)\n return l.a;\n if (dot(pro - l.b, l.a - l.b) < 0)\n return l.b;\n }\n return pro;\n}\n\n// ///////////////////////////////////////////////////////////////////////////////////////// 多边形\n\nusing Polygon = vector<Point<ld>>;\nld area(vector<Pd> P) // 任意多边形的面积 ok\n{\n int n = P.size();\n ld ans = 0;\n for (int i = 0; i < n; i++)\n {\n ans += cross(P[i], P[(i + 1) % n]);\n }\n return ans / 2.0;\n}\nint contains(Polygon g, Point<ld> p) // 点与多边形位置关系 内2 上1 外0 ok\n{\n int n = g.size();\n bool x = false;\n for (int i = 0; i < n; i++)\n {\n Point<ld> a = g[i] - p, b = g[(i + 1) % n] - p;\n if (abs(cross(a, b)) < eps && dot(a, b) < eps)\n return 1;\n if (a.y > b.y)\n swap(a, b);\n if (a.y < eps && eps < b.y && cross(a, b) > eps)\n x = !x;\n }\n return (x ? 2 : 0);\n}\nbool isConvexHull(Polygon p) // 是否为凸包 ok\n{\n int n = p.size();\n int same[2] = {};\n for (int i = 0; i < n; i++)\n {\n int l = (i + n - 1) % n, r = (i + 1) % n;\n if (sign(cross(p[l] - p[i], p[r] - p[i])) <= 0)\n same[0] = 1;\n else\n same[1] = 1;\n }\n return same[0] + same[1] < 2;\n}\n\nPolygon getHull(Polygon p) // 点集求凸包 <=不选共线点 <选共线点\n{\n Polygon h, l;\n sort(p.begin(), p.end());\n p.erase(unique(p.begin(), p.end()), p.end());\n if (p.size() <= 1)\n return p;\n for (auto a : p)\n {\n while (h.size() > 1 && cross(a - h.back(), a - h[h.size() - 2]) <= 0) //\n h.pop_back();\n while (l.size() > 1 && cross(a - l.back(), a - l[l.size() - 2]) >= 0) //\n l.pop_back();\n l.push_back(a);\n h.push_back(a);\n }\n l.pop_back();\n reverse(h.begin(), h.end());\n h.pop_back();\n l.insert(l.end(), h.begin(), h.end());\n return l;\n}\n\nPolygon sortConvexHullCCW(Polygon h) // 将凸包点集按逆时针排序,从y最小(y相同则x最小)的点开始\n{\n reverse(h.begin() + 1, h.end());\n int pos = 0;\n for (int i = 0; i < h.size(); i++)\n {\n if (h[i].y < h[pos].y)\n pos = i;\n else if (h[i].y == h[pos].y)\n {\n if (h[i].x < h[pos].x)\n pos = i;\n }\n }\n rotate(h.begin(), h.begin() + pos, h.end());\n return h;\n}\n\nld diameter(Polygon h) // 旋转卡壳求凸包直径\n{\n auto poly = h;\n if (poly.size() == 1)\n return 0;\n if (poly.size() == 2)\n return len(poly[1] - poly[0]);\n if (poly.size() == 3)\n return max({len(poly[1] - poly[0]), len(poly[2] - poly[1]), len(poly[0] - poly[2])});\n\n size_t cur = 0;\n ld ans = 0;\n for (size_t i = 0; i < poly.size(); i++)\n {\n size_t j = (i + 1) % poly.size();\n Line<ld> line(poly[i], poly[j]);\n while (disPointToLine(poly[cur], line) <= disPointToLine(poly[(cur + 1) % poly.size()], line))\n {\n cur = (cur + 1) % poly.size();\n }\n ans = max(ans, max(len(poly[i] - poly[cur]), len(poly[j] - poly[cur])));\n }\n return ans;\n}\nvoid _()\n{\n int n;\n cin >> n;\n vector<Pd> h(n);\n for (auto &v : h)\n cin >> v;\n\n // bug(h.size());\n h = getHull(h);\n // bug(h.size());\n // bugv(h);\n ld ans = diameter(h);\n\n cout << ans << '\\n';\n // cout << (int)round(ans * ans) << '\\n';\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8164, "score_of_the_acc": -0.6581, "final_rank": 10 }, { "submission_id": "aoj_CGL_4_B_10842630", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nconst double eps = 1e-10;\nconst int N = 800010;\nint sgn(double x)\n{\n if (x < -eps) return -1;\n if (x > eps) return 1;\n return 0;\n}\nstruct Vector\n{\n double x, y;\n Vector(double x = 0, double y = 0) : x(x), y(y) {}\n Vector operator + (Vector v) { return Vector(x + v.x, y + v.y); }\n Vector operator - (Vector v) { return Vector(x - v.x, y - v.y); }\n bool operator == (Vector v) { return x == v.x && y == v.y; }\n};\ndouble distance(Vector A, Vector B) { return sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y)); }\ndouble cross(Vector A, Vector B) { return A.x * B.y - A.y * B.x; }\nint n, m;\nVector p[N], ch[N];\nint ConvexHull(Vector* p, int n, Vector* ch)\n{\n n = unique(p, p + n) - p;\n sort(p, p + n, [](const Vector& A, const Vector& B) {\n return sgn(A.x - B.x) < 0 || sgn(A.x - B.x) == 0 && sgn(A.y - B.y) < 0;\n });\n int m = 1;\n ch[0] = p[0];\n for (int i = 1; i < n; i++)\n {\n while (m > 1 && sgn(cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 1])) <= 0)\n m--;\n ch[m++] = p[i];\n }\n int k = m;\n for (int i = n - 2; ~i; i--)\n {\n while (m > k && sgn(cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 1])) <= 0)\n m--;\n ch[m++] = p[i];\n }\n if (n > 1) m--;\n return m;\n}\ndouble ch_d(int m)\n{\n if (m < 3) return distance(ch[0], ch[1]);\n double d = 0;\n for (int i = 0, j = 2; i < m; i++)\n {\n Vector& A = ch[i], & B = ch[(i + 1) % m];\n while (sgn(cross(A - ch[j], B - ch[j]) - cross(A - ch[(j + 1) % m], B - ch[(j + 1) % m])) <= 0)\n j = (j + 1) % m;\n d = max({ d, distance(A, ch[j]), distance(B, ch[j]) });\n }\n return d;\n}\nvoid solve()\n{\n ios::sync_with_stdio(0); cin.tie(0);\n cin >> n;\n for (int i = 0; i < n; i++)\n cin >> p[i].x >> p[i].y;\n int m = ConvexHull(p, n, ch);\n cout << fixed << setprecision(12) << ch_d(m) << endl;\n}\nint main()\n{\n ios::sync_with_stdio(0); cin.tie(0);\n solve();\n return 0; \n}", "accuracy": 1, "time_ms": 20, "memory_kb": 28912, "score_of_the_acc": -1.1667, "final_rank": 18 } ]
aoj_CGL_5_B_cpp
Minimum Enclosing Circle There are $N$ points on a two-dimensional plane. Find the smallest circle that encloses all of these points. Such a circle is called the Minimum Enclosing Circle. A Minimum Enclosing Circle can be efficiently found using an algorithm based on the following properties. Let the sequence of $N$ points be $p_0, p_1, ..., p_{N-1}$, and let $P_i = \{p_0, p_1, ..., p_i\}$. Let $D_i$ be the minimum enclosing circle of $P_i$. For $1 < i < N$, the following holds: If $p_i$ is contained in $D_{i-1}$, then $D_i = D_{i-1}$. If $p_i$ is not contained in $D_{i-1}$, then $p_i$ lies on the boundary of $D_i$. Input The input is given in the following format. $N$ $x_0$ $y_0$ $x_1$ $y_1$ : $x_{N-1}$ $y_{N-1}$ The first line contains the number of points $N$. For the next $N$ lines, the coordinates of the $i$-th point are given as two integers $x_i$ and $y_i$. Output Output the smallest circle in the following format. $cx$ $cy$ $r$ Output the center coordinates $(cx, cy)$ of the circle and its radius $r$ on a single line, separated by spaces. The output values should be in a decimal fraction with an error less than 0.000001. Constraints $2 \leq N \leq 100000$ $-1000000 \leq x_i, y_i \leq 1000000$ No two given points have the same coordinates. Sample Input and Output Sample Input 1 5 0 0 0 3 4 0 3 2 2 4 Sample Output 1 2.00000000 1.50000000 2.50000000 Sample Input 2 3 0 0 1 1 2 2 Sample Output 2 1.00000000 1.00000000 1.41421356
[ { "submission_id": "aoj_CGL_5_B_11065578", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define pii pair<int, int>\n#define pll pair<ll, ll>\n#define vi vector<int>\n#define vl vector<ll>\n#define ov4(a, b, c, d, name, ...) name\n#define rep3(i, a, b, c) for(ll i = (a); i < (b); i += (c))\n#define rep2(i, a, b) rep3(i, a, b, 1)\n#define rep1(i, n) rep2(i, 0, n)\n#define rep0(n) rep1(aaaaa, n)\n#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)\n#define per(i, a, b) for(ll i = (a)-1; i >= (b); i--)\n#define fore(e, v) for(auto&& e : v)\n#define all(a) begin(a), end(a)\n#define si(a) (int)(size(a))\n#define lb(v, x) (lower_bound(all(v), x) - begin(v))\n#define eb emplace_back\n\ntemplate<typename T, typename S> bool chmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; }\ntemplate<typename T, typename S> bool chmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; }\n\nconst int INF = 1e9 + 100;\nconst ll INFL = 3e18 + 100;\n\n#define i128 __int128_t\n\nstruct _ {\n _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }\n} __;\n\ntemplate<class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n typedef Point P;\n T x, y;\n explicit Point(T x=0, T y=0) : x(x), y(y) {}\n bool operator<(P p) const { return tie(x, y) < tie(p.x, p.y); }\n bool operator==(P p) const { return tie(x, y) == tie(p.x, p.y); }\n P operator+(P p) const { return P(x + p.x, y + p.y); }\n P operator-(P p) const { return P(x - p.x, y - p.y); }\n P operator*(T d) const { return P(x * d, y * d); }\n P operator/(T d) const { return P(x / d, y / d); }\n T dot(P p) const { return x * p.x + y * p.y; }\n T cross(P p) const { return x * p.y - y * p.x; }\n T cross(P a, P b) const { return (a - *this).cross(b - *this); }\n T dist2() const { return x*x + y*y; }\n double dist() const { return sqrt((double)dist2()); }\n P perp() const { return P(-y, x); }\n};\n\ntypedef Point<double> P;\ndouble ccRadius(const P& A, const P& B, const P& C) {\n return (B - A).dist() * (C - B).dist() * (A - C).dist() / abs((B - A).cross(C - A)) / 2;\n}\n\nP ccCenter(const P& A, const P& B, const P& C) {\n P b = C - A, c = B - A;\n return A + (b * c.dist2() - c * b.dist2()).perp() / b.cross(c) / 2;\n}\n\npair<P, double> mec(vector<P> ps) {\n shuffle(all(ps), mt19937(time(0)));\n P o = ps[0];\n double r = 0, EPS = 1 + 1e-8;\n rep(i, si(ps)) if ((o - ps[i]).dist() > r * EPS) {\n o = ps[i], r = 0;\n rep(j, i) if ((o - ps[j]).dist() > r * EPS) {\n o = (ps[i] + ps[j]) / 2;\n r = (o - ps[i]).dist();\n rep(k, j) if ((o - ps[k]).dist() > r * EPS) {\n o = ccCenter(ps[i], ps[j], ps[k]);\n r = (o - ps[i]).dist();\n }\n }\n }\n return {o, r};\n}\n\nint main() {\n int n;\n cin >> n;\n vector<P> v;\n rep(i, n) {\n double x, y;\n cin >> x >> y;\n v.push_back(P(x, y));\n }\n\n cout << setprecision(20) << fixed;\n auto res = mec(v);\n cout << res.first.x << \" \" << res.first.y << \" \" << res.second << endl;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 7404, "score_of_the_acc": -0.1356, "final_rank": 4 }, { "submission_id": "aoj_CGL_5_B_11025056", "code_snippet": "// https://tubo28.me/compprog/algorithm/ より.\n\n#include <bits/stdc++.h>\n// #define int int64_t\n\n#define FOR(i, a, b) for (int i = (a); i < int(b); ++i)\n#define RFOR(i, a, b) for (int i = (b)-1; i >= int(a); --i)\n#define rep(i, n) FOR(i, 0, n)\n#define rep1(i, n) FOR(i, 1, int(n) + 1)\n#define rrep(i, n) RFOR(i, 0, n)\n#define rrep1(i, n) RFOR(i, 1, int(n) + 1)\n#define all(c) begin(c), end(c)\nnamespace io {\n#ifdef LOCAL\n#define dump(...) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #__VA_ARGS__ << \" = \"; \\\n io::print_to(os, \", \", \"\\n\", __VA_ARGS__); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dump_(cntnr) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #cntnr << \" = [\"; \\\n io::print_to_(os, \", \", \"]\\n\", all(cntnr)); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dumpf(fmt, ...) \\\n do { \\\n const int N = 4096; \\\n auto b = new char[N]; \\\n int l = snprintf(b, N, \"%d:\\t\", __LINE__); \\\n snprintf(b + l, N - l, fmt, ##__VA_ARGS__); \\\n std::cerr << io::highlight(b) << std::endl; \\\n delete[] b; \\\n } while (0)\n#else\n#define dump(...)\n#define dump_(...)\n#define dumpf(...)\n#endif\nstd::string highlight(std::string s) {\n#ifdef _MSC_VER\n return s;\n#else\n return \"\\033[33m\" + s + \"\\033[0m\";\n#endif\n}\ntemplate <typename T>\nvoid print_to(std::ostream &os, std::string, std::string tail, const T &first) {\n os << first << tail;\n}\ntemplate <typename F, typename... R>\nvoid print_to(std::ostream &os, std::string del, std::string tail, const F &first,\n const R &... rest) {\n os << first << del;\n print_to(os, del, tail, rest...);\n}\ntemplate <typename I>\nvoid print_to_(std::ostream &os, std::string del, std::string tail, I begin, I end) {\n for (I it = begin; it != end;) {\n os << *it;\n os << (++it != end ? del : tail);\n }\n}\ntemplate <typename F, typename... R>\nvoid println(const F &first, const R &... rest) {\n print_to(std::cout, \"\\n\", \"\\n\", first, rest...);\n}\ntemplate <typename F, typename... R>\nvoid print(const F &first, const R &... rest) {\n print_to(std::cout, \" \", \"\\n\", first, rest...);\n}\ntemplate <typename I>\nvoid println_(I begin, I end) {\n print_to_(std::cout, \"\\n\", \"\\n\", begin, end);\n}\ntemplate <typename I>\nvoid print_(I begin, I end) {\n print_to_(std::cout, \" \", \"\\n\", begin, end);\n}\ntemplate <typename C>\nvoid println_(const C &cntnr) {\n println_(std::begin(cntnr), std::end(cntnr));\n}\ntemplate <typename C>\nvoid print_(const C &cntnr) {\n print_(std::begin(cntnr), std::end(cntnr));\n}\nint _ = (\n#ifndef LOCAL\n std::cin.tie(nullptr), std::ios::sync_with_stdio(false),\n#endif\n std::cout.precision(10), std::cout.setf(std::ios::fixed));\n}\nusing io::print;\nusing io::println;\nusing io::println_;\nusing io::print_;\ntemplate <typename T>\nusing vec = std::vector<T>;\nusing vi = vec<int>;\nusing vvi = vec<vi>;\nusing pii = std::pair<int, int>;\nusing ll = long long;\nusing ld = long double;\nusing namespace std;\n// const int MOD = 1000000007;\n\n\n\n\nusing ld = long double;\nusing P = std::complex<ld>;\nusing G = std::vector<P>;\nconst ld pi = std::acos(-1);\nconst ld eps = 1e-10;\nconst ld inf = 1e12;\n\nld cross(const P &a, const P &b) { return a.real() * b.imag() - a.imag() * b.real(); }\nld dot(const P &a, const P &b) { return a.real() * b.real() + a.imag() * b.imag(); }\n\n/*\n CCW\n\n -- BEHIND -- [a -- ON -- b] --- FRONT --\n\n CW\n */\nenum CCW_RESULT { CCW = +1, CW = -1, BEHIND = +2, FRONT = -2, ON = 0 };\nint ccw(P a, P b, P c) {\n b -= a;\n c -= a;\n if (cross(b, c) > eps) return CCW; // counter clockwise\n if (cross(b, c) < -eps) return CW; // clockwise\n if (dot(b, c) < 0) return BEHIND; // c--a--b on line\n if (norm(b) < norm(c)) return FRONT; // a--b--c on line\n return ON;\n}\n\nnamespace std {\nbool operator<(const P &a, const P &b) {\n return std::abs(real(a) - real(b)) > eps ? real(a) < real(b) : imag(a) < imag(b);\n}\n}\n\nstruct L : public std::vector<P> {\n L(const P &a = P(), const P &b = P()) : std::vector<P>(2) {\n begin()[0] = a;\n begin()[1] = b;\n }\n\n // Ax + By + C = 0\n L(ld A, ld B, ld C) {\n if (std::abs(A) < eps && std::abs(B) < eps) {\n abort();\n } else if (std::abs(A) < eps) {\n *this = L(P(0, -C / B), P(1, -C / B));\n } else if (std::abs(B) < eps) {\n *this = L(P(-C / A, 0), P(-C / A, 1));\n } else {\n *this = L(P(0, -C / B), P(-C / A, 0));\n }\n }\n};\n\nstruct C {\n P p;\n ld r;\n C(const P &p = 0, ld r = 0) : p(p), r(r) {}\n};\n\n\n\n\nbool intersectLL(const L &l, const L &m) {\n return std::abs(cross(l[1] - l[0], m[1] - m[0])) > eps || // non-parallel\n std::abs(cross(l[1] - l[0], m[0] - l[0])) < eps; // same line\n}\nbool intersectLS(const L &l, const L &s) {\n return cross(l[1] - l[0], s[0] - l[0]) * // s[0] is left of l\n cross(l[1] - l[0], s[1] - l[0]) <\n eps; // s[1] is right of l\n}\nbool intersectLP(const L &l, const P &p) { return std::abs(cross(l[1] - p, l[0] - p)) < eps; }\nbool intersectSS(const L &s, const L &t) {\n return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 &&\n ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0;\n}\nbool intersectSP(const L &s, const P &p) {\n return std::abs(s[0] - p) + std::abs(s[1] - p) - std::abs(s[1] - s[0]) <\n eps; // triangle inequality\n}\n\nP projection(const L &l, const P &p) {\n ld t = dot(p - l[0], l[0] - l[1]) / norm(l[0] - l[1]);\n return l[0] + t * (l[0] - l[1]);\n}\nP reflection(const L &l, const P &p) { return p + (ld)2 * (projection(l, p) - p); }\nld distanceLP(const L &l, const P &p) { return std::abs(p - projection(l, p)); }\nld distanceLL(const L &l, const L &m) { return intersectLL(l, m) ? 0 : distanceLP(l, m[0]); }\nld distanceLS(const L &l, const L &s) {\n if (intersectLS(l, s)) return 0;\n return std::min(distanceLP(l, s[0]), distanceLP(l, s[1]));\n}\nld distanceSP(const L &s, const P &p) {\n const P r = projection(s, p);\n if (intersectSP(s, r)) return std::abs(r - p);\n return std::min(std::abs(s[0] - p), std::abs(s[1] - p));\n}\nld distanceSS(const L &s, const L &t) {\n if (intersectSS(s, t)) return 0;\n return std::min(std::min(distanceSP(s, t[0]), distanceSP(s, t[1])),\n std::min(distanceSP(t, s[0]), distanceSP(t, s[1])));\n}\nP crosspointLL(const L &l, const L &m) {\n ld A = cross(l[1] - l[0], m[1] - m[0]);\n ld B = cross(l[1] - l[0], l[1] - m[0]);\n if (std::abs(A) < eps && std::abs(B) < eps) return m[0]; // same line\n if (std::abs(A) < eps) assert(false); // !!!PRECONDITION NOT SATISFIED!!!\n return m[0] + B / A * (m[1] - m[0]);\n}\n\n\n// 符号付二倍面積 abs(area2(G pol))/2.0 で求められる.\n// polは頂点反時計回りで渡す\nld area2(const G& pol) {\n ld s = 0;\n int n = pol.size();\n for (int i = 0; i < n; ++i) s += cross(pol[i], pol[(i + 1) % n]);\n return s;\n}\n\n\n// 凸包\n// == CWを != CCWに置換すると 退化した角を除く.\nG andrewScan(G ps) {\n int N = ps.size(), k = 0;\n std::sort(ps.begin(), ps.end());\n G res(N * 2);\n for (int i = 0; i < N; i++) {\n while (k >= 2 && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n int t = k + 1;\n for (int i = N - 2; i >= 0; i--) {\n while (k >= t && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n res.resize(k - 1);\n return res;\n}\n//凸包終.\n\n\n/*\n// 凸多角形の直径\n// 最近点対と競合.\n#define curr(P, i) P[i]\n#define next(P, i) P[(i + 1) % P.size()]\n#define diff(P, i) (next(P, i) - curr(P, i))\nld convex_diameter(const G &pt) {\n const int n = pt.size();\n int is = 0, js = 0;\n for (int i = 1; i < n; ++i) {\n if (imag(pt[i]) > imag(pt[is])) is = i;\n if (imag(pt[i]) < imag(pt[js])) js = i;\n }\n ld maxd = norm(pt[is] - pt[js]);\n int i, maxi, j, maxj;\n i = maxi = is;\n j = maxj = js;\n do {\n if (cross(diff(pt, i), diff(pt, j)) >= 0)\n j = (j + 1) % n;\n else\n i = (i + 1) % n;\n if (norm(pt[i] - pt[j]) > maxd) {\n maxd = norm(pt[i] - pt[j]);\n maxi = i;\n maxj = j;\n }\n } while (i != is || j != js);\n return maxd; /* farthest pair is (maxi, maxj). */\n/*\n}\n*/\n\n//凸多角形の直径終.\n\n// 凸多角形の切断. (左側のみ)\n// 右側: lを逆に.\n//@require intersection.cc\nG convex_cut(const G& pol, const L& l) {\n G res;\n int n = pol.size();\n for (int i = 0; i < n; ++i) {\n P A = pol[i], B = pol[(i + 1) % n];\n if (ccw(l[0], l[1], A) != -1) res.push_back(A);\n if (ccw(l[0], l[1], A) * ccw(l[0], l[1], B) < 0) res.push_back(crosspointLL(L(A, B), l));\n }\n return res;\n}\n//凸多角形の切断終.\n\n// 最近点対.\n// O(N log N)\n// [半開区間)iter渡し, x座標昇順.\n// 凸多角形の直径と競合.\ntemplate <class iter>\nstd::tuple<ld, P, P> closest_pair(iter left, iter right) {\n int n = distance(left, right);\n\n if (n == 1) {\n return std::make_tuple(std::numeric_limits<ld>::max(), *left, *left);\n }\n\n if (n == 2) {\n if (left[0].imag() > left[1].imag()) swap(left[0], left[1]);\n return std::make_tuple(norm(left[0] - left[1]), left[0], left[1]);\n }\n\n iter middle = std::next(left, n / 2);\n ld x = middle->real();\n auto d = std::min(closest_pair(left, middle), closest_pair(middle, right));\n std::inplace_merge(left, middle, right,\n [](const P &a, const P &b) { return a.imag() < b.imag(); });\n\n std::vector<iter> around;\n for (iter i = left; i != right; ++i) {\n ld dx = fabs(i->real() - x);\n ld &opt = std::get<0>(d);\n if (dx * dx >= opt) continue;\n for (auto j = around.rbegin(); j != around.rend(); ++j) {\n ld dx = i->real() - (**j).real();\n ld dy = i->imag() - (**j).imag();\n if (dy * dy >= opt) break;\n ld norm = dx * dx + dy * dy;\n if (opt > norm) {\n d = std::make_tuple(norm, *i, **j);\n }\n }\n around.push_back(i);\n }\n return d;\n};\n\n// 最近点対 終.\n\n\n// 最小包含円.\n// 期待値 O(N).\n// [半開区間)iter渡し. seedは適当な整数or time(0).\ntemplate <class iter>\nstd::pair<P, ld> min_ball(iter left, iter right, int seed = 1333) {\n const int n = right - left;\n\n assert(n >= 1);\n if (n == 1) {\n return {*left, ld(0)};\n }\n\n std::mt19937 mt(seed);\n std::shuffle(left, right, mt);\n // std::random_shuffle(left, right); // simple but deprecated\n\n iter ps = left;\n using circle = std::pair<P, ld>;\n\n auto make_circle_3 = [](const P &a, const P &b, const P &c) -> circle {\n ld A = std::norm(b - c), B = std::norm(c - a), C = std::norm(a - b),\n S = cross(b - a, c - a);\n P p = (A * (B + C - A) * a + B * (C + A - B) * b + C * (A + B - C) * c) / (4 * S * S);\n ld r2 = std::norm(p - a);\n return {p, r2};\n };\n\n auto make_circle_2 = [](const P &a, const P &b) -> circle {\n P c = (a + b) / (ld)2;\n ld r2 = std::norm(a - c);\n return {c, r2};\n };\n\n auto in_circle = [](const P &a, const circle &c) -> bool {\n return std::norm(a - c.first) <= c.second + eps;\n };\n\n circle c = make_circle_2(ps[0], ps[1]);\n\n // MiniDisc\n for (int i = 2; i < n; ++i) {\n if (!in_circle(ps[i], c)) {\n // MiniDiscWithPoint\n c = make_circle_2(ps[0], ps[i]);\n for (int j = 1; j < i; ++j) {\n if (!in_circle(ps[j], c)) {\n // MiniDiscWith2Points\n c = make_circle_2(ps[i], ps[j]);\n for (int k = 0; k < j; ++k) {\n if (!in_circle(ps[k], c)) {\n c = make_circle_3(ps[i], ps[j], ps[k]);\n }\n }\n }\n }\n }\n }\n return c;\n}\n\n// P:点 point x: .real() y: .imag()\n// L:直線 lineF\n// S:線分 section\n// G:多角形 vector<P>\n\nsigned main() {\n int N;\n cin >> N;\n G g(N);\n rep(i, N){\n ld xi, yi;\n cin >> xi >> yi;\n g[i] = P(xi, yi);\n }\n cout << fixed << setprecision(10);\n sort(all(g));\n auto [o, rr] = min_ball(all(g), 1333);\n cout << o.real() << \" \" << o.imag() << \" \" << sqrt(rr) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 6232, "score_of_the_acc": -0.913, "final_rank": 17 }, { "submission_id": "aoj_CGL_5_B_11008120", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n#define print(s) cout << s;\n#define println(s) cout << s << endl;\n#define eps (1e-10)\n#define bigint 2000000000\n#define biglong 2000000000000000000L\n#define rep(i,s,n) for(int i=s;i<(int)(n);i++)\n#define sz(x) (int)(x).size()\n#define all(x) (x).begin(), (x).end()//いるらしい\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n\n\n//ーーー入出力\ntemplate<typename T>\nT next() {T a; cin >> a; return a;}\n\ntemplate<typename T>\nvector<T> arrayInput(int n) {\n vector<T> a(n);\n for (int i = 0; i < n; i++) cin >> a[i];\n return a;\n}\n\ntemplate<typename T>\nvector<vector<T>> arrayInput(int h, int w) {\n vector<vector<T>> a(h, vector<T>(w));\n for (int i = 0; i < h; i++)\n for (int j = 0; j < w; j++)\n cin >> a[i][j];\n return a;\n}\n\n\ntemplate <typename T>\nvoid arrayPrint(const vector<T>& vec, bool blank = true) {\n int n = vec.size();\n for (int i = 0; i < n; ++i) {\n cout << vec[i];\n if (blank && i != n - 1) cout << ' ';\n }\n cout << '\\n';\n}\nvoid arrayPrint(const vector<string>& vec, bool blank = false) {\n int n = vec.size();\n for (int i = 0; i < n; ++i) {\n cout << vec[i];\n if (blank && i != n - 1) cout << ' ';\n }\n cout << '\\n';\n}\nvoid arrayPrint(const vector<bool>& vec, bool blank = true) {\n int n = vec.size();\n for (int i = 0; i < n; ++i) {\n cout << (vec[i] ? 'T' : 'F');\n if (blank && i != n - 1) cout << ' ';\n }\n cout << '\\n';\n}\n\ntemplate <typename T>\nvoid arrayPrint(const vector<vector<T>>& mat, bool blank = true) {\n for (const auto& row : mat) {\n arrayPrint(row, blank);\n }\n}\nvoid arrayPrint(const vector<vector<string>>& mat, bool blank = false) {\n for (const auto& row : mat) {\n arrayPrint(row, blank);\n }\n}\n\nvoid arrayPrint(const vector<vector<bool>>& mat, bool blank = true) {\n for (const auto& row : mat) {\n arrayPrint(row, blank);\n }\n}\n\ntemplate <class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n typedef Point P;\n T x, y;\n explicit Point(T x=0, T y=0) : x(x), y(y) {}\n bool operator<(P p) const { return tie(x,y) < tie(p.x,p.y); }\n bool operator==(P p) const { return tie(x,y)==tie(p.x,p.y); }\n P operator+(P p) const { return P(x+p.x, y+p.y); }\n P operator-(P p) const { return P(x-p.x, y-p.y); }\n P operator*(T d) const { return P(x*d, y*d); }\n P operator/(T d) const { return P(x/d, y/d); }\n T dot(P p) const { return x*p.x + y*p.y; }\n T cross(P p) const { return x*p.y - y*p.x; }\n T cross(P a, P b) const { return (a-*this).cross(b-*this); }\n T dist2() const { return x*x + y*y; }\n double dist() const { return sqrt((double)dist2()); }\n // angle to x-axis in interval [-pi, pi]\n double angle() const { return atan2(y, x); }\n P unit() const { return *this/dist(); } // makes dist()=1\n P perp() const { return P(-y, x); } // rotates +90 degrees\n P normal() const { return perp().unit(); }\n // returns point rotated 'a' radians ccw around the origin\n P rotate(double a) const {\n return P(x*cos(a)-y*sin(a),x*sin(a)+y*cos(a)); }\n friend ostream& operator<<(ostream& os, P p) {\n return os << \"(\" << p.x << \",\" << p.y << \")\"; }\n};\ntypedef Point<ld> P;\ntemplate<class P>\npair<int, P> lineInter(P s1, P e1, P s2, P e2) {\n auto d = (e1 - s1).cross(e2 - s2);\n if (d == 0) // if parallel\n return {-(s1.cross(e1, s2) == 0), P(0, 0)};\n auto p = s2.cross(e1, e2), q = s2.cross(e2, s1);\n return {1, (s1 * p + e1 * q) / d};\n}\n\nvector<P> convexHull(vector<P> pts) {\n if (sz(pts) <= 1) return pts;\n sort(all(pts));\n vector<P> h(sz(pts)+1);\n int s = 0, t = 0;\n for (int it = 2; it--; s = --t, reverse(all(pts)))\n for (P p : pts) {\n while (t >= s + 2 && h[t-2].cross(h[t-1], p) <= 0) t--;\n h[t++] = p;\n }\n return {h.begin(), h.begin() + t - (t == 2 && h[0] == h[1])};\n}\n\n\n\n\nvector<P> polygonCut(const vector<P>& poly, P s, P e) {//左を切り落とす\n vector<P> res;\n rep(i,0,sz(poly)) {\n P cur = poly[i], prev = i ? poly[i-1] : poly.back();\n auto a = s.cross(e, cur), b = s.cross(e, prev);\n if ((a < 0) != (b < 0))\n res.push_back(cur + (prev - cur) * (a / (a - b)));\n if (a < 0)\n res.push_back(cur);\n }\n return res;\n}\ntemplate<class T>\nT polygonArea2(vector<Point<T>>& v) {\n T a = v.back().cross(v[0]);\n rep(i,0,sz(v)-1) a += v[i].cross(v[i+1]);\n return a;\n}\n\n\npair<P, P> closest(vector<P> v) {\n assert(sz(v) > 1);\n set<P> S;\n sort(all(v), [](P a, P b) { return a.y < b.y; });\n pair<ld, pair<P, P>> ret{(ld)LLONG_MAX, {P(), P()}};\n int j = 0;\n for (P p : v) {\n P d{1 + (ld)sqrt(ret.first), 0};\n while (v[j].y <= p.y - d.x) S.erase(v[j++]);\n auto lo = S.lower_bound(p - d), hi = S.upper_bound(p + d);\n for (; lo != hi; ++lo)\n ret = min(ret, {(*lo - p).dist2(), {*lo, p}});\n S.insert(p);\n }\n return ret.second;\n}\n\ndouble ccRadius(const P& A, const P& B, const P& C) {\n return (B-A).dist()*(C-B).dist()*(A-C).dist()/\n abs((B-A).cross(C-A))/2;\n}\nP ccCenter(const P& A, const P& B, const P& C) {\n P b = C-A, c = B-A;\n return A + (b*c.dist2()-c*b.dist2()).perp()/b.cross(c)/2;\n}\npair<P, ld> mec(vector<P> ps) {\n shuffle(all(ps), mt19937(time(0)));\n P o = ps[0];\n double r = 0, EPS = 1 + 1e-8;\n rep(i,0,sz(ps)) if ((o - ps[i]).dist() > r * EPS) {\n o = ps[i], r = 0;\n rep(j,0,i) if ((o - ps[j]).dist() > r * EPS) {\n o = (ps[i] + ps[j]) / 2;\n r = (o - ps[i]).dist();\n rep(k,0,j) if ((o - ps[k]).dist() > r * EPS) {\n o = ccCenter(ps[i], ps[j], ps[k]);\n r = (o - ps[i]).dist();\n }\n }\n }\n return {o, r};\n}\n\nint main() {\n cin.tie(0) -> sync_with_stdio(0);\n cin.exceptions(cin.failbit);\n cout << fixed << setprecision(10) << endl;\n int n; cin >> n;\n vector<P> pts(n);\n for (int i=0;i<n;i++) {\n ld x,y;\n cin >> x >> y;\n pts[i] = P(x,y);\n }\n auto ans = mec(pts);\n cout << ans.first.x << \" \" << ans.first.y << \" \" << ans.second << endl;\n\n\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 9416, "score_of_the_acc": -0.3982, "final_rank": 9 }, { "submission_id": "aoj_CGL_5_B_10995687", "code_snippet": "#include <bits/stdc++.h>\n\ntypedef long long int64;\n\ntypedef long double db;\n \nconst db eps=1e-8L,pi=std::acos(-1.0L);\n\nstruct point{\n \n db x,y;\n \n point():x(),y(){}\n point(db _x,db _y):x(_x),y(_y){}\n\n db &operator[](int p){return p?y:x;}\n const db &operator[](int p)const{return p?y:x;}\n\n friend point operator+(const point &a,const point &b){return point(a.x+b.x,a.y+b.y);}\n friend point operator-(const point &a,const point &b){return point(a.x-b.x,a.y-b.y);}\n friend point operator*(const point &a,const db &b){return point(a.x*b,a.y*b);}\n friend point operator*(const db &b,const point &a){return point(a.x*b,a.y*b);}\n friend point operator/(const point &a,const db &b){return point(a.x/b,a.y/b);}\n \n friend db operator*(const point &a,const point &b){return a.x*b.x+a.y*b.y;}\n friend db operator%(const point &a,const point &b){return a.x*b.y-a.y*b.x;}\n \n friend bool operator==(const point &a,const point &b){return std::abs(a.x-b.x)<=eps&&std::abs(a.y-b.y)<=eps;}\n friend bool operator!=(const point &a,const point &b){return std::abs(a.x-b.x)>eps||std::abs(a.y-b.y)>eps;}\n \n db mod2()const{return x*x+y*y;}\n db mod()const{return std::sqrt(x*x+y*y);}\n db dis2(const point &a)const{return (*this-a).mod2();}\n db dis(const point &a)const{return (*this-a).mod();}\n point unit()const{return *this/mod();}\n\n db ang()const{return std::atan2(y,x);}\n db ang(const point &a)const{return std::atan2(*this%a,*this*a);}\n point norm()const{return point(-y,x);}\n point rot(const db &th)const{db s=std::sin(th),c=std::cos(th);return point(x*c-y*s,x*s+y*c);}\n\n};\n\nstruct PolarAngleCmp{\n point o;\n PolarAngleCmp(const point &_o):o(_o){}\n bool operator()(const point &a,const point &b)const{\n db t=(a-o)%(b-o);\n return std::abs(t)<=eps?(a-o).mod2()<(b-o).mod2():t>eps;\n }\n};\n\nstruct PointPairCmp{\n bool operator()(const point &a,const point &b)const{\n return std::abs(a.y-b.y)<=eps?a.x<b.x:a.y<b.y;\n }\n};\n\nstruct line{\n \n point s,t;\n \n line():s(),t(){}\n line(point _s,point _t):s(_s),t(_t){}\n \n point &operator[](int p){return p?t:s;}\n const point &operator[](int p)const{return p?t:s;}\n\n db x(db y)const{return s.x+(y-s.y)/(t.y-s.y)*(t.x-s.x);}\n db y(db x)const{return s.y+(x-s.x)/(t.x-s.x)*(t.y-s.y);}\n \n point vec()const{return t-s;}\n db len2()const{return (t-s).mod2();}\n db len()const{return (t-s).mod();}\n\n point pro(const point &a)const{return s+(t-s)*((a-s)*(t-s)/(t-s).mod2());}\n point ref(const point &a)const{return 2*pro(a)-a;}\n db dis2(const point &a)const{return (pro(a)-a).mod2();}\n db dis(const point &a)const{return (pro(a)-a).mod();}\n\n // seg_in 不包括端点 seg_on 包括端点\n bool on(const point &a)const{return std::abs((a-s)%(a-t))<=eps;}\n bool seg_in(const point &a)const{return on(a)&&((a-s)*(a-t)<-eps);}\n bool seg_on(const point &a)const{return seg_in(a)||a==s||a==t;}\n\n // -1 重合 0 相交 1 平行\n int para(const line &b)const{\n const line &a=*this;\n return std::abs(a.vec()%b.vec())>eps?0:on(b.s)?-1:1;\n }\n\n // 包括端点\n int seg_cross(const line &b)const{\n const line &a=*this;\n if (std::max(a.s.x,a.t.x)+eps<std::min(b.s.x,b.t.x)) return 0;\n if (std::max(b.s.x,b.t.x)+eps<std::min(a.s.x,a.t.x)) return 0;\n if (std::max(a.s.y,a.t.y)+eps<std::min(b.s.y,b.t.y)) return 0;\n if (std::max(b.s.y,b.t.y)+eps<std::min(a.s.y,a.t.y)) return 0;\n auto sgn=[&](db x){return std::abs(x)<=eps?0:(x>0?1:-1);};\n if (sgn((a.s-b.s)%b.vec())*sgn((a.t-b.s)%b.vec())>0) return 0;\n if (sgn((b.s-a.s)%a.vec())*sgn((b.t-a.s)%a.vec())>0) return 0;\n return 1;\n }\n\n point cross(const line &b)const{\n const line &a=*this;\n point u=a.s-b.s,v=a.vec(),w=b.vec();\n return a.s+(w%u)/(v%w)*v;\n }\n \n};\n\ntypedef std::vector<point> polygon;\n\n// 1 在多边形内 0 不在多边形内 -1 在多边形边界上\nint InPolygon(const polygon &a,const point &b){\n int res=0;\n for (int i=0;i<(int)a.size();++i){\n point u=a[i],v=a[(i+1)%(int)a.size()];\n if (line(u,v).seg_on(b)) return -1;\n if (std::abs(u.y-v.y)<=eps) continue;\n if (u.y>v.y) std::swap(u,v);\n if ((b-u)%(v-u)>eps) continue;\n if (b.y>u.y+eps&&b.y<=v.y+eps) res^=1;\n }\n return res&1;\n}\n\n// 1 在多边形内 0 不在多边形内 -1 在多边形边界上\nint InConvex(const polygon &a,const point &b){\n if (b==a[0]) return -1;\n if ((a.back()-a[0])%(b-a[0])>eps) return 0;\n if (line(a.back(),a[0]).seg_on(b)) return -1;\n const point &o=a[0];\n int p=std::lower_bound(a.begin(),a.end()-1,b,PolarAngleCmp(o))-a.begin();\n if (line(a[p-1],a[p]).seg_on(b)) return -1;\n return (a[p]-a[p-1])%(b-a[p-1])>=-eps;\n}\n\npolygon ConvexHull(polygon a){\n point o=*std::min_element(a.begin(),a.end(),PointPairCmp());\n std::sort(a.begin(),a.end(),PolarAngleCmp(o));\n polygon res({a.front()});\n for (int i=1;i<(int)a.size();++i){\n for (;res.size()>=2&&(res.back()-res.end()[-2])%(a[i]-res.back())<=eps;res.pop_back());\n res.push_back(a[i]);\n }\n return res;\n}\n\ndb Diameter(polygon a){\n db res=0;\n int n=a.size();\n a.push_back(a[0]);\n for (int i=0,j=1;i<n;++i){\n for (;(a[i+1]-a[i])%(a[j]-a[i])<(a[i+1]-a[i])%(a[j+1]-a[i])-eps;j=(j+1)%n);\n res=std::max({res,(a[j]-a[i]).mod2(),(a[j]-a[i+1]).mod2()});\n }\n return std::sqrt(res);\n}\n\npolygon Minkowski(polygon a,polygon b){\n int n=a.size(),m=b.size();\n polygon res({a[0]+b[0]});\n a.push_back(a[0]);b.push_back(b[0]);\n for (int i=0,j=0;;){\n (a[i+1]-a[i])%(b[j+1]-b[j])>eps?i=(i+1)%n:j=(j+1)%m;\n point t=a[i]+b[j];\n if (res.size()>=2&&std::abs((t-res.back())%(res.back()-res.end()[-2]))<=eps)\n res.pop_back();\n res.push_back(t);\n if (!i&&!j) break;\n }\n res.pop_back();\n return res;\n}\n\n// 半平面在直线逆时针方向\npolygon HalfPlaneIntersection(std::vector<line> a){ // 半平面在直线逆时针方向\n const db inf=1e20L;\n a.emplace_back(point(-inf,-inf),point(inf,-inf));\n a.emplace_back(point(inf,-inf),point(inf,inf));\n a.emplace_back(point(inf,inf),point(-inf,inf));\n a.emplace_back(point(-inf,inf),point(-inf,-inf));\n std::sort(a.begin(),a.end(),[&](const line &a,const line &b){\n auto up=[&](const point &a){return a.y>eps||(std::abs(a.y)<=eps&&a.x>eps);};\n bool ua=up(a.vec()),ub=up(b.vec());\n if (ua!=ub) return ua<ub;\n db t=a.vec()%b.vec();\n if (std::abs(t)>eps) return t>eps;\n return (a[0]-b[0])%b.vec()<-eps;\n });\n std::deque<point> qc;\n std::deque<line> ql;\n ql.emplace_back(a[0]);\n auto popback=[&](const line &a){\n for (;!qc.empty()&&(qc.back()-a.s)%a.vec()>=-eps;)\n qc.pop_back(),ql.pop_back();\n };\n auto popfront=[&](const line &a){\n for (;!qc.empty()&&(qc.front()-a.s)%a.vec()>=-eps;)\n qc.pop_front(),ql.pop_front();\n };\n for (int i=1;i<(int)a.size();++i){\n if (a[i].vec()*a[i-1].vec()>=eps&&std::abs(a[i].vec()%a[i-1].vec())<=eps) continue;\n popback(a[i]);popfront(a[i]);\n if (!ql.empty()){\n if (std::abs(a[i].vec()%ql.back().vec())<=eps) return {};\n qc.push_back(a[i].cross(ql.back()));\n }\n ql.push_back(a[i]);\n }\n popback(ql.front());popfront(ql.back());\n qc.push_back(ql.front().cross(ql.back()));\n if (qc.size()<=2) return {};\n polygon res;\n for (auto t:qc) res.push_back(t);\n return res;\n}\n\nstruct circle{\n\n point o;\n db r;\n\n circle():o(),r(){}\n circle(point _o,db _r):o(_o),r(_r){}\n\n point operator()(db th)const{return o+r*point(std::cos(th),std::sin(th));}\n\n bool in(const point &a)const{return o.dis2(a)<=r*r+eps;}\n bool on(const point &a)const{return std::abs(o.dis2(a)-r*r)<=eps;}\n\n};\n\n// 外接圆,共线时是三点的最小圆覆盖\ncircle CircumCircle(point a,point b,point c){\n if (std::abs((a-b)%(b-c))<=eps){\n if (PointPairCmp()(a,b)) std::swap(a,b);\n if (PointPairCmp()(a,c)) std::swap(a,c);\n if (PointPairCmp()(b,c)) std::swap(b,c);\n return circle((a+c)/2,a.dis(c)/2);\n }\n point u=(a+b)/2,v=(a+c)/2;\n line p(u,u+(b-a).norm()),q(v,v+(c-a).norm());\n point o=p.cross(q);\n return circle(o,o.dis(a));\n}\n\n// 内切圆,共线时可能出错\ncircle InCircle(const point &a,const point &b,const point &c){\n line p(a,a+(b-a).unit()+(c-a).unit());\n line q(b,b+(a-b).unit()+(c-b).unit());\n point o=p.cross(q);\n return circle(o,line(a,b).dis(o));\n}\n\ncircle MinimumEnclosingCircle(polygon a){\n std::shuffle(a.begin(),a.end(),std::mt19937(time(0)));\n circle res(a[0],0);\n for (int i=1;i<(int)a.size();++i){\n if (res.in(a[i])) continue;\n res=circle(a[i],0);\n for (int j=0;j<i;++j){\n if (res.in(a[j])) continue;\n res=circle((a[i]+a[j])/2,(a[i]-a[j]).mod()/2);\n for (int k=0;k<j;++k){\n if (res.in(a[k])) continue;\n res=CircumCircle(a[i],a[j],a[k]);\n }\n }\n }\n return res;\n}\n\n\n\n\n\ndb Area(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=a[i]%a[(i+1)%(int)a.size()];\n assert(std::abs(res)>=-eps);\n return res/2;\n}\n\ndb Length(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=(a[i]-a[(i+1)%(int)a.size()]).mod();\n return res;\n}\n\nvoid work(){\n int n;\n std::cin>>n;\n polygon a(n);\n for (int i=0;i<n;++i) std::cin>>a[i].x>>a[i].y;\n auto c=MinimumEnclosingCircle(a);\n std::cout<<c.o.x<<' '<<c.o.y<<' ';\n std::cout<<c.r<<'\\n';\n\n // point a,b,c;\n // std::cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y;\n // circle ans=CircumCircle(a,b,c);\n // std::cout<<ans.o.x<<\" \"<<ans.o.y<<\" \"<<ans.r<<\"\\n\";\n}\n\nint main(){\n std::ios::sync_with_stdio(0);\n std::cin.tie(0);\n std::cout<<std::fixed<<std::setprecision(12);\n std::cerr<<std::fixed<<std::setprecision(2);\n int T=1;\n // std::cin>>T;\n for (;T--;) work();\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 9436, "score_of_the_acc": -0.3991, "final_rank": 10 }, { "submission_id": "aoj_CGL_5_B_10995181", "code_snippet": "#include <bits/stdc++.h>\n\ntypedef long long int64;\n\ntypedef long double db;\n \nconst db eps=1e-8L,pi=std::acos(-1.0L);\n\nstruct point{\n \n db x,y;\n \n point():x(),y(){}\n point(db _x,db _y):x(_x),y(_y){}\n\n db &operator[](int p){return p?y:x;}\n const db &operator[](int p)const{return p?y:x;}\n\n friend point operator+(const point &a,const point &b){return point(a.x+b.x,a.y+b.y);}\n friend point operator-(const point &a,const point &b){return point(a.x-b.x,a.y-b.y);}\n friend point operator*(const point &a,const db &b){return point(a.x*b,a.y*b);}\n friend point operator*(const db &b,const point &a){return point(a.x*b,a.y*b);}\n friend point operator/(const point &a,const db &b){return point(a.x/b,a.y/b);}\n \n friend db operator*(const point &a,const point &b){return a.x*b.x+a.y*b.y;}\n friend db operator%(const point &a,const point &b){return a.x*b.y-a.y*b.x;}\n \n friend bool operator==(const point &a,const point &b){return std::abs(a.x-b.x)<=eps&&std::abs(a.y-b.y)<=eps;}\n friend bool operator!=(const point &a,const point &b){return std::abs(a.x-b.x)>eps||std::abs(a.y-b.y)>eps;}\n \n db mod2()const{return x*x+y*y;}\n db mod()const{return std::sqrt(x*x+y*y);}\n db dis2(const point &a)const{return (*this-a).mod2();}\n db dis(const point &a)const{return (*this-a).mod();}\n point unit()const{return *this/mod();}\n\n db ang()const{return std::atan2(y,x);}\n db ang(const point &a)const{return std::atan2(*this%a,*this*a);}\n point norm()const{return point(-y,x);}\n point rot(const db &th)const{db s=std::sin(th),c=std::cos(th);return point(x*c-y*s,x*s+y*c);}\n\n};\n\nstruct PolarAngleCmp{\n point o;\n PolarAngleCmp(const point &_o):o(_o){}\n bool operator()(const point &a,const point &b)const{\n db t=(a-o)%(b-o);\n return std::abs(t)<=eps?(a-o).mod2()<(b-o).mod2():t>eps;\n }\n};\n\nstruct PointPairCmp{\n bool operator()(const point &a,const point &b)const{\n return std::abs(a.y-b.y)<=eps?a.x<b.x:a.y<b.y;\n }\n};\n\nstruct line{\n \n point s,t;\n \n line():s(),t(){}\n line(point _s,point _t):s(_s),t(_t){}\n \n point &operator[](int p){return p?t:s;}\n const point &operator[](int p)const{return p?t:s;}\n\n db x(db y)const{return s.x+(y-s.y)/(t.y-s.y)*(t.x-s.x);}\n db y(db x)const{return s.y+(x-s.x)/(t.x-s.x)*(t.y-s.y);}\n \n point vec()const{return t-s;}\n db len2()const{return (t-s).mod2();}\n db len()const{return (t-s).mod();}\n\n point pro(const point &a)const{return s+(t-s)*((a-s)*(t-s)/(t-s).mod2());}\n point ref(const point &a)const{return 2*pro(a)-a;}\n db dis2(const point &a)const{return (pro(a)-a).mod2();}\n db dis(const point &a)const{return (pro(a)-a).mod();}\n\n // seg_in 不包括端点 seg_on 包括端点\n bool on(const point &a)const{return std::abs((a-s)%(a-t))<=eps;}\n bool seg_in(const point &a)const{return on(a)&&((a-s)*(a-t)<-eps);}\n bool seg_on(const point &a)const{return seg_in(a)||a==s||a==t;}\n\n // -1 重合 0 相交 1 平行\n int para(const line &b)const{\n const line &a=*this;\n return std::abs(a.vec()%b.vec())>eps?0:on(b.s)?-1:1;\n }\n\n // 包括端点\n int seg_cross(const line &b)const{\n const line &a=*this;\n if (std::max(a.s.x,a.t.x)+eps<std::min(b.s.x,b.t.x)) return 0;\n if (std::max(b.s.x,b.t.x)+eps<std::min(a.s.x,a.t.x)) return 0;\n if (std::max(a.s.y,a.t.y)+eps<std::min(b.s.y,b.t.y)) return 0;\n if (std::max(b.s.y,b.t.y)+eps<std::min(a.s.y,a.t.y)) return 0;\n auto sgn=[&](db x){return std::abs(x)<=eps?0:(x>0?1:-1);};\n if (sgn((a.s-b.s)%b.vec())*sgn((a.t-b.s)%b.vec())>0) return 0;\n if (sgn((b.s-a.s)%a.vec())*sgn((b.t-a.s)%a.vec())>0) return 0;\n return 1;\n }\n\n point cross(const line &b)const{\n const line &a=*this;\n point u=a.s-b.s,v=a.vec(),w=b.vec();\n return a.s+(w%u)/(v%w)*v;\n }\n \n};\n\ntypedef std::vector<point> polygon;\n\n// 1 在多边形内 0 不在多边形内 -1 在多边形边界上\nint InPolygon(const polygon &a,const point &b){\n int res=0;\n for (int i=0;i<(int)a.size();++i){\n point p=a[i],q=a[(i+1)%(int)a.size()];\n if (line(p,q).seg_on(b)) return -1;\n if (std::abs(p.y-q.y)<=eps) continue;\n if (p.y>q.y) std::swap(p,q);\n if ((b-p)%(q-p)>eps) continue;\n if (b.y>p.y+eps&&b.y<=q.y+eps) res^=1;\n }\n return res&1;\n}\n\n// 1 在多边形内 0 不在多边形内 -1 在多边形边界上\nint InConvex(const polygon &a,const point &b){\n if (b==a[0]) return -1;\n if ((a.back()-a[0])%(b-a[0])>eps) return 0;\n if (line(a.back(),a[0]).seg_on(b)) return -1;\n const point &o=a[0];\n int p=std::lower_bound(a.begin(),a.end()-1,b,PolarAngleCmp(o))-a.begin();\n if (line(a[p-1],a[p]).seg_on(b)) return -1;\n return (a[p]-a[p-1])%(b-a[p-1])>=-eps;\n}\n\npolygon ConvexHull(polygon a){\n point o=*std::min_element(a.begin(),a.end(),PointPairCmp());\n std::sort(a.begin(),a.end(),PolarAngleCmp(o));\n polygon res({a.front()});\n for (int i=1;i<(int)a.size();++i){\n for (;res.size()>=2&&(res.back()-res.end()[-2])%(a[i]-res.back())<=eps;res.pop_back());\n res.push_back(a[i]);\n }\n return res;\n}\n\ndb Diameter(polygon a){\n db res=0;\n int n=a.size();\n a.push_back(a[0]);\n for (int i=0,j=1;i<n;++i){\n for (;(a[i+1]-a[i])%(a[j]-a[i])<(a[i+1]-a[i])%(a[j+1]-a[i])-eps;j=(j+1)%n);\n res=std::max({res,(a[j]-a[i]).mod2(),(a[j]-a[i+1]).mod2()});\n }\n return std::sqrt(res);\n}\n\npolygon Minkowski(polygon a,polygon b){\n int n=a.size(),m=b.size();\n polygon res({a[0]+b[0]});\n a.push_back(a[0]);b.push_back(b[0]);\n for (int i=0,j=0;;){\n (a[i+1]-a[i])%(b[j+1]-b[j])>eps?i=(i+1)%n:j=(j+1)%m;\n point t=a[i]+b[j];\n if (res.size()>=2&&std::abs((t-res.back())%(res.back()-res.end()[-2]))<=eps)\n res.pop_back();\n res.push_back(t);\n if (!i&&!j) break;\n }\n res.pop_back();\n return res;\n}\n\n// 半平面在直线逆时针方向\npolygon HalfPlaneIntersection(std::vector<line> a){ // 半平面在直线逆时针方向\n const db inf=1e20L;\n a.emplace_back(point(-inf,-inf),point(inf,-inf));\n a.emplace_back(point(inf,-inf),point(inf,inf));\n a.emplace_back(point(inf,inf),point(-inf,inf));\n a.emplace_back(point(-inf,inf),point(-inf,-inf));\n std::sort(a.begin(),a.end(),[&](const line &a,const line &b){\n auto up=[&](const point &a){return a.y>eps||(std::abs(a.y)<=eps&&a.x>eps);};\n bool ua=up(a.vec()),ub=up(b.vec());\n if (ua!=ub) return ua<ub;\n db t=a.vec()%b.vec();\n if (std::abs(t)>eps) return t>eps;\n return (a[0]-b[0])%b.vec()<-eps;\n });\n std::deque<point> qc;\n std::deque<line> ql;\n ql.emplace_back(a[0]);\n auto popback=[&](const line &a){\n for (;!qc.empty()&&(qc.back()-a.s)%a.vec()>=-eps;)\n qc.pop_back(),ql.pop_back();\n };\n auto popfront=[&](const line &a){\n for (;!qc.empty()&&(qc.front()-a.s)%a.vec()>=-eps;)\n qc.pop_front(),ql.pop_front();\n };\n for (int i=1;i<(int)a.size();++i){\n if (a[i].vec()*a[i-1].vec()>=eps&&std::abs(a[i].vec()%a[i-1].vec())<=eps) continue;\n popback(a[i]);popfront(a[i]);\n if (!ql.empty()){\n if (std::abs(a[i].vec()%ql.back().vec())<=eps) return {};\n qc.push_back(a[i].cross(ql.back()));\n }\n ql.push_back(a[i]);\n }\n popback(ql.front());popfront(ql.back());\n qc.push_back(ql.front().cross(ql.back()));\n if (qc.size()<=2) return {};\n polygon res;\n for (auto &p:qc) res.push_back(p);\n return res;\n}\n\nstruct circle{\n\n point o;\n db r;\n\n circle():o(),r(){}\n circle(point _o,db _r):o(_o),r(_r){}\n\n point operator()(db th)const{return o+r*point(std::cos(th),std::sin(th));}\n\n bool in(const point &a)const{return o.dis2(a)<=r*r+eps;}\n bool on(const point &a)const{return std::abs(o.dis2(a)-r*r)<=eps;}\n\n circle(point a,point b,point c){\n if (std::abs((a-b)%(b-c))<=eps){\n if (PointPairCmp()(a,b)) std::swap(a,b);\n if (PointPairCmp()(a,c)) std::swap(a,c);\n if (PointPairCmp()(b,c)) std::swap(b,c);\n o=(a+b)/2;\n r=(b-a).mod()/2;\n }else{\n point u=(a+b)/2,v=(a+c)/2;\n line p(u,u+(b-a).norm()),q(v,v+(c-a).norm());\n o=p.cross(q);\n r=o.dis(a);\n }\n }\n\n};\n\ncircle MinimumEnclosingCircle(polygon a){\n std::shuffle(a.begin(),a.end(),std::mt19937(time(0)));\n circle res(a[0],0);\n for (int i=1;i<(int)a.size();++i){\n if (res.in(a[i])) continue;\n res=circle(a[i],0);\n for (int j=0;j<i;++j){\n if (res.in(a[j])) continue;\n res=circle((a[i]+a[j])/2,(a[i]-a[j]).mod()/2);\n for (int k=0;k<j;++k){\n if (res.in(a[k])) continue;\n res=circle(a[i],a[j],a[k]);\n }\n }\n }\n return res;\n}\n\n\n\n\n\ndb Area(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=a[i]%a[(i+1)%(int)a.size()];\n assert(std::abs(res)>=-eps);\n return res/2;\n}\n\ndb Length(const polygon &a){\n db res=0;\n for (int i=0;i<(int)a.size();++i)\n res+=(a[i]-a[(i+1)%(int)a.size()]).mod();\n return res;\n}\n\nvoid work(){\n int n;\n std::cin>>n;\n polygon a(n);\n for (int i=0;i<n;++i) std::cin>>a[i].x>>a[i].y;\n auto c=MinimumEnclosingCircle(a);\n std::cout<<c.o.x<<' '<<c.o.y<<' '<<c.r<<'\\n';\n}\n\nint main(){\n std::ios::sync_with_stdio(0);\n std::cin.tie(0);\n std::cout<<std::fixed<<std::setprecision(12);\n std::cerr<<std::fixed<<std::setprecision(2);\n int T=1;\n // std::cin>>T;\n for (;T--;) work();\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 9436, "score_of_the_acc": -0.3991, "final_rank": 10 }, { "submission_id": "aoj_CGL_5_B_10939044", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i< (n); ++i)\n#define repi(i, a, b) for (int i = (a); i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define fore(i, a) for(auto &i:a)\nusing ll = long long;\nusing int64 = long long;\n#define DEBUG(x) cerr << #x << \": \"; for (auto _ : x) cerr << _ << \" \"; cerr << endl;\nconst int64 infll = (1LL << 62) - 1;\nconst int inf = (1 << 30) - 1;\n\nstruct IoSetup {\n\tIoSetup() {\n\t\tcin.tie(nullptr);\n\t\tios::sync_with_stdio(false);\n\t\tcout << fixed << setprecision(10);\n\t\tcerr << fixed << setprecision(10);\n\t}\n} iosetup;\n\ntemplate <typename T1, typename T2>\nostream& operator<<(ostream& os, const pair<T1, T2>& p) {\n\tos << p.first << \" \" << p.second;\n\treturn os;\n}\n\ntemplate <typename T1, typename T2>\nistream& operator>>(istream& is, pair<T1, T2>& p) {\n\tis >> p.first >> p.second;\n\treturn is;\n}\n\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n\tfor (int i = 0; i < (int)v.size(); i++) {\n\t\tos << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n\t}\n\treturn os;\n}\n\ntemplate <typename T>\nistream& operator>>(istream& is, vector<T>& v) {\n\tfor (T& in : v) is >> in;\n\treturn is;\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmax(T1& a, T2 b) {\n\treturn a < b && (a = b, true);\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmin(T1& a, T2 b) {\n\treturn a > b && (a = b, true);\n}\n\ntemplate <typename T = int64>\nvector<T> make_v(size_t a) {\n\treturn vector<T>(a);\n}\n\ntemplate <typename T, typename... Ts>\nauto make_v(size_t a, Ts... ts) {\n\treturn vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value == 0>::type fill_v(T& t, const V& v) {\n\tt = v;\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value != 0>::type fill_v(T& t, const V& v) {\n\tfor (auto& e : t) fill_v(e, v);\n}\n\ntemplate <typename F>\nstruct FixPoint : F {\n\texplicit FixPoint(F&& f) : F(std::forward<F>(f)) {}\n\n\ttemplate <typename... Args>\n\t\tdecltype(auto) operator()(Args&&... args) const {\n\t\t\treturn F::operator()(*this, std::forward<Args>(args)...);\n\t\t}\n};\n\ntemplate <typename F>\ninline decltype(auto) MFP(F&& f) {\n\treturn FixPoint<F>{std::forward<F>(f)};\n}\n//Geometry\nnamespace geometry {\nusing Real = double;\nconst Real EPS = 1e-15;\nconst Real PI = acos(static_cast<Real>(-1));\n\nenum { OUT, ON, IN };\n\ninline int sign(const Real& r) { return r <= -EPS ? -1 : r >= EPS ? 1 : 0; }\n\ninline bool equals(const Real& a, const Real& b) { return sign(a - b) == 0; }\n} // namespace geometry\n\nnamespace geometry {\nusing Point = complex<Real>;\n\nistream& operator>>(istream& is, Point& p) {\n Real a, b;\n is >> a >> b;\n p = Point(a, b);\n return is;\n}\n\nostream& operator<<(ostream& os, const Point& p) {\n return os << real(p) << \" \" << imag(p);\n}\n\nPoint operator*(const Point& p, const Real& d) {\n return Point(real(p) * d, imag(p) * d);\n}\n\n// rotate point p counterclockwise by theta rad\nPoint rotate(Real theta, const Point& p) {\n return Point(cos(theta) * real(p) - sin(theta) * imag(p),\n sin(theta) * real(p) + cos(theta) * imag(p));\n}\n\nReal cross(const Point& a, const Point& b) {\n return real(a) * imag(b) - imag(a) * real(b);\n}\n\nReal dot(const Point& a, const Point& b) {\n return real(a) * real(b) + imag(a) * imag(b);\n}\n\nbool compare_x(const Point& a, const Point& b) {\n return equals(real(a), real(b)) ? imag(a) < imag(b) : real(a) < real(b);\n}\n\nbool compare_y(const Point& a, const Point& b) {\n return equals(imag(a), imag(b)) ? real(a) < real(b) : imag(a) < imag(b);\n}\n\nusing Points = vector<Point>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Line {\n Point a, b;\n\n Line() = default;\n\n Line(const Point& a, const Point& b) : a(a), b(b) {}\n\n Line(const Real& A, const Real& B, const Real& C) { // Ax+By=C\n if (equals(A, 0)) {\n assert(!equals(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (equals(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (equals(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n friend ostream& operator<<(ostream& os, Line& l) {\n return os << l.a << \" to \" << l.b;\n }\n\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n};\n\nusing Lines = vector<Line>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Segment : Line {\n Segment() = default;\n\n using Line::Line;\n};\n\nusing Segments = vector<Segment>;\n} // namespace geometry\nnamespace geometry {\nstruct Circle {\n Point p;\n Real r{};\n\n Circle() = default;\n\n Circle(const Point& p, const Real& r) : p(p), r(r) {}\n};\n\nusing Circles = vector<Circle>;\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A\nPoint projection(const Line& l, const Point& p) {\n auto t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);\n return l.a + (l.a - l.b) * t;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B\nPoint reflection(const Line& l, const Point& p) {\n return p + (projection(l, p) - p) * 2;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C\nconstexpr int COUNTER_CLOCKWISE = +1;\nconstexpr int CLOCKWISE = -1;\nconstexpr int ONLINE_BACK = +2; // c-a-b\nconstexpr int ONLINE_FRONT = -2; // a-b-c\nconstexpr int ON_SEGMENT = 0; // a-c-b\nint ccw(const Point& a, Point b, Point c) {\n b = b - a, c = c - a;\n if (sign(cross(b, c)) == +1) return COUNTER_CLOCKWISE;\n if (sign(cross(b, c)) == -1) return CLOCKWISE;\n if (sign(dot(b, c)) == -1) return ONLINE_BACK;\n if (norm(b) < norm(c)) return ONLINE_FRONT;\n return ON_SEGMENT;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_orthogonal(const Line& a, const Line& b) {\n return equals(dot(a.a - a.b, b.a - b.b), 0.0);\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_parallel(const Line& a, const Line& b) {\n return equals(cross(a.b - a.a, b.b - b.a), 0.0);\n}\n} // namespace geometry\n\nnamespace geometry {\nbool is_intersect_ss(const Segment& s, const Segment& t) {\n return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&\n ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;\n}\n} // namespace geometry\nnamespace geometry {\nbool is_intersect_sp(const Segment& s, const Point& p) {\n return ccw(s.a, s.b, p) == ON_SEGMENT;\n}\n} // namespace geometry\n\nnamespace geometry {\nPoint cross_point_ll(const Line& l, const Line& m) {\n Real A = cross(l.b - l.a, m.b - m.a);\n Real B = cross(l.b - l.a, l.b - m.a);\n if (equals(abs(A), 0) && equals(abs(B), 0)) return m.a;\n return m.a + (m.b - m.a) * B / A;\n}\n} // namespace geometry\nnamespace geometry {\nReal distance_sp(const Segment& s, const Point& p) {\n Point r = projection(s, p);\n if (is_intersect_sp(s, r)) return abs(r - p);\n return min(abs(s.a - p), abs(s.b - p));\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D\nReal distance_ss(const Segment& a, const Segment& b) {\n if (is_intersect_ss(a, b)) return 0;\n return min({distance_sp(a, b.a), distance_sp(a, b.b), distance_sp(b, a.a),\n distance_sp(b, a.b)});\n}\n} // namespace geometry\nnamespace geometry {\nusing Polygon = vector<Point>;\nusing Polygons = vector<Polygon>;\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A\nReal area(const Polygon& p) {\n int n = (int)p.size();\n Real A = 0;\n for (int i = 0; i < n; ++i) {\n A += cross(p[i], p[(i + 1) % n]);\n }\n return A * 0.5;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B\nbool is_convex_polygon(const Polygon& p) {\n int n = (int)p.size();\n for (int i = 0; i < n; i++) {\n if (ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == CLOCKWISE)\n return false;\n }\n return true;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C\nint contains(const Polygon& Q, const Point& p) {\n bool in = false;\n for (int i = 0; i < Q.size(); i++) {\n Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;\n if (imag(a) > imag(b)) swap(a, b);\n if (sign(imag(a)) <= 0 && 0 < sign(imag(b)) && sign(cross(a, b)) < 0)\n in = !in;\n if (equals(cross(a, b), 0) && sign(dot(a, b)) <= 0) return ON;\n }\n return in ? IN : OUT;\n}\n} // namespace geometry\nnamespace geometry {\nint convex_polygon_contains(const Polygon& Q, const Point& p) {\n int N = (int)Q.size();\n Point g = (Q[0] + Q[N / 3] + Q[N * 2 / 3]) / 3.0;\n if (equals(imag(g), imag(p)) && equals(real(g), real(p))) return IN;\n Point gp = p - g;\n int l = 0, r = N;\n while (r - l > 1) {\n int mid = (l + r) / 2;\n Point gl = Q[l] - g;\n Point gm = Q[mid] - g;\n if (cross(gl, gm) > 0) {\n if (cross(gl, gp) >= 0 && cross(gm, gp) <= 0)\n r = mid;\n else\n l = mid;\n } else {\n if (cross(gl, gp) <= 0 && cross(gm, gp) >= 0)\n l = mid;\n else\n r = mid;\n }\n }\n r %= N;\n Real v = cross(Q[l] - p, Q[r] - p);\n return sign(v) == 0 ? ON : sign(v) == -1 ? OUT : IN;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A\nPolygon convex_hull(Polygon& p, bool strict = true) {\n int n = (int)p.size(), k = 0;\n if (n <= 2) return p;\n sort(begin(p), end(p), compare_x);\n vector<Point> ch(2 * n);\n auto check = [&](int i) {\n return sign(cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1])) <= -1 + strict;\n };\n for (int i = 0; i < n; ch[k++] = p[i++]) {\n while (k >= 2 && check(i)) --k;\n }\n for (int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {\n while (k >= t && check(i)) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B\npair<int, int> convex_polygon_diameter(const Polygon& p) {\n int N = (int)p.size();\n int is = 0, js = 0;\n for (int i = 1; i < N; i++) {\n if (imag(p[i]) > imag(p[is])) is = i;\n if (imag(p[i]) < imag(p[js])) js = i;\n }\n Real maxdis = norm(p[is] - p[js]);\n\n int maxi, maxj, i, j;\n i = maxi = is;\n j = maxj = js;\n do {\n if (cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {\n j = (j + 1) % N;\n } else {\n i = (i + 1) % N;\n }\n if (norm(p[i] - p[j]) > maxdis) {\n maxdis = norm(p[i] - p[j]);\n maxi = i;\n maxj = j;\n }\n } while (i != is || j != js);\n return minmax(maxi, maxj);\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C\n// cut with a straight line l and return a convex polygon on the left\nPolygon convex_polygon_cut(const Polygon& U, const Line& l) {\n Polygon ret;\n for (int i = 0; i < U.size(); i++) {\n const Point& now = U[i];\n const Point& nxt = U[(i + 1) % U.size()];\n auto cf = cross(l.a - now, l.b - now);\n auto cs = cross(l.a - nxt, l.b - nxt);\n if (sign(cf) >= 0) {\n ret.emplace_back(now);\n }\n if (sign(cf) * sign(cs) < 0) {\n ret.emplace_back(cross_point_ll(Line(now, nxt), l));\n }\n }\n return ret;\n}\n} // namespace geometry\nnamespace geometry {\ndouble closest_pair(Points &pts) {\n\tsort(pts.begin(), pts.end(), compare_x);\n\tvector<Point> buf(pts.size());\n\tauto dist2 = [](Point a, Point b){\n\t\tPoint c = a-b;\n\t\treturn c.real()*c.real()+c.imag()*c.imag();\n\t};\n\tfunction<double(int,int)> rec = [&](int l, int r) -> double {\n\t\tif (r - l <= 3) {\n\t\t\tdouble d2 = 1e300;\n\t\t\tfor (int i = l; i < r; ++i)\n\t\t\t\tfor (int j = i + 1; j < r; ++j)\n\t\t\t\t\td2 = min(d2, dist2(pts[i], pts[j]));\n\t\t\tsort(pts.begin() + l, pts.begin() + r, compare_y);\n\t\t\treturn d2;\n\t\t}\n\n\t\tint m = (l + r) / 2;\n\t\tdouble xmid = pts[m].real();\n\t\tdouble d2 = min(rec(l, m), rec(m, r));\n\n\t\tmerge(pts.begin()+l, pts.begin()+m, pts.begin()+m, pts.begin()+r, buf.begin(), compare_y);\n\t\tcopy(buf.begin(), buf.begin() + (r - l), pts.begin() + l);\n\n\t\tint sz = 0;\n\t\tfor (int i = l; i < r; ++i) {\n\t\t\tif ((pts[i].real() - xmid) * (pts[i].real() - xmid) < d2)\n\t\t\t\tbuf[sz++] = pts[i];\n\t\t}\n\n\t\tfor (int i = 0; i < sz; ++i)\n\t\t\tfor (int j = i - 1; j >= 0 && (buf[i].imag() - buf[j].imag()) * (buf[i].imag() - buf[j].imag()) < d2; --j)\n\t\t\t\td2 = min(d2, dist2(buf[i], buf[j]));\n\n\t\treturn d2;\n\t};\n\n\treturn sqrt(rec(0, pts.size()));\n}\n}\n\nnamespace geometry {\n\nbool in_circle(const Circle& c, const Point& p) {\n return abs(c.p - p) <= c.r + EPS;\n}\n\nCircle circle_from(const Point& A, const Point& B) {\n Point c = (A + B) / Real(2);\n Real r = abs(A - B) / Real(2);\n return Circle(c, r);\n}\n\nCircle circle_from(const Point& A, const Point& B, const Point& C) {\n Real a1 = real(B) - real(A);\n Real b1 = imag(B) - imag(A);\n Real c1 = (a1 * (real(A) + real(B)) + b1 * (imag(A) + imag(B))) / 2;\n\n Real a2 = real(C) - real(A);\n Real b2 = imag(C) - imag(A);\n Real c2 = (a2 * (real(A) + real(C)) + b2 * (imag(A) + imag(C))) / 2;\n\n Real det = a1 * b2 - a2 * b1;\n if (fabs(det) < EPS) return Circle(Point(0, 0), 1e18);\n\n Real cx = (c1 * b2 - c2 * b1) / det;\n Real cy = (a1 * c2 - a2 * c1) / det;\n Point center(cx, cy);\n Real radius = abs(center - A);\n return Circle(center, radius);\n}\n\nCircle welzl_rec(vector<Point>& P, vector<Point> R, int n) {\n if (n == 0 || R.size() == 3) {\n if (R.empty()) return Circle(Point(0, 0), 0);\n if (R.size() == 1) return Circle(R[0], 0);\n if (R.size() == 2) return circle_from(R[0], R[1]);\n return circle_from(R[0], R[1], R[2]);\n }\n\n Point p = P[n - 1];\n Circle D = welzl_rec(P, R, n - 1);\n if (in_circle(D, p)) return D;\n\n R.push_back(p);\n return welzl_rec(P, R, n - 1);\n}\n\nCircle minimum_enclosing_circle(Points P) {\n random_device rd;\n mt19937 g(rd());\n shuffle(P.begin(), P.end(), g); \n return welzl_rec(P, {}, (int)P.size());\n}\n\n} // namespace geometry\nusing namespace geometry;\nint main(){\n\tll n; cin >> n;\n\tPoints p(n);\n\trep(i, n)cin >> p[i];\n\tCircle c = minimum_enclosing_circle(p);\n\tcout << c.p << \" \" << c.r << endl;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 25536, "score_of_the_acc": -1.6667, "final_rank": 20 }, { "submission_id": "aoj_CGL_5_B_10936568", "code_snippet": "// 非再帰版\n// ここでのアルゴリズムで最小円が求まらない場合は、半径0の円が返される。最小円は存在するのだが、求まらない場合がありうるかも\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\nstruct Point {\n double x, y;\n};\n\nstruct Circle {\n Point c; // 中心\n double r; // 半径\n};\n\n// 距離\ndouble dist(const Point &a, const Point &b) {\n return hypot(a.x - b.x, a.y - b.y);\n}\n\n// 点 p が円 c の内部にあるか(誤差を考慮して <= r+EPS)\nbool inCircle(const Circle &c, const Point &p) {\n const double EPS = 1e-9;\n return dist(c.c, p) <= c.r + EPS;\n}\n\n// 2点を直径とする円\nCircle circleFrom2Points(const Point &a, const Point &b) {\n Point center{ (a.x + b.x)/2.0, (a.y + b.y)/2.0 };\n double r = dist(a, b) / 2.0;\n return {center, r};\n}\n\n// 3点から外接円を作る\nCircle circleFrom3Points(const Point &a, const Point &b, const Point &c) {\n // 外心を計算\n double d = 2*(a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y));\n if (fabs(d) < 1e-12) {\n // ほぼ直線上の場合 → 最大距離の2点で直径円\n Circle c1 = circleFrom2Points(a, b);\n Circle c2 = circleFrom2Points(a, c);\n Circle c3 = circleFrom2Points(b, c);\n // 半径最小のものを返す\n Circle res = c1;\n if (c2.r > res.r) res = c2;\n if (c3.r > res.r) res = c3;\n return res;\n }\n double ux = ((a.x*a.x+a.y*a.y)*(b.y-c.y) +\n (b.x*b.x+b.y*b.y)*(c.y-a.y) +\n (c.x*c.x+c.y*c.y)*(a.y-b.y)) / d;\n double uy = ((a.x*a.x+a.y*a.y)*(c.x-b.x) +\n (b.x*b.x+b.y*b.y)*(a.x-c.x) +\n (c.x*c.x+c.y*c.y)*(b.x-a.x)) / d;\n Point center{ux, uy};\n double r = dist(center, a);\n return {center, r};\n}\n\n\nconst int Remove = 0;\nconst int Compare = 1;\nconst int Ret = 2; \n\n// idxはPで使用する最初のindex\nCircle welzl(vector<Point> &P) {\n int idx = 0;\n vector<Point> R(3);\n int Rnum = 0;\n vector<int> state(P.size(), 0);\n Circle D; \n\n while (idx >= 0){\n \n if (idx >= P.size()){\n if (Rnum == 0) D = {{0,0}, 0};\n else if (Rnum == 1) D = {R[0], 0};\n else if (Rnum == 2) D = circleFrom2Points(R[0], R[1]);\n else if (Rnum == 3) D = circleFrom3Points(R[0], R[1], R[2]);\n else D = {{0,0}, 0};\n --idx;\n } else if (state[idx] == Remove){\n state[idx] = Compare;\n ++idx;\n } else if (state[idx] == Compare){\n if (inCircle(D, P[idx])){\n state[idx] = Remove; //修正\n --idx;\n } else {\n state[idx] = Ret;\n R[Rnum] = P[idx];\n ++Rnum;\n ++idx;\n }\n } else if (state[idx] == Ret){\n state[idx] = Remove;\n --Rnum;\n --idx;\n }\n }\n\n return D;\n}\n \n\n\n\n\n\n// メイン関数(入口)\n// Circle minimumEnclosingCircle(vector<Point> P) {\n// return welzl(P);\n// }\n\n// 使用例\n// 再帰本体\n// welzl(P, {}, P.size())の戻り値は\n// P = [(1,2)] --> c=(1,2), r = 0.0\n// P =[(0,0), (1,0)] --> c=(0.5,0) r=0.5\n// P =[(0,0), (1,0), (0,1)] --> c=(0.5,0.5) r=0.707\n\nint main() {\n\n int n;\n cin >> n;\n vector<Point> P(n);\n for (int i = 0; i < n; i++) cin >> P[i].x >> P[i].y;\n random_shuffle(P.begin(), P.end());\n \n Circle C = welzl(P);\n\n printf(\"%.8f %.8f %.8f\\n\", C.c.x, C.c.y, C.r);\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 5020, "score_of_the_acc": -1.0219, "final_rank": 18 }, { "submission_id": "aoj_CGL_5_B_10912969", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#include <iostream>\ntemplate <typename T, typename U>\nostream& operator<<(ostream& os, const pair<T, U>& p) {return os<<'(' <<p.first<<\", \"<<p.second<<')';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {os<<'[';for(auto it=v.begin();it!=v.end();++it){os<<*it; if(next(it)!=v.end()){os<<\", \";}}return os<<']';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<vector<T>>& vv) {os<<\"[\\n\";for(auto it=vv.begin();it!=vv.end();++it){os<<\" \"<<*it;if(next(it)!=vv.end()){os<<\",\\n\";}else{os<<\"\\n\";}}return os<<\"]\";}\n#define dump(x) cerr << #x << \" = \" << (x) << '\\n'\n#else\n#define dump(x) (void)0\n#endif\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\ntemplate<class T> using pq = priority_queue<T>;\ntemplate<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>;\n#define out(x) cout<<x<<'\\n'\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define OVERLOAD_REP(_1,_2,_3,name,...) name\n#define REP1(i,n) for (auto i = std::decay_t<decltype(n)>{}; (i) < (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) < (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\ntemplate<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};\ntemplate<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};\nconst ll INF=(1LL<<60);\nconst ll mod=998244353;\nusing Graph = vector<vector<ll>>;\nusing Network = vector<vector<pair<ll,ll>>>;\nusing Grid = vector<string>;\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int dx2[8] = {1, 1, 1, 0, 0, -1, -1, -1};\nconst int dy2[8] = {1, 0, -1, 1, -1, 1, 0, -1};\n\n// #include \"../geo.hpp\"\n\n#pragma once\n\nusing D = long double;\nconst D EPS = 1e-12L;\nconst D PI = acosl(-1.0L);\nusing P2 = complex<D>;\nstruct L2{P2 a, b;};\nstruct S2{P2 a, b;};\nusing G2 = vector<P2>;\n\nint sgn(D x){return (x>EPS)-(x<-EPS);}\nint cmp(D a, D b){return sgn(a-b);}\nbool eq(D a, D b){return cmp(a, b)==0;}\nbool lt(D a, D b){return cmp(a, b)<0;}\nbool le(D a, D b){return cmp(a, b)<=0;}\nbool gt(D a, D b){return cmp(a, b)>0;}\nbool ge(D a, D b){return cmp(a, b)>=0;}\nbool eqP2(P2 a, P2 b){return eq(real(a), real(b)) && eq(imag(a), imag(b));}\nbool ltP2(P2 a, P2 b) {\n return lt(real(a), real(b)) || (eq(real(a), real(b)) && lt(imag(a), imag(b)));\n}\n\nD dot(P2 a, P2 b) {return real(conj(a)*b);}\nD cross(P2 a, P2 b) {return imag(conj(a)*b);}\nint ccw(P2 a, P2 b, P2 c) {\n b-=a; c-=a;\n auto cr=cross(b, c), dt=dot(b, c);\n if (cr > EPS) return +1; // counter clockwise\n if (cr < -EPS) return -1; // clockwise\n if (dt < -EPS) return +2; // c--a--b\n if (lt(norm(b), norm(c))) return -2; // a--b--c\n return 0; // a--c--b\n}\nint turn(P2 a, P2 b, P2 c) { return sgn(cross(b - a, c - a)); }\n\nP2 rot(P2 a, D th) { return a*polar<D>(1, th); }\nP2 rot90(P2 a) { return P2(-imag(a), real(a)); }\nbool ltP2Arg(P2 a, P2 b) {\n auto up = [](P2 p) { return (imag(p) > 0 || (eq(imag(p), 0) && ge(real(p), 0))); };\n if (up(a) != up(b)) return up(a);\n if (!eq(cross(a, b), 0)) return cross(a, b) > 0;\n return lt(norm(a), norm(b));\n}\n\ninline void rd(P2& p) {D x, y; cin>>x>>y; p = P2(x, y);}\n#define setp(n) cout<<setprecision(n)<<fixed\ninline void pr(const P2& p) {setp(12); cout<<real(p)<<' '<<imag(p)<<'\\n';}\n\n// ----------------------------------------------------------------------------------\n\nP2 proj(L2 l, P2 p) { P2 a=p-l.a, b=l.b-l.a; return l.a+b*dot(a, b)/norm(b);}\nP2 refl(L2 l, P2 p) { return proj(l, p)*2.0L - p; }\nbool isParallel(L2 l, L2 m){ return eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isPerp(L2 l, L2 m){ return eq(dot(l.a-l.b, m.a-m.b), 0); }\n\nbool isLL(L2 l, L2 m){ return !eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isLS(L2 l, S2 s){ return turn(l.a, l.b, s.a)*turn(l.a, l.b, s.b)<=0; }\nbool isSS(S2 s, S2 t) {\n return\n ccw(s.a,s.b,t.a)*ccw(s.a,s.b,t.b) <= 0 &&\n ccw(t.a,t.b,s.a)*ccw(t.a,t.b,s.b) <= 0;\n}\n\nP2 cpLL(L2 l, L2 m) {\n P2 a=l.b-l.a, b=m.b-m.a;\n D d=cross(a, b);\n if (eq(d, 0)) return P2(INF, INF); // parallel\n return l.a + a*cross(m.b-l.a,b)/d;\n}\n\nD distLP(L2 l, P2 p) { return abs(cross(l.b-l.a, p-l.a))/abs(l.b-l.a); }\nD distSP(S2 s, P2 p) {\n P2 a=s.a, b=s.b;\n if (lt(dot(b-a, p-a), 0)) return abs(p-a);\n if (lt(dot(a-b, p-b), 0)) return abs(p-b);\n return distLP({a,b}, p);\n}\nD distSS(S2 s, S2 t) {\n if (isSS(s, t)) return 0;\n return min({distSP(s, t.a), distSP(s, t.b), distSP(t, s.a), distSP(t, s.b)});\n}\n\nD area(G2 g) {\n D s=0;\n int n=g.size();\n rep(i, n) s+=cross(g[i], g[(i+1)%n]);\n return s/2.0L;\n}\n\nbool isConvex(G2 g) {\n int n=g.size();\n if (n < 3) return false;\n int dir = 0;\n rep(i,n){\n int s = turn(g[i], g[(i+1)%n], g[(i+2)%n]);\n if (s == 0) return false; // -> continue : allows three points on a line\n if (dir == 0) dir = s;\n else if (dir*s < 0) return false;\n }\n return true;\n}\n\nint inG(G2 g, P2 p) {\n bool in=false;\n int n=g.size();\n rep(i, n) {\n P2 a=g[i], b=g[(i+1)%n];\n if (ccw(a, b, p) == 0) return 1; // on boundary\n if (a.imag() > b.imag()) swap(a, b);\n if (le(a.imag(), p.imag()) && lt(p.imag(), b.imag()) && turn(a, b, p) > 0) in=!in;\n }\n return in ? 2 : 0; // inside : outside\n}\n\nG2 hull(G2 g) {\n sort(all(g), ltP2);\n g.erase(unique(all(g), eqP2), g.end());\n if (g.size()<=1) return g;\n G2 lo, up;\n for (auto &p:g) {\n while (lo.size()>=2 && turn(lo[lo.size()-2], lo.back(), p)<=0) lo.pop_back(); //-> turn()<0 : allow three points on a line\n lo.push_back(p);\n }\n reverse(all(g));\n for (auto &p:g) {\n while (up.size()>=2 && turn(up[up.size()-2], up.back(), p)<=0) up.pop_back(); // -> turn()<0 : allow three points on a line\n up.push_back(p);\n }\n lo.pop_back(); up.pop_back();\n lo.insert(lo.end(), all(up));\n return lo;\n}\n\npair<P2, P2> diameter(const G2& h) {\n int n=h.size();\n if(n==0) return {P2(0,0), P2(0,0)};\n if(n==1) return {h[0], h[0]};\n auto area2=[&](int i, int j, int k) {return abs(cross(h[j]-h[i], h[k]-h[i]));};\n D maxd=0;\n pair<P2, P2> res={h[0], h[0]};\n int j=1;\n rep(i, n) {\n int ni=(i+1)%n;\n while (gt(area2(i, ni, (j+1)%n), area2(i, ni, j))) j=(j+1)%n;\n if (gt(abs(h[i]-h[j]), maxd)) maxd=abs(h[i]-h[j]), res={h[i], h[j]};\n if (gt(abs(h[ni]-h[j]), maxd)) maxd=abs(h[ni]-h[j]), res={h[ni], h[j]};\n }\n return res;\n}\n\n// int inConvex(G2 h, P2 p) {\n// int n=h.size();\n// if (n==0) return 0;\n// if (n==1) return eqP2(h[0], p) ? 2 : 0;\n// if (n==2) return ccw(h[0], h[1], p)==0 && le(abs(h[0]-p)+abs(h[1]-p), abs(h[0]-h[1])) ? 2 : 0;\n// int left=1, right=n-1;\n// while (right-left>1) {\n// int mid=(left+right)/2;\n// if (turn(h[0], h[mid], p)<0) right=mid;\n// else left=mid;\n// }\n// if (turn(h[0], h[left], p)<0) return 0;\n// if (turn(h[left], h[right%n], p)<0) return 0;\n// if (turn(h[right%n], h[0], p)<0) return 0;\n// if (turn(h[0], h[left], p)==0 || turn(h[left], h[right%n], p)==0 || turn(h[right%n], h[0], p)==0) return 2;\n// return 1;\n// }\n\nG2 cutConvex(G2 h, L2 l) {\n int n=h.size();\n G2 res;\n if (n==0) return res;\n auto inside=[&](P2 p){ return turn(l.a, l.b, p) >= 0; };\n rep(i, n) {\n P2 a=h[i], b=h[(i+1)%n];\n bool ina=inside(a), inb=inside(b);\n if (ina&&inb) res.push_back(b);\n else if (ina&&!inb) {\n res.push_back(proj({a,b}, l.a));\n }\n else if (!ina&&inb) {\n res.push_back(proj({a,b}, l.a));\n res.push_back(b);\n }\n }\n return res;\n}\n\n\npair<P2, P2> closestPair(G2 g) {\n auto ps = g;\n int n=ps.size();\n if (n < 2) return {P2(0,0), P2(0,0)};\n sort(all(ps), ltP2);\n D mind = norm(ps[0]-ps[1]);\n pair<P2, P2> res = {ps[0], ps[1]};\n set<pair<D,int>> box;\n int j=0;\n rep(i, n) {\n D xi=real(ps[i]), yi=imag(ps[i]);\n D rad = sqrtl(mind);\n while (j<i && gt(xi - real(ps[j]), rad)) {\n box.erase({imag(ps[j]), j});\n j++;\n }\n auto it = box.lower_bound({yi - rad, -1});\n for (; it != box.end() && le(it->first, yi + rad); ++it) {\n int k = it->second;\n D d = norm(ps[i]-ps[k]);\n if (lt(d, mind)) mind=d, res={ps[i], ps[k]}, rad = sqrtl(mind);\n }\n box.insert({yi, i});\n }\n return res;\n}\n\n\nstruct C2 { P2 o; D r; };\n\nC2 makeC2(P2 a, P2 b) {\n return C2{(a+b)/D(2), abs(a-b)/D(2)};\n}\nC2 makeC2(P2 a, P2 b, P2 c) {\n P2 B=b-a, C=c-a;\n D d=2*cross(B, C);\n if (eq(d, 0)) {\n D ab=norm(B), bc=norm(b-c), ca=norm(c-a);\n if (le(ab, bc) && le(ab, ca)) return makeC2(a, b);\n if (le(bc, ca)) return makeC2(b, c);\n return makeC2(c, a);\n }\n P2 o=a+(rot90(B)*norm(C)-rot90(C)*norm(B))/d;\n return C2{o, abs(o-a)};\n}\n\nC2 incircle(P2 a, P2 b, P2 c) {\n D ab=abs(b-a), bc=abs(c-b), ca=abs(a-c);\n P2 o=(a*bc+b*ca+c*ab)/(ab+bc+ca);\n D r=abs(cross(b-a, o-a))/abs(b-a);\n return C2{o, r};\n}\n\nvector<P2> cpCL(L2 l, C2 c) {\n vector<P2> res;\n P2 a=l.a-c.o, d=l.b-l.a;\n D A=norm(d), B=2*dot(a, d), C=norm(a)-c.r*c.r;\n D Dlt=B*B-4*A*C;\n if (lt(Dlt, 0)) return res;\n D s = le(Dlt, 0) ? 0 : sqrtl(max<D>(0, Dlt));\n D t1 = (-B - s)/(2*A), t2 = (-B + s)/(2*A);\n res.push_back(c.o + a + d*t1);\n if (gt(Dlt, 0)) res.push_back(c.o + a + d*t2);\n return res;\n}\n\nvector<P2> cpCC(C2 c1, C2 c2) {\n vector<P2> res;\n P2 d=c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n D a=(c1.r*c1.r-c2.r*c2.r+L*L)/(2*L), h2=c1.r*c1.r-a*a;\n if (lt(h2, 0)) return res;\n P2 m=c1.o+d*(a/L), n=rot90(d)*( (lt(h2, 0) ? 0 : sqrtl(max<D>(0, h2))/L) );\n res.push_back(m-n);\n if (gt(h2, 0)) res.push_back(m+n);\n return res;\n}\n\nD isaCC(C2 c1, C2 c2) {\n D d=abs(c1.o-c2.o), r1=c1.r, r2=c2.r;\n if (ge(d, r1+r2)) return 0;\n if (le(d, abs(r1-r2))) {\n D r=min(r1, r2);\n return PI*r*r;\n }\n auto f = [&] (D z) { return max<D>(-1, min<D>(1, z)); };\n D a = 2*acosl(f((d*d+r1*r1-r2*r2)/(2*d*r1)));\n D b = 2*acosl(f((d*d+r2*r2-r1*r1)/(2*d*r2)));\n return 0.5L*(r1*r1*(a-sinl(a)) + r2*r2*(b-sinl(b)));\n}\n\nvector<L2> tangCP(C2 c, P2 p) {\n vector<L2> res;\n P2 v = p - c.o;\n D d2 = norm(v), r2 = c.r*c.r;\n if (lt(d2, r2)) return res;\n if (eq(d2, r2)) {\n res.push_back({c.o+v*(r2/d2), p});\n return res;\n }\n D h = c.r*sqrtl(max<D>(0, d2 - r2));\n P2 n1 = (v*r2 - rot90(v)*h)/d2;\n P2 n2 = (v*r2 + rot90(v)*h)/d2;\n res.push_back({c.o+n1, p});\n res.push_back({c.o+n2, p});\n return res;\n}\n\nvector<L2> tangCC(C2 c1, C2 c2) {\n vector<L2> res;\n P2 d = c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n P2 e = d/L;\n auto add = [&] (int s) {\n D c=(s*c2.r - c1.r)/L;\n if (gt(c*c, 1)) return;\n D s2 = max<D>(0, 1 - c*c);\n if (eq(s2, 0)) {\n P2 n = e*c;\n res.push_back({c1.o-n*c1.r, c2.o-n*c2.r});\n } else {\n D s = sqrtl(s2);\n P2 n1 = e*c + rot90(e)*s;\n P2 n2 = e*c - rot90(e)*s;\n res.push_back({c1.o-n1*c1.r, c2.o-n1*c2.r});\n res.push_back({c1.o-n2*c1.r, c2.o-n2*c2.r});\n }\n };\n add(+1); // external\n add(-1); // internal\n return res;\n}\n\nC2 mec(G2 ps) {\n auto inC2=[&](C2 c, P2 p){ return le(abs(c.o - p), c.r); };\n mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n shuffle(all(ps), rng);\n int n=ps.size();\n if(n==0) return C2{P2(0,0), 0};\n C2 c{ps[0], 0};\n rep(i, n) {\n if (inC2(c, ps[i])) continue;\n c={ps[i], 0};\n rep(j, i) {\n if (inC2(c, ps[j])) continue;\n c=makeC2(ps[i], ps[j]);\n rep(k, j) {\n if (inC2(c, ps[k])) continue;\n c=makeC2(ps[i], ps[j], ps[k]);\n }\n }\n }\n return c;\n}\n\nvector<P2> cpSegs(vector<S2> ss) {\n struct E { D x; int t; D y, y1, y2; }; // t: 0=add(H), 1=query(V), 2=remove(H)\n vector<E> es; es.reserve(ss.size()*2);\n\n for(auto s: ss) {\n if (eq(s.a.imag(), s.b.imag())) {\n if (gt(s.a.real(), s.b.real())) swap(s.a, s.b);\n es.push_back({s.a.real(), 0, s.a.imag(), 0, 0});\n es.push_back({s.b.real(), 2, s.a.imag(), 0, 0});\n } else {\n if (gt(s.a.imag(), s.b.imag())) swap(s.a, s.b);\n es.push_back({s.a.real(), 1, 0, s.a.imag(), s.b.imag()});\n }\n }\n\n sort(all(es), [](E a, E b) {\n if (!eq(a.x, b.x)) return lt(a.x, b.x);\n return a.t < b.t;\n });\n\n multiset<D> active;\n vector<P2> res; res.reserve(ss.size());\n for (auto e : es) {\n if (e.t == 0) { // add\n active.insert(e.y);\n } else if (e.t == 2) { // remove\n auto it = active.find(e.y);\n if (it != active.end()) active.erase(it);\n } else { // query\n for (auto it = active.lower_bound(e.y1); it != active.end() && le(*it, e.y2); ++it) {\n res.push_back(P2(e.x, *it));\n }\n }\n }\n\n sort(all(res), ltP2);\n res.erase(unique(all(res), eqP2), res.end());\n return res;\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_A\nvoid Projection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(proj(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_B\nvoid Reflection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(refl(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_C\nvoid CounterClockwise() {\n P2 p0, p1;\n rd(p0); rd(p1);\n ll q; cin>>q;\n while(q--) {\n P2 p; rd(p);\n int res = ccw(p0, p1, p);\n if (res == +1) out(\"COUNTER_CLOCKWISE\");\n else if (res == -1) out(\"CLOCKWISE\");\n else if (res == +2) out(\"ONLINE_BACK\");\n else if (res == -2) out(\"ONLINE_FRONT\");\n else out(\"ON_SEGMENT\");\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_2_A\nvoid ParallelOrthogonal() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n if (isParallel({p1, p2}, {p3, p4})) out(2);\n else if(isPerp({p1, p2}, {p3, p4})) out(1);\n else out(0);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_B\nvoid IntersectionSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n out(isSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_C\nvoid CrossPointSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n L2 s1 = {p1, p2}, s2 = {p3, p4};\n pr(cpLL(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_D\nvoid DistanceSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n setp(12);\n out(distSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_A\nvoid Area() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n setp(1);\n out(area(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_B\nvoid IsConvex() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n out(isConvex(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_C\nvoid PolygonPointContainment() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n out(inG(g, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\nvoid ConvexHull() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n G2 h = hull(g);\n out(h.size());\n ll sx = INF, sy = INF;\n ll id = -1;\n rep(i, h.size()) {\n if (lt(imag(h[i]), sy)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n else if (eq(imag(h[i]), sy) && lt(real(h[i]), sx)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n }\n rep(i, h.size()) {\n ll ni = (id + i) % h.size();\n pr(h[ni]);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_B\nvoid DiameterOfConvexPolygon() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = diameter(g);\n setp(12);\n out(abs(p1 - p2));\n // todo\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_C\nvoid ConvexCut() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n G2 h = cutConvex(g, l);\n setp(12);\n out(area(h));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_A\nvoid ClosestPair() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = closestPair(g);\n setp(12);\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_B\nvoid MinimumEnclosingCircle() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [c, r] = mec(g);\n pr(c);\n setp(12);\n out(r);\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/6/CGL_6_A\nvoid SegmentIntersections() {\n ll n;cin>>n;\n vector<S2> seg(n);\n rep(i, n) {\n P2 a, b; rd(a); rd(b);\n seg[i] = {a, b};\n }\n out(cpSegs(seg).size());\n}\n\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_A\nvoid IntersectionOfCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n out(tangCC(c1, c2).size());\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_B\nvoid IncircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [ic, ir] = incircle(a, b, c);\n pr(ic);\n setp(12);\n out(ir);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_C\nvoid CircumscribedCircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [cc, cr] = makeC2(a, b, c);\n pr(cc);\n setp(12);\n out(cr);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_D\nvoid CrossPointsCL() {\n P2 c; D r;\n rd(c); cin>>r;\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n auto ps = cpCL(l, {c, r});\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n }\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_E\nvoid CrossPointsCC() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ps = cpCC(c1, c2);\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_F\nvoid TangentToCircle() {\n P2 p, c; D r;\n rd(p);\n rd(c); cin>>r;\n C2 c1={c, r};\n auto ls = tangCP(c1, p);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_G\nvoid CommonTangent() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ls = tangCC(c1, c2);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_H\n// void IntersectionCP() {\n// ll n;cin>>n;\n// D r; cin>>r;\n// C2 c = {P2(0, 0), r};\n// G2 g(n);\n// rep(i, n) rd(g[i]);\n// out(isaCP(c, g));\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_I\nvoid AreaOfIntersectionBetweenTwoCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n setp(12);\n out(isaCC(c1, c2));\n}\n\nint main() {\n cin.tie(0);\n ios_base::sync_with_stdio(false);\n\n // Projection();\n // Reflection();\n // CounterClockwise();\n\n // ParallelOrthogonal();\n // IntersectionSS();\n // CrossPointSS();\n // DistanceSS();\n\n // Area();\n // IsConvex();\n // PolygonPointContainment();\n\n // ConvexHull();\n // DiameterOfConvexPolygon();\n // ConvexCut();\n\n // ClosestPair();\n MinimumEnclosingCircle();\n\n // SegmentIntersections();\n\n // IntersectionOfCircles();\n // IncircleOfTriangle();\n // CircumscribedCircleOfTriangle();\n // CrossPointsCL();\n // CrossPointsCC();\n // TangentToCircle();\n // CommonTangent();\n // IntersectionCP();\n // AreaOfIntersectionBetweenTwoCircles();\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 9472, "score_of_the_acc": -0.9008, "final_rank": 16 }, { "submission_id": "aoj_CGL_5_B_10909936", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#include <iostream>\ntemplate <typename T, typename U>\nostream& operator<<(ostream& os, const pair<T, U>& p) {return os<<'(' <<p.first<<\", \"<<p.second<<')';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {os<<'[';for(auto it=v.begin();it!=v.end();++it){os<<*it; if(next(it)!=v.end()){os<<\", \";}}return os<<']';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<vector<T>>& vv) {os<<\"[\\n\";for(auto it=vv.begin();it!=vv.end();++it){os<<\" \"<<*it;if(next(it)!=vv.end()){os<<\",\\n\";}else{os<<\"\\n\";}}return os<<\"]\";}\n#define dump(x) cerr << #x << \" = \" << (x) << '\\n'\n#else\n#define dump(x) (void)0\n#endif\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\ntemplate<class T> using pq = priority_queue<T>;\ntemplate<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>;\n#define out(x) cout<<x<<'\\n'\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define OVERLOAD_REP(_1,_2,_3,name,...) name\n#define REP1(i,n) for (auto i = std::decay_t<decltype(n)>{}; (i) < (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) < (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\ntemplate<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};\ntemplate<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};\nconst ll INF=(1LL<<60);\nconst ll mod=998244353;\nusing Graph = vector<vector<ll>>;\nusing Network = vector<vector<pair<ll,ll>>>;\nusing Grid = vector<string>;\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int dx2[8] = {1, 1, 1, 0, 0, -1, -1, -1};\nconst int dy2[8] = {1, 0, -1, 1, -1, 1, 0, -1};\n\n// #include \"../geo.hpp\"\n\nusing D = long double;\nconst D EPS = 1e-12L;\nusing P2 = complex<D>;\nstruct L2{P2 a, b;};\nstruct S2{P2 a, b;};\nusing G2 = vector<P2>;\n\nint sgn(D x){return (x>EPS)-(x<-EPS);}\nint cmp(D a, D b){return sgn(a-b);}\nbool eq(D a, D b){return cmp(a, b)==0;}\nbool lt(D a, D b){return cmp(a, b)<0;}\nbool le(D a, D b){return cmp(a, b)<=0;}\nbool gt(D a, D b){return cmp(a, b)>0;}\nbool ge(D a, D b){return cmp(a, b)>=0;}\nbool eqP2(P2 a, P2 b){return eq(real(a), real(b)) && eq(imag(a), imag(b));}\nbool ltP2(P2 a, P2 b) {\n return lt(real(a), real(b)) || (eq(real(a), real(b)) && lt(imag(a), imag(b)));\n}\n\nD dot(P2 a, P2 b) {return real(conj(a)*b);}\nD cross(P2 a, P2 b) {return imag(conj(a)*b);}\nint ccw(P2 a, P2 b, P2 c) {\n b-=a; c-=a;\n auto cr=cross(b, c), dt=dot(b, c);\n if (cr > EPS) return +1; // counter clockwise\n if (cr < -EPS) return -1; // clockwise\n if (dt < -EPS) return +2; // c--a--b\n if (lt(norm(b), norm(c))) return -2; // a--b--c\n return 0; // a--c--b\n}\nint turn(P2 a, P2 b, P2 c) { return sgn(cross(b - a, c - a)); }\n\nP2 rot(P2 a, D th) { return a*polar<D>(1, th); }\nP2 rot90(P2 a) { return P2(-imag(a), real(a)); }\n\ninline void rd(P2& p) {D x, y; cin>>x>>y; p = P2(x, y);}\ninline void pr(const P2& p) {cout<<setprecision(12)<<fixed<<real(p)<<' '<<imag(p)<<'\\n';}\n\n\nP2 proj(L2 l, P2 p) { P2 a=p-l.a, b=l.b-l.a; return l.a+b*dot(a, b)/norm(b);}\nP2 refl(L2 l, P2 p) { return proj(l, p)*2.0L - p; }\nbool isParallel(L2 l, L2 m){ return eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isPerp(L2 l, L2 m){ return eq(dot(l.a-l.b, m.a-m.b), 0); }\n\nbool isLL(L2 l, L2 m){ return !eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isLS(L2 l, S2 s){ return turn(l.a, l.b, s.a)*turn(l.a, l.b, s.b)<=0; }\nbool isSS(S2 s, S2 t) {\n return\n ccw(s.a,s.b,t.a)*ccw(s.a,s.b,t.b) <= 0 &&\n ccw(t.a,t.b,s.a)*ccw(t.a,t.b,s.b) <= 0;\n}\n\nP2 cpLL(L2 l, L2 m) {\n P2 a=l.b-l.a, b=m.b-m.a;\n D d=cross(a, b);\n if (eq(d, 0)) return P2(INF, INF); // parallel\n return l.a + a*cross(m.b-l.a,b)/d;\n}\n\nD distLP(L2 l, P2 p) { return abs(cross(l.b-l.a, p-l.a))/abs(l.b-l.a); }\nD distSP(S2 s, P2 p) {\n P2 a=s.a, b=s.b;\n if (lt(dot(b-a, p-a), 0)) return abs(p-a);\n if (lt(dot(a-b, p-b), 0)) return abs(p-b);\n return distLP({a,b}, p);\n}\nD distSS(S2 s, S2 t) {\n if (isSS(s, t)) return 0;\n return min({distSP(s, t.a), distSP(s, t.b), distSP(t, s.a), distSP(t, s.b)});\n}\n\nD area(G2 g) {\n D s=0;\n int n=g.size();\n rep(i, n) s+=cross(g[i], g[(i+1)%n]);\n return s/2.0L;\n}\n\nbool isConvex(G2 g) {\n int n=g.size();\n if (n < 3) return false;\n int dir = 0;\n rep(i,n){\n int s = turn(g[i], g[(i+1)%n], g[(i+2)%n]);\n if (s == 0) return false; // -> continue : allows three points on a line\n if (dir == 0) dir = s;\n else if (dir*s < 0) return false;\n }\n return true;\n}\n\nint inG(G2 g, P2 p) {\n bool in=false;\n int n=g.size();\n rep(i, n) {\n P2 a=g[i], b=g[(i+1)%n];\n if (ccw(a, b, p) == 0) return 2; // on boundary\n if (a.imag() > b.imag()) swap(a, b);\n if (le(a.imag(), p.imag()) && lt(p.imag(), b.imag()) && turn(a, b, p) > 0) in=!in;\n }\n return in ? 1 : 0; // inside : outside\n}\n\nG2 hull(G2 g) {\n sort(all(g), ltP2);\n g.erase(unique(all(g), eqP2), g.end());\n if (g.size()<=1) return g;\n G2 lo, up;\n for (auto &p:g) {\n while (lo.size()>=2 && turn(lo[lo.size()-2], lo.back(), p)<=0) lo.pop_back(); //-> turn()<0 : allow three points on a line\n lo.push_back(p);\n }\n reverse(all(g));\n for (auto &p:g) {\n while (up.size()>=2 && turn(up[up.size()-2], up.back(), p)<=0) up.pop_back(); // -> turn()<0 : allow three points on a line\n up.push_back(p);\n }\n lo.pop_back(); up.pop_back();\n lo.insert(lo.end(), all(up));\n return lo;\n}\n\npair<P2, P2> diameter(const G2& h) {\n int n=h.size();\n if(n==0) return {P2(0,0), P2(0,0)};\n if(n==1) return {h[0], h[0]};\n auto area2=[&](int i, int j, int k) {return abs(cross(h[j]-h[i], h[k]-h[i]));};\n D maxd=0;\n pair<P2, P2> res={h[0], h[0]};\n int j=1;\n rep(i, n) {\n int ni=(i+1)%n;\n while (gt(area2(i, ni, (j+1)%n), area2(i, ni, j))) j=(j+1)%n;\n if (gt(abs(h[i]-h[j]), maxd)) maxd=abs(h[i]-h[j]), res={h[i], h[j]};\n if (gt(abs(h[ni]-h[j]), maxd)) maxd=abs(h[ni]-h[j]), res={h[ni], h[j]};\n }\n return res;\n}\n\n// int inConvex(G2 h, P2 p) {\n// int n=h.size();\n// if (n==0) return 0;\n// if (n==1) return eqP2(h[0], p) ? 2 : 0;\n// if (n==2) return ccw(h[0], h[1], p)==0 && le(abs(h[0]-p)+abs(h[1]-p), abs(h[0]-h[1])) ? 2 : 0;\n// int left=1, right=n-1;\n// while (right-left>1) {\n// int mid=(left+right)/2;\n// if (turn(h[0], h[mid], p)<0) right=mid;\n// else left=mid;\n// }\n// if (turn(h[0], h[left], p)<0) return 0;\n// if (turn(h[left], h[right%n], p)<0) return 0;\n// if (turn(h[right%n], h[0], p)<0) return 0;\n// if (turn(h[0], h[left], p)==0 || turn(h[left], h[right%n], p)==0 || turn(h[right%n], h[0], p)==0) return 2;\n// return 1;\n// }\n\nG2 cutConvex(G2 h, L2 l) {\n int n=h.size();\n G2 res;\n if (n==0) return res;\n auto inside=[&](P2 p){ return turn(l.a, l.b, p) >= 0; };\n rep(i, n) {\n P2 a=h[i], b=h[(i+1)%n];\n bool ina=inside(a), inb=inside(b);\n if (ina&&inb) res.push_back(b);\n else if (ina&&!inb) {\n res.push_back(proj({a,b}, l.a));\n }\n else if (!ina&&inb) {\n res.push_back(proj({a,b}, l.a));\n res.push_back(b);\n }\n }\n return res;\n}\n\n\npair<P2, P2> closestPair(G2 g) {\n auto ps = g;\n int n=ps.size();\n if (n < 2) return {P2(0,0), P2(0,0)};\n sort(all(ps), ltP2);\n D mind = norm(ps[0]-ps[1]);\n pair<P2, P2> res = {ps[0], ps[1]};\n set<pair<D,int>> box;\n int j=0;\n rep(i, n) {\n D xi=real(ps[i]), yi=imag(ps[i]);\n D rad = sqrtl(mind);\n while (j<i && gt(xi - real(ps[j]), rad)) {\n box.erase({imag(ps[j]), j});\n j++;\n }\n auto it = box.lower_bound({yi - rad, -1});\n for (; it != box.end() && le(it->first, yi + rad); ++it) {\n int k = it->second;\n D d = norm(ps[i]-ps[k]);\n if (lt(d, mind)) mind=d, res={ps[i], ps[k]}, rad = sqrtl(mind);\n }\n box.insert({yi, i});\n }\n return res;\n}\n\nstruct C2 { P2 c; D r; };\n\nC2 makeC2(P2 a, P2 b) {\n return C2{(a+b)/D(2), abs(a-b)/D(2)};\n}\nC2 makeC2(P2 a, P2 b, P2 c) {\n P2 B=b-a, C=c-a;\n D d=2*cross(B, C);\n if (eq(d, 0)) {\n D ab=norm(B), bc=norm(b-c), ca=norm(c-a);\n if (le(ab, bc) && le(ab, ca)) return makeC2(a, b);\n if (le(bc, ca)) return makeC2(b, c);\n return makeC2(c, a);\n }\n P2 o=a+(rot90(B)*norm(C)-rot90(C)*norm(B))/d;\n return C2{o, abs(o-a)};\n}\n\nC2 mec(G2 ps) {\n auto inC2=[&](C2 c, P2 p){ return le(abs(c.c - p), c.r); };\n mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n shuffle(all(ps), rng);\n int n=ps.size();\n if(n==0) return C2{P2(0,0), 0};\n C2 c{ps[0], 0};\n rep(i, n) {\n if (inC2(c, ps[i])) continue;\n c={ps[i], 0};\n rep(j, i) {\n if (inC2(c, ps[j])) continue;\n c=makeC2(ps[i], ps[j]);\n rep(k, j) {\n if (inC2(c, ps[k])) continue;\n c=makeC2(ps[i], ps[j], ps[k]);\n }\n }\n }\n return c;\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_A\nvoid Projection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(proj(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_B\nvoid Reflection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(refl(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_C\nvoid CounterClockwise() {\n P2 p0, p1;\n rd(p0); rd(p1);\n ll q; cin>>q;\n while(q--) {\n P2 p; rd(p);\n int res = ccw(p0, p1, p);\n if (res == +1) out(\"COUNTER_CLOCKWISE\");\n else if (res == -1) out(\"CLOCKWISE\");\n else if (res == +2) out(\"ONLINE_BACK\");\n else if (res == -2) out(\"ONLINE_FRONT\");\n else out(\"ON_SEGMENT\");\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_2_A\nvoid ParallelOrthogonal() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n if (isParallel({p1, p2}, {p3, p4})) out(2);\n else if(isPerp({p1, p2}, {p3, p4})) out(1);\n else out(0);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_B\nvoid IntersectionSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n out(isSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_C\nvoid CrossPointSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n L2 s1 = {p1, p2}, s2 = {p3, p4};\n pr(cpLL(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_D\nvoid DistanceSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n cout<<setprecision(12)<<fixed;\n out(distSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_A\nvoid Area() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n cout<<setprecision(12)<<fixed;\n out(area(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_B\nvoid IsConvex() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n out(isConvex(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_C\nvoid PolygonPointContainment() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n out(inG(g, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\nvoid ConvexHull() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n G2 h = hull(g);\n out(h.size());\n rep(i, h.size()) pr(h[i]);\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_B\nvoid DiameterOfConvexPolygon() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = diameter(g);\n cout<<setprecision(12)<<fixed;\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_C\nvoid ConvexCut() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n G2 h = cutConvex(g, l);\n cout<<setprecision(12)<<fixed;\n out(area(h));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_A\nvoid ClosestPair() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = closestPair(g);\n cout<<setprecision(12)<<fixed;\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_B\nvoid MinimumEnclosingCircle() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [c, r] = mec(g);\n pr(c);\n cout<<setprecision(12)<<fixed;\n out(r);\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/6/CGL_6_A\n// void SegmentIntersections() {\n// // todo;\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_A\n// void IntersectionOfCircles() {\n// P2 c1, c2; D r1, r2;\n// rd(c1); cin>>r1;\n// rd(c2); cin>>r2;\n// C2 c1={c1, r1}, c2={c2, r2};\n// out(isCC(c1, c2));\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_B\n// void IncircleOfTriangle() {\n// P2 a, b, c; rd(a); rd(b); rd(c);\n// auto [ic, ir] = incircle(a, b, c);\n// pr(ic);\n// cout<<setprecision(12)<<fixed;\n// out(ir);\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_C\n// void CircumscribedCircleOfTriangle() {\n// P2 a, b, c; rd(a); rd(b); rd(c);\n// auto [cc, cr] = circumcircle(a, b, c);\n// pr(cc);\n// cout<<setprecision(12)<<fixed;\n// out(cr);\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_D\n// void CrossPointsCL() {\n// P2 c; D r;\n// rd(c); cin>>r;\n// ll q;cin>>q;\n// while(q--) {\n// P2 a, b; rd(a); rd(b);\n// L2 l = {a, b};\n// auto ps = cpCL(l, {c, r});\n// sort(all(ps), ltP2);\n// pr(ps[0]);\n// pr(ps[(ps.size()-1)]);\n// }\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_E\n// void CrossPointsCC() {\n// P2 c1, c2; D r1, r2;\n// rd(c1); cin>>r1;\n// rd(c2); cin>>r2;\n// C2 c1={c1, r1}, c2={c2, r2};\n// auto ps = cpCC(c1, c2);\n// sort(all(ps), ltP2);\n// pr(ps[0]);\n// pr(ps[(ps.size()-1)]);\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_F\n// void TangentToCircle() {\n// P2 p, c; D r;\n// rd(p);\n// rd(c); cin>>r;\n// C2 c1={c, r};\n// auto ps = tangentCP(c1, p);\n// sort(all(ps), ltP2);\n// pr(ps[0]);\n// pr(ps[(ps.size()-1)]);\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_G\n// void CommonTangent() {\n// P2 c1, c2; D r1, r2;\n// rd(c1); cin>>r1;\n// rd(c2); cin>>r2;\n// C2 c1={c1, r1}, c2={c2, r2};\n// auto ls = tangentCC(c1, c2);\n// vector<P2> ps;\n// for (auto l : ls) {\n// ps.push_back(l.a);\n// ps.push_back(l.b);\n// }\n// sort(all(ps), ltP2);\n// for (auto p : ps) pr(p);\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_H\n// void IntersectionCP() {\n// ll n;cin>>n;\n// D r; cin>>r;\n// C2 c = {P2(0, 0), r};\n// G2 g(n);\n// rep(i, n) rd(g[i]);\n// out(isaCP(c, g));\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_I\n// void AreaOfIntersectionBetweenTwoCircles() {\n// P2 c1, c2; D r1, r2;\n// rd(c1); cin>>r1;\n// rd(c2); cin>>r2;\n// C2 c1={c1, r1}, c2={c2, r2};\n// cout<<setprecision(12)<<fixed;\n// out(isaCC(c1, c2));\n// }\n\nint main() {\n cin.tie(0);\n ios_base::sync_with_stdio(false);\n\n // Projection();\n // Reflection();\n // CounterClockwise();\n\n // ParallelOrthogonal();\n // IntersectionSS();\n // CrossPointSS();\n // DistanceSS();\n\n // Area();\n // IsConvex();\n // PolygonPointContainment();\n\n // ConvexHull();\n // DiameterOfConvexPolygon();\n // ConvexCut();\n\n // ClosestPair();\n MinimumEnclosingCircle();\n\n // SegmentIntersections();\n\n // IntersectionOfCircles();\n // IncircleOfTriangle();\n // CircumscribedCircleOfTriangle();\n // CrossPointsCL();\n // CrossPointsCC();\n // TangentToCircle();\n // CommonTangent();\n // IntersectionCP();\n // AreaOfIntersectionBetweenTwoCircles();\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 9444, "score_of_the_acc": -1.0662, "final_rank": 19 }, { "submission_id": "aoj_CGL_5_B_10905569", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <climits>\n#include <unordered_map>\n#include <queue>\n#include <deque>\n#include <math.h>\n#include <limits.h>\n#include <set>\n#include <stack>\n#include <map>\n#include <bits/stdc++.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <cmath>\n#define Lt Line<T>\n#define Pt Point<T>\n#define ll long long\n\n\n\n//#define double long double\nusing namespace std;\n\n\nconst ll N=2e4+10,M=1e6+10,MOD=998244353;\n\ntypedef std::pair<ll,ll> pii;\ntypedef std::pair<ll,std::pair<ll,ll> > piii;\n\n\n//ll n,m;\n\nusing ld = long double;\nconst ld PI = acos(-1);\nconst ld EPS = 1e-7;\nconst ld INF = numeric_limits<ld>::max();\n#define cc(x) cout << fixed << setprecision(x);\n\nld fgcd(ld x, ld y) { // 实数域gcd\n return abs(y) < EPS ? abs(x) : fgcd(y, fmod(x, y));\n}\ntemplate<class T, class S> bool equal(T x, S y) {\n return -EPS < x - y && x - y < EPS;\n}\ntemplate<class T> int sign(T x) {\n if (-EPS < x && x < EPS) return 0;\n return x < 0 ? -1 : 1;\n}\n\n\n\ntemplate<class T> struct Point { // 在C++17下使用 emplace_back 绑定可能会导致CE!\n T x, y;\n Point(T x_ = 0, T y_ = 0) : x(x_), y(y_) {} // 初始化\n template<class U> operator Point<U>() { // 自动类型匹配\n return Point<U>(U(x), U(y));\n }\n Point &operator+=(Point p) & { return x += p.x, y += p.y, *this; }\n Point &operator+=(T t) & { return x += t, y += t, *this; }\n Point &operator-=(Point p) & { return x -= p.x, y -= p.y, *this; }\n Point &operator-=(T t) & { return x -= t, y -= t, *this; }\n Point &operator*=(T t) & { return x *= t, y *= t, *this; }\n Point &operator/=(T t) & { return x /= t, y /= t, *this; }\n Point operator-() const { return Point(-x, -y); }\n friend Point operator+(Point a, Point b) { return a += b; }\n friend Point operator+(Point a, T b) { return a += b; }\n friend Point operator-(Point a, Point b) { return a -= b; }\n friend Point operator-(Point a, T b) { return a -= b; }\n friend Point operator*(Point a, T b) { return a *= b; }\n friend Point operator*(T a, Point b) { return b *= a; }\n friend Point operator/(Point a, T b) { return a /= b; }\n friend bool operator<(Point a, Point b) {\n return equal(a.x, b.x) ? a.y < b.y - EPS : a.x < b.x - EPS;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return !(a < b) && !(b < a); }\n friend bool operator!=(Point a, Point b) { return a < b || b < a; }\n friend auto &operator>>(istream &is, Point &p) {\n return is >> p.x >> p.y;\n }\n friend auto &operator<<(ostream &os, Point p) {\n return os << \"(\" << p.x << \", \" << p.y << \")\";\n }\n};\ntemplate<class T> struct Line {\n Point<T> a, b;\n Line(Point<T> a_ = Point<T>(), Point<T> b_ = Point<T>()) : a(a_), b(b_) {}\n template<class U> operator Line<U>() { // 自动类型匹配\n return Line<U>(Point<U>(a), Point<U>(b));\n }\n friend auto &operator<<(ostream &os, Line l) {\n return os << \"<\" << l.a << \", \" << l.b << \">\";\n }\n};\n\nusing Pd = Point<ld>;\nusing Ld = Line<ld>;\n\ntemplate<class T> T cross(Point<T> a, Point<T> b) { // 叉乘\n return a.x * b.y - a.y * b.x;\n}\ntemplate<class T> T cross(Point<T> p1, Point<T> p2, Point<T> p0) { // 叉乘 (p1 - p0) x (p2 - p0);\n return cross(p1 - p0, p2 - p0);\n}\n\ntemplate<class T> T dot(Point<T> a, Point<T> b) { // 点乘\n return a.x * b.x + a.y * b.y;\n}\ntemplate<class T> T dot(Point<T> p1, Point<T> p2, Point<T> p0) { // 点乘 (p1 - p0) * (p2 - p0);\n return dot(p1 - p0, p2 - p0);\n}\n\ntemplate <class T> ld dis(T x1, T y1, T x2, T y2) {\n ld val = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n return sqrt(val);\n}\ntemplate <class T> ld dis(Point<T> a, Point<T> b) {\n return dis(a.x, a.y, b.x, b.y);\n}\n\ntemplate<class T> Point<T> rotate(Point<T> p1, Point<T> p2) { // 旋转\n Point<T> vec = p1 - p2;\n return {-vec.y, vec.x};\n}\n\nPoint<ld> rotate(Point<ld> p, ld rad) {\n return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)};\n}\n\nPoint<ld> rotate(Point<ld> a, Point<ld> b, ld rad) {\n ld x = (a.x - b.x) * cos(rad) + (a.y - b.y) * sin(rad) + b.x;\n ld y = (b.x - a.x) * sin(rad) + (a.y - b.y) * cos(rad) + b.y;\n return {x, y};\n}\n\ntemplate<class T> bool onLine(Point<T> a, Point<T> b, Point<T> c) {\n return sign(cross(b, a, c)) == 0;\n}\ntemplate<class T> bool onLine(Point<T> p, Line<T> l) {\n return onLine(p, l.a, l.b);\n}\n\ntemplate<class T> bool lineParallel(Line<T> p1, Line<T> p2) {\n return sign(cross(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool lineVertical(Line<T> p1, Line<T> p2) {\n return sign(dot(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool same(Line<T> l1, Line<T> l2) {\n return lineParallel(Line{l1.a, l2.b}, {l1.b, l2.a}) &&\n lineParallel(Line{l1.a, l2.a}, {l1.b, l2.b}) && lineParallel(l1, l2);\n}\n\ntemplate<class T> ld disPointToLine(Point<T> p, Line<T> l) {\n ld ans = cross(p, l.a, l.b);\n return abs(ans) / dis(l.a, l.b); // 面积除以底边长\n}\n\ntemplate<class T> bool pointOnSegment(Point<T> p, Line<T> l) { // 端点也算作在直线上\n return sign(cross(p, l.a, l.b)) == 0 && min(l.a.x, l.b.x) <= p.x && p.x <= max(l.a.x, l.b.x) &&\n min(l.a.y, l.b.y) <= p.y && p.y <= max(l.a.y, l.b.y);\n}\n\ntemplate<class T> bool segmentIntersection(Line<T> l1, Line<T> l2) {\n auto [s1, e1] = l1;\n auto [s2, e2] = l2;\n auto A = max(s1.x, e1.x), AA = min(s1.x, e1.x);\n auto B = max(s1.y, e1.y), BB = min(s1.y, e1.y);\n auto C = max(s2.x, e2.x), CC = min(s2.x, e2.x);\n auto D = max(s2.y, e2.y), DD = min(s2.y, e2.y);\n return A >= CC && B >= DD && C >= AA && D >= BB &&\n sign(cross(s1, s2, e1) * cross(s1, e1, e2)) == 1 &&\n sign(cross(s2, s1, e2) * cross(s2, e2, e1)) == 1;\n}//其中重叠、相交于端点均视为不相交。\n\nPd lineIntersection(Ld l1, Ld l2) {\n ld val = cross(l2.b - l2.a, l1.a - l2.a) / cross(l2.b - l2.a, l1.a - l1.b);\n return l1.a + (l1.b - l1.a) * val;\n}\n\npair<Pd, ld> pointToLine(Pd p, Ld l) {\n Pd ans = lineIntersection({p, p + rotate(l.a, l.b)}, l);\n return {ans, dis(p, ans)};\n}\n\npair<Pd, ld> pointToSegment(Pd p, Ld l) {\n if (sign(dot(p, l.b, l.a)) == -1) { // 特判到两端点的距离\n return {l.a, dis(p, l.a)};\n } else if (sign(dot(p, l.a, l.b)) == -1) {\n return {l.b, dis(p, l.b)};\n }\n return pointToLine(p, l);\n}\n\nld DisSegToSeg(Ld l1,Ld l2)\n{\n // if(lineParallel(l1,l2)) \n // {\n // auto [t1,ans1]=pointToSegment(l1.a,l2);\n // return ans1;\n // }\n if(segmentIntersection(l1,l2)) return 0.0;\n auto [t1,ans1]=pointToSegment(l1.a,l2);\n auto [t2,ans2]=pointToSegment(l1.b,l2);\n auto [t3,ans3]=pointToSegment(l2.a,l1);\n auto [t4,ans4]=pointToSegment(l2.b,l1);\n //cout<<ans1<<' '<<ans2<<' '<<ans3<<' '<<ans4<<'\\n';\n return min(min(ans1,ans2),min(ans3,ans4));\n}\n\ntemplate<class T> ld area(vector<Point<T>> P) {\n int n = P.size();\n ld ans = 0;\n for (int i = 0; i < n; i++) {\n ans += cross(P[i], P[(i + 1) % n]);\n }\n return ans / 2.0;\n}\n\ntemplate<class T> vector<Point<T>> staticConvexHull(vector<Point<T>> A, int flag = 1) {\n int n = A.size();\n if (n <= 2) { // 特判\n return A;\n }\n vector<Point<T>> ans(n * 2);\n sort(A.begin(), A.end());\n int now = -1;\n for (int i = 0; i < n; i++) { // 维护下凸包\n while (now > 0 && cross(A[i], ans[now], ans[now - 1]) < 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n int pre = now;\n for (int i = n - 2; i >= 0; i--) { // 维护上凸包\n while (now > pre && cross(A[i], ans[now], ans[now - 1]) <= 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n ans.resize(now);\n sort(ans.begin(),ans.end());\n ans.erase(unique(ans.begin(),ans.end()),ans.end());\n return ans;\n}\n\n\n\ntemplate<class T> T sqr(T x) {\n return x * x;\n}\n\ntemplate<class T> T disEx(Pt a1,Pt a2)\n{\n return (a1.x-a2.x)*(a1.x-a2.x)+(a1.y-a2.y)*(a1.y-a2.y);\n}\n\n// 计算最小包围圆(最小圆覆盖)\n// 输入:点集的迭代器范围 [left, right),随机种子 seed\n// 输出:pair<圆心, 半径平方>\ntemplate <class T>\nstd::pair<Point<T>, ld> min_ball(vector<Pt> A, int seed = 1333) {\n \n const int n = A.size(); // 点的数量\n\n assert(n >= 1); // 至少需要1个点\n \n // 特殊情况处理:只有1个点\n if (n == 1) {\n return {A[0], ld(0)}; // 圆就是点本身,半径为0\n }\n\n // 随机数生成器\n std::mt19937 mt(seed);\n // 随机打乱点集顺序 - 这是保证O(n)期望时间复杂度的关键\n std::shuffle(A.begin(), A.end(), mt);\n\n vector<Pt> &ps=A;\n\n using circle = std::pair<Pt, ld>; // 圆类型:圆心 + 半径平方\n\n // 通过三个点构造圆的lambda函数\n auto make_circle_3 = [](const Pt &a, const Pt &b, const Pt &c) -> circle {\n // 使用三角形外心公式计算圆心\n ld A = disEx(b , c), // |BC|²\n B = disEx(c , a), // |CA|² \n C = disEx(a , b), // |AB|²\n S = cross(b - a, c - a); // 三角形面积的2倍\n \n // 外心坐标公式(重心坐标形式)\n Pt p = (A * (B + C - A) * a + B * (C + A - B) * b + C * (A + B - C) * c) / (4 * S * S);\n ld r2 = disEx(p , a); // 半径的平方\n return {p, r2};\n };\n\n // 通过两个点构造圆的lambda函数(以两点为直径的圆)\n auto make_circle_2 = [](const Pt &a, const Pt &b) -> circle {\n Pt c = (a + b) / (ld)2; // 圆心为两点中点\n ld r2 = disEx(a , c); // 半径平方\n return {c, r2};\n };\n\n // 判断点是否在圆内的lambda函数\n auto in_circle = [](const Pt &a, const circle &c) -> bool {\n // 判断点到圆心的距离平方是否 <= 半径平方 + 容误差\n return disEx(a , c.first) <= c.second + EPS;\n };\n\n // 初始化:用前两个点构造初始圆\n circle c = make_circle_2(ps[0], ps[1]);\n\n // 主循环:逐个处理剩余的点\n for (int i = 2; i < n; ++i) {\n // 如果当前点不在当前圆内,需要更新圆\n if (!in_circle(ps[i], c)) {\n // MiniDiscWithPoint: 新圆必须包含当前点ps[i]\n c = make_circle_2(ps[0], ps[i]); // 初始尝试:用第一个点和当前点构造圆\n \n // 检查前面的点是否都在新圆内\n for (int j = 1; j < i; ++j) {\n if (!in_circle(ps[j], c)) {\n // MiniDiscWith2Points: 新圆必须包含ps[i]和ps[j]\n c = make_circle_2(ps[i], ps[j]); // 用当前两个点构造圆\n \n // 检查更前面的点\n for (int k = 0; k < j; ++k) {\n if (!in_circle(ps[k], c)) {\n // 三个点确定唯一圆\n c = make_circle_3(ps[i], ps[j], ps[k]);\n }\n }\n }\n }\n }\n // 如果当前点在圆内,直接跳过(概率O(1/k),这是算法高效的关键)\n }\n return c;\n}\n\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(0);\n\n cc(12);\n \n int n; cin>>n;\n vector<Pd> z(n);\n for(auto &t:z) cin>>t;\n auto [ans,r]=min_ball(z);\n\n cout<<ans.x<<' '<<ans.y<<' '<<sqrt(r)<<'\\n';\n \n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 9748, "score_of_the_acc": -0.2473, "final_rank": 8 }, { "submission_id": "aoj_CGL_5_B_10897568", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n\nconst double eps = 0;\nstruct Point{\n double x,y;\n bool operator<(Point p){\n if(x!=p.x)return x<p.x;\n return y<p.y;\n }\n};\nstruct cir{\n Point o;\n double r;\n};\nvector<Point>p(100010);\nint n;\ndouble dis(Point a,Point b){\n return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));\n}\ncir get(Point a,Point b,Point c){\n double a1 = b.x-a.x,a2 = c.x-a.x,b1 = b.y-a.y,b2 = c.y-a.y;\n double c1 = b.x*b.x-a.x*a.x+b.y*b.y-a.y*a.y;\n double c2 = c.x*c.x-a.x*a.x+c.y*c.y-a.y*a.y;\n cir ans;\n ans.o = Point{(b2*c1-b1*c2)/(b2*a1*2-b1*a2*2),(a2*c1-a1*c2)/(a2*b1*2-a1*b2*2)};\n ans.r = dis(a,ans.o);\n return ans;\n}\ncir make(){\n cir ans;\n ans.o = p[1];ans.r = 0;\n for(int i =2;i<=n;i++){\n if(dis(ans.o,p[i])>ans.r+eps){\n ans.o = p[i],ans.r = 0;\n for(int j =1;j<=i-1;j++){\n if(dis(ans.o,p[j])>ans.r+eps){\n ans.o.x = (p[i].x+p[j].x)/2;\n ans.o.y =(p[i].y+p[j].y)/2;\n ans.r = dis(ans.o,p[j]);\n for(int k = 1;k<=j-1;k++){\n if(dis(ans.o,p[k])>ans.r+eps){\n ans = get(p[i],p[j],p[k]);\n }\n }\n }\n }\n }\n }\n return ans;\n}\n\nsigned main(){\n cin>>n;\n for(int i =1;i<=n;i++){\n cin>>p[i].x>>p[i].y;\n }\n random_shuffle(p.begin()+1,p.begin()+1+n);\n cir ans = make();\n printf(\"%.10lf %.10lf %.10lf\\n\",ans.o.x,ans.o.y,ans.r);\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4560, "score_of_the_acc": -0.5, "final_rank": 13 }, { "submission_id": "aoj_CGL_5_B_10897565", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n\nconst double eps = 1e-12;\nstruct Point{\n double x,y;\n bool operator<(Point p){\n if(x!=p.x)return x<p.x;\n return y<p.y;\n }\n};\nstruct cir{\n Point o;\n double r;\n};\nvector<Point>p(100010);\nint n;\ndouble dis(Point a,Point b){\n return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));\n}\ncir get(Point a,Point b,Point c){\n double a1 = b.x-a.x,a2 = c.x-a.x,b1 = b.y-a.y,b2 = c.y-a.y;\n double c1 = b.x*b.x-a.x*a.x+b.y*b.y-a.y*a.y;\n double c2 = c.x*c.x-a.x*a.x+c.y*c.y-a.y*a.y;\n cir ans;\n ans.o = Point{(b2*c1-b1*c2)/(b2*a1*2-b1*a2*2),(a2*c1-a1*c2)/(a2*b1*2-a1*b2*2)};\n ans.r = dis(a,ans.o);\n return ans;\n}\ncir make(){\n cir ans;\n ans.o = p[1];ans.r = 0;\n for(int i =2;i<=n;i++){\n if(dis(ans.o,p[i])>ans.r+eps){\n ans.o = p[i],ans.r = 0;\n for(int j =1;j<=i-1;j++){\n if(dis(ans.o,p[j])>ans.r+eps){\n ans.o.x = (p[i].x+p[j].x)/2;\n ans.o.y =(p[i].y+p[j].y)/2;\n ans.r = dis(ans.o,p[j]);\n for(int k = 1;k<=j-1;k++){\n if(dis(ans.o,p[k])>ans.r+eps){\n ans = get(p[i],p[j],p[k]);\n }\n }\n }\n }\n }\n }\n return ans;\n}\n\nsigned main(){\n cin>>n;\n for(int i =1;i<=n;i++){\n cin>>p[i].x>>p[i].y;\n }\n random_shuffle(p.begin()+1,p.begin()+1+n);\n cir ans = make();\n printf(\"%.10lf %.10lf %.10lf\\n\",ans.o.x,ans.o.y,ans.r);\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 4568, "score_of_the_acc": -0.5004, "final_rank": 14 }, { "submission_id": "aoj_CGL_5_B_10878925", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define fio ios_base::sync_with_stdio(0); cin.tie(0); cin.exceptions(cin.failbit);\n#define int long long\n#define vt vector\n#define pb emplace_back\n#define sz(x) (int) x.size()\n#define all(x) x.begin(), x.end()\n#define rep(i, from, to) for (int i = from; i <= to; ++i)\n#pragma GCC optimize(\"Ofast,unroll-loops,no-stack-protector,fast-math\")\n// #pragma GCC target(\"avx,avx2,fma\")\n#define X first\n#define Y second\n#define PD pair<double, double>\nconst int mxn = 1000 + 5, MOD = 1e9 + 7, INF = 0x3f3f3f3f3f3f3f3f;\nPD operator + (PD a, PD b) {return {a.X + b.X, a.Y + b.Y};}\nPD operator - (PD a, PD b) {return {a.X - b.X, a.Y - b.Y};}\ndouble operator ^ (PD a, PD b) {return a.X * b.Y - a.Y * b.X;}\ndouble abs2(PD a) {return a.X * a.X + a.Y * a.Y;}\nPD operator / (PD a, double b) {return {a.X / b, a.Y / b};}\nint n, m;\n\n// 外心\npair<PD, double> circumCenter (PD a, PD b, PD c) {\n b = b - a; c = c - a;\n double area4 = 2. * (b ^ c);\n PD center;\n center.X = (b.X * b.X * c.Y - c.X * c.X * b.Y + b.Y * c.Y * (b.Y - c.Y)) / area4;\n center.Y = (b.X * c.X * (c.X - b.X) - b.Y * b.Y * c.X + b.X * c.Y * c.Y) / area4;\n return {a + center, abs2(center)};\n}\n// 最小覆蓋圓\npair<PD, double> minimumEnclosingCircle (vt<PD> &pts) {\n // random shuffle make it O(n)\n mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n shuffle(all(pts), rng);\n \n PD c = pts[0];\n double r2 = 0;\n rep(i, 1, sz(pts) - 1) {\n if (abs2(pts[i] - c) <= r2) continue;\n c = pts[i]; r2 = 0;\n rep(j, 0, i - 1) {\n if (abs2(pts[j] - c) <= r2) continue;\n c = (pts[i] + pts[j]) / 2;\n r2 = abs2(pts[i] - c);\n rep(k, 0, j - 1) {\n if (abs2(pts[k] - c) > r2) {\n tie(c, r2) = circumCenter(pts[i], pts[j], pts[k]);\n }\n }\n }\n }\n return {c, r2};\n}\n\nvoid solve() {\n cin >> n;\n vt<pair<double, double>> pts;\n rep(i, 1, n) {\n PD pt;\n cin >> pt.X >> pt.Y;\n pts.pb(pt);\n }\n auto [c, r2] = minimumEnclosingCircle(pts);\n cout << setprecision(10) << fixed << c.X << ' ' << c.Y << ' ' << sqrtl(r2) << '\\n';\n}\n\nsigned main(void){\n #ifdef AutoIO\n freopen(\"P:\\\\Code\\\\C\\\\input.txt\",\"r\",stdin);\n freopen(\"P:\\\\Code\\\\C\\\\output.txt\",\"w\",stdout);\n #endif\n fio\n int t = 1;\n // cin >> t;\n while (t--) solve();\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 5256, "score_of_the_acc": -0.1998, "final_rank": 5 }, { "submission_id": "aoj_CGL_5_B_10855303", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nnamespace DBG\n{\n template <class T>\n void _dbg(const char *f, T t) { cerr << f << '=' << t << '\\n'; }\n template <class A, class... B>\n void _dbg(const char *f, A a, B... b)\n {\n while (*f != ',')\n cerr << *f++;\n cerr << '=' << a << \",\";\n _dbg(f + 1, b...);\n }\n template <typename Container>\n void _print(const char *f, const Container &v)\n {\n cerr << f << \" = [ \";\n for (const auto &x : v)\n cerr << x << \", \";\n cerr << \"]\\n\";\n }\n#define bug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n#define bugv(container) _print(#container, container)\n}\nusing namespace DBG;\n\nvoid _();\nint main()\n{\n ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n cout << fixed << setprecision(10);\n int T = 1;\n // cin >> T;\n while (T--)\n _();\n return 0;\n}\n\n#define int long long\n\nusing ld = long double;\nconst ld eps = 1e-9; // 9 12 15\nconst ld PI = acos(-1);\n#define Pt Point<T>\n#define Pd Point<ld>\n#define Lt Line<T>\n#define Ld Line<ld>\n\nint sign(ld x) // 判符号\n{\n if (fabsl(x) < eps)\n return 0;\n else\n return x < 0 ? -1 : 1;\n}\nbool equal(ld x, ld y) { return !sign(x - y); } // 近似\nbool big(ld has, ld tar) { return sign(has - tar) > 0; }\n\n//////////////////////////////////////////////////////////////////////////// 点类\n\n// 点与向量\ntemplate <class T>\nstruct Point\n{\n T x, y;\n\n Point(T x = 0, T y = 0) : x(x), y(y) {} // 带参构造\n\n // 运算符重载\n Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }\n Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }\n Point operator*(T k) const { return Point(x * k, y * k); }\n Point operator/(T k) const { return Point(x / k, y / k); }\n\n friend bool operator<(Point a, Point b)\n {\n if (!equal(a.x, b.x))\n return a.x < b.x;\n return a.y < b.y;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return equal(a.x, b.x) && equal(a.y, b.y); } // 近似\n friend bool operator!=(Point a, Point b) { return !(a == b); }\n friend auto &operator>>(istream &is, Point &p) { return is >> p.x >> p.y; }\n friend auto &operator<<(ostream &os, Point p) { return os << \"(\" << p.x << \", \" << p.y << \")\"; }\n};\n\nld len(Point<ld> a) { return sqrtl(a.x * a.x + a.y * a.y); }; // 模长\nld dis(Point<ld> a, Point<ld> b) { return len(a - b); } // 两点距离\nld dis1(Pd a, Pd b) { return abs(a.x - b.x) + abs(a.y - b.y); } // 曼哈顿距离\n\nld cross(Point<ld> a, Point<ld> b) { return a.x * b.y - a.y * b.x; } // 叉积 ab*sin 两点与原点三角形面积 判两点位置关系两侧\nld cross(Point<ld> p0, Point<ld> p1, Point<ld> p2) { return cross(p1 - p0, p2 - p0); }\nld dot(Point<ld> a, Point<ld> b) { return a.x * b.x + a.y * b.y; } // 点积 ab*cos 结合判两点象限位置关系\nld dot(Point<ld> p0, Point<ld> p1, Point<ld> p2) { return dot(p1 - p0, p2 - p0); }\nld angle(Point<ld> a, Point<ld> b) { return atan2(cross(a, b), dot(a, b)); } // 向量夹角[-pi, pi] 非负fabsl\nld angle(Pd p) { return atan2l(p.y, p.x); } // 极角\n\nbool angle0(Pd a, Pd b) { return fabs(cross(a, b)) < eps && dot(a, b) > 0; } // 夹角为0\nbool angle180(Pd a, Pd b) { return cross(a, b) < eps && !angle0(a, b); } // 夹角为180\n\nPoint<ld> standardize(Point<ld> h) // 转换为单位向量\n{\n ld l = len(h);\n if (sign(l) == 0)\n return {0, 0}; // 防止除零\n return h / l;\n}\nPd rotate(Pd p, ld rad) { return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)}; } // 向量旋转任意角度\n\nPd rotate90(Pd a) { return Point<ld>{-a.y, a.x}; } // 旋转90° 垂直向量\nld toDeg(ld x) { return x * 180 / PI; } // 弧度转角度\nld toArc(ld x) { return PI / 180 * x; } // 角度转弧度\nld angle(ld a, ld b, ld c) { return acos((a * a + b * b - c * c) / (2.0 * a * b)); } // 余弦定理 三边求角C弧度\n\nvoid psort(vector<Pd> &ps, Pd o = Pd(0, 0)) // 选定极点 极角排序 ✅\n{ // 三四一二 [ (0, -1), (1, 0), (0, 1), (-1, 0), ]\n sort(ps.begin(), ps.end(), [&](Pd &A, Pd &B)\n { A=A-o,B=B-o;\n\t auto f=[](Pd A){return A.y>0||(A.y==0&&A.x<0);};\n\t if(f(A)!=f(B))return f(A)<f(B);\n\t else if(cross(A,B)!=0)return cross(A,B)>0;\n\t return dis(A,{0,0})<dis(B,{0,0}); });\n}\n//////////////////////////////////////////////////////////////////////// 直线与线段\n\n// 直线\ntemplate <class T>\nstruct Line\n{\n Point<T> a, b;\n Line(Pt a_ = {}, Pt b_ = {}) : a(a_), b(b_) {}\n friend auto &operator<<(ostream &os, Line l) { return os << \"<\" << l.a << \", \" << l.b << \">\"; }\n};\nbool pointOnLineLeft(Pd p, Ld l) { return cross(l.b - l.a, p - l.a) > 0; } // 点在直线左侧 ✅\nbool onLine(Pd a, Pd b, Pd c) { return sign(cross(a - b, c - b)) == 0; } // 点是否在直线上(三点是否共线)✅\nbool onLine(Pd p, Ld l) { return onLine(p, l.a, l.b); }\n// 线段:点是否在线段上 ✅\nbool pointOnSegment(Pd p, Ld l) { return fabsl(cross(l.a - p, l.b - p)) < eps && dot(l.a - p, l.b - p) <= 0; }\nbool Parallel(Pd p1, Pd p2) { return equal(0, cross(p1, p2)); } // 平行 ✅\nbool Orthogonal(Pd p1, Pd p2) { return equal(0, dot(p1, p2)); } // 垂直 ✅\nLd midSegment(Ld l) { return {(l.a + l.b) / 2, (l.a + l.b) / 2 + rotate90(l.a - l.b)}; } // 线段的中垂线\n\nld disPointToLine(Pd p, Ld l, bool isSegment = false) // 点到直线/线段的最近距离 ✅\n{\n ld len_ab = dis(l.a, l.b);\n if (sign(len_ab) == 0)\n return dis(p, l.a);\n if (!isSegment)\n {\n ld ans = cross(p, l.a, l.b);\n return fabsl(ans) / dis(l.a, l.b); // 面积除以底边长\n }\n else\n {\n if (dot(p - l.a, l.b - l.a) <= 0)\n return dis(p, l.a);\n if (dot(p - l.b, l.a - l.b) <= 0)\n return dis(p, l.b);\n ld ans = cross(p, l.a, l.b);\n return fabsl(ans) / dis(l.a, l.b);\n }\n}\n\nPd lineIntersection(Ld l1, Ld l2, bool seg1 = false, bool seg2 = false) // 两直线/线段相交交点 ✅\n{\n ld det = cross(l1.b - l1.a, l2.b - l2.a);\n if (sign(det) == 0) // 1. 平行或共线\n {\n if (sign(cross(l2.a - l1.a, l1.b - l1.a)) != 0) // 如果不共线 -> 平行\n return Pd(1e18, 1e18);\n\n if (!seg1 || !seg2)\n return seg1 ? l1.a : l2.a; // 含直线的情况\n\n if (pointOnSegment(l1.a, l2)) // 共线情况:检查端点是否重合/相连\n return l1.a;\n if (pointOnSegment(l1.b, l2))\n return l1.b;\n if (pointOnSegment(l2.a, l1))\n return l2.a;\n if (pointOnSegment(l2.b, l1))\n return l2.b;\n return Pd(1e18, 1e18); // 完全不相交\n }\n\n ld t = cross(l2.a - l1.a, l2.b - l2.a) / det; // 2. 一般情况,唯一交点\n Pd inter = l1.a + (l1.b - l1.a) * t;\n\n if ((seg1 && !pointOnSegment(inter, l1)) || (seg2 && !pointOnSegment(inter, l2)))\n return Pd(1e18, 1e18); // 不在线段上\n\n return inter;\n}\n\nPd project(Pd p, Ld l, bool isSegment = false) // 点在直线/线段上的投影点(垂足)✅\n{\n Pd h = l.b - l.a;\n ld r = dot(h, p - l.a) / (h.x * h.x + h.y * h.y);\n Pd pro = l.a + h * r;\n if (isSegment)\n {\n if (dot(pro - l.a, l.b - l.a) < 0)\n return l.a;\n if (dot(pro - l.b, l.a - l.b) < 0)\n return l.b;\n }\n return pro;\n}\n// //////////////////////////////////////////////////////////////////////////////////// 圆\n\nstruct Circle\n{\n Pd o;\n ld r;\n Circle(Pd o_ = {}, ld r_ = 0) : o(o_), r(r_) {}\n};\n\n// 外心 三角形外接圆的圆心,三角形三边垂直平分线的交点 ✅\nPd center1(Pd p1, Pd p2, Pd p3) { return lineIntersection(midSegment({p1, p2}), midSegment({p2, p3})); }\n// 内心 三角形内切圆的圆心,三角形三个内角的角平分线的交点 到三角形三边的距离相等 ✅\nPd center2(Pd p1, Pd p2, Pd p3)\n{\n#define atan2t(p) atan2(p.y, p.x)\n Line<ld> U = {p1, {}}, V = {p2, {}};\n ld m, n, alpha;\n m = atan2t((p2 - p1));\n n = atan2t((p3 - p1));\n alpha = (m + n) / 2;\n U.b = {p1.x + cos(alpha), p1.y + sin(alpha)};\n m = atan2t((p1 - p2));\n n = atan2t((p3 - p2));\n alpha = (m + n) / 2;\n V.b = {p2.x + cos(alpha), p2.y + sin(alpha)};\n return lineIntersection(U, V);\n}\n// 垂心 三角形的三条高线所在直线的交点 锐角三角形的垂心在三角形内;直角三角形的垂心在直角顶点上;钝角三角形的垂心在三角形外\nPd center3(Pd p1, Pd p2, Pd p3)\n{\n Ld U = {p1, p1 + rotate90(p2 - p3)}; // 垂线\n Ld V = {p2, p2 + rotate90(p1 - p3)};\n return lineIntersection(U, V);\n}\n\ntuple<int, Pd, Pd> lineCircleCross(Ld l, Pd o, ld r) // 直线是否与圆相交及交点\n{ // 同时返回相交状态和交点:0代表不相交;1代表相切;2代表相交\n Pd P = project(o, l);\n ld d = dis(P, o), tmp = r * r - d * d;\n if (sign(tmp) == -1)\n return {0, {}, {}};\n else if (sign(tmp) == 0)\n return {1, P, {}};\n Pd vec = standardize(l.b - l.a) * sqrt(tmp);\n return {2, P + vec, P - vec};\n}\ntuple<int, Pd, Pd> segmentCircleCross(Ld l, Pd o, ld r) // 线段与圆交点个数\n{\n auto [type, U, V] = lineCircleCross(l, o, r);\n bool f1 = pointOnSegment(U, l), f2 = pointOnSegment(V, l);\n if (type == 1 && f1)\n return {1, U, {}};\n else if (type == 2 && f1 && f2)\n return {3, U, V};\n else if (type == 2 && f1)\n return {2, U, {}};\n else if (type == 2 && f2)\n return {2, V, {}};\n else\n return {0, {}, {}};\n}\n\n// 两圆是否相交及交点 同时返回相交状态和交点: 0-内含, 1-相离, 2-相切, 3-相交{1交点时判内切外切} ✅\ntuple<int, Pd, Pd> circleIntersection(Circle c1, Circle c2)\n{\n Pd p1 = c1.o;\n ld r1 = c1.r;\n Pd p2 = c2.o;\n ld r2 = c2.r;\n ld d = dis(p1, p2);\n if (sign(d) == 0)\n return {(equal(r1, r2) ? -1 : 0), {}, {}}; // 重合 or 不交\n if (sign(r1 + r2 - d) < 0)\n return {1, {}, {}}; // 外离\n if (sign(fabsl(r1 - r2) - d) > 0)\n return {0, {}, {}}; // 内含\n ld x = (d * d + r1 * r1 - r2 * r2) / (2 * d);\n ld y = sqrtl(max((ld)0, r1 * r1 - x * x));\n Pd mid = p1 + (p2 - p1) * (x / d);\n Pd pA = mid + rotate(standardize(p2 - p1), PI / 2) * y;\n Pd pB = mid - rotate(standardize(p2 - p1), PI / 2) * y;\n if (pA == pB)\n return {2, pA, pA};\n return {3, pA, pB};\n}\n\n// 根据圆心角获取圆上某点 将圆上最右侧的点以圆心为旋转中心,逆时针旋转 rad 度\nPoint<ld> getPoint(Point<ld> p, ld r, ld rad) { return {p.x + cos(rad) * r, p.y + sin(rad) * r}; }\n\nint tangentCnt(Circle c1, Circle c2) // 公切线数量 两圆位置关系 ✅\n{ // 0内含 1内接 2相交 3相切 4相离\n if (c1.r < c2.r)\n swap(c1, c2);\n ld d = len(c1.o - c2.o);\n ld r = c1.r + c2.r;\n if (equal(d, r))\n return 3;\n if (d > r)\n return 4;\n if (equal(d + c2.r, c1.r))\n return 1;\n if (d + c2.r < c1.r)\n return 0;\n return 2;\n}\n\nld disEx(Pd a, Pd b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } // dis无开根版\n\npair<int, vector<Point<ld>>> tangent(Point<ld> p, Circle c) // 点到圆的切线数量与切点 ✅\n{\n Point<ld> A = c.o;\n ld r = c.r;\n vector<Point<ld>> ans;\n Point<ld> u = p - A;\n ld d = len(u);\n if (d < r - eps)\n return {0, {}}; // 点在圆内,无切线\n\n else if (sign(d - r) == 0)\n {\n ans.push_back(p); // 点在圆上,切点就是自己\n return {1, ans};\n }\n else // 点在圆外,有两条切线\n {\n u = u / d; // 单位向量\n Pd v = rotate90(u);\n ld h = sqrt(d * d - r * r);\n ans.push_back(A + u * (r * r / d) + v * (r * h / d));\n ans.push_back(A + u * (r * r / d) - v * (r * h / d));\n return {2, ans};\n }\n}\n\n// 同时返回两圆公切线数量以及每个圆的切点。 ✅\ntuple<int, vector<Point<ld>>, vector<Point<ld>>> tangent(Circle c1, Circle c2)\n{\n Point<ld> A = c1.o;\n ld Ar = c1.r;\n Point<ld> B = c2.o;\n ld Br = c2.r;\n vector<Point<ld>> a, b;\n\n bool swapped = false;\n if (Ar < Br)\n swap(Ar, Br), swap(A, B), swapped = true;\n\n ld d2 = disEx(B, A); // 平方距离\n ld dif = Ar - Br, sum = Ar + Br;\n if (d2 < dif * dif)\n return {0, {}, {}}; // 内含\n ld base = atan2(B.y - A.y, B.x - A.x);\n if (d2 == 0 && Ar == Br)\n return {-1, {}, {}}; // 重合\n if (d2 == dif * dif)\n { // 内切\n a.push_back(getPoint(A, Ar, base));\n b.push_back(getPoint(B, Br, base));\n if (swapped)\n return {1, b, a};\n else\n return {1, a, b};\n }\n ld d = sqrt(d2);\n ld ang = acos(dif / d);\n a.push_back(getPoint(A, Ar, base + ang));\n a.push_back(getPoint(A, Ar, base - ang));\n b.push_back(getPoint(B, Br, base + ang));\n b.push_back(getPoint(B, Br, base - ang));\n\n if (d2 == sum * sum) // 外切\n {\n a.push_back(getPoint(A, Ar, base));\n b.push_back(getPoint(B, Br, base + PI));\n }\n else if (d2 > sum * sum) // 相离\n {\n ang = acos(sum / d);\n a.push_back(getPoint(A, Ar, base + ang));\n a.push_back(getPoint(A, Ar, base - ang));\n b.push_back(getPoint(B, Br, base + ang + PI));\n b.push_back(getPoint(B, Br, base - ang + PI));\n }\n\n if (swapped)\n return {(int)a.size(), b, a};\n else\n return {(int)a.size(), a, b};\n}\n\n// 两圆相交面积 ✅\nld circleIntersectionArea(Circle c1, Circle c2)\n{\n Pd p1 = c1.o;\n ld r1 = c1.r;\n Pd p2 = c2.o;\n ld r2 = c2.r;\n ld d = dis(p1, p2);\n if (sign(fabsl(r1 - r2) - d) >= 0) // 一圆包含另一圆\n return PI * min(r1 * r1, r2 * r2);\n if (sign(r1 + r2 - d) <= 0) // 两圆相离\n return 0;\n\n ld theta1 = angle(r1, d, r2);\n ld theta2 = angle(r2, d, r1);\n ld area1 = r1 * r1 * (theta1 - sin(2 * theta1) / 2);\n ld area2 = r2 * r2 * (theta2 - sin(2 * theta2) / 2);\n return area1 + area2;\n}\n\n// 点到圆的最近点\n// 返回 {圆上最近点, 距离}\n// pair<Pd, ld> pointToCircle(Pd p, Pd o, ld r) {\n// if (r < 0) { // 非法半径\n// return {o, -1};\n// }\n// Pd v = p - o;\n// ld d = len(v);\n// if (sign(d) == 0) {\n// // p 就是圆心,任意取圆上点\n// Pd nearest = {o.x + r, o.y};\n// return {nearest, r};\n// }\n// Pd nearest = o + v * (r / max(d, eps)); // 防止除0\n// return {nearest, dis(p, nearest)};\n// }\n\n// 三点确定一圆\n// 返回 (状态, 圆)\n// 状态:0:不存在(三点共线或重合) 1:唯一圆\npair<int, Circle> getCircle(Pd A, Pd B, Pd C)\n{\n if (sign(len(A - B)) == 0 || sign(len(A - C)) == 0 || sign(len(B - C)) == 0)\n return {0, {}}; // 排除退化情况:点重合\n if (sign(cross(B - A, C - A)) == 0) // 排除三点共线\n return {0, {}};\n\n Pd o = center1(A, B, C);\n ld r = dis(A, o);\n return {1, Circle(o, r)};\n}\nCircle minCircle(vector<Pd> &p) // 最小圆覆盖\n{\n random_shuffle(p.begin(), p.end()); // 随机打乱\n Circle c = {p[0], 0};\n int n = p.size();\n for (int i = 1; i < n; i++)\n if (c.r < dis(c.o, p[i]))\n {\n c = {p[i], 0};\n for (int j = 0; j < i; j++)\n if (c.r < dis(c.o, p[j]))\n {\n c = {(p[i] + p[j]) / 2, dis(p[i], p[j]) / 2};\n for (int k = 0; k < j; k++)\n if (c.r < dis(c.o, p[k]))\n c = getCircle(p[i], p[j], p[k]).second;\n }\n }\n return c;\n}\n\nvoid _()\n{\n int n;\n cin >> n;\n vector<Pd> p(n);\n for (auto &v : p)\n cin >> v;\n\n auto C = minCircle(p);\n\n // cout << C.r << ' ';\n cout << C.o.x << ' ' << C.o.y << ' ' << C.r << '\\n';\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 6236, "score_of_the_acc": -0.2466, "final_rank": 7 }, { "submission_id": "aoj_CGL_5_B_10854463", "code_snippet": "#include<bits/stdc++.h>\n#define siz(x) int((x).size())\n#define all(x) std::begin(x),std::end(x)\n#define fi first\n#define se second\nusing namespace std;\nusing unt=unsigned;\nusing loli=long long;\nusing lolu=unsigned long long;\nusing pii=pair<int,int>;\nmt19937_64 rng(random_device{}());\nconstexpr double eps=1e-8;\ntemplate<typename any>inline any sqr(const any &x){return x*x;}\ninline int get_op(double x){if(fabs(x)<eps)return 0;return x>0?1:-1;}\ndouble det(array<double,3>a0,array<double,3>a1,array<double,3>a2){\n\tdouble sum=0;\n\tsum+=a0[0]*a1[1]*a2[2];\n\tsum+=a1[0]*a2[1]*a0[2];\n\tsum+=a2[0]*a0[1]*a1[2];\n\tsum-=a0[2]*a1[1]*a2[0];\n\tsum-=a0[1]*a1[0]*a2[2];\n\tsum-=a0[0]*a1[2]*a2[1];\n\treturn sum;\n}\nstruct bector{\n\tdouble x,y;\n\tbool operator<(const bector&t)const{return fabs(x-t.x)<eps?y<t.y:x<t.x;}\n\tbool operator==(const bector&t)const{return fabs(x-t.x)<eps&&fabs(y-t.y)<eps;}\n\tbector(double a=0,double b=0):x(a),y(b){}\n\tdouble operator~()const{return sqrt(x*x+y*y);}\n\tdouble operator*()const{return x*x+y*y;}\n\tfriend istream&operator>>(istream&a,bector&b){return a>>b.x>>b.y;}\n\tfriend ostream&operator<<(ostream&a,const bector&b){return a<<b.x<<' '<<b.y;}\n\tfriend bector operator+(const bector&a,const bector&b){return {a.x+b.x,a.y+b.y};}\n\tbector&operator+=(const bector&t){x+=t.x,y+=t.y;return *this;}\n\tfriend bector operator-(const bector&a,const bector&b){return {a.x-b.x,a.y-b.y};}\n\tbector&operator-=(const bector&t){x-=t.x,y-=t.y;return *this;}\n\tfriend bector operator*(const bector&a,double b){return {a.x*b,a.y*b};}\n\tfriend bector operator*(double b,const bector&a){return {a.x*b,a.y*b};}\n\tbector&operator*=(double t){x*=t,y*=t;return *this;}\n\tfriend bector operator/(const bector&a,double b){return {a.x/b,a.y/b};}\n\tbector&operator/=(double t){x/=t,y/=t;return *this;}\n\tfriend double operator*(const bector&a,const bector&b){return a.x*b.x+a.y*b.y;}\n\tfriend double operator/(const bector&a,const bector&b){return a.x*b.y-a.y*b.x;}\n\tbool frontis(const bector&t)const{auto r=*this*t;return get_op(r)>0;}\n\tbool backis(const bector&t)const{auto r=*this*t;return get_op(r)<0;}\n\tbool leftis(const bector&t)const{auto r=*this/t;return get_op(r)>0;}\n\tbool rightis(const bector&t)const{auto r=*this/t;return get_op(r)<0;}\n\tbool front1s(const bector&t)const{auto r=*this*t;return get_op(r)>=0;}\n\tbool back1s(const bector&t)const{auto r=*this*t;return get_op(r)<=0;}\n\tbool left1s(const bector&t)const{auto r=*this/t;return get_op(r)>=0;}\n\tbool right1s(const bector&t)const{auto r=*this/t;return get_op(r)<=0;}\n\tfriend double dis(const bector&a,const bector&b){return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}\n\tbector rot90()const{return {-y,x};}\n\tdouble arg()const{return atan2(y,x);}\n\tbector rotate(const bector&a,double r){\n\t\tauto u=a-*this;\n\t\treturn *this+bector{u.x*cos(r)-u.y*sin(r),u.x*sin(r)+u.y*cos(r)};\n\t}\n\tfriend double c0s(const bector&x,const bector&y){\n\t\t// 求 cos<x,y>\n\t\treturn x*y/~x/~y;\n\t}\n\tbector unit()const{\n\t\treturn (*this)/~(*this);\n\t}\n\tfriend bool operator&(const bector&a,const bector&b){return !get_op(a*b);}\n\tfriend bool operator|(const bector&a,const bector&b){return !get_op(a/b);}\n\tfriend double triarea(const bector&x,const bector&y,const bector&z){\n\t\treturn (y-x)/(z-x)/2;\n\t}\n};\nbector polar(double p,double r){return {cos(r)*p,sin(r)*p};}\nstruct segment{\n\tbector p1,p2;\n\tsegment(const bector&a={0,0},const bector&b={0,0}):p1(a),p2(b){};\n\tfriend istream&operator>>(istream&a,segment &b){return a>>b.p1>>b.p2;}\n\tfriend ostream&operator<<(ostream&a,const segment&b){return a<<b.p1<<' '<<b.p2;}\n\tfriend bool operator&(const segment&a,const segment&b){return !get_op((a.p2-a.p1)*(b.p2-b.p1));}\n\tfriend bool operator|(const segment&a,const segment&b){return !get_op((a.p2-a.p1)/(b.p2-b.p1));}\n\tbool leftis(const bector&t)const{return (p2-p1).leftis(t-p1);}\n\tbool rightis(const bector&t)const{return (p2-p1).rightis(t-p1);}\n\tbool left1s(const bector&t)const{return (p2-p1).left1s(t-p1);}\n\tbool right1s(const bector&t)const{return (p2-p1).right1s(t-p1);}\n\tbool check(const bector&t)const{\n\t\t// cerr<<left1s(t)<<' '<<right1s(t)<<'\\n';\n\t\treturn left1s(t)&&right1s(t);\n\t}\n\t// bool check(const bector&t)const{return left1s(t)&&right1s(t);}\n\tfriend bool banana(const segment&a,const segment&b){\n\t\t// 判断是否相交\n\t\tif(min(a.p1.x,a.p2.x)>max(b.p1.x,b.p2.x)||min(b.p1.x,b.p2.x)>max(a.p1.x,a.p2.x)||min(a.p1.y,a.p2.y)>max(b.p1.y,b.p2.y)||min(b.p1.y,b.p2.y)>max(a.p1.y,a.p2.y))return false;\n\t\treturn get_op(((a.p2-a.p1)/(b.p1-a.p1))*((a.p2-a.p1)/(b.p2-a.p1)))<=0&&get_op(((b.p2-b.p1)/(a.p1-b.p1))*((b.p2-b.p1)/(a.p2-b.p1)))<=0;\n\t}\n\tfriend bector focus(const segment&a,const segment&b){\n\t\t// 输入必须保证有交,输出交点\n\t\tbector v=a.p2-a.p1,w=b.p2-b.p1,u=a.p1-b.p1;\n\t\treturn a.p1+v*((w/u)/(v/w));\n\t}\n\tfriend double dis(const segment&a,const bector&b){\n\t\tif(a.p1==a.p2)return ~(b-a.p1);\n\t\tauto v1=a.p2-a.p1,v2=b-a.p1,v3=b-a.p2;\n\t\tif(v1.backis(v2))return ~v2;\n\t\tif(v1.frontis(v3))return ~v3;\n\t\treturn fabs(v1/v2)/~v1;\n\t}\n\tfriend double dis(const segment&a,const segment&b){\n\t\t// 求线段间最短距离\n\t\tif(banana(a,b))return 0;\n\t\treturn min({dis(a,b.p1),dis(a,b.p2),dis(b,a.p1),dis(b,a.p2)});\n\t}\n\tbector project(const bector&a)const{\n\t\t// 求点 a 在当前线段上的投影点坐标\n\t\tif(a==p1||a==p2)return a;\n\t\tauto u=p2-p1,v=a-p1;\n\t\treturn c0s(u,v)*(~v)*u.unit()+p1;\n\t}\n\tdouble pr0ject(const bector&a)const{\n\t\treturn dis(a,project(a));\n\t}\n\tbector reflect(const bector&a)const{\n\t\t// 求点 a 在当前线段上的对称点\n\t\treturn 2*project(a)-a;\n\t}\n\tsegment&sort(){if(p2<p1)std::swap(p1,p2);return *this;}\n};\nstruct circle{\n\tbector p;double r;\n\tcircle(const bector&a={0,0},double b=0):p(a),r(b){}\n\tcircle(bector p1,bector p2){\n\t\tp=(p1+p2)/2;\n\t\tr=dis(p1,p2)/2;\n\t}\n\tcircle(bector p1,bector p2,bector p3){\n\t\tp.x=det({*p1,p1.y,1},{*p2,p2.y,1},{*p3,p3.y,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tp.y=-det({*p1,p1.x,1},{*p2,p2.x,1},{*p3,p3.x,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tr=dis(p,p1);\n\t}\n\tfriend istream&operator>>(istream&a,circle &b){return a>>b.p>>b.r;}\n\tfriend ostream&operator<<(ostream&a,const circle &b){return a<<b.p<<' '<<b.r;}\n\tbool check(bector t){\n\t\treturn dis(p,t)-r<=eps;\n\t}\n\tfriend segment focus(const circle &a,const segment&b){\n\t\tauto d=b.project(a.p),u=b.p2-b.p1,e=u/~u;\n\t\tauto t=sqrt(a.r*a.r-sqr(dis(d,a.p)));\n\t\treturn segment{d+e*t,d-e*t}.sort();\n\t}\n\tfriend segment focus(const circle &a,const circle &b){\n\t\tauto d=dis(a.p,b.p),l=acos((sqr(a.r)+sqr(d)-sqr(b.r))/(2*a.r*d)),t=(b.p-a.p).arg();\n\t\treturn segment{a.p+polar(a.r,t+l),a.p+polar(a.r,t-l)}.sort();\n\t}\n\tsegment tangent(const bector&a){\n\t\tauto u=a-p;\n\t\tauto l=acos(r/~u);\n\t\tu=u*r/~u;\n\t\treturn segment{p.rotate(p+u,+l),p.rotate(p+u,-l)}.sort();\n\t}\n};\nstruct points:vector<bector>{\n#define p (*this)\n\tpoints&read(istream&t,int n=-1){\n\t\tif(n==-1)cin>>n;\n\t\tp.resize(n);\n\t\tfor(int i=0;i<n;i++)t>>p[i];\n\t\treturn *this;\n\t}\n\tdouble area()const{\n\t\t// 无需满足多边形是凸的\n\t\tdouble ans=0;\n\t\tfor(int i=1;i<siz(p)-1;i++)ans+=(p[i]-p[0])/(p[i+1]-p[0]);\n\t\treturn ans/2;\n\t}\n\tpoints tobag(){\n\t\tsort(all(p));\n\t\terase(unique(all(p)),end());\n\t\tpoints b;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\twhile(siz(b)>1&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<=0)\n\t\t\t// while(siz(b)>1&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<0)\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(p[i]);\n\t\t}\n\t\tint o=siz(b);\n\t\tfor(int i=siz(p)-2;~i;i--){\n\t\t\twhile(siz(b)>o&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<=0)\n\t\t\t// while(siz(b)>o&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<0)\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(p[i]);\n\t\t}\n\t\t// if(siz(p)>1)b.pop_back();\n\t\treturn b;\n\t}\n\tdouble xzqk()const{\n\t\tif(siz(p)==1)return 0;\n\t\tif(siz(p)==2)return dis(p[0],p[1]);\n\t\tif(siz(p)==3)return max({dis(p[0],p[1]),dis(p[0],p[2]),dis(p[1],p[2])});\n\t\tdouble ans=0;\n\t\tfor(int i=1,j=2;i<siz(p);i++){\n\t\t\twhile(get_op(triarea(p[i-1],p[i],p[j])-triarea(p[i-1],p[i],p[(j+1)%siz(p)]))<=0)\n\t\t\t\t(++j)%=siz(p);\n\t\t\tans=max({ans,dis(p[i-1],p[j]),dis(p[i],p[j])});\n\t\t}\n\t\treturn ans;\n\t}\n\tdouble kqzx(){\n\t\tsort(all(p));\n\t\tauto solve=[&](auto&&self,int l,int r){\n\t\t\tif(l==r)return 1e18;\n\t\t\tint mid=(l+r)/2;\n\t\t\tdouble ans=min(self(self,l,mid),self(self,mid+1,r));\n\t\t\tpoints b;\n\t\t\tfor(int i=l;i<=r;i++)if(fabs(p[mid].x-p[i].x)<=ans)b.push_back(p[i]);\n\t\t\tsort(all(b),[](const bector&x,const bector&y){\n\t\t\t\tif(x.y==y.y)return x.x<y.x;\n\t\t\t\treturn x.y<y.y;\n\t\t\t});\n\t\t\tfor(int i=0;i<siz(b);i++)for(int j=i+1;j<siz(b);j++){\n\t\t\t\tif(b[j].y-b[i].y>=ans)break;\n\t\t\t\tans=min(ans,dis(b[i],b[j]));\n\t\t\t}\n\t\t\treturn ans;\n\t\t};\n\t\treturn solve(solve,0,siz(p)-1);\n\t}\n\tcircle incircle(){\n\t\tassert(siz(p)==3);\n\t\tauto u=p[1]-p[0],v=p[2]-p[0];u=u/~u*~v;\n\t\tsegment l1{p[0],p[0]+u+v};\n\t\tu=p[2]-p[1],v=p[0]-p[1];u=u/~u*~v;\n\t\tsegment l2{p[1],p[1]+u+v};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(segment{p[0],p[1]},pp)};\n\t}\n\tcircle outcirce(){\n\t\tassert(siz(p)==3);\n\t\tauto u=p[1]-p[0],mid=(p[0]+p[1])/2;\n\t\tsegment l1{mid,mid+u.rot90()};\n\t\tu=p[2]-p[0],mid=(p[0]+p[2])/2;\n\t\tsegment l2{mid,mid+u.rot90()};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(p[0],pp)};\n\t}\n\tint contains(bector t){\n\t\t// 无需满足多边形是凸的\n\t\t// 2表示包含,1表示在边上,0表示在外面\n\t\tbool res=false;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tauto a=p[i]-t,b=p[(i+1)%siz(p)]-t;\n\t\t\tif(!a.leftis(b)&&!a.rightis(b)&&!a.frontis(b))return 1;\n\t\t\tif(a.y>b.y)std::swap(a,b);\n\t\t\tif(a.y<eps&&eps<b.y&&a.leftis(b))res=!res;\n\t\t}\n\t\treturn res?2:0;\n\t}\n\tpoints leftpoints(const segment&l)const{\n\t\tpoints b;\n\t\t// cerr<<\"check \"<<l<<'\\n';\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tif(l.check(p[i]))b.push_back(p[i]);\n\t\t\telse if(l.rightis(p[(i-1+siz(p))%siz(p)])&&l.leftis(p[i])&&l.rightis(p[(i+1)%siz(p)])){\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i-1+siz(p))%siz(p)])));\n\t\t\t\tb.push_back(p[i]);\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i+1)%siz(p)])));\n\t\t\t}else if(l.leftis(p[i])&&l.rightis(p[(i+1)%siz(p)])){\n\t\t\t\tb.push_back(p[i]);\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i+1)%siz(p)])));\n\t\t\t}else if(l.leftis(p[i])&&l.rightis(p[(i-1+siz(p))%siz(p)])){\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i-1+siz(p))%siz(p)])));\n\t\t\t\tb.push_back(p[i]);\n\t\t\t}else if(l.leftis(p[i]))b.push_back(p[i]);\n\t\t}\n\t\treturn b;\n\t}\n\tcircle mingenshin(){\n\t\tshuffle(all(p),rng);\n\t\tcircle ans;\n\t\tfor(int i=0;i<siz(p);i++)if(!ans.check(p[i])){\n\t\t\tans={p[i],0};\n\t\t\tfor(int j=0;j<i;j++)if(!ans.check(p[j])){\n\t\t\t\tans=circle(p[i],p[j]);\n\t\t\t\tfor(int k=0;k<j;k++)if(!ans.check(p[k])){\n\t\t\t\t\tans=circle(p[i],p[j],p[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n#undef p\n};\nsigned main(){\n//\tfreopen(\".in\",\"r\",stdin);\n//\tfreopen(\".out\",\"w\",stdout);\n\tstd::ios::sync_with_stdio(false);cin.tie(nullptr);\n\tcout<<setiosflags(ios::fixed)<<setprecision(10);\n\tpoints a;\n\ta.read(cin);\n\tcircle o=a.mingenshin();\n\tcout<<o.p<<' '<<o.r<<'\\n';\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4672, "score_of_the_acc": -0.0053, "final_rank": 1 }, { "submission_id": "aoj_CGL_5_B_10848020", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing pll = pair<ll, ll>;\nusing vl = vector<ll>;\ntemplate <class T> using vec = vector<T>;\ntemplate <class T> using vv = vec<vec<T>>;\ntemplate <class T> using vvv = vv<vec<T>>;\ntemplate <class T> using minpq = priority_queue<T, vector<T>, greater<T>>;\n#define rep(i, r) for(ll i = 0; i < (r); i++)\n#define reps(i, l, r) for(ll i = (l); i < (r); i++)\n#define rrep(i, l, r) for(ll i = (r) - 1; i >= l; i--)\ntemplate <class T> void uniq(T &a) { sort(all(a)); erase(unique(all(a)), a.end()); }\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (ll)(a).size()\nconst ll INF = numeric_limits<ll>::max() / 4;\nconst ld inf = numeric_limits<ld>::max() / 2;\nconst ll mod1 = 1000000007;\nconst ll mod2 = 998244353;\nconst ld pi = 3.141592653589793238;\ntemplate <class T> void rev(T &a) { reverse(all(a)); }\nll popcnt(ll a) { return __builtin_popcountll(a); }\ntemplate<typename T>\nbool chmax(T &a, const T& b) { return a < b ? a = b, true : false; }\ntemplate<typename T>\nbool chmin(T &a, const T& b) { return a > b ? a = b, true : false; }\nconst ll mod = mod1;\nstruct mint {\n\tll x;\n\tmint(ll y = 0) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}\n\tmint &operator+=(const mint &p) {\n\t\tif ((x += p.x) >= mod) x -= mod;\n\t\treturn *this;\n\t}\n\tmint &operator-=(const mint &p) {\n\t\tif ((x += mod - p.x) >= mod) x -= mod;\n\t\treturn *this;\n\t}\n\tmint &operator*=(const mint &p) {\n\t\tx = (ll)(1ll * x * p.x % mod);\n\t\treturn *this;\n\t}\n\tmint &operator/=(const mint &p) {\n\t\t*this *= p.inv();\n\t\treturn *this;\n\t}\n\tmint operator-() const { return mint(-x); }\n\tmint operator+(const mint &p) const { return mint(*this) += p; }\n\tmint operator-(const mint &p) const { return mint(*this) -= p; }\n\tmint operator*(const mint &p) const { return mint(*this) *= p; }\n\tmint operator/(const mint &p) const { return mint(*this) /= p; }\n\tbool operator==(const mint &p) const { return x == p.x; }\n\tbool operator!=(const mint &p) const { return x != p.x; }\n\tfriend ostream &operator<<(ostream &os, const mint &p) { return os << p.x; }\n\tfriend istream &operator>>(istream &is, mint &a) {\n\t\tll t; is >> t; a = mint(t); return (is);\n\t}\n\tmint inv() const { return pow(mod - 2); }\n\tmint pow(ll n) const {\n\t\tmint ret(1), mul(x);\n\t\twhile (n > 0) {\n\t\t\tif (n & 1) ret *= mul;\n\t\t\tmul *= mul;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn ret;\n\t}\n};\nvoid YesNo(bool t) {\n\tcout << (t ? \"Yes\" : \"No\") << endl;\n}\n#define EPS (1e-10)\n#define eq(a, b) (fabs((a) - (b)) < EPS)\nll sign(ld x) { return (x >= EPS) - (x <= -EPS); }\nclass Point {\n\ttypedef Point P;\npublic:\n\tld x, y;\n\n\tPoint(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}\n\n\tP operator+(Point p) const { return P(x + p.x, y + p.y); }\n\tP operator-(Point p) const { return P(x - p.x, y - p.y); }\n\tP operator*(ld a) const { return P(a * x, a * y); }\n\tP operator/(ld a) const { return P(x / a, y / a); }\n\n\tld abs() const { return sqrtl(norm()); }\n\tld norm() const { return x * x + y * y; }\n\n\tbool operator<(const P& p) const { return tie(x, y) < tie(p.x, p.y); }\n\tbool operator==(const P& p) const { return eq(x, p.x) && eq(y, p.y); }\n\tld dot(P p) const { return x * p.x + y * p.y; }\n\tld cross(P p) const { return x * p.y - y * p.x; }\n\tld cross(P a, P b) const { return (a-*this).cross(b-*this); }\n\tld angle() const { return atan2(y, x); }\n\tP unit() const { return *this / abs(); }\n\tP perp() const { return P(-y, x); }\n\tP normal() const { return perp()/abs(); }\n\tP rotate(ld theta) const {\n\t\treturn P(x*cosl(theta)-y*sinl(theta), x*sinl(theta)+y*cosl(theta));\n\t}\n\tP rotate(ld theta, Point &p) const {\n\t\treturn (*this - p).rotate(theta) + p;\n\t}\n};\ntypedef Point Vector;\nstruct Segment {\n\tPoint s;\n\tPoint e;\n};\ntypedef Segment Line;\nclass Circle {\npublic:\n\tPoint c;\n\tld r;\n\tCircle(Point c = Point(), ld r = 0.0) : c(c), r(r) {}\n};\ntypedef vector<Point> Polygon;\npair<bool, Point> lineInter(Line l1, Line l2) {\n\tauto d = (l1.e - l1.s).cross(l2.e - l2.s);\n\tif (sign(d) == 0) return { -eq(l1.s.cross(l1.e, l2.s), (ld)0), Point(0, 0) };\n\tauto p = l2.s.cross(l1.e, l2.e), q = l2.s.cross(l2.e, l1.s);\n\treturn {1, (l1.s * p + l1.e * q) / d};\n}\nPolygon polygonCut(Polygon &p, Point s, Point e) {\n\tPolygon res;\n\trep(i, sz(p)) {\n\t\tPoint cur = p[i], prev = i ? p[i - 1] : p.back();\n\t\tbool side = sign(s.cross(e, cur)) < 0;\n\t\tif (side != (sign(s.cross(e, prev)) < 0)) {\n\t\t\tres.push_back(lineInter({s, e}, {cur, prev}).second);\n\t\t}\n\t\tif (side) res.push_back(cur);\n\t}\n\treturn res;\n}\nld Area(Polygon S) {\n\tld ans = 0;\n\trep(i, sz(S) - 2) {\n\t\tans += (S[i + 1] - S[0]).cross(S[i + 2] - S[0]) * 0.5;\n\t}\n\treturn ans;\n}\nCircle ccCicle(Point &A, Point &B, Point &C) {\n\tPoint b = C - A, c = B - A;\n\tPoint center = A + (b * c.norm() - c * b.norm()).perp() / b.cross(c) / 2;\n\tld radius = (B - A).abs() * (C - B).abs() * (A - C).abs() / fabs((B - A).cross(C - A)) / 2;\n\treturn Circle(center, radius);\n}\nCircle mec(Polygon ps) {\n\tshuffle(all(ps), mt19937(time(0)));\n\tCircle c = {ps[0], 0};\n\tld eps = 1 + 1e-10;\n\trep(i, sz(ps)) if ((c.c - ps[i]).abs() > c.r * eps) {\n\t\tc.c = ps[i], c.r = 0;\n\t\trep(j, i) if ((c.c - ps[j]).abs() > c.r * eps) {\n\t\t\tc.c = (ps[i] + ps[j]) / 2;\n\t\t\tc.r = (c.c - ps[i]).abs();\n\t\t\trep(k, j) if ((c.c - ps[k]).abs() > c.r * eps) {\n\t\t\t\tc = ccCicle(ps[i], ps[j], ps[k]);\n\t\t\t}\n\t\t}\n\t}\n\treturn c;\n}\nvoid solve() {\n\tll n; cin >> n;\n\tPolygon g(n);\n\trep(i, n) cin >> g[i].x >> g[i].y;\n\tCircle ans = mec(g);\n\tcout << fixed << setprecision(12) << ans.c.x << ' ' << ans.c.y << ' ' << ans.r << endl;\n}\nint main() {\n\tll T = 1;\n\t// cin >> T;\n\twhile (T--) solve();\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 9416, "score_of_the_acc": -0.7315, "final_rank": 15 }, { "submission_id": "aoj_CGL_5_B_10831813", "code_snippet": "#ifndef HIDDEN_IN_VS // 折りたたみ用\n\n// 警告の抑制\n#define _CRT_SECURE_NO_WARNINGS\n\n// ライブラリの読み込み\n#include <bits/stdc++.h>\nusing namespace std;\n\n// 型名の短縮\nusing ll = long long; using ull = unsigned long long; // -2^63 ~ 2^63 = 9e18(int は -2^31 ~ 2^31 = 2e9)\nusing pii = pair<int, int>;\tusing pll = pair<ll, ll>;\tusing pil = pair<int, ll>;\tusing pli = pair<ll, int>;\nusing vi = vector<int>;\t\tusing vvi = vector<vi>;\t\tusing vvvi = vector<vvi>;\tusing vvvvi = vector<vvvi>;\nusing vl = vector<ll>;\t\tusing vvl = vector<vl>;\t\tusing vvvl = vector<vvl>;\tusing vvvvl = vector<vvvl>;\nusing vb = vector<bool>;\tusing vvb = vector<vb>;\t\tusing vvvb = vector<vvb>;\nusing vc = vector<char>;\tusing vvc = vector<vc>;\t\tusing vvvc = vector<vvc>;\nusing vd = vector<double>;\tusing vvd = vector<vd>;\t\tusing vvvd = vector<vvd>;\ntemplate <class T> using priority_queue_rev = priority_queue<T, vector<T>, greater<T>>;\nusing Graph = vvi;\n\n// 定数の定義\nconst double PI = acos(-1);\nint DX[4] = { 1, 0, -1, 0 }; // 4 近傍(下,右,上,左)\nint DY[4] = { 0, 1, 0, -1 };\nint INF = 1001001001; ll INFL = 4004004003094073385LL; // (int)INFL = INF, (int)(-INFL) = -INF;\n\n// 入出力高速化\nstruct fast_io { fast_io() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(18); } } fastIOtmp;\n\n// 汎用マクロの定義\n#define all(a) (a).begin(), (a).end()\n#define sz(x) ((int)(x).size())\n#define lbpos(a, x) (int)distance((a).begin(), std::lower_bound(all(a), (x)))\n#define ubpos(a, x) (int)distance((a).begin(), std::upper_bound(all(a), (x)))\n#define Yes(b) {cout << ((b) ? \"Yes\\n\" : \"No\\n\");}\n#define rep(i, n) for(int i = 0, i##_len = int(n); i < i##_len; ++i) // 0 から n-1 まで昇順\n#define repi(i, s, t) for(int i = int(s), i##_end = int(t); i <= i##_end; ++i) // s から t まで昇順\n#define repir(i, s, t) for(int i = int(s), i##_end = int(t); i >= i##_end; --i) // s から t まで降順\n#define repe(v, a) for(const auto& v : (a)) // a の全要素(変更不可能)\n#define repea(v, a) for(auto& v : (a)) // a の全要素(変更可能)\n#define repb(set, d) for(int set = 0, set##_ub = 1 << int(d); set < set##_ub; ++set) // d ビット全探索(昇順)\n#define repis(i, set) for(int i = lsb(set), bset##i = set; i < 32; bset##i -= 1 << i, i = lsb(bset##i)) // set の全要素(昇順)\n#define repp(a) sort(all(a)); for(bool a##_perm = true; a##_perm; a##_perm = next_permutation(all(a))) // a の順列全て(昇順)\n#define uniq(a) {sort(all(a)); (a).erase(unique(all(a)), (a).end());} // 重複除去\n#define EXIT(a) {cout << (a) << endl; exit(0);} // 強制終了\n#define inQ(x, y, u, l, d, r) ((u) <= (x) && (l) <= (y) && (x) < (d) && (y) < (r)) // 半開矩形内判定\n\n// 汎用関数の定義\ntemplate <class T> inline ll powi(T n, int k) { ll v = 1; rep(i, k) v *= n; return v; }\ntemplate <class T> inline bool chmax(T& M, const T& x) { if (M < x) { M = x; return true; } return false; } // 最大値を更新(更新されたら true を返す)\ntemplate <class T> inline bool chmin(T& m, const T& x) { if (m > x) { m = x; return true; } return false; } // 最小値を更新(更新されたら true を返す)\ntemplate <class T> inline T getb(T set, int i) { return (set >> i) & T(1); }\ntemplate <class T> inline T smod(T n, T m) { n %= m; if (n < 0) n += m; return n; } // 非負mod\n\n// 演算子オーバーロード\ntemplate <class T, class U> inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }\ntemplate <class T> inline istream& operator>>(istream& is, vector<T>& v) { repea(x, v) is >> x; return is; }\ntemplate <class T> inline vector<T>& operator--(vector<T>& v) { repea(x, v) --x; return v; }\ntemplate <class T> inline vector<T>& operator++(vector<T>& v) { repea(x, v) ++x; return v; }\n\n#endif // 折りたたみ用\n\n\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n\n#ifdef _MSC_VER\n#include \"localACL.hpp\"\n#endif\n\nusing mint = modint998244353;\n//using mint = static_modint<(int)1e9+7>;\n//using mint = modint; // mint::set_mod(m);\n\nusing vm = vector<mint>; using vvm = vector<vm>; using vvvm = vector<vvm>; using vvvvm = vector<vvvm>; using pim = pair<int, mint>;\n#endif\n\n\n#ifdef _MSC_VER // 手元環境(Visual Studio)\n#include \"local.hpp\"\n#else // 提出用(gcc)\nint mute_dump = 0;\nint frac_print = 0;\n#if __has_include(<atcoder/all>)\nnamespace atcoder {\n\tinline istream& operator>>(istream& is, mint& x) { ll x_; is >> x_; x = x_; return is; }\n\tinline ostream& operator<<(ostream& os, const mint& x) { os << x.val(); return os; }\n}\n#endif\ninline int popcount(int n) { return __builtin_popcount(n); }\ninline int popcount(ll n) { return __builtin_popcountll(n); }\ninline int lsb(int n) { return n != 0 ? __builtin_ctz(n) : 32; }\ninline int lsb(ll n) { return n != 0 ? __builtin_ctzll(n) : 64; }\ninline int msb(int n) { return n != 0 ? (31 - __builtin_clz(n)) : -1; }\ninline int msb(ll n) { return n != 0 ? (63 - __builtin_clzll(n)) : -1; }\n#define dump(...)\n#define dumpel(v)\n#define dump_math(v)\n#define input_from_file(f)\n#define output_to_file(f)\n#define Assert(b) { if (!(b)) { vc MLE(1<<30); EXIT(MLE.back()); } } // RE の代わりに MLE を出す\n#endif\n\n\n//【平面上の点,二次元ベクトル】\n/*\n* 平面における点/二次元ベクトルを表す構造体\n*\n* Point<T>() : O(1)\n*\t(0, 0) で初期化する.\n*\n* Point<T>(T x, T y) : O(1)\n*\t(x, y) で初期化する.\n*\n* p1 == p2, p1 != p2, p1 < p2, p1 > p2, p1 <= p2, p1 >= p2 : O(1)\n*\tx 座標優先,次いで y 座標の大小比較を行う.\n*\n* p1 + p2, p1 - p2, c * p, p * c, p / c : O(1)\n*\tベクトルとみなした加算,減算,スカラー倍,スカラー除算を行う.複合代入演算子も使用可.\n*\n* T sqnorm() : O(1)\n*\t自身の 2 乗ノルムを返す.\n*\n* double norm() : O(1)\n*\t自身のノルムを返す.\n*\n* Point<double> normalize() : O(1)\n*\t自身を正規化したベクトルを返す.\n*\n* T dot(Point<T> p) : O(1)\n*\t自身と p との内積を返す.\n*\n* T cross(Point<T> p) : O(1)\n*\t自身と p との外積を返す.\n*\n* double angle(Point<T> p) : O(1)\n*\t自身から p までの成す角度を返す.\n*/\ntemplate <class T>\nstruct Point {\n\t// 点の x 座標,y 座標\n\tT x, y;\n\n\t// コンストラクタ\n\tPoint() : x(0), y(0) {}\n\tPoint(T x_, T y_) : x(x_), y(y_) {}\n\n\t// 代入\n\tPoint(const Point& old) = default;\n\tPoint& operator=(const Point& other) = default;\n\n\t// キャスト\n\toperator Point<ll>() const { return Point<ll>((ll)x, (ll)y); }\n\toperator Point<double>() const { return Point<double>((double)x, (double)y); }\n\n\t// 入出力\n\tfriend istream& operator>>(istream& is, Point& p) { is >> p.x >> p.y; return is; }\n\tfriend ostream& operator<<(ostream& os, const Point& p) { os << '(' << p.x << ',' << p.y << ')'; return os; }\n\n\t// 比較(x 座標優先)\n\tbool operator==(const Point& p) const { return x == p.x && y == p.y; }\n\tbool operator!=(const Point& p) const { return !(*this == p); }\n\tbool operator<(const Point& p) const { return x == p.x ? y < p.y : x < p.x; }\n\tbool operator>=(const Point& p) const { return !(*this < p); }\n\tbool operator>(const Point& p) const { return x == p.x ? y > p.y : x > p.x; }\n\tbool operator<=(const Point& p) const { return !(*this > p); }\n\n\t// 加算,減算,スカラー倍,スカラー除算\n\tPoint& operator+=(const Point& p) { x += p.x; y += p.y;\treturn *this; }\n\tPoint operator+(const Point& p) const { Point q(*this); return q += p; }\n\tPoint& operator-=(const Point& p) { x -= p.x; y -= p.y;\treturn *this; }\n\tPoint operator-(const Point& p) const { Point q(*this); return q -= p; }\n\tPoint& operator*=(const T& c) { x *= c; y *= c;\treturn *this; }\n\tPoint operator*(const T& c) const { Point q(*this); return q *= c; }\n\tPoint& operator/=(const T& c) { x /= c; y /= c;\treturn *this; }\n\tPoint operator/(const T& c) const { Point q(*this); return q /= c; }\n\tfriend Point operator*(const T& sc, const Point& p) { return p * sc; }\n\tPoint operator-() const { Point a = *this; return a *= -1; }\n\n\t// 二乗ノルム,ノルム,正規化\n\tT sqnorm() const { return x * x + y * y; }\n\tdouble norm() const { return sqrt((double)x * x + (double)y * y); }\n\tPoint<double> normalize() const { return Point<double>(*this) / norm(); }\n\n\t// 内積,外積,成す角度\n\tT dot(const Point& other) const { return x * other.x + y * other.y; }\n\tT cross(const Point& other) const { return x * other.y - y * other.x; }\n\tdouble angle(const Point& other) const {\n\t\treturn atan2(this->cross(other), this->dot(other));\n\t}\n};\n\n\n//【点の内外判定(円,直径指定)】O(1)\n/*\n* 2 点 a, b を直径の両端にもつ円 C と点 p の内外関係を判定する.\n*\n* 戻り値:\n*\t点 p が円 C の外部にあれば -1\n*\t点 p が円 C の境界にあれば 0\n*\t点 p が円 C の内部にあれば 1\n*/\ntemplate <class T>\nint inner_circle_by_diameter(const Point<T>& a, const Point<T>& b, const Point<T>& p) {\n\t// verify : https://atcoder.jp/contests/abc151/tasks/abc151_f\n\n\t//【方法】\n\t// タレスの定理の逆より,∠ a p b の大きさと 90°の大小を比較して判定できる.\n\t// 代わりに cos(∠ a p b) と cos(90°) = 0 の大小を比較して判定できる.\n\t// 代わりに内積 (p - a).(p - b) の符号を見て判定できる.\n\n\tT ip = (a - p).dot(b - p);\n\n\tif (ip > 0) return -1;\n\tif (ip < 0) return 1;\n\treturn 0;\n}\n\n\n//【点の内外判定(円,3 点指定)】O(1)\n/*\n* 3 点 a, b, c を通る円 C と点 p の内外関係を判定する.\n*\n* 戻り値:\n*\t点 p が円 C の外部にあれば -1\n*\t点 p が円 C の境界にあれば 0\n*\t点 p が円 C の内部にあれば 1\n*/\ntemplate <class T>\nint inner_circle_by_3points(const Point<T>& a, const Point<T>& b, const Point<T>& c, const Point<T>& p) {\n\t// verify : https://atcoder.jp/contests/abc151/tasks/abc151_f\n\n\t//【方法】\n\t// a, b, c, p を複素平面上の点とみなせば,複比による共円判定条件より\n\t//\t\t(b - c)(a - p) / (a - c)(b - p) ∈ R\n\t// なら 4 点 a, b, c, p は共円である.そうでないときは,p が無限遠点にあるときの\n\t//\t\t(b - c) / (a - c)\n\t// と虚部の符号を比較して,等しいなら外部,異なるなら内部と判定できる.\n\t//\n\t// 複素数 num / dnm = (A + B i) / (C + D i) の虚部の符号の決定方法を考える.\n\t// 分母の実数化を行うと,\n\t//\t\t(A + B i) / (C + D i)\n\t//\t\t= (A + B i) (C - D i) / (C^2 + D^2)\n\t//\t\t= ((A C + B D) + (- A D + B C) i) / (C^2 + D^2)\n\t// となる.分母は正の実数なので,- A D + B C の符号を見れば良い.\n\n\tT num_re = (b.x - c.x) * (a.x - p.x) - (b.y - c.y) * (a.y - p.y);\n\tT num_im = (b.x - c.x) * (a.y - p.y) + (b.y - c.y) * (a.x - p.x);\n\tT dnm_re = (a.x - c.x) * (b.x - p.x) - (a.y - c.y) * (b.y - p.y);\n\tT dnm_im = (a.x - c.x) * (b.y - p.y) + (a.y - c.y) * (b.x - p.x);\n\tT im = -num_re * dnm_im + num_im * dnm_re;\n\n\tif (im == 0) return 0;\n\n\tT num2_re = b.x - c.x;\n\tT num2_im = b.y - c.y;\n\tT dnm2_re = a.x - c.x;\n\tT dnm2_im = a.y - c.y;\n\tT im2 = -num2_re * dnm2_im + num2_im * dnm2_re;\n\n\tif ((im > 0) == (im2 > 0)) return -1;\n\telse return 1;\n}\n\n\ntemplate <class T>\ntuple<int, int, int> minimum_enclosing_circle(const vector<Point<T>>& p) {\n\tint n = sz(p);\n\n\tvi idx(n);\n\tiota(all(idx), 0);\n\tmt19937_64 mt((int)time(NULL));\n\tshuffle(all(idx), mt);\n\n\tint i1 = -1, i2 = -1, i3 = -1;\n\n\trep(t, n) {\n\t\tint i = idx[t];\n\n\t\tif (i3 != -1 && inner_circle_by_3points(p[i1], p[i2], p[i3], p[i]) >= 0) continue;\n\t\tif (i3 == -1 && i2 != -1 && inner_circle_by_diameter(p[i1], p[i2], p[i]) >= 0) continue;\n\t\ti1 = i;\n\t\ti2 = -1;\n\t\ti3 = -1;\n\n\t\trep(s, t) {\n\t\t\tint j = idx[s];\n\n\t\t\tif (i3 != -1 && inner_circle_by_3points(p[i1], p[i2], p[i3], p[j]) >= 0) continue;\n\t\t\tif (i3 == -1 && i2 != -1 && inner_circle_by_diameter(p[i1], p[i2], p[j]) >= 0) continue;\n\t\t\ti2 = j;\n\t\t\ti3 = -1;\n\n\t\t\trep(u, s) {\n\t\t\t\tint k = idx[u];\n\n\t\t\t\tif (i3 != -1 && inner_circle_by_3points(p[i1], p[i2], p[i3], p[k]) >= 0) continue;\n\t\t\t\tif (i3 == -1 && i2 != -1 && inner_circle_by_diameter(p[i1], p[i2], p[k]) >= 0) continue;\n\t\t\t\ti3 = k;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { i1, i2, i3 };\n}\n\n\n//【平面内の円】\n/*\n* {p, r} : 点 p を中心とする半径 r の円を表す.\n*/\ntemplate <class T>\nusing Circle = pair<Point<T>, T>;\n\n\n//【外接円】O(1)\n/*\n* 三角形 a b c の外接円を返す.\n*/\ntemplate <class T>\nCircle<double> circircle(const Point<T>& a, const Point<T>& b, const Point<T>& c) {\n\t// verify : https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/all/CGL_7_C\n\n\t//【方法】\n\t// Mathematica で\n\t//\tSolve[(x1-x)^2 + (y1-y)^2 == (x2-x)^2 + (y2-y)^2 == (x3-x)^2 + (y3-y)^2, {x, y}] // FullSimplify\n\t// を実行し,結果を CForm[] して整形した.\n\n\tdouble x1 = a.x, y1 = a.y;\n\tdouble x2 = b.x, y2 = b.y;\n\tdouble x3 = c.x, y3 = c.y;\n\n\tdouble dnm = 2 * (x3 * (-y1 + y2) + x2 * (y1 - y3) + x1 * (-y2 + y3));\n\n\tPoint<double> o;\n\to.x = (x3 * x3 * (y2 - y1) + x2 * x2 * (y1 - y3)\n\t\t+ (x1 * x1 + (y1 - y2) * (y1 - y3)) * (y3 - y2)) / dnm;\n\to.y = (y3 * y3 * (x1 - x2) + (y2 * y2) * (x3 - x1)\n\t\t+ ((y1 * y1) + (x1 - x2) * (x1 - x3)) * (x2 - x3)) / dnm;\n\tauto r = (Point<double>(a) - o).norm();\n\treturn { o, r };\n}\n\n\nint main() {\n//\tinput_from_file(\"input.txt\");\n//\toutput_to_file(\"output.txt\");\n\n\tint n;\n\tcin >> n;\n\n\tvector<Point<__int128>> p(n);\n\trep(i, n) {\n\t\tll x, y;\n\t\tcin >> x >> y;\n\n\t\tp[i] = { x, y };\n\t}\n\n\tauto [i1, i2, i3] = minimum_enclosing_circle(p);\n\tdump(i1, i2, i3);\n\n\tif (i3 == -1) {\n\t\tdouble cx = (p[i1].x + p[i2].x) / 2.;\n\t\tdouble cy = (p[i1].y + p[i2].y) / 2.;\n\t\tdouble r = (p[i1] - p[i2]).norm() / 2.;\n\n\t\tcout << cx << \" \" << cy << \" \" << r << endl;\n\t}\n\telse {\n\t\tauto c = circircle(p[i1], p[i2], p[i3]);\n\n\t\tcout << c.first.x << \" \" << c.first.y << \" \" << c.second << endl;\n\t}\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6940, "score_of_the_acc": -0.1135, "final_rank": 3 }, { "submission_id": "aoj_CGL_5_B_10831645", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n double x, y;\n};\n\ndouble dist(const Point &a, const Point &b) {\n return hypot(a.x - b.x, a.y - b.y);\n}\n\nstruct Circle {\n Point c;\n double r;\n Circle(Point _c = {0,0}, double _r = -1) : c(_c), r(_r) {}\n};\n\nbool is_in_circle(const Circle &C, const Point &p, double eps = 1e-9) {\n return dist(C.c, p) <= C.r + eps;\n}\n\nCircle circle2(const Point &a, const Point &b) {\n Point c{ (a.x + b.x) / 2.0, (a.y + b.y) / 2.0 };\n double r = dist(a, b) / 2.0;\n return Circle(c, r);\n}\n\nCircle circle3(const Point &a, const Point &b, const Point &c) {\n double d = 2 * (a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y));\n if (fabs(d) < 1e-12) return Circle({0,0}, -1); // collinear\n\n double ux = ((a.x*a.x + a.y*a.y)*(b.y-c.y) + \n (b.x*b.x + b.y*b.y)*(c.y-a.y) + \n (c.x*c.x + c.y*c.y)*(a.y-b.y)) / d;\n double uy = ((a.x*a.x + a.y*a.y)*(c.x-b.x) + \n (b.x*b.x + b.y*b.y)*(a.x-c.x) + \n (c.x*c.x + c.y*c.y)*(b.x-a.x)) / d;\n Point o{ux, uy};\n double r = dist(o, a);\n return Circle(o, r);\n}\n\nCircle mec(vector<Point> &P) {\n random_shuffle(P.begin(), P.end());\n Circle C;\n for (int i = 0; i < (int)P.size(); i++) {\n if (C.r < 0 || !is_in_circle(C, P[i])) {\n C = Circle(P[i], 0);\n for (int j = 0; j < i; j++) {\n if (!is_in_circle(C, P[j])) {\n C = circle2(P[i], P[j]);\n for (int k = 0; k < j; k++) {\n if (!is_in_circle(C, P[k])) {\n Circle cc = circle3(P[i], P[j], P[k]);\n if (cc.r >= 0) C = cc;\n }\n }\n }\n }\n }\n }\n return C;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int N;\n cin >> N;\n vector<Point> P(N);\n for (int i = 0; i < N; i++) {\n cin >> P[i].x >> P[i].y;\n }\n\n Circle C = mec(P);\n const double eps = 1e-6;\n\n cout << fixed << setprecision(18);\n cout << C.c.x << \" \" << C.c.y << \" \" << C.r << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 5376, "score_of_the_acc": -0.2056, "final_rank": 6 }, { "submission_id": "aoj_CGL_5_B_10806036", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define rep(i, l, r) for(int i = (l); i < (r); ++i)\n#define FOR(i, l, r) for(int i = (l); i <= (r); ++i)\n#define tcT template<class T\n#define tcTU tcT, class U\n#define mp make_pair\n#define mt make_tuple\n#define ff first\n#define ss second\n#define el \"\\n\"\n#define sz(v) (int)v.size()\n#define all(v) begin(v), end(v)\n#define rall(v) rbegin(v), rend(v)\n#define pb push_back\n#define eb emplace_back\n#define compact(v) v.erase(unique(all(v)), end(v))\n\ntcT> int lwb(const vector<T>& a, const T& b){ return int(lower_bound(all(a), b) - begin(a)); }\ntcT> int upb(const vector<T>& a, const T& b){ return int(upper_bound(all(a), b) - begin(a)); }\n\nusing ll = long long;\nusing db = double;\nusing ld = long double;\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\nusing vi = vector<int>;\nusing vl = vector<ll>;\nusing vb = vector<bool>;\nusing vd = vector<db>;\nusing vc = vector<char>;\nusing vstr = vector<string>;\nusing vpi = vector<pi>;\nusing vpl = vector<pl>;\n\ntcT> bool minimize(T& a, const T& b){ if(a > b) return a = b, true; return false; } \ntcT> bool maximize(T& a, const T& b){ if(a < b) return a = b, true; return false; } \ntcT> T ceil_div(T a, T b){ return (a / b) + ((a ^ b) > 0 && a % b); }\ntcT> T floor_div(T a, T b){ return (a / b) - ((a ^ b) < 0 && a % b); }\ntcT> void safe_erase(vector<T>& a, T x){\n auto it = find(all(a), x);\n if(it != a.end()) a.erase(it);\n}\n\nconst auto start_time = std::chrono::high_resolution_clock::now();\ndb time_elapsed(){ return chrono::duration<db>(std::chrono::high_resolution_clock::now() - \n start_time).count(); }\n\nvoid setIO(){\n ios_base::sync_with_stdio(0); cin.tie(0);\n#define task \"task\"\n if(fopen(task\".inp\", \"r\")){\n freopen(task\".inp\", \"r\", stdin);\n // freopen(task\".out\", \"w\", stdout);\n }\n}\n\n// Basic geometry objects: Point, Line, Segment\n// Works with both integers and floating points\n// Unless the problem has precision issue, can use Point, which uses double\n// and has more functionalities.\n// For integers, can use P<long long>\n#ifndef EPS // allow test files to overwrite EPS\n#define EPS 1e-15\n#endif\nconst double PI = acos(-1.0l);\ndouble DEG_to_RAD(double d) { return d * PI / 180.0; }\ndouble RAD_to_DEG(double r) { return r * 180.0 / PI; }\ninline int cmp(double a, double b) { return (a < b - EPS) ? -1 : ((a > b + EPS) ? 1 : 0); }\n// for int types\ntemplate<typename T, typename std::enable_if<!std::is_floating_point<T>::value>::type * = nullptr>\ninline int cmp(T a, T b) { return (a == b) ? 0 : (a < b) ? -1 : 1; }\ntemplate<typename T>\nstruct P {\n T x, y;\n P() { x = y = T(0); }\n P(T _x, T _y) : x(_x), y(_y) {}\n\n P operator + (const P& a) const { return P(x+a.x, y+a.y); }\n P operator - (const P& a) const { return P(x-a.x, y-a.y); }\n P operator * (T k) const { return P(x*k, y*k); }\n P<double> operator / (double k) const { return P(x/k, y/k); }\n T operator * (const P& a) const { return x*a.x + y*a.y; } // dot product\n T operator % (const P& a) const { return x*a.y - y*a.x; } // cross product\n int cmp(const P<T>& q) const { if (int t = ::cmp(x,q.x)) return t; return ::cmp(y,q.y); }\n #define Comp(x) bool operator x (const P& q) const { return cmp(q) x 0; }\n Comp(>) Comp(<) Comp(==) Comp(>=) Comp(<=) Comp(!=)\n #undef Comp\n T norm() { return x*x + y*y; }\n double len() { return hypot(x, y); }\n P<double> rotate(double alpha) {\n double cosa = cos(alpha), sina = sin(alpha);\n return P(x * cosa - y * sina, x * sina + y * cosa);\n }\n};\nusing Point = P<double>;\n\n// Compare points by (y, x)\ntemplate<typename T = double>\nbool cmpy(const P<T>& a, const P<T>& b) {\n if (cmp(a.y, b.y)) return a.y < b.y;\n return a.x < b.x;\n};\n\ntemplate<typename T>\nint ccw(P<T> a, P<T> b, P<T> c) {\n return cmp((b-a)%(c-a), T(0));\n}\n\ndouble angle(Point a, Point o, Point b) { // min of directed angle AOB & BOA\n a = a - o; b = b - o;\n return acos((a * b) / sqrt(a.norm()) / sqrt(b.norm()));\n}\n\ndouble directed_angle(Point a, Point o, Point b) { // angle AOB, in range [0, 2*PI)\n double t = -atan2(a.y - o.y, a.x - o.x)\n + atan2(b.y - o.y, b.x - o.x);\n while (t < 0) t += 2*PI;\n return t;\n}\n\n// Distance from p to Line ab (closest Point --> c)\n// i.e. c is projection of p on AB\ndouble distToLine(Point p, Point a, Point b, Point &c) {\n Point ap = p - a, ab = b - a;\n double u = (ap * ab) / ab.norm();\n c = a + (ab * u);\n return (p-c).len();\n}\n\n// Distance from p to segment ab (closest Point --> c)\ndouble distToLineSegment(Point p, Point a, Point b, Point &c) {\n Point ap = p - a, ab = b - a;\n double u = (ap * ab) / ab.norm();\n if (u < 0.0) {\n c = Point(a.x, a.y);\n return (p - a).len();\n }\n if (u > 1.0) {\n c = Point(b.x, b.y);\n return (p - b).len();\n }\n return distToLine(p, a, b, c);\n}\n\n// NOTE: WILL NOT WORK WHEN a = b = 0.\nstruct Line {\n double a, b, c; // ax + by + c = 0\n Point A, B; // Added for polygon intersect line. Do not rely on assumption that these are valid\n\n Line(double _a, double _b, double _c) : a(_a), b(_b), c(_c) {} \n\n Line(Point _A, Point _B) : A(_A), B(_B) {\n a = B.y - A.y;\n b = A.x - B.x;\n c = - (a * A.x + b * A.y);\n }\n Line(Point P, double m) {\n a = -m; b = 1;\n c = -((a * P.x) + (b * P.y));\n }\n double f(Point p) {\n return a*p.x + b*p.y + c;\n }\n};\nostream& operator << (ostream& cout, const Line& l) {\n cout << l.a << \"*x + \" << l.b << \"*y + \" << l.c;\n return cout;\n}\n\nbool areParallel(Line l1, Line l2) {\n return cmp(l1.a*l2.b, l1.b*l2.a) == 0;\n}\n\nbool areSame(Line l1, Line l2) {\n return areParallel(l1 ,l2) && cmp(l1.c*l2.a, l2.c*l1.a) == 0\n && cmp(l1.c*l2.b, l1.b*l2.c) == 0;\n}\n\nbool areIntersect(Line l1, Line l2, Point &p) {\n if (areParallel(l1, l2)) return false;\n double dx = l1.b*l2.c - l2.b*l1.c;\n double dy = l1.c*l2.a - l2.c*l1.a;\n double d = l1.a*l2.b - l2.a*l1.b;\n p = Point(dx/d, dy/d);\n return true;\n}\n\n// closest point from p in line l. (= projection of p onto line l)\nvoid proj(Line l, Point p, Point &ans) {\n if (fabs(l.b) < EPS) {\n ans.x = -(l.c) / l.a; ans.y = p.y;\n return;\n }\n if (fabs(l.a) < EPS) {\n ans.x = p.x; ans.y = -(l.c) / l.b;\n return;\n }\n Line perp(l.b, -l.a, - (l.b*p.x - l.a*p.y));\n areIntersect(l, perp, ans);\n}\n\n// Tested:\n// - https://cses.fi/problemset/task/2190/\ntemplate<typename T>\nbool onSegment(const P<T>& a, const P<T>& b, const P<T>& p) { // returns true if p is on segment [a, b]\n return ccw(a, b, p) == 0 && min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x) && min(a.y, b.y) <= p.y && p.y <= max(a.y, b.y);\n}\n\n// Returns true if segment [a, b] and [c, d] intersects\ntemplate<typename T>\nbool segmentIntersect(const P<T>& a, const P<T>& b, const P<T>& c, const P<T>& d) {\n if (onSegment(a, b, c) || onSegment(a, b, d) || onSegment(c, d, a) || onSegment(c, d, b)) return true;\n return ccw(a, b, c) * ccw(a, b, d) < 0 && ccw(c, d, a) * ccw(c, d, b) < 0;\n}\n\nstruct Circle : Point {\n double r;\n Circle(double _x = 0, double _y = 0, double _r = 0) : Point(_x, _y), r(_r) {}\n Circle(Point p, double _r) : Point(p), r(_r) {}\n \n bool contains(Point p) { return (*this - p).len() <= r + EPS; }\n double area() const { return r*r*M_PI; }\n // definitions in https://en.wikipedia.org/wiki/Circle\n // assumption: 0 <= theta <= 2*PI\n // theta: angle in radian\n double sector_area(double theta) const {\n return 0.5 * r * r * theta;\n }\n // assumption: 0 <= theta <= 2*PI\n // theta: angle in radian\n double segment_area(double theta) const {\n return 0.5 * r * r * (theta - sin(theta));\n }\n};\nistream& operator >> (istream& cin, Circle& c) {\n cin >> c.x >> c.y >> c.r;\n return cin;\n}\nostream& operator << (ostream& cout, const Circle& c) {\n cout << '(' << c.x << \", \" << c.y << \") \" << c.r;\n return cout;\n}\n// Find common tangents to 2 circles\n// Tested:\n// - http://codeforces.com/gym/100803/ - H\n// Helper method\nvoid tangents(Point c, double r1, double r2, vector<Line> & ans) {\n double r = r2 - r1;\n #define sqr(x) (x)*(x)\n double z = sqr(c.x) + sqr(c.y);\n double d = z - sqr(r);\n if (d < -EPS) return;\n d = sqrt(fabs(d));\n Line l((c.x * r + c.y * d) / z,\n (c.y * r - c.x * d) / z,\n r1);\n ans.push_back(l);\n}\n// Actual method: returns vector containing all common tangents\nvector<Line> tangents(Circle a, Circle b) {\n vector<Line> ans; ans.clear();\n for (int i=-1; i<=1; i+=2)\n for (int j=-1; j<=1; j+=2)\n tangents(b-a, a.r*i, b.r*j, ans);\n for(int i = 0; i < (int) ans.size(); ++i)\n ans[i].c -= ans[i].a * a.x + ans[i].b * a.y;\n\n vector<Line> ret;\n for(int i = 0; i < (int) ans.size(); ++i) {\n if (std::none_of(ret.begin(), ret.end(), [&] (Line l) { return areSame(l, ans[i]); })) {\n ret.push_back(ans[i]);\n }\n }\n return ret;\n}\n\n// Circle & line intersection\n// Tested:\n// - http://codeforces.com/gym/100803/ - H\nvector<Point> intersection(Line l, Circle cir) {\n double r = cir.r, a = l.a, b = l.b, c = l.c + l.a*cir.x + l.b*cir.y;\n vector<Point> res;\n\n double x0 = -a*c/(a*a+b*b), y0 = -b*c/(a*a+b*b);\n if (c*c > r*r*(a*a+b*b)+EPS) return res;\n else if (fabs(c*c - r*r*(a*a+b*b)) < EPS) {\n res.push_back(Point(x0, y0) + Point(cir.x, cir.y));\n return res;\n } else {\n double d = r*r - c*c/(a*a+b*b);\n double mult = sqrt (d / (a*a+b*b));\n double ax,ay,bx,by;\n ax = x0 + b * mult;\n bx = x0 - b * mult;\n ay = y0 - a * mult;\n by = y0 + a * mult;\n\n res.push_back(Point(ax, ay) + Point(cir.x, cir.y));\n res.push_back(Point(bx, by) + Point(cir.x, cir.y));\n return res;\n }\n}\n\n// helper functions for commonCircleArea\ndouble cir_area_solve(double a, double b, double c) {\n return acos((a*a + b*b - c*c) / 2 / a / b);\n}\ndouble cir_area_cut(double a, double r) {\n double s1 = a * r * r / 2;\n double s2 = sin(a) * r * r / 2;\n return s1 - s2;\n}\n// Tested: http://codeforces.com/contest/600/problem/D\ndouble commonCircleArea(Circle c1, Circle c2) { //return the common area of two circle\n if (c1.r < c2.r) swap(c1, c2);\n double d = (c1 - c2).len();\n if (d + c2.r <= c1.r + EPS) return c2.r*c2.r*M_PI;\n if (d >= c1.r + c2.r - EPS) return 0.0;\n double a1 = cir_area_solve(d, c1.r, c2.r);\n double a2 = cir_area_solve(d, c2.r, c1.r);\n return cir_area_cut(a1*2, c1.r) + cir_area_cut(a2*2, c2.r);\n}\n\n// Check if 2 circle intersects. Return true if 2 circles touch\nbool areIntersect(Circle u, Circle v) {\n if (cmp((u - v).len(), u.r + v.r) > 0) return false;\n if (cmp((u - v).len() + v.r, u.r) < 0) return false;\n if (cmp((u - v).len() + u.r, v.r) < 0) return false;\n return true;\n}\n\n// If 2 circle touches, will return 2 (same) points\n// If 2 circle are same --> be careful\n// Tested:\n// - http://codeforces.com/gym/100803/ - H\n// - http://codeforces.com/gym/100820/ - I\nvector<Point> circleIntersect(Circle u, Circle v) {\n vector<Point> res;\n if (!areIntersect(u, v)) return res;\n double d = (u - v).len();\n double alpha = acos((u.r * u.r + d*d - v.r * v.r) / 2.0 / u.r / d);\n Point p1 = (v - u).rotate(alpha);\n Point p2 = (v - u).rotate(-alpha);\n res.push_back(p1 / p1.len() * u.r + u);\n res.push_back(p2 / p2.len() * u.r + u);\n return res;\n}\n\n// Smallest enclosing circle:\n// Given N points. Find the smallest circle enclosing these points.\n// Amortized complexity: O(N)\n//\n// Tested:\n// - https://oj.vnoi.info/problem/icpc22_mt_l\nstruct SmallestEnclosingCircle {\n Circle getCircle(vector<Point> points) {\n assert(!points.empty());\n\n random_shuffle(points.begin(), points.end());\n Circle c(points[0], 0);\n int n = points.size();\n\n for (int i = 1; i < n; i++)\n if ((points[i] - c).len() > c.r + EPS){\n c = Circle(points[i], 0);\n for (int j = 0; j < i; j++)\n if ((points[j] - c).len() > c.r + EPS){\n c = Circle((points[i] + points[j]) / 2, (points[i] - points[j]).len() / 2);\n for (int k = 0; k < j; k++)\n if ((points[k] - c).len() > c.r + EPS)\n c = getCircumcircle(points[i], points[j], points[k]);\n }\n }\n\n return c;\n }\n // NOTE: This code work only when a, b, c are not collinear and no 2 points are same --> DO NOT\n // copy and use in other cases.\n Circle getCircumcircle(Point a, Point b, Point c) {\n assert(ccw(a, b, c));\n double d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));\n assert(fabs(d) > EPS);\n double x = (a.norm() * (b.y - c.y) + b.norm() * (c.y - a.y) + c.norm() * (a.y - b.y)) / d;\n double y = (a.norm() * (c.x - b.x) + b.norm() * (a.x - c.x) + c.norm() * (b.x - a.x)) / d;\n Point p(x, y);\n return Circle(p, (p - a).len());\n }\n};\n\nint n;\nvector<Point>points;\n\nvoid testcase(int n_case){\n cin >> n;\n points.resize(n);\n rep(i, 0, n) {\n cin >> points[i].x >> points[i].y;\n }\n\n SmallestEnclosingCircle c;\n Circle ans = c.getCircle(points);\n cout << fixed << setprecision(8) << ans.x << \" \" << ans.y << \" \" << ans.r << el;\n}\n\nint main(){\n setIO();\n int T = 1; \n // cin >> T;\n rep(i, 0, T) testcase(i);\n // cerr << '\\n' << \"Execution time : \" << (time_elapsed() * 1000.0) << \" ms\";\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 6308, "score_of_the_acc": -0.4167, "final_rank": 12 }, { "submission_id": "aoj_CGL_5_B_10804346", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define tcT template<class T\n#define tcTU tcT, class U\n\n#define all(v) begin(v), end(v)\n#define rall(v) rbegin(v), rend(v)\n#define sz(v) (int)v.size()\n#define compact(v) v.erase(unique(all(v)), end(v))\n#define pb push_back\n#define eb emplace_back\n\n#define FOR(i, l, r) for(int i = (l); i <= (r); ++i)\n#define rep(i, l, r) for(int i = (l); i < (r); ++i)\n\n#define mp make_pair\n#define mt make_tuple\n#define ff first\n#define ss second\n\nusing ll = long long;\nusing db = double;\nusing ull = unsigned long long;\nusing ld = long double;\nusing str = string;\n\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\n\nusing vi = vector<int>;\nusing vl = vector<ll>;\nusing vd = vector<db>;\nusing vc = vector<char>;\nusing vb = vector<bool>;\nusing vstr = vector<str>;\n\nusing vpi = vector<pi>;\nusing vpl = vector<pl>;\n\ntcT> using min_heap = priority_queue<T, vector<T>, greater<T>>;\ntcT> using max_heap = priority_queue<T>;\n\ntcT> bool minimize(T& a, const T& b){\n if(a > b) return a = b, true;\n return false;\n}\n\ntcT> bool maximize(T& a, const T& b){\n if(a < b) return a = b, true;\n return false;\n}\n\n#ifdef LOCAL\n #define dbg(...) (cerr << \"#\" << __LINE__ << \" | \" << \"[\" << #__VA_ARGS__ << \"] = \", print(__VA_ARGS__))\n\n template<class A, class B> ostream& operator << (ostream& stream, const pair<A, B>& p){ return stream << '(' << p.ff << ',' << p.ss << ')'; }\n template<class T> void print_one(const T& x){ cerr << x; }\n template<class It> void print_range(It a, It b){\n cerr << '{';\n bool first = true;\n for(It it = a; it != b; ++it){\n if(!first) cerr << \",\";\n print_one(*it);\n first = false;\n }\n cerr << '}';\n }\n\n template<class T> void print_one(const vector<T>& v){ print_range(v.begin(), v.end()); }\n template<class T> void print_one(const set<T>& v){ print_range(v.begin(), v.end()); }\n template<class T> void print_one(const multiset<T>& v){ print_range(v.begin(), v.end()); }\n template<class T, class U> void print_one(const map<T, U>& m){\n cerr << '{';\n bool first = true;\n for(auto& kv : m){\n if(!first) cerr << ',';\n cerr << '('; print_one(kv.ff); cerr << \": \"; print_one(kv.ss); cerr << ')';\n }\n cerr << '}';\n }\n\n inline void print(){ cerr << '\\n'; }\n template<class T> void print(const T& v){ print_one(v); cerr << '\\n'; }\n template<class T, class...U> void print(const T& a, const U&...b){\n print_one(a); cerr << \", \";\n print(b...);\n }\n#else\n #define dbg(...) ((void)0)\n#endif // LOCAL\n\nvoid setIO(){\n ios_base::sync_with_stdio(0); cin.tie(0);\n#define task \"task\"\n if(fopen(task\".inp\", \"r\")){\n freopen(task\".inp\", \"r\", stdin);\n freopen(task\".out\", \"w\", stdout);\n }\n}\n\n#define sqr(x) ((x) * (x))\n#define FORD(i,a,b) for(int i=(a),_b=(b); i>=_b; i--)\n#define REP(i,a) for(int i=0,_a=(a); i<_a; i++)\n#define EACH(it,a) for(__typeof(a.begin()) it = a.begin(); it != a.end(); ++it)\n\n// Basic geometry objects: Point, Line, Segment\n// Works with both integers and floating points\n// Unless the problem has precision issue, can use Point, which uses double\n// and has more functionalities.\n// For integers, can use P<long long>\n#ifndef EPS // allow test files to overwrite EPS\n#define EPS 1e-15\n#endif\nconst double PI = acos(-1.0l);\ndouble DEG_to_RAD(double d) { return d * PI / 180.0; }\ndouble RAD_to_DEG(double r) { return r * 180.0 / PI; }\ninline int cmp(double a, double b) { return (a < b - EPS) ? -1 : ((a > b + EPS) ? 1 : 0); }\n// for int types\ntemplate<typename T, typename std::enable_if<!std::is_floating_point<T>::value>::type * = nullptr>\ninline int cmp(T a, T b) { return (a == b) ? 0 : (a < b) ? -1 : 1; }\ntemplate<typename T>\nstruct P {\n T x, y;\n P() { x = y = T(0); }\n P(T _x, T _y) : x(_x), y(_y) {}\n\n P operator + (const P& a) const { return P(x+a.x, y+a.y); }\n P operator - (const P& a) const { return P(x-a.x, y-a.y); }\n P operator * (T k) const { return P(x*k, y*k); }\n P<double> operator / (double k) const { return P(x/k, y/k); }\n T operator * (const P& a) const { return x*a.x + y*a.y; } // dot product\n T operator % (const P& a) const { return x*a.y - y*a.x; } // cross product\n int cmp(const P<T>& q) const { if (int t = ::cmp(x,q.x)) return t; return ::cmp(y,q.y); }\n #define Comp(x) bool operator x (const P& q) const { return cmp(q) x 0; }\n Comp(>) Comp(<) Comp(==) Comp(>=) Comp(<=) Comp(!=)\n #undef Comp\n T norm() { return x*x + y*y; }\n double len() { return hypot(x, y); }\n P<double> rotate(double alpha) {\n double cosa = cos(alpha), sina = sin(alpha);\n return P(x * cosa - y * sina, x * sina + y * cosa);\n }\n};\nusing Point = P<double>;\n\n// Compare points by (y, x)\ntemplate<typename T = double>\nbool cmpy(const P<T>& a, const P<T>& b) {\n if (cmp(a.y, b.y)) return a.y < b.y;\n return a.x < b.x;\n};\n\ntemplate<typename T>\nint ccw(P<T> a, P<T> b, P<T> c) {\n return cmp((b-a)%(c-a), T(0));\n}\n\ndouble angle(Point a, Point o, Point b) { // min of directed angle AOB & BOA\n a = a - o; b = b - o;\n return acos((a * b) / sqrt(a.norm()) / sqrt(b.norm()));\n}\n\ndouble directed_angle(Point a, Point o, Point b) { // angle AOB, in range [0, 2*PI)\n double t = -atan2(a.y - o.y, a.x - o.x)\n + atan2(b.y - o.y, b.x - o.x);\n while (t < 0) t += 2*PI;\n return t;\n}\n\n// Distance from p to Line ab (closest Point --> c)\n// i.e. c is projection of p on AB\ndouble distToLine(Point p, Point a, Point b, Point &c) {\n Point ap = p - a, ab = b - a;\n double u = (ap * ab) / ab.norm();\n c = a + (ab * u);\n return (p-c).len();\n}\n\n// Distance from p to segment ab (closest Point --> c)\ndouble distToLineSegment(Point p, Point a, Point b, Point &c) {\n Point ap = p - a, ab = b - a;\n double u = (ap * ab) / ab.norm();\n if (u < 0.0) {\n c = Point(a.x, a.y);\n return (p - a).len();\n }\n if (u > 1.0) {\n c = Point(b.x, b.y);\n return (p - b).len();\n }\n return distToLine(p, a, b, c);\n}\n\n// NOTE: WILL NOT WORK WHEN a = b = 0.\nstruct Line {\n double a, b, c; // ax + by + c = 0\n Point A, B; // Added for polygon intersect line. Do not rely on assumption that these are valid\n\n Line(double _a, double _b, double _c) : a(_a), b(_b), c(_c) {} \n\n Line(Point _A, Point _B) : A(_A), B(_B) {\n a = B.y - A.y;\n b = A.x - B.x;\n c = - (a * A.x + b * A.y);\n }\n Line(Point P, double m) {\n a = -m; b = 1;\n c = -((a * P.x) + (b * P.y));\n }\n double f(Point p) {\n return a*p.x + b*p.y + c;\n }\n};\nostream& operator << (ostream& cout, const Line& l) {\n cout << l.a << \"*x + \" << l.b << \"*y + \" << l.c;\n return cout;\n}\n\nbool areParallel(Line l1, Line l2) {\n return cmp(l1.a*l2.b, l1.b*l2.a) == 0;\n}\n\nbool areSame(Line l1, Line l2) {\n return areParallel(l1 ,l2) && cmp(l1.c*l2.a, l2.c*l1.a) == 0\n && cmp(l1.c*l2.b, l1.b*l2.c) == 0;\n}\n\nbool areIntersect(Line l1, Line l2, Point &p) {\n if (areParallel(l1, l2)) return false;\n double dx = l1.b*l2.c - l2.b*l1.c;\n double dy = l1.c*l2.a - l2.c*l1.a;\n double d = l1.a*l2.b - l2.a*l1.b;\n p = Point(dx/d, dy/d);\n return true;\n}\n\n// closest point from p in line l. (= projection of p onto line l)\nvoid proj(Line l, Point p, Point &ans) {\n if (fabs(l.b) < EPS) {\n ans.x = -(l.c) / l.a; ans.y = p.y;\n return;\n }\n if (fabs(l.a) < EPS) {\n ans.x = p.x; ans.y = -(l.c) / l.b;\n return;\n }\n Line perp(l.b, -l.a, - (l.b*p.x - l.a*p.y));\n areIntersect(l, perp, ans);\n}\n\n// Tested:\n// - https://cses.fi/problemset/task/2190/\ntemplate<typename T>\nbool onSegment(const P<T>& a, const P<T>& b, const P<T>& p) { // returns true if p is on segment [a, b]\n return ccw(a, b, p) == 0 && min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x) && min(a.y, b.y) <= p.y && p.y <= max(a.y, b.y);\n}\n\n// Returns true if segment [a, b] and [c, d] intersects\ntemplate<typename T>\nbool segmentIntersect(const P<T>& a, const P<T>& b, const P<T>& c, const P<T>& d) {\n if (onSegment(a, b, c) || onSegment(a, b, d) || onSegment(c, d, a) || onSegment(c, d, b)) return true;\n return ccw(a, b, c) * ccw(a, b, d) < 0 && ccw(c, d, a) * ccw(c, d, b) < 0;\n}\n\nstruct Circle : Point {\n double r;\n Circle(double _x = 0, double _y = 0, double _r = 0) : Point(_x, _y), r(_r) {}\n Circle(Point p, double _r) : Point(p), r(_r) {}\n \n bool contains(Point p) { return (*this - p).len() <= r + EPS; }\n double area() const { return r*r*M_PI; }\n // definitions in https://en.wikipedia.org/wiki/Circle\n // assumption: 0 <= theta <= 2*PI\n // theta: angle in radian\n double sector_area(double theta) const {\n return 0.5 * r * r * theta;\n }\n // assumption: 0 <= theta <= 2*PI\n // theta: angle in radian\n double segment_area(double theta) const {\n return 0.5 * r * r * (theta - sin(theta));\n }\n};\nistream& operator >> (istream& cin, Circle& c) {\n cin >> c.x >> c.y >> c.r;\n return cin;\n}\nostream& operator << (ostream& cout, const Circle& c) {\n cout << '(' << c.x << \", \" << c.y << \") \" << c.r;\n return cout;\n}\n// Find common tangents to 2 circles\n// Tested:\n// - http://codeforces.com/gym/100803/ - H\n// Helper method\nvoid tangents(Point c, double r1, double r2, vector<Line> & ans) {\n double r = r2 - r1;\n double z = sqr(c.x) + sqr(c.y);\n double d = z - sqr(r);\n if (d < -EPS) return;\n d = sqrt(fabs(d));\n Line l((c.x * r + c.y * d) / z,\n (c.y * r - c.x * d) / z,\n r1);\n ans.push_back(l);\n}\n// Actual method: returns vector containing all common tangents\nvector<Line> tangents(Circle a, Circle b) {\n vector<Line> ans; ans.clear();\n for (int i=-1; i<=1; i+=2)\n for (int j=-1; j<=1; j+=2)\n tangents(b-a, a.r*i, b.r*j, ans);\n for(int i = 0; i < (int) ans.size(); ++i)\n ans[i].c -= ans[i].a * a.x + ans[i].b * a.y;\n\n vector<Line> ret;\n for(int i = 0; i < (int) ans.size(); ++i) {\n if (std::none_of(ret.begin(), ret.end(), [&] (Line l) { return areSame(l, ans[i]); })) {\n ret.push_back(ans[i]);\n }\n }\n return ret;\n}\n\n// Circle & line intersection\n// Tested:\n// - http://codeforces.com/gym/100803/ - H\nvector<Point> intersection(Line l, Circle cir) {\n double r = cir.r, a = l.a, b = l.b, c = l.c + l.a*cir.x + l.b*cir.y;\n vector<Point> res;\n\n double x0 = -a*c/(a*a+b*b), y0 = -b*c/(a*a+b*b);\n if (c*c > r*r*(a*a+b*b)+EPS) return res;\n else if (fabs(c*c - r*r*(a*a+b*b)) < EPS) {\n res.push_back(Point(x0, y0) + Point(cir.x, cir.y));\n return res;\n } else {\n double d = r*r - c*c/(a*a+b*b);\n double mult = sqrt (d / (a*a+b*b));\n double ax,ay,bx,by;\n ax = x0 + b * mult;\n bx = x0 - b * mult;\n ay = y0 - a * mult;\n by = y0 + a * mult;\n\n res.push_back(Point(ax, ay) + Point(cir.x, cir.y));\n res.push_back(Point(bx, by) + Point(cir.x, cir.y));\n return res;\n }\n}\n\n// helper functions for commonCircleArea\ndouble cir_area_solve(double a, double b, double c) {\n return acos((a*a + b*b - c*c) / 2 / a / b);\n}\ndouble cir_area_cut(double a, double r) {\n double s1 = a * r * r / 2;\n double s2 = sin(a) * r * r / 2;\n return s1 - s2;\n}\n// Tested: http://codeforces.com/contest/600/problem/D\ndouble commonCircleArea(Circle c1, Circle c2) { //return the common area of two circle\n if (c1.r < c2.r) swap(c1, c2);\n double d = (c1 - c2).len();\n if (d + c2.r <= c1.r + EPS) return c2.r*c2.r*M_PI;\n if (d >= c1.r + c2.r - EPS) return 0.0;\n double a1 = cir_area_solve(d, c1.r, c2.r);\n double a2 = cir_area_solve(d, c2.r, c1.r);\n return cir_area_cut(a1*2, c1.r) + cir_area_cut(a2*2, c2.r);\n}\n\n// Check if 2 circle intersects. Return true if 2 circles touch\nbool areIntersect(Circle u, Circle v) {\n if (cmp((u - v).len(), u.r + v.r) > 0) return false;\n if (cmp((u - v).len() + v.r, u.r) < 0) return false;\n if (cmp((u - v).len() + u.r, v.r) < 0) return false;\n return true;\n}\n\n// If 2 circle touches, will return 2 (same) points\n// If 2 circle are same --> be careful\n// Tested:\n// - http://codeforces.com/gym/100803/ - H\n// - http://codeforces.com/gym/100820/ - I\nvector<Point> circleIntersect(Circle u, Circle v) {\n vector<Point> res;\n if (!areIntersect(u, v)) return res;\n double d = (u - v).len();\n double alpha = acos((u.r * u.r + d*d - v.r * v.r) / 2.0 / u.r / d);\n Point p1 = (v - u).rotate(alpha);\n Point p2 = (v - u).rotate(-alpha);\n res.push_back(p1 / p1.len() * u.r + u);\n res.push_back(p2 / p2.len() * u.r + u);\n return res;\n}\n\n// Smallest enclosing circle:\n// Given N points. Find the smallest circle enclosing these points.\n// Amortized complexity: O(N)\n//\n// Tested:\n// - https://oj.vnoi.info/problem/icpc22_mt_l\nstruct SmallestEnclosingCircle {\n Circle getCircle(vector<Point> points) {\n assert(!points.empty());\n\n random_shuffle(points.begin(), points.end());\n Circle c(points[0], 0);\n int n = points.size();\n\n for (int i = 1; i < n; i++)\n if ((points[i] - c).len() > c.r + EPS){\n c = Circle(points[i], 0);\n for (int j = 0; j < i; j++)\n if ((points[j] - c).len() > c.r + EPS){\n c = Circle((points[i] + points[j]) / 2, (points[i] - points[j]).len() / 2);\n for (int k = 0; k < j; k++)\n if ((points[k] - c).len() > c.r + EPS)\n c = getCircumcircle(points[i], points[j], points[k]);\n }\n }\n\n return c;\n }\n // NOTE: This code work only when a, b, c are not collinear and no 2 points are same --> DO NOT\n // copy and use in other cases.\n Circle getCircumcircle(Point a, Point b, Point c) {\n assert(ccw(a, b, c));\n double d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));\n assert(fabs(d) > EPS);\n double x = (a.norm() * (b.y - c.y) + b.norm() * (c.y - a.y) + c.norm() * (a.y - b.y)) / d;\n double y = (a.norm() * (c.x - b.x) + b.norm() * (a.x - c.x) + c.norm() * (b.x - a.x)) / d;\n Point p(x, y);\n return Circle(p, (p - a).len());\n }\n};\n\nvoid testcase(){\n int N;\n cin >> N;\n vector<Point> pts(N);\n\n rep(i, 0, N){\n int x, y;\n cin >> x >> y;\n pts[i] = Point(x, y);\n }\n\n SmallestEnclosingCircle C;\n Circle result = C.getCircle(pts);\n\n cout << fixed << setprecision(12) << result.x << ' ' << result.y << ' ' << result.r << '\\n';\n}\n\nint main(){\n setIO();\n int T = 1;\n // cin >> T;\n while(T--){\n testcase();\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 6252, "score_of_the_acc": -0.0807, "final_rank": 2 } ]
aoj_CGL_5_A_cpp
Closest Pair For given n points in metric space, find the distance of the closest points. Input n x 0 y 0 x 1 y 1 : x n-1 y n-1 The first integer n is the number of points. In the following n lines, the coordinate of the i -th point is given by two real numbers x i and y i . Each value is a real number with at most 6 digits after the decimal point. Output Print the distance in a line. The output values should be in a decimal fraction with an error less than 0.000001. Constraints 2 ≤ n ≤ 100,000 -100 ≤ x , y ≤ 100 Sample Input 1 2 0.0 0.0 1.0 0.0 Sample Output 1 1.000000 Sample Input 2 3 0.0 0.0 2.0 0.0 1.0 1.0 Sample Output 2 1.41421356237
[ { "submission_id": "aoj_CGL_5_A_11065295", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define pii pair<int, int>\n#define pll pair<ll, ll>\n#define vi vector<int>\n#define vl vector<ll>\n#define ov4(a, b, c, d, name, ...) name\n#define rep3(i, a, b, c) for(ll i = (a); i < (b); i += (c))\n#define rep2(i, a, b) rep3(i, a, b, 1)\n#define rep1(i, n) rep2(i, 0, n)\n#define rep0(n) rep1(aaaaa, n)\n#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)\n#define per(i, a, b) for(ll i = (a)-1; i >= (b); i--)\n#define fore(e, v) for(auto&& e : v)\n#define all(a) begin(a), end(a)\n#define si(a) (int)(size(a))\n#define lb(v, x) (lower_bound(all(v), x) - begin(v))\n#define eb emplace_back\n\ntemplate<typename T, typename S> bool chmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; }\ntemplate<typename T, typename S> bool chmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; }\n\nconst int INF = 1e9 + 100;\nconst ll INFL = 3e18 + 100;\n\n#define i128 __int128_t\n\nstruct _ {\n _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }\n} __;\n\ntemplate<class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n typedef Point P;\n T x, y;\n explicit Point(T x=0, T y=0) : x(x), y(y) {}\n bool operator<(P p) const { return tie(x, y) < tie(p.x, p.y); }\n bool operator==(P p) const { return tie(x, y) == tie(p.x, p.y); }\n P operator+(P p) const { return P(x + p.x, y + p.y); }\n P operator-(P p) const { return P(x - p.x, y - p.y); }\n P operator*(T d) const { return P(x * d, y * d); }\n P operator/(T d) const { return P(x / d, y / d); }\n T dot(P p) const { return x * p.x + y * p.y; }\n T cross(P p) const { return x * p.y - y * p.x; }\n T cross(P a, P b) const { return (a - *this).cross(b - *this); }\n T dist2() const { return x*x + y*y; }\n double dist() const { return sqrt((double)dist2()); }\n P perp() const { return P(-y, x); }\n};\n\ntemplate<class P>\nP lineProj(P a, P b, P p, bool refl=false) {\n P v = b - a;\n return p - v.perp() * (1 + refl) * v.cross(p - a) / v.dist2();\n}\n\ntemplate<class P>\nbool onSegment(P s, P e, P p) {\n return p.cross(s, e) == 0 and (s - p).dot(e - p) <= 0;\n}\n\ntemplate<class P>\nvector<P> segInter(P a, P b, P c, P d) {\n auto oa = c.cross(d, a), ob = c.cross(d, b),\n oc = a.cross(b, c), od = a.cross(b, d);\n if (sgn(oa) * sgn(ob) < 0 and sgn(oc) * sgn(od) < 0) {\n return {(a * ob - b * oa) / (ob - oa)};\n }\n set<P> s;\n if (onSegment(c, d, a)) s.insert(a);\n if (onSegment(c, d, b)) s.insert(b);\n if (onSegment(a, b, c)) s.insert(c);\n if (onSegment(a, b, d)) s.insert(d);\n return {all(s)};\n}\n\ntemplate<class P>\ndouble segDist(P s, P e, P p) {\n if (s == e) return (p - s).dist();\n auto d = (s - e).dist2(), t = min(d, max(.0, (p - s).dot(e - s)));\n return ((p - s) * d - (e - s) * t).dist() / d;\n}\n\ntemplate<class P>\ndouble segDist(P s1, P e1, P s2, P e2) {\n if (!segInter(s1, e1, s2, e2).empty()) return 0;\n auto a = min(segDist(s1, e1, s2), segDist(s1, e1, e2));\n auto b = min(segDist(s2, e2, s1), segDist(s2, e2, e1));\n return min(a, b);\n}\n\ntemplate<class P>\npair<int, P> lineInter(P s1, P e1, P s2, P e2) {\n auto d = (e1 - s2).cross(e2 - s2);\n if(d == 0) {\n return {-(s1.cross(e1, s2) == 0), P(0, 0)};\n }\n auto p = s2.cross(e1, e2), q = s2.cross(e2, s1);\n return {1, (s1 * p + e1 * q) / d};\n}\n\ntemplate<class T>\nT polygonArea2(vector<Point<T>> &v) {\n if (si(v) <= 2) return 0; // \n T a = v.back().cross(v[0]);\n rep(i, si(v) - 1) a += v[i].cross(v[i + 1]);\n return a;\n}\n\nusing P = Point<ll>;\n\n// speed star library\n// typedef Point<long double> P;\nvector<P> convex_hull(vector<P> pts) {\n int n = si(pts), k = 0;\n if (n <= 2) return pts;\n sort(all(pts));\n vector<P> ch(2 * n);\n for(int i = 0; i < n; ch[k++] = pts[i++]) {\n while(k >= 2 and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) <= -1.0e-14) --k;\n }\n for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = pts[i--]) {\n while(k >= t and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) <= -1.0e-14) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n\narray<P, 2> hullDiameter(vector<P> S) {\n int n = si(S), j = n < 2 ? 0 : 1;\n pair<long double, array<P, 2>> res({0, {S[0], S[0]}});\n rep(i, j) {\n for (;; j = (j + 1) % n) {\n res = max(res, {(S[i] - S[j]).dist2(), {S[i], S[j]}});\n if ((S[(j + 1) % n] - S[j]).cross(S[i + 1] - S[i]) >= 1.0e-14) break;\n }\n }\n return res.second;\n}\n\n// typedef Point<double> P;\nvector<P> polygonCut(const vector<P> &poly, P s, P e) {\n vector<P> res;\n rep(i, si(poly)) {\n P cur = poly[i], prev = i ? poly[i - 1] : poly.back();\n auto a = s.cross(e, cur), b = s.cross(e, prev);\n if ((a < 0) != (b < 0)) res.push_back(cur + (prev - cur) * (a / (a - b)));\n if (a < 0) res.push_back(cur);\n }\n return res;\n}\n\ntemplate<class P>\nbool inPolygon(vector<P> &p, P a, bool strict = true) {\n int cnt = 0, n = si(p);\n rep(i, n) {\n P q = p[(i + 1) % n];\n if (onSegment(p[i], q, a)) return !strict;\n cnt ^= ((a.y < p[i].y) - (a.y < q.y)) * a.cross(p[i], q) > 0;\n }\n return cnt;\n}\n\n// typedef Point<ll> P;\npair<P, P> closest(vector<P> v) {\n assert(si(v) > 1);\n set<P> S;\n sort(all(v), [](P a, P b) { return a.y < b.y; });\n pair<ll, pair<P, P>> ret{LLONG_MAX, {P(), P()}};\n int j = 0;\n fore(p, v) {\n P d{1 + (ll)sqrt(ret.first), 0};\n while (v[j].y <= p.y - d.x) S.erase(v[j++]);\n auto lo = S.lower_bound(p - d), hi = S.upper_bound(p + d);\n for (; lo != hi; ++lo) ret = min(ret, {(*lo - p).dist2(), {*lo, p}});\n S.insert(p);\n }\n return ret.second;\n} \n\nusing P = Point<ll>;\n\nll conv(string s) {\n s += \"000000\";\n ll res = 0;\n int cnt = 1;\n fore(c, s) {\n if (isdigit(c)) {\n res *= 10;\n res += c - '0';\n cnt++;\n if (cnt == 0) break;\n } if (c == '.') {\n cnt = -6;\n }\n }\n if (s[0] == '-') res *= -1;\n return res;\n}\n\nint main() {\n int n;\n cin >> n;\n vector<P> v;\n rep(i, n) {\n string s, t;\n cin >> s >> t;\n v.push_back(P(conv(s), conv(t)));\n }\n\n cout << setprecision(15) << fixed;\n auto res = closest(v);\n cout << (double)(res.first - res.second).dist() / 1e6 << endl;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 11880, "score_of_the_acc": -0.5371, "final_rank": 11 }, { "submission_id": "aoj_CGL_5_A_11065277", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define pii pair<int, int>\n#define pll pair<ll, ll>\n#define vi vector<int>\n#define vl vector<ll>\n#define ov4(a, b, c, d, name, ...) name\n#define rep3(i, a, b, c) for(ll i = (a); i < (b); i += (c))\n#define rep2(i, a, b) rep3(i, a, b, 1)\n#define rep1(i, n) rep2(i, 0, n)\n#define rep0(n) rep1(aaaaa, n)\n#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)\n#define per(i, a, b) for(ll i = (a)-1; i >= (b); i--)\n#define fore(e, v) for(auto&& e : v)\n#define all(a) begin(a), end(a)\n#define si(a) (int)(size(a))\n#define lb(v, x) (lower_bound(all(v), x) - begin(v))\n#define eb emplace_back\n\ntemplate<typename T, typename S> bool chmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; }\ntemplate<typename T, typename S> bool chmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; }\n\nconst int INF = 1e9 + 100;\nconst ll INFL = 3e18 + 100;\n\n#define i128 __int128_t\n\nstruct _ {\n _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }\n} __;\n\ntemplate<class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n typedef Point P;\n T x, y;\n explicit Point(T x=0, T y=0) : x(x), y(y) {}\n bool operator<(P p) const { return tie(x, y) < tie(p.x, p.y); }\n bool operator==(P p) const { return tie(x, y) == tie(p.x, p.y); }\n P operator+(P p) const { return P(x + p.x, y + p.y); }\n P operator-(P p) const { return P(x - p.x, y - p.y); }\n P operator*(T d) const { return P(x * d, y * d); }\n P operator/(T d) const { return P(x / d, y / d); }\n T dot(P p) const { return x * p.x + y * p.y; }\n T cross(P p) const { return x * p.y - y * p.x; }\n T cross(P a, P b) const { return (a - *this).cross(b - *this); }\n T dist2() const { return x*x + y*y; }\n double dist() const { return sqrt((double)dist2()); }\n P perp() const { return P(-y, x); }\n};\n\ntemplate<class P>\nP lineProj(P a, P b, P p, bool refl=false) {\n P v = b - a;\n return p - v.perp() * (1 + refl) * v.cross(p - a) / v.dist2();\n}\n\ntemplate<class P>\nbool onSegment(P s, P e, P p) {\n return p.cross(s, e) == 0 and (s - p).dot(e - p) <= 0;\n}\n\ntemplate<class P>\nvector<P> segInter(P a, P b, P c, P d) {\n auto oa = c.cross(d, a), ob = c.cross(d, b),\n oc = a.cross(b, c), od = a.cross(b, d);\n if (sgn(oa) * sgn(ob) < 0 and sgn(oc) * sgn(od) < 0) {\n return {(a * ob - b * oa) / (ob - oa)};\n }\n set<P> s;\n if (onSegment(c, d, a)) s.insert(a);\n if (onSegment(c, d, b)) s.insert(b);\n if (onSegment(a, b, c)) s.insert(c);\n if (onSegment(a, b, d)) s.insert(d);\n return {all(s)};\n}\n\ntemplate<class P>\ndouble segDist(P s, P e, P p) {\n if (s == e) return (p - s).dist();\n auto d = (s - e).dist2(), t = min(d, max(.0, (p - s).dot(e - s)));\n return ((p - s) * d - (e - s) * t).dist() / d;\n}\n\ntemplate<class P>\ndouble segDist(P s1, P e1, P s2, P e2) {\n if (!segInter(s1, e1, s2, e2).empty()) return 0;\n auto a = min(segDist(s1, e1, s2), segDist(s1, e1, e2));\n auto b = min(segDist(s2, e2, s1), segDist(s2, e2, e1));\n return min(a, b);\n}\n\ntemplate<class P>\npair<int, P> lineInter(P s1, P e1, P s2, P e2) {\n auto d = (e1 - s2).cross(e2 - s2);\n if(d == 0) {\n return {-(s1.cross(e1, s2) == 0), P(0, 0)};\n }\n auto p = s2.cross(e1, e2), q = s2.cross(e2, s1);\n return {1, (s1 * p + e1 * q) / d};\n}\n\ntemplate<class T>\nT polygonArea2(vector<Point<T>> &v) {\n if (si(v) <= 2) return 0; // \n T a = v.back().cross(v[0]);\n rep(i, si(v) - 1) a += v[i].cross(v[i + 1]);\n return a;\n}\n\n// speed star library\ntypedef Point<long double> P;\nvector<P> convex_hull(vector<P> pts) {\n int n = si(pts), k = 0;\n if (n <= 2) return pts;\n sort(all(pts));\n vector<P> ch(2 * n);\n for(int i = 0; i < n; ch[k++] = pts[i++]) {\n while(k >= 2 and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) <= -1.0e-14) --k;\n }\n for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = pts[i--]) {\n while(k >= t and (ch[k - 1] - ch[k - 2]).cross(pts[i] - ch[k - 1]) <= -1.0e-14) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n\narray<P, 2> hullDiameter(vector<P> S) {\n int n = si(S), j = n < 2 ? 0 : 1;\n pair<long double, array<P, 2>> res({0, {S[0], S[0]}});\n rep(i, j) {\n for (;; j = (j + 1) % n) {\n res = max(res, {(S[i] - S[j]).dist2(), {S[i], S[j]}});\n if ((S[(j + 1) % n] - S[j]).cross(S[i + 1] - S[i]) >= 1.0e-14) break;\n }\n }\n return res.second;\n}\n\n// typedef Point<double> P;\nvector<P> polygonCut(const vector<P> &poly, P s, P e) {\n vector<P> res;\n rep(i, si(poly)) {\n P cur = poly[i], prev = i ? poly[i - 1] : poly.back();\n auto a = s.cross(e, cur), b = s.cross(e, prev);\n if ((a < 0) != (b < 0)) res.push_back(cur + (prev - cur) * (a / (a - b)));\n if (a < 0) res.push_back(cur);\n }\n return res;\n}\n\ntemplate<class P>\nbool inPolygon(vector<P> &p, P a, bool strict = true) {\n int cnt = 0, n = si(p);\n rep(i, n) {\n P q = p[(i + 1) % n];\n if (onSegment(p[i], q, a)) return !strict;\n cnt ^= ((a.y < p[i].y) - (a.y < q.y)) * a.cross(p[i], q) > 0;\n }\n return cnt;\n}\n\nusing ld = long double;\n// typedef Point<ll> P;\npair<P, P> closest(vector<P> v) {\n assert(si(v) > 1);\n set<P> S;\n sort(all(v), [](P a, P b) { return a.y < b.y; });\n pair<ld, pair<P, P>> ret{LLONG_MAX, {P(), P()}};\n int j = 0;\n fore(p, v) {\n P d{1 + (ld)sqrt(ret.first), 0};\n while (v[j].y <= p.y - d.x) S.erase(v[j++]);\n auto lo = S.lower_bound(p - d), hi = S.upper_bound(p + d);\n for (; lo != hi; ++lo) ret = min(ret, {(*lo - p).dist2(), {*lo, p}});\n S.insert(p);\n }\n return ret.second;\n} \n\nusing P = Point<long double>;\n\nint main() {\n int n;\n cin >> n;\n vector<P> v;\n rep(i, n) {\n double x, y;\n cin >> x >> y;\n v.push_back(P(x, y));\n }\n\n cout << setprecision(20);\n auto res = closest(v);\n cout << (res.first - res.second).dist() << endl;;\n}", "accuracy": 0.40625, "time_ms": 780, "memory_kb": 4844, "score_of_the_acc": -1, "final_rank": 20 }, { "submission_id": "aoj_CGL_5_A_11065081", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint n;\nvector<pair<double,double>> point;\ndouble distance(pair<double,double> a, pair<double,double> b)\n{\n return sqrt((a.first-b.first)*(a.first-b.first)\n +(a.second-b.second)*(a.second-b.second));\n}\ndouble bruteforce(int left, int right)\n{\n double mind=INT_MAX;\n for(int i=left;i<right;i++)\n mind=min(mind,distance(point[i],point[i+1]));\n return mind;\n}\ndouble recursion(int left, int right)\n{\n if(right-left+1<=3)\n {\n return bruteforce(left,right);\n }\n int midx=left+(right-left+1)/2;\n double d=min(recursion(left,midx),recursion(midx+1,right));\n vector<pair<double,double>> strip;\n for(int i=left;i<=midx;i++)\n {\n if(abs(point[i].first-point[midx].first)<d)\n strip.push_back({point[i].second,point[i].first});\n }\n for(int i=midx+1;i<=right;i++)\n {\n if(abs(point[i].first-point[midx].first)<d)\n strip.push_back({point[i].second,point[i].first});\n }\n sort(strip.begin(),strip.end());\n for(int i=0;i<strip.size();i++)\n {\n for(int j=i+1;j<min(i+8,(int)strip.size());j++)\n d=min(d,distance(strip[i],strip[j]));\n }\n return d;\n}\nint main()\n{\n\n cin>>n;\n for(int i=0;i<n;i++)\n {\n double a,b;\n cin>>a>>b;\n point.push_back({a,b});\n }\n sort(point.begin(),point.end());\n cout << fixed << setprecision(12) << recursion(0,n-1);\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 7632, "score_of_the_acc": -0.2804, "final_rank": 6 }, { "submission_id": "aoj_CGL_5_A_11047893", "code_snippet": "// --- Start of include: ./../../akakoi_lib/template/template.cpp ---\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i,n) for(ll i=0;i<(ll)(n);++i)\nbool chmin(auto& a, auto b) {return a>b?a=b,1:0;}\nbool chmax(auto& a, auto b) {return a<b?a=b,1:0;}\n// int main() {\n// ios::sync_with_stdio(false);\n// cin.tie(0);\n// }\n// --- End of include: ./../../akakoi_lib/template/template.cpp ---\n// --- Start of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n/// @brief 幾何ライブラリ\nnamespace Geometry {\n using Real = long double;\n const Real EPS = 1e-9;\n\n bool almostEqual(Real a, Real b) { return abs(a - b) < EPS; }\n bool lessThan(Real a, Real b) { return a < b && !almostEqual(a, b); }\n bool greaterThan(Real a, Real b) { return a > b && !almostEqual(a, b); }\n bool lessThanOrEqual(Real a, Real b) { return a < b || almostEqual(a, b); }\n bool greaterThanOrEqual(Real a, Real b) { return a > b || almostEqual(a, b); }\n\n /// @brief 2次元平面上の位置ベクトル\n struct Point {\n Real x, y;\n Point() = default;\n Point(Real x, Real y) : x(x), y(y) {}\n\n Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); }\n Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); }\n Point operator*(Real k) const { return Point(x * k, y * k); }\n Point operator/(Real k) const { return Point(x / k, y / k); }\n\n /// @brief p との内積を返す\n Real dot(const Point& p) const { return x * p.x + y * p.y; }\n\n /// @brief p との外積を返す\n Real cross(const Point& p) const { return x * p.y - y * p.x; }\n\n /// @brief p1 と p2 を端点とするベクトルとの外積を返す\n Real cross(const Point& p1, const Point& p2) const { return (p1.x - x) * (p2.y - y) - (p1.y - y) * (p2.x - x); }\n\n /// @brief 2乗ノルムを返す\n Real norm() const { return x * x + y * y; }\n\n /// @brief ユークリッドノルムを返す\n Real abs() const { return sqrt(norm()); }\n\n /// @brief 偏角を返す\n Real arg() const { return atan2(y, x); }\n\n bool operator==(const Point& p) const { return almostEqual(x, p.x) && almostEqual(y, p.y); }\n friend istream& operator>>(istream& is, Point& p) { return is >> p.x >> p.y; }\n };\n\n /// @brief 直線\n struct Line {\n Point a, b;\n Line() = default;\n Line(const Point& _a, const Point& _b) : a(_a), b(_b) {}\n\n /// @brief 直線 Ax+By=C を定義する\n Line(const Real& A, const Real& B, const Real& C) {\n if (almostEqual(A, 0)) {\n assert(!almostEqual(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (almostEqual(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (almostEqual(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n bool operator==(const Line& l) const { return a == l.a && b == l.b; }\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n };\n\n /// @brief 線分\n struct Segment : Line {\n Segment() = default;\n using Line::Line;\n };\n\n /// @brief 円\n struct Circle {\n Point center; ///< 中心\n Real r; ///< 半径\n\n Circle() = default;\n Circle(Real x, Real y, Real r) : center(x, y), r(r) {}\n Circle(Point _center, Real r) : center(_center), r(r) {}\n\n bool operator==(const Circle& C) const { return center == C.center && r == C.r; }\n friend istream& operator>>(istream& is, Circle& C) { return is >> C.center >> C.r; }\n };\n\n //-----------------------------------------------------------\n\n /// @brief 3点の進行方向\n enum Orientation {\n COUNTER_CLOCKWISE, ///< 反時計回り\n CLOCKWISE, ///< 時計回り\n ONLINE_BACK,\n ONLINE_FRONT,\n ON_SEGMENT\n };\n\n /// @brief 3点 p0, p1, p2 の進行方向を返す\n Orientation ccw(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0;\n Point b = p2 - p0;\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) return COUNTER_CLOCKWISE;\n if (lessThan(cross_product, 0)) return CLOCKWISE;\n if (lessThan(a.dot(b), 0)) return ONLINE_BACK;\n if (lessThan(a.norm(), b.norm())) return ONLINE_FRONT;\n return ON_SEGMENT;\n }\n\n string orientationToString(Orientation o) {\n switch (o) {\n case COUNTER_CLOCKWISE:\n return \"COUNTER_CLOCKWISE\";\n case CLOCKWISE:\n return \"CLOCKWISE\";\n case ONLINE_BACK:\n return \"ONLINE_BACK\";\n case ONLINE_FRONT:\n return \"ONLINE_FRONT\";\n case ON_SEGMENT:\n return \"ON_SEGMENT\";\n default:\n return \"UNKNOWN\";\n }\n }\n\n /// @brief ベクトル p の直線 p1, p2 への正射影ベクトルを返す\n Point projection(const Point& p1, const Point& p2, const Point& p) {\n Point base = p2 - p1;\n Real r = (p - p1).dot(base) / base.norm();\n return p1 + base * r;\n }\n\n /// @brief ベクトル p の直線 l への正射影ベクトルを返す\n Point projection(const Line& l, const Point& p) {\n Point base = l.b - l.a;\n Real r = (p - l.a).dot(base) / base.norm();\n return l.a + base * r;\n }\n\n /// @brief ベクトル p の直線 p1, p2 に対する鏡像ベクトルを返す\n Point reflection(const Point& p1, const Point& p2, const Point& p) {\n Point proj = projection(p1, p2, p);\n return proj * 2 - p;\n }\n\n /// @brief ベクトル p の直線 l に対する鏡像ベクトルを返す\n Point reflection(const Line& l, const Point& p) {\n Point proj = projection(l, p);\n return proj * 2 - p;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 直線の平行判定\n bool isParallel(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線の直交判定\n bool isOrthogonal(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分の平行判定\n bool isParallel(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分の直交判定\n bool isOrthogonal(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 直線と線分の平行判定\n bool isParallel(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線と線分の直交判定\n bool isOrthogonal(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分と直線の平行判定\n bool isParallel(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分と直線の直交判定\n bool isOrthogonal(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 点が直線上にあるか判定\n bool isPointOnLine(const Point& p, const Line& l) { return almostEqual((l.b - l.a).cross(p - l.a), 0.0); }\n\n /// @brief 点が線分上にあるか判定\n bool isPointOnSegment(const Point& p, const Segment& s) {\n return lessThanOrEqual(min(s.a.x, s.b.x), p.x) &&\n lessThanOrEqual(p.x, max(s.a.x, s.b.x)) &&\n lessThanOrEqual(min(s.a.y, s.b.y), p.y) &&\n lessThanOrEqual(p.y, max(s.a.y, s.b.y)) &&\n almostEqual((s.b - s.a).cross(p - s.a), 0.0);\n }\n\n /// @brief 直線の交差判定\n bool isIntersecting(const Segment& s1, const Segment& s2) {\n Point p0p1 = s1.b - s1.a, p0p2 = s2.a - s1.a, p0p3 = s2.b - s1.a, p2p3 = s2.b - s2.a, p2p0 = s1.a - s2.a, p2p1 = s1.b - s2.a;\n Real d1 = p0p1.cross(p0p2), d2 = p0p1.cross(p0p3), d3 = p2p3.cross(p2p0), d4 = p2p3.cross(p2p1);\n if (lessThan(d1 * d2, 0) && lessThan(d3 * d4, 0)) return true;\n if (almostEqual(d1, 0.0) && isPointOnSegment(s2.a, s1)) return true;\n if (almostEqual(d2, 0.0) && isPointOnSegment(s2.b, s1)) return true;\n if (almostEqual(d3, 0.0) && isPointOnSegment(s1.a, s2)) return true;\n if (almostEqual(d4, 0.0) && isPointOnSegment(s1.b, s2)) return true;\n return false;\n }\n\n /// @brief 線分の交点を返す\n Point getIntersection(const Segment& s1, const Segment& s2) {\n assert(isIntersecting(s1, s2));\n auto cross = [](Point p, Point q) { return p.x * q.y - p.y * q.x; };\n Point base = s2.b - s2.a;\n Real d1 = abs(cross(base, s1.a - s2.a));\n Real d2 = abs(cross(base, s1.b - s2.a));\n Real t = d1 / (d1 + d2);\n return s1.a + (s1.b - s1.a) * t;\n }\n\n /// @brief 点と線分の距離を返す\n Real distancePointToSegment(const Point& p, const Segment& s) {\n Point proj = projection(s.a, s.b, p);\n if (isPointOnSegment(proj, s))\n return (p - proj).abs();\n else\n return min((p - s.a).abs(), (p - s.b).abs());\n }\n\n /// @brief 線分と線分の距離を返す\n Real distanceSegmentToSegment(const Segment& s1, const Segment& s2) {\n if (isIntersecting(s1, s2)) return 0.0;\n return min({distancePointToSegment(s1.a, s2),\n distancePointToSegment(s1.b, s2),\n distancePointToSegment(s2.a, s1),\n distancePointToSegment(s2.b, s1)});\n }\n\n //-----------------------------------------------------------\n\n /// @brief 多角形の面積を返す\n Real getPolygonArea(const vector<Point>& points) {\n int n = points.size();\n Real area = 0.0;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n area += points[i].x * points[j].y;\n area -= points[i].y * points[j].x;\n }\n return abs(area) / 2.0;\n }\n\n /// @brief 多角形が凸か判定\n bool isConvex(const vector<Point>& points) {\n int n = points.size();\n bool has_positive = false, has_negative = false;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n int k = (i + 2) % n;\n Point a = points[j] - points[i];\n Point b = points[k] - points[j];\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) has_positive = true;\n if (lessThan(cross_product, 0)) has_negative = true;\n }\n return !(has_positive && has_negative);\n }\n\n /// @brief 点が凸多角形の辺上に存在するか判定\n bool isPointOnPolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n Segment s(a, b);\n if (isPointOnSegment(p, s)) return true;\n }\n return false;\n }\n\n /// @brief 点が多角形の内部に存在するか判定(辺上は含まない)\n bool isPointInsidePolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n bool inPolygon = false;\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n if (greaterThan(a.y, b.y)) swap(a, b);\n if (lessThanOrEqual(a.y, p.y) && lessThan(p.y, b.y) && greaterThan((b - a).cross(p - a), 0)) inPolygon = !inPolygon;\n }\n return inPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 凸包を求める\n vector<Point> convexHull(vector<Point>& points, bool include_collinear = false) {\n int n = points.size();\n if (n <= 1) return points;\n sort(points.begin(), points.end(), [](const Point& l, const Point& r) -> bool {\n if (almostEqual(l.y, r.y)) return lessThan(l.x, r.x);\n return lessThan(l.y, r.y);\n });\n if (n == 2) return points;\n vector<Point> upper = {points[0], points[1]}, lower = {points[0], points[1]};\n for (int i = 2; i < n; i++) {\n while (upper.size() >= 2 && ccw(upper.end()[-2], upper.end()[-1], points[i]) != CLOCKWISE) {\n if (ccw(upper.end()[-2], upper.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n upper.pop_back();\n }\n upper.push_back(points[i]);\n while (lower.size() >= 2 && ccw(lower.end()[-2], lower.end()[-1], points[i]) != COUNTER_CLOCKWISE) {\n if (ccw(lower.end()[-2], lower.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n lower.pop_back();\n }\n lower.push_back(points[i]);\n }\n reverse(upper.begin(), upper.end());\n upper.pop_back();\n lower.pop_back();\n lower.insert(lower.end(), upper.begin(), upper.end());\n return lower;\n }\n\n /// @brief 凸包の直径を求める\n Real convexHullDiameter(const vector<Point>& hull) {\n int n = hull.size();\n if (n == 1) return 0;\n int k = 1;\n Real max_dist = 0;\n for (int i = 0; i < n; i++) {\n while (true) {\n int j = (k + 1) % n;\n Point dist1 = hull[i] - hull[j], dist2 = hull[i] - hull[k];\n max_dist = max(max_dist, dist1.abs());\n max_dist = max(max_dist, dist2.abs());\n if (dist1.abs() > dist2.abs())\n k = j;\n else\n break;\n }\n Point dist = hull[i] - hull[k];\n max_dist = max(max_dist, dist.abs());\n }\n return max_dist;\n }\n\n /// @brief 凸包を直線で切断して左側を返す\n vector<Point> cutPolygon(const vector<Point>& g, const Line& l) {\n auto isLeft = [](const Point& p1, const Point& p2, const Point& p) -> bool { return (p2 - p1).cross(p - p1) > 0; };\n vector<Point> newPolygon;\n int n = g.size();\n for (int i = 0; i < n; i++) {\n const Point& cur = g[i];\n const Point& next = g[(i + 1) % n];\n if (isLeft(l.a, l.b, cur)) newPolygon.push_back(cur);\n if ((isLeft(l.a, l.b, cur) && !isLeft(l.a, l.b, next)) || (!isLeft(l.a, l.b, cur) && isLeft(l.a, l.b, next))) {\n Real A1 = (next - cur).cross(l.a - cur);\n Real A2 = (next - cur).cross(l.b - cur);\n Point intersection = l.a + (l.b - l.a) * (A1 / (A1 - A2));\n newPolygon.push_back(intersection);\n }\n }\n return newPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 最近点対の距離を求める\n /// @note points は x 座標でソートされている必要がある\n Real closestPair(vector<Point>& points, int l, int r) {\n if (r - l <= 1) return numeric_limits<Real>::max();\n int mid = (l + r) >> 1;\n Real x = points[mid].x;\n Real d = min(closestPair(points, l, mid), closestPair(points, mid, r));\n auto iti = points.begin(), itl = iti + l, itm = iti + mid, itr = iti + r;\n inplace_merge(itl, itm, itr, [](const Point& lhs, const Point& rhs) -> bool {\n return lessThan(lhs.y, rhs.y);\n });\n vector<Point> nearLine;\n for (int i = l; i < r; i++) {\n if (greaterThanOrEqual(fabs(points[i].x - x), d)) continue;\n int sz = nearLine.size();\n for (int j = sz - 1; j >= 0; j--) {\n Point dv = points[i] - nearLine[j];\n if (dv.y >= d) break;\n d = min(d, dv.abs());\n }\n nearLine.push_back(points[i]);\n }\n return d;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 線分の交差数を数える\n int countIntersections(vector<Segment> segments) {\n struct Event {\n Real x;\n int type; // 0:horizontal start,1:vertical,2:horizontal end\n Real y1, y2;\n Event(Real x, int type, Real y1, Real y2) : x(x), type(type), y1(y1), y2(y2) {}\n bool operator<(const Event& other) const {\n if (x == other.x) return type < other.type;\n return x < other.x;\n }\n };\n vector<Event> events;\n sort(segments.begin(), segments.end(), [](const Segment& lhs, const Segment& rhs) -> bool {\n return lessThan(min(lhs.a.x, lhs.b.x), min(rhs.a.x, rhs.b.x));\n });\n for (const auto& seg : segments) {\n if (seg.a.y == seg.b.y) {\n // Horizontal segment\n Real y = seg.a.y;\n Real x1 = min(seg.a.x, seg.b.x);\n Real x2 = max(seg.a.x, seg.b.x);\n events.emplace_back(x1, 0, y, y);\n events.emplace_back(x2, 2, y, y);\n } else {\n // Vertical segment\n Real x = seg.a.x;\n Real y1 = min(seg.a.y, seg.b.y);\n Real y2 = max(seg.a.y, seg.b.y);\n events.emplace_back(x, 1, y1, y2);\n }\n }\n sort(events.begin(), events.end());\n set<Real> activeSegments;\n int intersectionCount = 0;\n for (const auto& event : events) {\n if (event.type == 0) {\n // Add horizontal segment to active set\n activeSegments.insert(event.y1);\n } else if (event.type == 2) {\n // Remove horizontal segment from active set\n activeSegments.erase(event.y1);\n } else if (event.type == 1) {\n // Count intersections with vertical segment\n auto lower = activeSegments.lower_bound(event.y1);\n auto upper = activeSegments.upper_bound(event.y2);\n intersectionCount += distance(lower, upper);\n }\n }\n return intersectionCount;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 2つの円の交点の個数を返す\n int countCirclesIntersection(const Circle& c1, const Circle& c2) {\n Real d =\n sqrt((c1.center.x - c2.center.x) * (c1.center.x - c2.center.x) +\n (c1.center.y - c2.center.y) * (c1.center.y - c2.center.y));\n Real r1 = c1.r, r2 = c2.r;\n if (greaterThan(d, r1 + r2))\n return 4;\n else if (almostEqual(d, r1 + r2))\n return 3;\n else if (greaterThan(d, fabs(r1 - r2)))\n return 2;\n else if (almostEqual(d, fabs(r1 - r2)))\n return 1;\n else\n return 0;\n }\n\n /// @brief 内接円を求める\n Circle getInCircle(const Point& A, const Point& B, const Point& C) {\n Real a = (B - C).abs();\n Real b = (A - C).abs();\n Real c = (A - B).abs();\n Real s = (a + b + c) / 2;\n Real area = sqrt(s * (s - a) * (s - b) * (s - c));\n Real r = area / s;\n Real cx = (a * A.x + b * B.x + c * C.x) / (a + b + c);\n Real cy = (a * A.y + b * B.y + c * C.y) / (a + b + c);\n return Circle{Point(cx, cy), r};\n }\n\n /// @brief 外接円を求める\n Circle getCircumCircle(const Point& A, const Point& B, const Point& C) {\n Real D = 2 * (A.x * (B.y - C.y) + B.x * (C.y - A.y) + C.x * (A.y - B.y));\n Real Ux = ((A.x * A.x + A.y * A.y) * (B.y - C.y) + (B.x * B.x + B.y * B.y) * (C.y - A.y) + (C.x * C.x + C.y * C.y) * (A.y - B.y)) / D;\n Real Uy = ((A.x * A.x + A.y * A.y) * (C.x - B.x) + (B.x * B.x + B.y * B.y) * (A.x - C.x) + (C.x * C.x + C.y * C.y) * (B.x - A.x)) / D;\n Point center(Ux, Uy);\n Real radius = (center - A).abs();\n return Circle{center, radius};\n }\n\n /// @brief 円と直線の交点を求める\n vector<Point> getCircleLineIntersection(const Circle& c, Point p1, Point p2) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real dx = p2.x - p1.x;\n Real dy = p2.y - p1.y;\n Real a = dx * dx + dy * dy;\n Real b = 2 * (dx * (p1.x - cx) + dy * (p1.y - cy));\n Real c_const = (p1.x - cx) * (p1.x - cx) + (p1.y - cy) * (p1.y - cy) - r * r;\n Real discriminant = b * b - 4 * a * c_const;\n vector<Point> intersections;\n if (almostEqual(discriminant, 0)) {\n Real t = -b / (2 * a);\n Real ix = p1.x + t * dx;\n Real iy = p1.y + t * dy;\n intersections.emplace_back(ix, iy);\n intersections.emplace_back(ix, iy);\n } else if (discriminant > 0) {\n Real sqrt_discriminant = sqrt(discriminant);\n Real t1 = (-b + sqrt_discriminant) / (2 * a);\n Real t2 = (-b - sqrt_discriminant) / (2 * a);\n Real ix1 = p1.x + t1 * dx;\n Real iy1 = p1.y + t1 * dy;\n Real ix2 = p1.x + t2 * dx;\n Real iy2 = p1.y + t2 * dy;\n intersections.emplace_back(ix1, iy1);\n intersections.emplace_back(ix2, iy2);\n }\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 2つの円の交点を求める\n vector<Point> getCirclesIntersect(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real d = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n if (d > r1 + r2 || d < abs(r1 - r2)) return {}; // No intersection\n Real a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);\n Real h = sqrt(r1 * r1 - a * a);\n Real x0 = x1 + a * (x2 - x1) / d;\n Real y0 = y1 + a * (y2 - y1) / d;\n Real rx = -(y2 - y1) * (h / d);\n Real ry = (x2 - x1) * (h / d);\n Point p1(x0 + rx, y0 + ry);\n Point p2(x0 - rx, y0 - ry);\n vector<Point> intersections;\n intersections.push_back(p1);\n intersections.push_back(p2);\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 点から引ける円の接線の接点を求める\n vector<Point> getTangentLinesFromPoint(const Circle& c, const Point& p) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real px = p.x, py = p.y;\n Real dx = px - cx;\n Real dy = py - cy;\n Real d = (p - c.center).abs();\n if (lessThan(d, r))\n return {}; // No tangents if the point is inside the circle\n else if (almostEqual(d, r))\n return {p};\n Real a = r * r / d;\n Real h = sqrt(r * r - a * a);\n Real cx1 = cx + a * dx / d;\n Real cy1 = cy + a * dy / d;\n vector<Point> tangents;\n tangents.emplace_back(cx1 + h * dy / d, cy1 - h * dx / d);\n tangents.emplace_back(cx1 - h * dy / d, cy1 + h * dx / d);\n if (almostEqual(tangents[0].x, tangents[1].x)) {\n if (greaterThan(tangents[0].y, tangents[1].y)) swap(tangents[0], tangents[1]);\n } else if (greaterThan(tangents[0].x, tangents[1].x)) {\n swap(tangents[0], tangents[1]);\n }\n return tangents;\n }\n\n /// @brief 2つの円の共通接線を求める\n vector<Segment> getCommonTangentsLine(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real dx = x2 - x1;\n Real dy = y2 - y1;\n Real d = sqrt(dx * dx + dy * dy);\n vector<Segment> tangents;\n // Coincident circles(infinite tangents)\n if (almostEqual(d, 0) && almostEqual(r1, r2)) return tangents;\n // External tangents\n if (greaterThanOrEqual(d, r1 + r2)) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 + r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 + r2 * cos(a + sign * theta);\n Real cy2 = y2 + r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, r1 + r2)) break;\n }\n }\n // Internal tangents\n if (greaterThanOrEqual(d, fabs(r1 - r2))) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 - r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 - r2 * cos(a + sign * theta);\n Real cy2 = y2 - r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, fabs(r1 - r2))) break;\n }\n }\n sort(tangents.begin(), tangents.end(), [&](const Segment& s1, const Segment& s2) {\n if (almostEqual(s1.a.x, s2.a.x))\n return lessThan(s1.a.y, s2.a.y);\n else\n return lessThan(s1.a.x, s2.a.x);\n });\n return tangents;\n }\n}\n// --- End of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n\nusing namespace Geometry;\n\nvoid solve() {\n int n; cin >> n;\n vector<Point> P(n);\n rep(i, n) {\n Real x, y; cin >> x >> y;\n P[i] = {x, y};\n }\n sort(P.begin(), P.end(), [&] (Point &l, Point &r) {\n return l.x < r.x;\n });\n cout << closestPair(P, 0, P.size()) << endl;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout << fixed << setprecision(10);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 13424, "score_of_the_acc": -0.682, "final_rank": 15 }, { "submission_id": "aoj_CGL_5_A_11025017", "code_snippet": "// https://tubo28.me/compprog/algorithm/ より.\n\n#include <bits/stdc++.h>\n// #define int int64_t\n\n#define FOR(i, a, b) for (int i = (a); i < int(b); ++i)\n#define RFOR(i, a, b) for (int i = (b)-1; i >= int(a); --i)\n#define rep(i, n) FOR(i, 0, n)\n#define rep1(i, n) FOR(i, 1, int(n) + 1)\n#define rrep(i, n) RFOR(i, 0, n)\n#define rrep1(i, n) RFOR(i, 1, int(n) + 1)\n#define all(c) begin(c), end(c)\nnamespace io {\n#ifdef LOCAL\n#define dump(...) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #__VA_ARGS__ << \" = \"; \\\n io::print_to(os, \", \", \"\\n\", __VA_ARGS__); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dump_(cntnr) \\\n do { \\\n std::ostringstream os; \\\n os << __LINE__ << \":\\t\" << #cntnr << \" = [\"; \\\n io::print_to_(os, \", \", \"]\\n\", all(cntnr)); \\\n std::cerr << io::highlight(os.str()); \\\n } while (0)\n#define dumpf(fmt, ...) \\\n do { \\\n const int N = 4096; \\\n auto b = new char[N]; \\\n int l = snprintf(b, N, \"%d:\\t\", __LINE__); \\\n snprintf(b + l, N - l, fmt, ##__VA_ARGS__); \\\n std::cerr << io::highlight(b) << std::endl; \\\n delete[] b; \\\n } while (0)\n#else\n#define dump(...)\n#define dump_(...)\n#define dumpf(...)\n#endif\nstd::string highlight(std::string s) {\n#ifdef _MSC_VER\n return s;\n#else\n return \"\\033[33m\" + s + \"\\033[0m\";\n#endif\n}\ntemplate <typename T>\nvoid print_to(std::ostream &os, std::string, std::string tail, const T &first) {\n os << first << tail;\n}\ntemplate <typename F, typename... R>\nvoid print_to(std::ostream &os, std::string del, std::string tail, const F &first,\n const R &... rest) {\n os << first << del;\n print_to(os, del, tail, rest...);\n}\ntemplate <typename I>\nvoid print_to_(std::ostream &os, std::string del, std::string tail, I begin, I end) {\n for (I it = begin; it != end;) {\n os << *it;\n os << (++it != end ? del : tail);\n }\n}\ntemplate <typename F, typename... R>\nvoid println(const F &first, const R &... rest) {\n print_to(std::cout, \"\\n\", \"\\n\", first, rest...);\n}\ntemplate <typename F, typename... R>\nvoid print(const F &first, const R &... rest) {\n print_to(std::cout, \" \", \"\\n\", first, rest...);\n}\ntemplate <typename I>\nvoid println_(I begin, I end) {\n print_to_(std::cout, \"\\n\", \"\\n\", begin, end);\n}\ntemplate <typename I>\nvoid print_(I begin, I end) {\n print_to_(std::cout, \" \", \"\\n\", begin, end);\n}\ntemplate <typename C>\nvoid println_(const C &cntnr) {\n println_(std::begin(cntnr), std::end(cntnr));\n}\ntemplate <typename C>\nvoid print_(const C &cntnr) {\n print_(std::begin(cntnr), std::end(cntnr));\n}\nint _ = (\n#ifndef LOCAL\n std::cin.tie(nullptr), std::ios::sync_with_stdio(false),\n#endif\n std::cout.precision(10), std::cout.setf(std::ios::fixed));\n}\nusing io::print;\nusing io::println;\nusing io::println_;\nusing io::print_;\ntemplate <typename T>\nusing vec = std::vector<T>;\nusing vi = vec<int>;\nusing vvi = vec<vi>;\nusing pii = std::pair<int, int>;\nusing ll = long long;\nusing ld = long double;\nusing namespace std;\n// const int MOD = 1000000007;\n\n\n\n\nusing ld = long double;\nusing P = std::complex<ld>;\nusing G = std::vector<P>;\nconst ld pi = std::acos(-1);\nconst ld eps = 1e-10;\nconst ld inf = 1e12;\n\nld cross(const P &a, const P &b) { return a.real() * b.imag() - a.imag() * b.real(); }\nld dot(const P &a, const P &b) { return a.real() * b.real() + a.imag() * b.imag(); }\n\n/*\n CCW\n\n -- BEHIND -- [a -- ON -- b] --- FRONT --\n\n CW\n */\nenum CCW_RESULT { CCW = +1, CW = -1, BEHIND = +2, FRONT = -2, ON = 0 };\nint ccw(P a, P b, P c) {\n b -= a;\n c -= a;\n if (cross(b, c) > eps) return CCW; // counter clockwise\n if (cross(b, c) < -eps) return CW; // clockwise\n if (dot(b, c) < 0) return BEHIND; // c--a--b on line\n if (norm(b) < norm(c)) return FRONT; // a--b--c on line\n return ON;\n}\n\nnamespace std {\nbool operator<(const P &a, const P &b) {\n return std::abs(real(a) - real(b)) > eps ? real(a) < real(b) : imag(a) < imag(b);\n}\n}\n\nstruct L : public std::vector<P> {\n L(const P &a = P(), const P &b = P()) : std::vector<P>(2) {\n begin()[0] = a;\n begin()[1] = b;\n }\n\n // Ax + By + C = 0\n L(ld A, ld B, ld C) {\n if (std::abs(A) < eps && std::abs(B) < eps) {\n abort();\n } else if (std::abs(A) < eps) {\n *this = L(P(0, -C / B), P(1, -C / B));\n } else if (std::abs(B) < eps) {\n *this = L(P(-C / A, 0), P(-C / A, 1));\n } else {\n *this = L(P(0, -C / B), P(-C / A, 0));\n }\n }\n};\n\nstruct C {\n P p;\n ld r;\n C(const P &p = 0, ld r = 0) : p(p), r(r) {}\n};\n\n\n\n\nbool intersectLL(const L &l, const L &m) {\n return std::abs(cross(l[1] - l[0], m[1] - m[0])) > eps || // non-parallel\n std::abs(cross(l[1] - l[0], m[0] - l[0])) < eps; // same line\n}\nbool intersectLS(const L &l, const L &s) {\n return cross(l[1] - l[0], s[0] - l[0]) * // s[0] is left of l\n cross(l[1] - l[0], s[1] - l[0]) <\n eps; // s[1] is right of l\n}\nbool intersectLP(const L &l, const P &p) { return std::abs(cross(l[1] - p, l[0] - p)) < eps; }\nbool intersectSS(const L &s, const L &t) {\n return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 &&\n ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0;\n}\nbool intersectSP(const L &s, const P &p) {\n return std::abs(s[0] - p) + std::abs(s[1] - p) - std::abs(s[1] - s[0]) <\n eps; // triangle inequality\n}\n\nP projection(const L &l, const P &p) {\n ld t = dot(p - l[0], l[0] - l[1]) / norm(l[0] - l[1]);\n return l[0] + t * (l[0] - l[1]);\n}\nP reflection(const L &l, const P &p) { return p + (ld)2 * (projection(l, p) - p); }\nld distanceLP(const L &l, const P &p) { return std::abs(p - projection(l, p)); }\nld distanceLL(const L &l, const L &m) { return intersectLL(l, m) ? 0 : distanceLP(l, m[0]); }\nld distanceLS(const L &l, const L &s) {\n if (intersectLS(l, s)) return 0;\n return std::min(distanceLP(l, s[0]), distanceLP(l, s[1]));\n}\nld distanceSP(const L &s, const P &p) {\n const P r = projection(s, p);\n if (intersectSP(s, r)) return std::abs(r - p);\n return std::min(std::abs(s[0] - p), std::abs(s[1] - p));\n}\nld distanceSS(const L &s, const L &t) {\n if (intersectSS(s, t)) return 0;\n return std::min(std::min(distanceSP(s, t[0]), distanceSP(s, t[1])),\n std::min(distanceSP(t, s[0]), distanceSP(t, s[1])));\n}\nP crosspointLL(const L &l, const L &m) {\n ld A = cross(l[1] - l[0], m[1] - m[0]);\n ld B = cross(l[1] - l[0], l[1] - m[0]);\n if (std::abs(A) < eps && std::abs(B) < eps) return m[0]; // same line\n if (std::abs(A) < eps) assert(false); // !!!PRECONDITION NOT SATISFIED!!!\n return m[0] + B / A * (m[1] - m[0]);\n}\n\n\n// 符号付二倍面積 abs(area2(G pol))/2.0 で求められる.\n// polは頂点反時計回りで渡す\nld area2(const G& pol) {\n ld s = 0;\n int n = pol.size();\n for (int i = 0; i < n; ++i) s += cross(pol[i], pol[(i + 1) % n]);\n return s;\n}\n\n\n// 凸包\n// == CWを != CCWに置換すると 退化した角を除く.\nG andrewScan(G ps) {\n int N = ps.size(), k = 0;\n std::sort(ps.begin(), ps.end());\n G res(N * 2);\n for (int i = 0; i < N; i++) {\n while (k >= 2 && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n int t = k + 1;\n for (int i = N - 2; i >= 0; i--) {\n while (k >= t && ccw(res[k - 2], res[k - 1], ps[i]) == CW) k--;\n res[k++] = ps[i];\n }\n res.resize(k - 1);\n return res;\n}\n//凸包終.\n\n/*\n// 凸多角形の直径\n// 最近点対と競合.\n#define curr(P, i) P[i]\n#define next(P, i) P[(i + 1) % P.size()]\n#define diff(P, i) (next(P, i) - curr(P, i))\nld convex_diameter(const G &pt) {\n const int n = pt.size();\n int is = 0, js = 0;\n for (int i = 1; i < n; ++i) {\n if (imag(pt[i]) > imag(pt[is])) is = i;\n if (imag(pt[i]) < imag(pt[js])) js = i;\n }\n ld maxd = norm(pt[is] - pt[js]);\n int i, maxi, j, maxj;\n i = maxi = is;\n j = maxj = js;\n do {\n if (cross(diff(pt, i), diff(pt, j)) >= 0)\n j = (j + 1) % n;\n else\n i = (i + 1) % n;\n if (norm(pt[i] - pt[j]) > maxd) {\n maxd = norm(pt[i] - pt[j]);\n maxi = i;\n maxj = j;\n }\n } while (i != is || j != js);\n return maxd; /* farthest pair is (maxi, maxj). */\n/*\n}\n*/\n\n//凸多角形の直径終.\n\n// 凸多角形の切断. (左側のみ)\n// 右側: lを逆に.\n//@require intersection.cc\nG convex_cut(const G& pol, const L& l) {\n G res;\n int n = pol.size();\n for (int i = 0; i < n; ++i) {\n P A = pol[i], B = pol[(i + 1) % n];\n if (ccw(l[0], l[1], A) != -1) res.push_back(A);\n if (ccw(l[0], l[1], A) * ccw(l[0], l[1], B) < 0) res.push_back(crosspointLL(L(A, B), l));\n }\n return res;\n}\n//凸多角形の切断終.\n\n// 最近点対.\n// O(N log N)\n// [半開区間)iter渡し, x座標昇順.\n// 凸多角形の直径と競合.\ntemplate <class iter>\nstd::tuple<ld, P, P> closest_pair(iter left, iter right) {\n int n = distance(left, right);\n\n if (n == 1) {\n return std::make_tuple(std::numeric_limits<ld>::max(), *left, *left);\n }\n\n if (n == 2) {\n if (left[0].imag() > left[1].imag()) swap(left[0], left[1]);\n return std::make_tuple(norm(left[0] - left[1]), left[0], left[1]);\n }\n\n iter middle = std::next(left, n / 2);\n ld x = middle->real();\n auto d = std::min(closest_pair(left, middle), closest_pair(middle, right));\n std::inplace_merge(left, middle, right,\n [](const P &a, const P &b) { return a.imag() < b.imag(); });\n\n std::vector<iter> around;\n for (iter i = left; i != right; ++i) {\n ld dx = fabs(i->real() - x);\n ld &opt = std::get<0>(d);\n if (dx * dx >= opt) continue;\n for (auto j = around.rbegin(); j != around.rend(); ++j) {\n ld dx = i->real() - (**j).real();\n ld dy = i->imag() - (**j).imag();\n if (dy * dy >= opt) break;\n ld norm = dx * dx + dy * dy;\n if (opt > norm) {\n d = std::make_tuple(norm, *i, **j);\n }\n }\n around.push_back(i);\n }\n return d;\n};\n\n// 最近点対 終.\n\n// P:点 point x: .real() y: .imag()\n// L:直線 lineF\n// S:線分 section\n// G:多角形 vector<P>\n\nsigned main() {\n int N;\n cin >> N;\n G g(N);\n rep(i, N){\n ld xi, yi;\n cin >> xi >> yi;\n g[i] = P(xi, yi);\n }\n cout << fixed << setprecision(10);\n sort(all(g));\n cout << sqrt(get<0>(closest_pair(g.begin(), g.end()))) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 11196, "score_of_the_acc": -0.5389, "final_rank": 12 }, { "submission_id": "aoj_CGL_5_A_10939037", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i< (n); ++i)\n#define repi(i, a, b) for (int i = (a); i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define fore(i, a) for(auto &i:a)\nusing ll = long long;\nusing int64 = long long;\n#define DEBUG(x) cerr << #x << \": \"; for (auto _ : x) cerr << _ << \" \"; cerr << endl;\nconst int64 infll = (1LL << 62) - 1;\nconst int inf = (1 << 30) - 1;\n\nstruct IoSetup {\n\tIoSetup() {\n\t\tcin.tie(nullptr);\n\t\tios::sync_with_stdio(false);\n\t\tcout << fixed << setprecision(10);\n\t\tcerr << fixed << setprecision(10);\n\t}\n} iosetup;\n\ntemplate <typename T1, typename T2>\nostream& operator<<(ostream& os, const pair<T1, T2>& p) {\n\tos << p.first << \" \" << p.second;\n\treturn os;\n}\n\ntemplate <typename T1, typename T2>\nistream& operator>>(istream& is, pair<T1, T2>& p) {\n\tis >> p.first >> p.second;\n\treturn is;\n}\n\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n\tfor (int i = 0; i < (int)v.size(); i++) {\n\t\tos << v[i] << (i + 1 != v.size() ? \" \" : \"\");\n\t}\n\treturn os;\n}\n\ntemplate <typename T>\nistream& operator>>(istream& is, vector<T>& v) {\n\tfor (T& in : v) is >> in;\n\treturn is;\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmax(T1& a, T2 b) {\n\treturn a < b && (a = b, true);\n}\n\ntemplate <typename T1, typename T2>\ninline bool chmin(T1& a, T2 b) {\n\treturn a > b && (a = b, true);\n}\n\ntemplate <typename T = int64>\nvector<T> make_v(size_t a) {\n\treturn vector<T>(a);\n}\n\ntemplate <typename T, typename... Ts>\nauto make_v(size_t a, Ts... ts) {\n\treturn vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value == 0>::type fill_v(T& t, const V& v) {\n\tt = v;\n}\n\ntemplate <typename T, typename V>\ntypename enable_if<is_class<T>::value != 0>::type fill_v(T& t, const V& v) {\n\tfor (auto& e : t) fill_v(e, v);\n}\n\ntemplate <typename F>\nstruct FixPoint : F {\n\texplicit FixPoint(F&& f) : F(std::forward<F>(f)) {}\n\n\ttemplate <typename... Args>\n\t\tdecltype(auto) operator()(Args&&... args) const {\n\t\t\treturn F::operator()(*this, std::forward<Args>(args)...);\n\t\t}\n};\n\ntemplate <typename F>\ninline decltype(auto) MFP(F&& f) {\n\treturn FixPoint<F>{std::forward<F>(f)};\n}\n//Geometry\nnamespace geometry {\nusing Real = double;\nconst Real EPS = 1e-15;\nconst Real PI = acos(static_cast<Real>(-1));\n\nenum { OUT, ON, IN };\n\ninline int sign(const Real& r) { return r <= -EPS ? -1 : r >= EPS ? 1 : 0; }\n\ninline bool equals(const Real& a, const Real& b) { return sign(a - b) == 0; }\n} // namespace geometry\n\nnamespace geometry {\nusing Point = complex<Real>;\n\nistream& operator>>(istream& is, Point& p) {\n Real a, b;\n is >> a >> b;\n p = Point(a, b);\n return is;\n}\n\nostream& operator<<(ostream& os, const Point& p) {\n return os << real(p) << \" \" << imag(p);\n}\n\nPoint operator*(const Point& p, const Real& d) {\n return Point(real(p) * d, imag(p) * d);\n}\n\n// rotate point p counterclockwise by theta rad\nPoint rotate(Real theta, const Point& p) {\n return Point(cos(theta) * real(p) - sin(theta) * imag(p),\n sin(theta) * real(p) + cos(theta) * imag(p));\n}\n\nReal cross(const Point& a, const Point& b) {\n return real(a) * imag(b) - imag(a) * real(b);\n}\n\nReal dot(const Point& a, const Point& b) {\n return real(a) * real(b) + imag(a) * imag(b);\n}\n\nbool compare_x(const Point& a, const Point& b) {\n return equals(real(a), real(b)) ? imag(a) < imag(b) : real(a) < real(b);\n}\n\nbool compare_y(const Point& a, const Point& b) {\n return equals(imag(a), imag(b)) ? real(a) < real(b) : imag(a) < imag(b);\n}\n\nusing Points = vector<Point>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Line {\n Point a, b;\n\n Line() = default;\n\n Line(const Point& a, const Point& b) : a(a), b(b) {}\n\n Line(const Real& A, const Real& B, const Real& C) { // Ax+By=C\n if (equals(A, 0)) {\n assert(!equals(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (equals(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (equals(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n friend ostream& operator<<(ostream& os, Line& l) {\n return os << l.a << \" to \" << l.b;\n }\n\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n};\n\nusing Lines = vector<Line>;\n} // namespace geometry\n\nnamespace geometry {\nstruct Segment : Line {\n Segment() = default;\n\n using Line::Line;\n};\n\nusing Segments = vector<Segment>;\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A\nPoint projection(const Line& l, const Point& p) {\n auto t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);\n return l.a + (l.a - l.b) * t;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B\nPoint reflection(const Line& l, const Point& p) {\n return p + (projection(l, p) - p) * 2;\n}\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C\nconstexpr int COUNTER_CLOCKWISE = +1;\nconstexpr int CLOCKWISE = -1;\nconstexpr int ONLINE_BACK = +2; // c-a-b\nconstexpr int ONLINE_FRONT = -2; // a-b-c\nconstexpr int ON_SEGMENT = 0; // a-c-b\nint ccw(const Point& a, Point b, Point c) {\n b = b - a, c = c - a;\n if (sign(cross(b, c)) == +1) return COUNTER_CLOCKWISE;\n if (sign(cross(b, c)) == -1) return CLOCKWISE;\n if (sign(dot(b, c)) == -1) return ONLINE_BACK;\n if (norm(b) < norm(c)) return ONLINE_FRONT;\n return ON_SEGMENT;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_orthogonal(const Line& a, const Line& b) {\n return equals(dot(a.a - a.b, b.a - b.b), 0.0);\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\nbool is_parallel(const Line& a, const Line& b) {\n return equals(cross(a.b - a.a, b.b - b.a), 0.0);\n}\n} // namespace geometry\n\nnamespace geometry {\nbool is_intersect_ss(const Segment& s, const Segment& t) {\n return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&\n ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;\n}\n} // namespace geometry\nnamespace geometry {\nbool is_intersect_sp(const Segment& s, const Point& p) {\n return ccw(s.a, s.b, p) == ON_SEGMENT;\n}\n} // namespace geometry\n\nnamespace geometry {\nPoint cross_point_ll(const Line& l, const Line& m) {\n Real A = cross(l.b - l.a, m.b - m.a);\n Real B = cross(l.b - l.a, l.b - m.a);\n if (equals(abs(A), 0) && equals(abs(B), 0)) return m.a;\n return m.a + (m.b - m.a) * B / A;\n}\n} // namespace geometry\nnamespace geometry {\nReal distance_sp(const Segment& s, const Point& p) {\n Point r = projection(s, p);\n if (is_intersect_sp(s, r)) return abs(r - p);\n return min(abs(s.a - p), abs(s.b - p));\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D\nReal distance_ss(const Segment& a, const Segment& b) {\n if (is_intersect_ss(a, b)) return 0;\n return min({distance_sp(a, b.a), distance_sp(a, b.b), distance_sp(b, a.a),\n distance_sp(b, a.b)});\n}\n} // namespace geometry\nnamespace geometry {\nusing Polygon = vector<Point>;\nusing Polygons = vector<Polygon>;\n} // namespace geometry\n\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A\nReal area(const Polygon& p) {\n int n = (int)p.size();\n Real A = 0;\n for (int i = 0; i < n; ++i) {\n A += cross(p[i], p[(i + 1) % n]);\n }\n return A * 0.5;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B\nbool is_convex_polygon(const Polygon& p) {\n int n = (int)p.size();\n for (int i = 0; i < n; i++) {\n if (ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == CLOCKWISE)\n return false;\n }\n return true;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C\nint contains(const Polygon& Q, const Point& p) {\n bool in = false;\n for (int i = 0; i < Q.size(); i++) {\n Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;\n if (imag(a) > imag(b)) swap(a, b);\n if (sign(imag(a)) <= 0 && 0 < sign(imag(b)) && sign(cross(a, b)) < 0)\n in = !in;\n if (equals(cross(a, b), 0) && sign(dot(a, b)) <= 0) return ON;\n }\n return in ? IN : OUT;\n}\n} // namespace geometry\nnamespace geometry {\nint convex_polygon_contains(const Polygon& Q, const Point& p) {\n int N = (int)Q.size();\n Point g = (Q[0] + Q[N / 3] + Q[N * 2 / 3]) / 3.0;\n if (equals(imag(g), imag(p)) && equals(real(g), real(p))) return IN;\n Point gp = p - g;\n int l = 0, r = N;\n while (r - l > 1) {\n int mid = (l + r) / 2;\n Point gl = Q[l] - g;\n Point gm = Q[mid] - g;\n if (cross(gl, gm) > 0) {\n if (cross(gl, gp) >= 0 && cross(gm, gp) <= 0)\n r = mid;\n else\n l = mid;\n } else {\n if (cross(gl, gp) <= 0 && cross(gm, gp) >= 0)\n l = mid;\n else\n r = mid;\n }\n }\n r %= N;\n Real v = cross(Q[l] - p, Q[r] - p);\n return sign(v) == 0 ? ON : sign(v) == -1 ? OUT : IN;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A\nPolygon convex_hull(Polygon& p, bool strict = true) {\n int n = (int)p.size(), k = 0;\n if (n <= 2) return p;\n sort(begin(p), end(p), compare_x);\n vector<Point> ch(2 * n);\n auto check = [&](int i) {\n return sign(cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1])) <= -1 + strict;\n };\n for (int i = 0; i < n; ch[k++] = p[i++]) {\n while (k >= 2 && check(i)) --k;\n }\n for (int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {\n while (k >= t && check(i)) --k;\n }\n ch.resize(k - 1);\n return ch;\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B\npair<int, int> convex_polygon_diameter(const Polygon& p) {\n int N = (int)p.size();\n int is = 0, js = 0;\n for (int i = 1; i < N; i++) {\n if (imag(p[i]) > imag(p[is])) is = i;\n if (imag(p[i]) < imag(p[js])) js = i;\n }\n Real maxdis = norm(p[is] - p[js]);\n\n int maxi, maxj, i, j;\n i = maxi = is;\n j = maxj = js;\n do {\n if (cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {\n j = (j + 1) % N;\n } else {\n i = (i + 1) % N;\n }\n if (norm(p[i] - p[j]) > maxdis) {\n maxdis = norm(p[i] - p[j]);\n maxi = i;\n maxj = j;\n }\n } while (i != is || j != js);\n return minmax(maxi, maxj);\n}\n} // namespace geometry\nnamespace geometry {\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C\n// cut with a straight line l and return a convex polygon on the left\nPolygon convex_polygon_cut(const Polygon& U, const Line& l) {\n Polygon ret;\n for (int i = 0; i < U.size(); i++) {\n const Point& now = U[i];\n const Point& nxt = U[(i + 1) % U.size()];\n auto cf = cross(l.a - now, l.b - now);\n auto cs = cross(l.a - nxt, l.b - nxt);\n if (sign(cf) >= 0) {\n ret.emplace_back(now);\n }\n if (sign(cf) * sign(cs) < 0) {\n ret.emplace_back(cross_point_ll(Line(now, nxt), l));\n }\n }\n return ret;\n}\n} // namespace geometry\nnamespace geometry {\ndouble closest_pair(Points &pts) {\n\tsort(pts.begin(), pts.end(), compare_x);\n\tvector<Point> buf(pts.size());\n\tauto dist2 = [](Point a, Point b){\n\t\tPoint c = a-b;\n\t\treturn c.real()*c.real()+c.imag()*c.imag();\n\t};\n\tfunction<double(int,int)> rec = [&](int l, int r) -> double {\n\t\tif (r - l <= 3) {\n\t\t\tdouble d2 = 1e300;\n\t\t\tfor (int i = l; i < r; ++i)\n\t\t\t\tfor (int j = i + 1; j < r; ++j)\n\t\t\t\t\td2 = min(d2, dist2(pts[i], pts[j]));\n\t\t\tsort(pts.begin() + l, pts.begin() + r, compare_y);\n\t\t\treturn d2;\n\t\t}\n\n\t\tint m = (l + r) / 2;\n\t\tdouble xmid = pts[m].real();\n\t\tdouble d2 = min(rec(l, m), rec(m, r));\n\n\t\tmerge(pts.begin()+l, pts.begin()+m, pts.begin()+m, pts.begin()+r, buf.begin(), compare_y);\n\t\tcopy(buf.begin(), buf.begin() + (r - l), pts.begin() + l);\n\n\t\tint sz = 0;\n\t\tfor (int i = l; i < r; ++i) {\n\t\t\tif ((pts[i].real() - xmid) * (pts[i].real() - xmid) < d2)\n\t\t\t\tbuf[sz++] = pts[i];\n\t\t}\n\n\t\tfor (int i = 0; i < sz; ++i)\n\t\t\tfor (int j = i - 1; j >= 0 && (buf[i].imag() - buf[j].imag()) * (buf[i].imag() - buf[j].imag()) < d2; --j)\n\t\t\t\td2 = min(d2, dist2(buf[i], buf[j]));\n\n\t\treturn d2;\n\t};\n\n\treturn sqrt(rec(0, pts.size()));\n}\n}\nusing namespace geometry;\nint main(){\n\tll n; cin >> n;\n\tPoints p(n);\n\trep(i, n)cin >> p[i];\n\tcout << closest_pair(p) << endl;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 6308, "score_of_the_acc": -0.1388, "final_rank": 1 }, { "submission_id": "aoj_CGL_5_A_10938055", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n double x, y;\n Point(double x=0, double y=0): x(x), y(y) {}\n};\n\ninline double dist2(const Point &a, const Point &b) {\n double dx = a.x - b.x, dy = a.y - b.y;\n return dx * dx + dy * dy;\n}\n\ndouble closest_pair(vector<Point> &pts) {\n sort(pts.begin(), pts.end(), [](auto &a, auto &b){ return a.x < b.x; });\n vector<Point> buf(pts.size());\n\n function<double(int,int)> rec = [&](int l, int r) -> double {\n if (r - l <= 3) {\n double d2 = 1e300;\n for (int i = l; i < r; ++i)\n for (int j = i + 1; j < r; ++j)\n d2 = min(d2, dist2(pts[i], pts[j]));\n sort(pts.begin() + l, pts.begin() + r, [](auto &a, auto &b){ return a.y < b.y; });\n return d2;\n }\n\n int m = (l + r) / 2;\n double xmid = pts[m].x;\n double d2 = min(rec(l, m), rec(m, r));\n\n merge(pts.begin()+l, pts.begin()+m, pts.begin()+m, pts.begin()+r, buf.begin(), [](auto &a, auto &b){ return a.y < b.y; });\n copy(buf.begin(), buf.begin() + (r - l), pts.begin() + l);\n\n int sz = 0;\n for (int i = l; i < r; ++i) {\n if ((pts[i].x - xmid) * (pts[i].x - xmid) < d2)\n buf[sz++] = pts[i];\n }\n\n for (int i = 0; i < sz; ++i)\n for (int j = i - 1; j >= 0 && (buf[i].y - buf[j].y) * (buf[i].y - buf[j].y) < d2; --j)\n d2 = min(d2, dist2(buf[i], buf[j]));\n\n return d2;\n };\n\n return sqrt(rec(0, pts.size()));\n}\n\nint main() {\n int N;\n cin >> N;\n vector<Point> P(N);\n for (auto &p : P) cin >> p.x >> p.y;\n cout << fixed << setprecision(10) << closest_pair(P) << endl;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 6304, "score_of_the_acc": -0.1655, "final_rank": 2 }, { "submission_id": "aoj_CGL_5_A_10938053", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n double x, y;\n Point(double x=0, double y=0): x(x), y(y) {}\n};\n\n// 2点間の距離\ndouble dist(const Point &a, const Point &b) {\n double dx = a.x - b.x, dy = a.y - b.y;\n return sqrt(dx * dx + dy * dy);\n}\n\n// 最近接ペア距離 (分割統治法)\ndouble closest_pair(vector<Point> pts) {\n int n = pts.size();\n sort(pts.begin(), pts.end(), [](const Point& a, const Point& b){\n return a.x < b.x;\n });\n\n auto dfs = [&](auto self, int l, int r) -> double {\n if (r - l <= 3) {\n double d = 1e18;\n for (int i = l; i < r; ++i)\n for (int j = i + 1; j < r; ++j)\n d = min(d, dist(pts[i], pts[j]));\n sort(pts.begin() + l, pts.begin() + r, [](const Point& a, const Point& b){\n return a.y < b.y;\n });\n return d;\n }\n\n int m = (l + r) / 2;\n double xmid = pts[m].x;\n double d = min(self(self, l, m), self(self, m, r));\n\n inplace_merge(pts.begin() + l, pts.begin() + m, pts.begin() + r, [](const Point& a, const Point& b){\n return a.y < b.y;\n });\n\n vector<Point> buf;\n for (int i = l; i < r; ++i) {\n if (fabs(pts[i].x - xmid) >= d) continue;\n for (int j = (int)buf.size() - 1; j >= 0; --j) {\n if (pts[i].y - buf[j].y >= d) break;\n d = min(d, dist(pts[i], buf[j]));\n }\n buf.push_back(pts[i]);\n }\n return d;\n };\n\n return dfs(dfs, 0, n);\n}\n\nint main() {\n int N;\n cin >> N;\n vector<Point> P(N);\n for (int i = 0; i < N; ++i) cin >> P[i].x >> P[i].y;\n\n cout << fixed << setprecision(10) << closest_pair(P) << endl;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 9324, "score_of_the_acc": -0.4096, "final_rank": 8 }, { "submission_id": "aoj_CGL_5_A_10937810", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)\n#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)\n#define ALL(v) (v).begin(), (v).end()\n#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())\n#define SZ(v) (int)v.size()\n#define MIN(v) *min_element(ALL(v))\n#define MAX(v) *max_element(ALL(v))\n#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())\n#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())\n\nusing uint = unsigned int;\nusing ll = long long int;\nusing ull = unsigned long long;\nusing i128 = __int128_t;\nusing u128 = __uint128_t;\nconst int inf = 0x3fffffff;\nconst ll INF = 0x1fffffffffffffff;\n\ntemplate <typename T> inline bool chmax(T &a, T b) {\n if (a < b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <typename T> inline bool chmin(T &a, T b) {\n if (a > b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <typename T, typename U> T ceil(T x, U y) {\n assert(y != 0);\n if (y < 0)\n x = -x, y = -y;\n return (x > 0 ? (x + y - 1) / y : x / y);\n}\ntemplate <typename T, typename U> T floor(T x, U y) {\n assert(y != 0);\n if (y < 0)\n x = -x, y = -y;\n return (x > 0 ? x / y : (x - y + 1) / y);\n}\ntemplate <typename T> int popcnt(T x) {\n return __builtin_popcountll(x);\n}\ntemplate <typename T> int topbit(T x) {\n return (x == 0 ? -1 : 63 - __builtin_clzll(x));\n}\ntemplate <typename T> int lowbit(T x) {\n return (x == 0 ? -1 : __builtin_ctzll(x));\n}\n\ntemplate <class T, class U>\nostream &operator<<(ostream &os, const pair<T, U> &p) {\n os << \"P(\" << p.first << \", \" << p.second << \")\";\n return os;\n}\ntemplate <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {\n os << \"{\";\n for (int i = 0; i < vec.size(); i++) {\n os << vec[i] << (i + 1 == vec.size() ? \"\" : \", \");\n }\n os << \"}\";\n return os;\n}\ntemplate <typename T, typename U>\nostream &operator<<(ostream &os, const map<T, U> &map_var) {\n os << \"{\";\n for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {\n os << \"(\" << itr->first << \", \" << itr->second << \")\";\n itr++;\n if (itr != map_var.end())\n os << \", \";\n itr--;\n }\n os << \"}\";\n return os;\n}\ntemplate <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {\n os << \"{\";\n for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {\n os << *itr;\n ++itr;\n if (itr != set_var.end())\n os << \", \";\n itr--;\n }\n os << \"}\";\n return os;\n}\n#ifdef LOCAL\n#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)\n#else\n#define show(...) true\n#endif\ntemplate <typename T> void _show(int i, T name) {\n cerr << '\\n';\n}\ntemplate <typename T1, typename T2, typename... T3>\nvoid _show(int i, const T1 &a, const T2 &b, const T3 &...c) {\n for (; a[i] != ',' && a[i] != '\\0'; i++)\n cerr << a[i];\n cerr << \":\" << b << \" \";\n _show(i + 1, a, c...);\n}\n\n/**\n * @brief template\n */\n\nvoid Solve() {\n int N;\n cin >> N;\n vector<pair<double,double>> P(N);\n rep(i,0,N) {\n double x, y;\n cin >> x >> y;\n P[i] = {x,y};\n }\n sort(ALL(P));\n auto Dist = [&](int i, int j) -> double {\n return (P[i].first - P[j].first) * (P[i].first - P[j].first) + (P[i].second - P[j].second) * (P[i].second - P[j].second);\n };\n auto Calc = [&](auto self, int L, int R) -> double {\n if (R - L == 1) return INF;\n if (R - L == 2) return Dist(L,L+1);\n int MID = (L+R) / 2;\n double Ret = min(self(self,L,MID), self(self,MID,R));\n vector<int> ord(R-L);\n iota(ALL(ord),L);\n sort(ALL(ord),[&](int i, int j){return P[i].second < P[j].second;});\n double MX = P[MID].first;\n vector<int> V;\n for (int i : ord) {\n if ((P[i].first - MX) * (P[i].first - MX) > Ret) continue;\n rrep(j,0,SZ(V)) {\n if ((P[i].second - P[V[j]].second) * (P[i].second - P[V[j]].second) > Ret) break;\n chmin(Ret, Dist(i,V[j]));\n }\n V.push_back(i);\n }\n return Ret;\n };\n double ANS = Calc(Calc,0,N);\n printf(\"%.12f\\n\", sqrt(ANS));\n}\n\nint main() {\n cin.tie(0);\n ios_base::sync_with_stdio(false);\nint _ = 1;\n//cin >> _;\nwhile(_--) {\n Solve();\n}\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 5812, "score_of_the_acc": -0.1685, "final_rank": 3 }, { "submission_id": "aoj_CGL_5_A_10925084", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define f(i, a, b) for (int i = (a); i <= (b); i++)\n#define fd(i, a, b) for (int i = (a); i >= (b); i--)\n#define minimize(a, b) (a) = ((a) < (b) ? (a) : (b))\n#define maximize(a, b) (a) = ((a) > (b) ? (a) : (b)) \n#define fi first\n#define se second\n#define ll long long\n#define pii pair <double, double>\n#define pb push_back\n#define pi acos(-1)\n#define sz(a) (int)a.size()\n#define getbit(a, b) (((a) >> (b)) & 1)\n#define INOUT \"main\"\n#define INFT 0x3f3f3f3f\n\nvoid file()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(NULL); cout.tie(NULL);\n if (fopen(INOUT\".inp\", \"r\")) \n {\n freopen(INOUT\".inp\", \"r\", stdin); \n freopen(INOUT\".out\", \"w\", stdout);\n }\n}\n\nconst int MOD = 998244353;\nconst int MAX = 1e5 + 5;\nconst int INF = 1e18;\nint n;\npii point[MAX];\ndouble res = 1e18;\n\nsigned main()\n{\n file();\n\n cin >> n;\n f(i, 1, n) \n cin >> point[i].fi >> point[i].se;\n sort(point + 1, point + n + 1);\n\n set <pii> s;\n int j = 1;\n\n f(i, 1, n) \n {\n while(j < i && point[j].fi < point[i].fi - res)\n {\n s.erase({point[j].se, point[j].fi});\n j ++;\n }\n\n auto [x, y] = point[i];\n auto it = s.lower_bound({y - res, -INF});\n \n while(it != s.end())\n {\n if (it->fi >= y + res) break;\n\n double dx = x - it->se;\n double dy = y - it->fi;\n\n res = min(res, sqrt(dx * dx + dy * dy));\n it ++;\n }\n\n s.insert({y, x});\n } \n\n cout << fixed << setprecision(12) << res;\n\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 9904, "score_of_the_acc": -0.4133, "final_rank": 9 }, { "submission_id": "aoj_CGL_5_A_10925082", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define f(i, a, b) for (int i = (a); i <= (b); i++)\n#define fi first\n#define se second\n\nusing pii = pair<double,double>;\n\nconst int MAX = 1e5 + 5;\nconst int INF = 1e6;\nint n;\npii point[MAX];\ndouble res = 1e18;\n\nsigned main()\n{\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n cin >> n;\n f(i, 1, n)\n cin >> point[i].fi >> point[i].se;\n sort(point + 1, point + n + 1);\n\n set<pii> s;\n int j = 1;\n\n f(i, 1, n)\n {\n // 1) đảm bảo chỉ xoá những điểm đã được thêm (j < i)\n while (j < i && (point[i].fi - point[j].fi) > res)\n {\n // 2) erase by value (an toàn nếu phần tử không tồn tại)\n s.erase({point[j].se, point[j].fi});\n j++;\n }\n\n auto [x, y] = point[i];\n // lower_bound: tìm phần tử có y >= y-res (chuyển thành double)\n auto it = s.lower_bound({y - res, -1e18});\n\n while (it != s.end())\n {\n if (it->fi > y + res) break;\n\n double dx = x - it->se;\n double dy = y - it->fi;\n double dis = sqrt(dx*dx + dy*dy);\n if (dis < res) res = dis;\n ++it;\n }\n\n s.insert({y, x});\n }\n\n cout.setf(std::ios::fixed); cout<<setprecision(12)<<res<<\"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 10112, "score_of_the_acc": -0.4021, "final_rank": 7 }, { "submission_id": "aoj_CGL_5_A_10925063", "code_snippet": "#include <bits/stdc++.h>\n#define point pair<double, double>\n#define x first\n#define y second\nusing namespace std;\n\nconst double inf = 1e4;\n\nint main() {\n int n;\n cin >> n;\n vector<point> p(n);\n for (int i = 0; i < n; i++)\n cin >> p[i].x >> p[i].y;\n\n sort(p.begin(), p.end());\n set<point> s;\n double d = inf;\n\n for (int i = 0, j = 0; i < n; i++) {\n while (p[j].x < p[i].x - d)\n s.erase(s.find(make_pair(p[j].y, p[j].x))), j++;\n\n for (auto it = s.lower_bound(make_pair(p[i].y - d, -inf));\n it != s.upper_bound(make_pair(p[i].y + d, inf)); it++) {\n double dx = p[i].x - it->second;\n double dy = p[i].y - it->first;\n d = min(d, sqrt(dx * dx + dy * dy));\n }\n\n s.insert({p[i].y, p[i].x});\n }\n\n cout << setprecision(12) << fixed;\n cout << d << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 9984, "score_of_the_acc": -0.4464, "final_rank": 10 }, { "submission_id": "aoj_CGL_5_A_10912968", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#include <iostream>\ntemplate <typename T, typename U>\nostream& operator<<(ostream& os, const pair<T, U>& p) {return os<<'(' <<p.first<<\", \"<<p.second<<')';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {os<<'[';for(auto it=v.begin();it!=v.end();++it){os<<*it; if(next(it)!=v.end()){os<<\", \";}}return os<<']';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<vector<T>>& vv) {os<<\"[\\n\";for(auto it=vv.begin();it!=vv.end();++it){os<<\" \"<<*it;if(next(it)!=vv.end()){os<<\",\\n\";}else{os<<\"\\n\";}}return os<<\"]\";}\n#define dump(x) cerr << #x << \" = \" << (x) << '\\n'\n#else\n#define dump(x) (void)0\n#endif\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\ntemplate<class T> using pq = priority_queue<T>;\ntemplate<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>;\n#define out(x) cout<<x<<'\\n'\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define OVERLOAD_REP(_1,_2,_3,name,...) name\n#define REP1(i,n) for (auto i = std::decay_t<decltype(n)>{}; (i) < (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) < (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\ntemplate<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};\ntemplate<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};\nconst ll INF=(1LL<<60);\nconst ll mod=998244353;\nusing Graph = vector<vector<ll>>;\nusing Network = vector<vector<pair<ll,ll>>>;\nusing Grid = vector<string>;\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int dx2[8] = {1, 1, 1, 0, 0, -1, -1, -1};\nconst int dy2[8] = {1, 0, -1, 1, -1, 1, 0, -1};\n\n// #include \"../geo.hpp\"\n\n#pragma once\n\nusing D = long double;\nconst D EPS = 1e-12L;\nconst D PI = acosl(-1.0L);\nusing P2 = complex<D>;\nstruct L2{P2 a, b;};\nstruct S2{P2 a, b;};\nusing G2 = vector<P2>;\n\nint sgn(D x){return (x>EPS)-(x<-EPS);}\nint cmp(D a, D b){return sgn(a-b);}\nbool eq(D a, D b){return cmp(a, b)==0;}\nbool lt(D a, D b){return cmp(a, b)<0;}\nbool le(D a, D b){return cmp(a, b)<=0;}\nbool gt(D a, D b){return cmp(a, b)>0;}\nbool ge(D a, D b){return cmp(a, b)>=0;}\nbool eqP2(P2 a, P2 b){return eq(real(a), real(b)) && eq(imag(a), imag(b));}\nbool ltP2(P2 a, P2 b) {\n return lt(real(a), real(b)) || (eq(real(a), real(b)) && lt(imag(a), imag(b)));\n}\n\nD dot(P2 a, P2 b) {return real(conj(a)*b);}\nD cross(P2 a, P2 b) {return imag(conj(a)*b);}\nint ccw(P2 a, P2 b, P2 c) {\n b-=a; c-=a;\n auto cr=cross(b, c), dt=dot(b, c);\n if (cr > EPS) return +1; // counter clockwise\n if (cr < -EPS) return -1; // clockwise\n if (dt < -EPS) return +2; // c--a--b\n if (lt(norm(b), norm(c))) return -2; // a--b--c\n return 0; // a--c--b\n}\nint turn(P2 a, P2 b, P2 c) { return sgn(cross(b - a, c - a)); }\n\nP2 rot(P2 a, D th) { return a*polar<D>(1, th); }\nP2 rot90(P2 a) { return P2(-imag(a), real(a)); }\nbool ltP2Arg(P2 a, P2 b) {\n auto up = [](P2 p) { return (imag(p) > 0 || (eq(imag(p), 0) && ge(real(p), 0))); };\n if (up(a) != up(b)) return up(a);\n if (!eq(cross(a, b), 0)) return cross(a, b) > 0;\n return lt(norm(a), norm(b));\n}\n\ninline void rd(P2& p) {D x, y; cin>>x>>y; p = P2(x, y);}\n#define setp(n) cout<<setprecision(n)<<fixed\ninline void pr(const P2& p) {setp(12); cout<<real(p)<<' '<<imag(p)<<'\\n';}\n\n// ----------------------------------------------------------------------------------\n\nP2 proj(L2 l, P2 p) { P2 a=p-l.a, b=l.b-l.a; return l.a+b*dot(a, b)/norm(b);}\nP2 refl(L2 l, P2 p) { return proj(l, p)*2.0L - p; }\nbool isParallel(L2 l, L2 m){ return eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isPerp(L2 l, L2 m){ return eq(dot(l.a-l.b, m.a-m.b), 0); }\n\nbool isLL(L2 l, L2 m){ return !eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isLS(L2 l, S2 s){ return turn(l.a, l.b, s.a)*turn(l.a, l.b, s.b)<=0; }\nbool isSS(S2 s, S2 t) {\n return\n ccw(s.a,s.b,t.a)*ccw(s.a,s.b,t.b) <= 0 &&\n ccw(t.a,t.b,s.a)*ccw(t.a,t.b,s.b) <= 0;\n}\n\nP2 cpLL(L2 l, L2 m) {\n P2 a=l.b-l.a, b=m.b-m.a;\n D d=cross(a, b);\n if (eq(d, 0)) return P2(INF, INF); // parallel\n return l.a + a*cross(m.b-l.a,b)/d;\n}\n\nD distLP(L2 l, P2 p) { return abs(cross(l.b-l.a, p-l.a))/abs(l.b-l.a); }\nD distSP(S2 s, P2 p) {\n P2 a=s.a, b=s.b;\n if (lt(dot(b-a, p-a), 0)) return abs(p-a);\n if (lt(dot(a-b, p-b), 0)) return abs(p-b);\n return distLP({a,b}, p);\n}\nD distSS(S2 s, S2 t) {\n if (isSS(s, t)) return 0;\n return min({distSP(s, t.a), distSP(s, t.b), distSP(t, s.a), distSP(t, s.b)});\n}\n\nD area(G2 g) {\n D s=0;\n int n=g.size();\n rep(i, n) s+=cross(g[i], g[(i+1)%n]);\n return s/2.0L;\n}\n\nbool isConvex(G2 g) {\n int n=g.size();\n if (n < 3) return false;\n int dir = 0;\n rep(i,n){\n int s = turn(g[i], g[(i+1)%n], g[(i+2)%n]);\n if (s == 0) return false; // -> continue : allows three points on a line\n if (dir == 0) dir = s;\n else if (dir*s < 0) return false;\n }\n return true;\n}\n\nint inG(G2 g, P2 p) {\n bool in=false;\n int n=g.size();\n rep(i, n) {\n P2 a=g[i], b=g[(i+1)%n];\n if (ccw(a, b, p) == 0) return 1; // on boundary\n if (a.imag() > b.imag()) swap(a, b);\n if (le(a.imag(), p.imag()) && lt(p.imag(), b.imag()) && turn(a, b, p) > 0) in=!in;\n }\n return in ? 2 : 0; // inside : outside\n}\n\nG2 hull(G2 g) {\n sort(all(g), ltP2);\n g.erase(unique(all(g), eqP2), g.end());\n if (g.size()<=1) return g;\n G2 lo, up;\n for (auto &p:g) {\n while (lo.size()>=2 && turn(lo[lo.size()-2], lo.back(), p)<=0) lo.pop_back(); //-> turn()<0 : allow three points on a line\n lo.push_back(p);\n }\n reverse(all(g));\n for (auto &p:g) {\n while (up.size()>=2 && turn(up[up.size()-2], up.back(), p)<=0) up.pop_back(); // -> turn()<0 : allow three points on a line\n up.push_back(p);\n }\n lo.pop_back(); up.pop_back();\n lo.insert(lo.end(), all(up));\n return lo;\n}\n\npair<P2, P2> diameter(const G2& h) {\n int n=h.size();\n if(n==0) return {P2(0,0), P2(0,0)};\n if(n==1) return {h[0], h[0]};\n auto area2=[&](int i, int j, int k) {return abs(cross(h[j]-h[i], h[k]-h[i]));};\n D maxd=0;\n pair<P2, P2> res={h[0], h[0]};\n int j=1;\n rep(i, n) {\n int ni=(i+1)%n;\n while (gt(area2(i, ni, (j+1)%n), area2(i, ni, j))) j=(j+1)%n;\n if (gt(abs(h[i]-h[j]), maxd)) maxd=abs(h[i]-h[j]), res={h[i], h[j]};\n if (gt(abs(h[ni]-h[j]), maxd)) maxd=abs(h[ni]-h[j]), res={h[ni], h[j]};\n }\n return res;\n}\n\n// int inConvex(G2 h, P2 p) {\n// int n=h.size();\n// if (n==0) return 0;\n// if (n==1) return eqP2(h[0], p) ? 2 : 0;\n// if (n==2) return ccw(h[0], h[1], p)==0 && le(abs(h[0]-p)+abs(h[1]-p), abs(h[0]-h[1])) ? 2 : 0;\n// int left=1, right=n-1;\n// while (right-left>1) {\n// int mid=(left+right)/2;\n// if (turn(h[0], h[mid], p)<0) right=mid;\n// else left=mid;\n// }\n// if (turn(h[0], h[left], p)<0) return 0;\n// if (turn(h[left], h[right%n], p)<0) return 0;\n// if (turn(h[right%n], h[0], p)<0) return 0;\n// if (turn(h[0], h[left], p)==0 || turn(h[left], h[right%n], p)==0 || turn(h[right%n], h[0], p)==0) return 2;\n// return 1;\n// }\n\nG2 cutConvex(G2 h, L2 l) {\n int n=h.size();\n G2 res;\n if (n==0) return res;\n auto inside=[&](P2 p){ return turn(l.a, l.b, p) >= 0; };\n rep(i, n) {\n P2 a=h[i], b=h[(i+1)%n];\n bool ina=inside(a), inb=inside(b);\n if (ina&&inb) res.push_back(b);\n else if (ina&&!inb) {\n res.push_back(proj({a,b}, l.a));\n }\n else if (!ina&&inb) {\n res.push_back(proj({a,b}, l.a));\n res.push_back(b);\n }\n }\n return res;\n}\n\n\npair<P2, P2> closestPair(G2 g) {\n auto ps = g;\n int n=ps.size();\n if (n < 2) return {P2(0,0), P2(0,0)};\n sort(all(ps), ltP2);\n D mind = norm(ps[0]-ps[1]);\n pair<P2, P2> res = {ps[0], ps[1]};\n set<pair<D,int>> box;\n int j=0;\n rep(i, n) {\n D xi=real(ps[i]), yi=imag(ps[i]);\n D rad = sqrtl(mind);\n while (j<i && gt(xi - real(ps[j]), rad)) {\n box.erase({imag(ps[j]), j});\n j++;\n }\n auto it = box.lower_bound({yi - rad, -1});\n for (; it != box.end() && le(it->first, yi + rad); ++it) {\n int k = it->second;\n D d = norm(ps[i]-ps[k]);\n if (lt(d, mind)) mind=d, res={ps[i], ps[k]}, rad = sqrtl(mind);\n }\n box.insert({yi, i});\n }\n return res;\n}\n\n\nstruct C2 { P2 o; D r; };\n\nC2 makeC2(P2 a, P2 b) {\n return C2{(a+b)/D(2), abs(a-b)/D(2)};\n}\nC2 makeC2(P2 a, P2 b, P2 c) {\n P2 B=b-a, C=c-a;\n D d=2*cross(B, C);\n if (eq(d, 0)) {\n D ab=norm(B), bc=norm(b-c), ca=norm(c-a);\n if (le(ab, bc) && le(ab, ca)) return makeC2(a, b);\n if (le(bc, ca)) return makeC2(b, c);\n return makeC2(c, a);\n }\n P2 o=a+(rot90(B)*norm(C)-rot90(C)*norm(B))/d;\n return C2{o, abs(o-a)};\n}\n\nC2 incircle(P2 a, P2 b, P2 c) {\n D ab=abs(b-a), bc=abs(c-b), ca=abs(a-c);\n P2 o=(a*bc+b*ca+c*ab)/(ab+bc+ca);\n D r=abs(cross(b-a, o-a))/abs(b-a);\n return C2{o, r};\n}\n\nvector<P2> cpCL(L2 l, C2 c) {\n vector<P2> res;\n P2 a=l.a-c.o, d=l.b-l.a;\n D A=norm(d), B=2*dot(a, d), C=norm(a)-c.r*c.r;\n D Dlt=B*B-4*A*C;\n if (lt(Dlt, 0)) return res;\n D s = le(Dlt, 0) ? 0 : sqrtl(max<D>(0, Dlt));\n D t1 = (-B - s)/(2*A), t2 = (-B + s)/(2*A);\n res.push_back(c.o + a + d*t1);\n if (gt(Dlt, 0)) res.push_back(c.o + a + d*t2);\n return res;\n}\n\nvector<P2> cpCC(C2 c1, C2 c2) {\n vector<P2> res;\n P2 d=c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n D a=(c1.r*c1.r-c2.r*c2.r+L*L)/(2*L), h2=c1.r*c1.r-a*a;\n if (lt(h2, 0)) return res;\n P2 m=c1.o+d*(a/L), n=rot90(d)*( (lt(h2, 0) ? 0 : sqrtl(max<D>(0, h2))/L) );\n res.push_back(m-n);\n if (gt(h2, 0)) res.push_back(m+n);\n return res;\n}\n\nD isaCC(C2 c1, C2 c2) {\n D d=abs(c1.o-c2.o), r1=c1.r, r2=c2.r;\n if (ge(d, r1+r2)) return 0;\n if (le(d, abs(r1-r2))) {\n D r=min(r1, r2);\n return PI*r*r;\n }\n auto f = [&] (D z) { return max<D>(-1, min<D>(1, z)); };\n D a = 2*acosl(f((d*d+r1*r1-r2*r2)/(2*d*r1)));\n D b = 2*acosl(f((d*d+r2*r2-r1*r1)/(2*d*r2)));\n return 0.5L*(r1*r1*(a-sinl(a)) + r2*r2*(b-sinl(b)));\n}\n\nvector<L2> tangCP(C2 c, P2 p) {\n vector<L2> res;\n P2 v = p - c.o;\n D d2 = norm(v), r2 = c.r*c.r;\n if (lt(d2, r2)) return res;\n if (eq(d2, r2)) {\n res.push_back({c.o+v*(r2/d2), p});\n return res;\n }\n D h = c.r*sqrtl(max<D>(0, d2 - r2));\n P2 n1 = (v*r2 - rot90(v)*h)/d2;\n P2 n2 = (v*r2 + rot90(v)*h)/d2;\n res.push_back({c.o+n1, p});\n res.push_back({c.o+n2, p});\n return res;\n}\n\nvector<L2> tangCC(C2 c1, C2 c2) {\n vector<L2> res;\n P2 d = c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n P2 e = d/L;\n auto add = [&] (int s) {\n D c=(s*c2.r - c1.r)/L;\n if (gt(c*c, 1)) return;\n D s2 = max<D>(0, 1 - c*c);\n if (eq(s2, 0)) {\n P2 n = e*c;\n res.push_back({c1.o-n*c1.r, c2.o-n*c2.r});\n } else {\n D s = sqrtl(s2);\n P2 n1 = e*c + rot90(e)*s;\n P2 n2 = e*c - rot90(e)*s;\n res.push_back({c1.o-n1*c1.r, c2.o-n1*c2.r});\n res.push_back({c1.o-n2*c1.r, c2.o-n2*c2.r});\n }\n };\n add(+1); // external\n add(-1); // internal\n return res;\n}\n\nC2 mec(G2 ps) {\n auto inC2=[&](C2 c, P2 p){ return le(abs(c.o - p), c.r); };\n mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n shuffle(all(ps), rng);\n int n=ps.size();\n if(n==0) return C2{P2(0,0), 0};\n C2 c{ps[0], 0};\n rep(i, n) {\n if (inC2(c, ps[i])) continue;\n c={ps[i], 0};\n rep(j, i) {\n if (inC2(c, ps[j])) continue;\n c=makeC2(ps[i], ps[j]);\n rep(k, j) {\n if (inC2(c, ps[k])) continue;\n c=makeC2(ps[i], ps[j], ps[k]);\n }\n }\n }\n return c;\n}\n\nvector<P2> cpSegs(vector<S2> ss) {\n struct E { D x; int t; D y, y1, y2; }; // t: 0=add(H), 1=query(V), 2=remove(H)\n vector<E> es; es.reserve(ss.size()*2);\n\n for(auto s: ss) {\n if (eq(s.a.imag(), s.b.imag())) {\n if (gt(s.a.real(), s.b.real())) swap(s.a, s.b);\n es.push_back({s.a.real(), 0, s.a.imag(), 0, 0});\n es.push_back({s.b.real(), 2, s.a.imag(), 0, 0});\n } else {\n if (gt(s.a.imag(), s.b.imag())) swap(s.a, s.b);\n es.push_back({s.a.real(), 1, 0, s.a.imag(), s.b.imag()});\n }\n }\n\n sort(all(es), [](E a, E b) {\n if (!eq(a.x, b.x)) return lt(a.x, b.x);\n return a.t < b.t;\n });\n\n multiset<D> active;\n vector<P2> res; res.reserve(ss.size());\n for (auto e : es) {\n if (e.t == 0) { // add\n active.insert(e.y);\n } else if (e.t == 2) { // remove\n auto it = active.find(e.y);\n if (it != active.end()) active.erase(it);\n } else { // query\n for (auto it = active.lower_bound(e.y1); it != active.end() && le(*it, e.y2); ++it) {\n res.push_back(P2(e.x, *it));\n }\n }\n }\n\n sort(all(res), ltP2);\n res.erase(unique(all(res), eqP2), res.end());\n return res;\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_A\nvoid Projection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(proj(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_B\nvoid Reflection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(refl(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_C\nvoid CounterClockwise() {\n P2 p0, p1;\n rd(p0); rd(p1);\n ll q; cin>>q;\n while(q--) {\n P2 p; rd(p);\n int res = ccw(p0, p1, p);\n if (res == +1) out(\"COUNTER_CLOCKWISE\");\n else if (res == -1) out(\"CLOCKWISE\");\n else if (res == +2) out(\"ONLINE_BACK\");\n else if (res == -2) out(\"ONLINE_FRONT\");\n else out(\"ON_SEGMENT\");\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_2_A\nvoid ParallelOrthogonal() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n if (isParallel({p1, p2}, {p3, p4})) out(2);\n else if(isPerp({p1, p2}, {p3, p4})) out(1);\n else out(0);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_B\nvoid IntersectionSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n out(isSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_C\nvoid CrossPointSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n L2 s1 = {p1, p2}, s2 = {p3, p4};\n pr(cpLL(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_D\nvoid DistanceSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n setp(12);\n out(distSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_A\nvoid Area() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n setp(1);\n out(area(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_B\nvoid IsConvex() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n out(isConvex(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_C\nvoid PolygonPointContainment() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n out(inG(g, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\nvoid ConvexHull() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n G2 h = hull(g);\n out(h.size());\n ll sx = INF, sy = INF;\n ll id = -1;\n rep(i, h.size()) {\n if (lt(imag(h[i]), sy)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n else if (eq(imag(h[i]), sy) && lt(real(h[i]), sx)) {\n sx = real(h[i]);\n sy = imag(h[i]);\n id = i;\n }\n }\n rep(i, h.size()) {\n ll ni = (id + i) % h.size();\n pr(h[ni]);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_B\nvoid DiameterOfConvexPolygon() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = diameter(g);\n setp(12);\n out(abs(p1 - p2));\n // todo\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_C\nvoid ConvexCut() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n G2 h = cutConvex(g, l);\n setp(12);\n out(area(h));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_A\nvoid ClosestPair() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = closestPair(g);\n setp(12);\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_B\nvoid MinimumEnclosingCircle() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [c, r] = mec(g);\n pr(c);\n setp(12);\n out(r);\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/6/CGL_6_A\nvoid SegmentIntersections() {\n ll n;cin>>n;\n vector<S2> seg(n);\n rep(i, n) {\n P2 a, b; rd(a); rd(b);\n seg[i] = {a, b};\n }\n out(cpSegs(seg).size());\n}\n\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_A\nvoid IntersectionOfCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n out(tangCC(c1, c2).size());\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_B\nvoid IncircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [ic, ir] = incircle(a, b, c);\n pr(ic);\n setp(12);\n out(ir);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_C\nvoid CircumscribedCircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [cc, cr] = makeC2(a, b, c);\n pr(cc);\n setp(12);\n out(cr);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_D\nvoid CrossPointsCL() {\n P2 c; D r;\n rd(c); cin>>r;\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n auto ps = cpCL(l, {c, r});\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n }\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_E\nvoid CrossPointsCC() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ps = cpCC(c1, c2);\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_F\nvoid TangentToCircle() {\n P2 p, c; D r;\n rd(p);\n rd(c); cin>>r;\n C2 c1={c, r};\n auto ls = tangCP(c1, p);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_G\nvoid CommonTangent() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ls = tangCC(c1, c2);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_H\n// void IntersectionCP() {\n// ll n;cin>>n;\n// D r; cin>>r;\n// C2 c = {P2(0, 0), r};\n// G2 g(n);\n// rep(i, n) rd(g[i]);\n// out(isaCP(c, g));\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_I\nvoid AreaOfIntersectionBetweenTwoCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n setp(12);\n out(isaCC(c1, c2));\n}\n\nint main() {\n cin.tie(0);\n ios_base::sync_with_stdio(false);\n\n // Projection();\n // Reflection();\n // CounterClockwise();\n\n // ParallelOrthogonal();\n // IntersectionSS();\n // CrossPointSS();\n // DistanceSS();\n\n // Area();\n // IsConvex();\n // PolygonPointContainment();\n\n // ConvexHull();\n // DiameterOfConvexPolygon();\n // ConvexCut();\n\n ClosestPair();\n // MinimumEnclosingCircle();\n\n // SegmentIntersections();\n\n // IntersectionOfCircles();\n // IncircleOfTriangle();\n // CircumscribedCircleOfTriangle();\n // CrossPointsCL();\n // CrossPointsCC();\n // TangentToCircle();\n // CommonTangent();\n // IntersectionCP();\n // AreaOfIntersectionBetweenTwoCircles();\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 17944, "score_of_the_acc": -1.0541, "final_rank": 19 }, { "submission_id": "aoj_CGL_5_A_10904371", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <climits>\n#include <unordered_map>\n#include <queue>\n#include <deque>\n#include <math.h>\n#include <bits/stdc++.h>\n#define ll long long\n#define Lt Line<T>\n#define Pt Point<T>\nusing i64 = long long;\nusing namespace std;\n\nconst ll N=1e6+10,MOD=998244353;\n\ntypedef std::pair<ll,ll> pii;\ntypedef std::pair<ll,pii> piii;\n//i64 n,m,k;\n\nusing ld = long double;\nconst ld PI = acos(-1);\nconst ld EPS = 1e-7;\nconst ld INF = numeric_limits<ld>::max();\n#define cc(x) cout << fixed << setprecision(x);\n\nld fgcd(ld x, ld y) { // 实数域gcd\n return abs(y) < EPS ? abs(x) : fgcd(y, fmod(x, y));\n}\ntemplate<class T, class S> bool equal(T x, S y) {\n return -EPS < x - y && x - y < EPS;\n}\ntemplate<class T> int sign(T x) {\n if (-EPS < x && x < EPS) return 0;\n return x < 0 ? -1 : 1;\n}\n\ntemplate<class T> struct Point { // 在C++17下使用 emplace_back 绑定可能会导致CE!\n T x, y;\n Point(T x_ = 0, T y_ = 0) : x(x_), y(y_) {} // 初始化\n template<class U> operator Point<U>() { // 自动类型匹配\n return Point<U>(U(x), U(y));\n }\n Point &operator+=(Point p) & { return x += p.x, y += p.y, *this; }\n Point &operator+=(T t) & { return x += t, y += t, *this; }\n Point &operator-=(Point p) & { return x -= p.x, y -= p.y, *this; }\n Point &operator-=(T t) & { return x -= t, y -= t, *this; }\n Point &operator*=(T t) & { return x *= t, y *= t, *this; }\n Point &operator/=(T t) & { return x /= t, y /= t, *this; }\n Point operator-() const { return Point(-x, -y); }\n friend Point operator+(Point a, Point b) { return a += b; }\n friend Point operator+(Point a, T b) { return a += b; }\n friend Point operator-(Point a, Point b) { return a -= b; }\n friend Point operator-(Point a, T b) { return a -= b; }\n friend Point operator*(Point a, T b) { return a *= b; }\n friend Point operator*(T a, Point b) { return b *= a; }\n friend Point operator/(Point a, T b) { return a /= b; }\n friend bool operator<(Point a, Point b) {\n return equal(a.x, b.x) ? a.y < b.y - EPS : a.x < b.x - EPS;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return !(a < b) && !(b < a); }\n friend bool operator!=(Point a, Point b) { return a < b || b < a; }\n friend auto &operator>>(istream &is, Point &p) {\n return is >> p.x >> p.y;\n }\n friend auto &operator<<(ostream &os, Point p) {\n return os << \"(\" << p.x << \", \" << p.y << \")\";\n }\n};\ntemplate<class T> struct Line {\n Point<T> a, b;\n Line(Point<T> a_ = Point<T>(), Point<T> b_ = Point<T>()) : a(a_), b(b_) {}\n template<class U> operator Line<U>() { // 自动类型匹配\n return Line<U>(Point<U>(a), Point<U>(b));\n }\n friend auto &operator<<(ostream &os, Line l) {\n return os << \"<\" << l.a << \", \" << l.b << \">\";\n }\n};\n\nusing Pd = Point<ld>;\nusing Ld = Line<ld>;\n\n\ntemplate<class T> T cross(Point<T> a, Point<T> b) { // 叉乘\n return a.x * b.y - a.y * b.x;\n}\ntemplate<class T> T cross(Point<T> p1, Point<T> p2, Point<T> p0) { // 叉乘 (p1 - p0) x (p2 - p0);\n return cross(p1 - p0, p2 - p0);\n}\n\n\ntemplate<class T> T dot(Point<T> a, Point<T> b) { // 点乘\n return a.x * b.x + a.y * b.y;\n}\ntemplate<class T> T dot(Point<T> p1, Point<T> p2, Point<T> p0) { // 点乘 (p1 - p0) * (p2 - p0);\n return dot(p1 - p0, p2 - p0);\n}\n\n// template <class T> ld dis(T x1, T y1, T x2, T y2) {\n// ld val = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n// return sqrt(val);\n// }\n// template <class T> ld dis(Point<T> a, Point<T> b) {\n// return dis(a.x, a.y, b.x, b.y);\n// }\n\n// template<class T> Point<T> rotate(Point<T> p1, Point<T> p2) { // 旋转\n// Point<T> vec = p1 - p2;\n// return {-vec.y, vec.x};\n// }\n\n// ld toDeg(ld x) { // 弧度转角度\n// return x * 180 / PI;\n// }\n// ld toArc(ld x) { // 角度转弧度\n// return PI / 180 * x;\n// }\n\n// Point<ld> rotate(Point<ld> p, ld rad) {\n// return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)};\n// }\n\n// Point<ld> rotate(Point<ld> a, Point<ld> b, ld rad) {\n// ld x = (a.x - b.x) * cos(rad) + (a.y - b.y) * sin(rad) + b.x;\n// ld y = (b.x - a.x) * sin(rad) + (a.y - b.y) * cos(rad) + b.y;\n// return {x, y};\n// }\n\n// template<class T> bool onLine(Point<T> a, Point<T> b, Point<T> c) {\n// return sign(cross(b, a, c)) == 0;\n// }\n// template<class T> bool onLine(Point<T> p, Line<T> l) {\n// return onLine(p, l.a, l.b);\n// }\n\n// template<class T> bool pointOnLineLeft(Pt p, Lt l) {\n// return cross(l.b, p, l.a) > 0;\n// }\n\n// template<class T> bool pointOnLineSide(Pt p1, Pt p2, Lt vec) {\n// T val = cross(p1, vec.a, vec.b) * cross(p2, vec.a, vec.b);\n// return sign(val) == 1;\n// }\n// template<class T> bool pointNotOnLineSide(Pt p1, Pt p2, Lt vec) {\n// T val = cross(p1, vec.a, vec.b) * cross(p2, vec.a, vec.b);\n// return sign(val) == -1;\n// }\n\n// Pd lineIntersection(Ld l1, Ld l2) {\n// ld val = cross(l2.b - l2.a, l1.a - l2.a) / cross(l2.b - l2.a, l1.a - l1.b);\n// return l1.a + (l1.b - l1.a) * val;\n// }\n\n// template<class T> bool lineParallel(Lt p1, Lt p2) {\n// return sign(cross(p1.a - p1.b, p2.a - p2.b)) == 0;\n// }\n// template<class T> bool lineVertical(Lt p1, Lt p2) {\n// return sign(dot(p1.a - p1.b, p2.a - p2.b)) == 0;\n// }\n// template<class T> bool same(Line<T> l1, Line<T> l2) {\n// return lineParallel(Line{l1.a, l2.b}, {l1.b, l2.a}) &&\n// lineParallel(Line{l1.a, l2.a}, {l1.b, l2.b}) && lineParallel(l1, l2);\n// }\n\n// pair<Pd, ld> pointToLine(Pd p, Ld l) {\n// Pd ans = lineIntersection({p, p + rotate(l.a, l.b)}, l);\n// return {ans, dis(p, ans)};\n// }\n\n// template<class T> ld disPointToLine(Pt p, Lt l) {\n// ld ans = cross(p, l.a, l.b);\n// return abs(ans) / dis(l.a, l.b); // 面积除以底边长\n// }\n\n// template<class T> bool pointOnSegment(Pt p, Lt l) { // 端点也算作在直线上\n// return sign(cross(p, l.a, l.b)) == 0 && min(l.a.x, l.b.x) <= p.x && p.x <= max(l.a.x, l.b.x) &&\n// min(l.a.y, l.b.y) <= p.y && p.y <= max(l.a.y, l.b.y);\n// }\n\n// pair<Pd, ld> pointToSegment(Pd p, Ld l) {\n// if (sign(dot(p, l.b, l.a)) == -1) { // 特判到两端点的距离\n// return {l.a, dis(p, l.a)};\n// } else if (sign(dot(p, l.a, l.b)) == -1) {\n// return {l.b, dis(p, l.b)};\n// }\n// return pointToLine(p, l);\n// }\n\n// template<class T> bool segmentIntersection(Lt l1, Lt l2) {\n// auto [s1, e1] = l1;\n// auto [s2, e2] = l2;\n// auto A = max(s1.x, e1.x), AA = min(s1.x, e1.x);\n// auto B = max(s1.y, e1.y), BB = min(s1.y, e1.y);\n// auto C = max(s2.x, e2.x), CC = min(s2.x, e2.x);\n// auto D = max(s2.y, e2.y), DD = min(s2.y, e2.y);\n// return A >= CC && B >= DD && C >= AA && D >= BB &&\n// sign(cross(s1, s2, e1) * cross(s1, e1, e2)) == 1 &&\n// sign(cross(s2, s1, e2) * cross(s2, e2, e1)) == 1;\n// }\n\n// template<class T> int pointInPolygon(Point<T> a, vector<Point<T>> p) {\n// int n = p.size();\n// for (int i = 0; i < n; i++) {\n// if (pointOnSegment(a, Line{p[i], p[(i + 1) % n]})) {\n// return 2;\n// }\n// }\n// int t = 0;\n// for (int i = 0; i < n; i++) {\n// auto u = p[i], v = p[(i + 1) % n];\n// if (u.x < a.x && v.x >= a.x && pointOnLineLeft(a, Line{v, u})) {\n// t ^= 1;\n// }\n// if (u.x >= a.x && v.x < a.x && pointOnLineLeft(a, Line{u, v})) {\n// t ^= 1;\n// }\n// }\n// return t == 1;\n// }\n\n// template<class T> bool cmp1(Point<T> &a,Point<T> &b)\n// {\n// Point<T> a1(a.y,a.x);\n// Point<T> b1(b.y,b.x);\n// return a1<b1;\n// }\n\n// template<class T> vector<Point<T>> staticConvexHull(vector<Point<T>> A, int flag = 1) {\n// int n = A.size();\n// if (n <= 2) { // 特判\n// return A;\n// }\n// vector<Point<T>> ans(n * 2);\n// sort(A.begin(), A.end());\n// int now = -1;\n \n// for (int i = 0; i < n; i++) { // 维护下凸包\n// while (now > 0 && cross(A[i], ans[now], ans[now - 1]) <= 0) {\n// now--;\n// }\n// ans[++now] = A[i];\n// }\n// int pre = now;\n// for (int i = n - 2; i >= 0; i--) { // 维护上凸包\n// while (now > pre && cross(A[i], ans[now], ans[now - 1]) <= 0) {\n// now--;\n// }\n// ans[++now] = A[i];\n// }\n// ans.resize(now);\n// return ans;\n// }\n\n// template<class T>T GetConvexHullDis(vector<Pt> A)\n// {\n// int w=0; \n// T ans=max(dis(A[w],A[0]),dis(A[w],A[1]));\n// for(int i=0;i<A.size();i++)\n// {\n// int j=(i+1)%A.size();\n// int ne=(w+1)%A.size();\n// while(cross(A[ne],A[i],A[j])>=cross(A[w],A[i],A[j])) w=ne,ne=(w+1)%A.size();\n// ans=max(max(dis(A[w],A[i]),dis(A[w],A[j])),ans);\n// }\n// return ans;\n// }\n\n// vector<Pd> GetLineCrossHull(Ld L1,vector<Pd> A)\n// {\n// vector<Pd> ans;\n// for(int i=0;i<A.size();i++)\n// {\n// Pd a1=A[i]; Pd a2=A[(i+1)%A.size()];\n// bool f1=pointOnLineLeft(a1,L1);\n// bool f2=pointOnLineLeft(a2,L1);\n// if(f1) ans.push_back(a1);\n// if(f1==f2) continue;\n// Ld tem(a1,a2);\n// ans.push_back(lineIntersection(tem,L1));\n// }\n// return ans;\n// }\n\n// template<class T> ld area(vector<Point<T>> P) {\n// int n = P.size();\n// ld ans = 0;\n// for (int i = 0; i < n; i++) {\n// ans += cross(P[i], P[(i + 1) % n]);\n// }\n// return ans / 2.0;\n// }\n\ntemplate<class T> T sqr(T x) {\n return x * x;\n}\n\ntemplate<class T> T disEx(Pt a1,Pt a2)\n{\n return (a1.x-a2.x)*(a1.x-a2.x)+(a1.y-a2.y)*(a1.y-a2.y);\n}\n\ntemplate<class T> T ClosestPairDis(vector<Pt> A)\n{\n sort(A.begin(),A.end());\n T ans=disEx(A[0],A[1]);\n set<Pt> S;\n for(int i=0,h=0;i<A.size();i++)\n {\n Pt now={A[i].y,A[i].x};\n while(ans&&ans<=sqr(A[i].x-A[h].x))\n {\n S.erase({A[h].y,A[h].x});\n ++h;\n }\n auto it=S.lower_bound(now);\n for(auto k=it;k!=S.end()&&sqr(k->x-now.x)<ans;k++) ans=min(ans,disEx(*k,now));\n if(it!=S.begin())\n {\n for(auto k=prev(it);sqr(k->x-now.x)<ans;k--)\n {\n ans=min(ans,disEx(*k,now));\n if(k==S.begin()) break;\n }\n }\n S.insert(now);\n }\n return sqrt(ans);\n}\n\n\nint main() {\n \n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n\n\n cc(12);\n int n;\n cin>>n;\n vector<Pd> z(n);\n for(auto &t:z) cin>>t;\n cout<<ClosestPairDis(z)<<'\\n';\n\n\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 15456, "score_of_the_acc": -0.8236, "final_rank": 18 }, { "submission_id": "aoj_CGL_5_A_10895532", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long \n#define endl '\\n'\n\n#define maxn 200010\n\n\nstruct Point{\n double x,y;\n};vector<Point>p;\ndouble ans = 1e18;\ntypedef vector<Point>::iterator iter;\nbool cmpx(const Point &a,const Point &b){\n if(a.x!=b.x)return a.x<b.x;\n return a.y<b.y;\n}\nbool cmpy(const Point &a,const Point &b){\n if(a.y!=b.y)return a.y<b.y;\n return a.x<b.x;\n}\ndouble dis(Point a,Point b){\n return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));\n}\n\nvoid solve(const iter l,const iter r,double &d){\n if(r-l<=1)return;\n vector<Point>Q;\n iter mid = l+(r-l)/2;\n double w = mid->x;\n solve(l,mid,d);\n solve(mid,r,d);\n inplace_merge(l,mid,r,cmpy);\n for(iter i=l;i!=r;i++) if(abs(w-i->x)<=d) Q.push_back(*i);\n for(iter i=Q.begin(),j=i;i!=Q.end();i++){\n while(j!=Q.end()&&j->y<=i->y+d) j++;\n for(iter k=i+1;k!=j;k++) d=min(d,dis(*i,*k));\n }\n}\n\n\nsigned main(){\n ios::sync_with_stdio(false);\n cin.tie(NULL);\n int n;\n cin>>n;\n for(int i =1;i<=n;i++){\n Point t;\n cin>>t.x>>t.y;\n p.push_back(t);\n }\n sort(p.begin(), p.end(), cmpx);\n solve(p.begin(),p.end(),ans);\n printf(\"%.10lf\\n\",ans);\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 7904, "score_of_the_acc": -0.2606, "final_rank": 5 }, { "submission_id": "aoj_CGL_5_A_10870193", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ld = long double;\n\nstruct Pt {\n ld x, y;\n};\n\nstatic inline ld dist2(const Pt& a, const Pt& b) {\n ld dx = a.x - b.x;\n ld dy = a.y - b.y;\n return dx*dx + dy*dy;\n}\n\n// Resolve [l, r) em pts (inicialmente ordenado por x).\n// Retorna menor d^2 e mantém pts[l:r) ordenado por y ao terminar.\nld closest_rec(vector<Pt>& pts, int l, int r, vector<Pt>& tmp) {\n int n = r - l;\n if (n <= 3) {\n ld best = numeric_limits<ld>::infinity();\n for (int i = l; i < r; ++i)\n for (int j = i + 1; j < r; ++j)\n best = min(best, dist2(pts[i], pts[j]));\n // ordena por y\n sort(pts.begin() + l, pts.begin() + r, [](const Pt& a, const Pt& b){\n if (a.y != b.y) return a.y < b.y;\n return a.x < b.x;\n });\n return best;\n }\n int m = (l + r) >> 1;\n ld midx = pts[m].x;\n ld dl = closest_rec(pts, l, m, tmp);\n ld dr = closest_rec(pts, m, r, tmp);\n ld best = min(dl, dr);\n\n // merge por y (pts[l:m] e pts[m:r] já ordenados por y)\n int i = l, j = m, k = 0;\n while (i < m || j < r) {\n if (j == r || (i < m && (pts[i].y < pts[j].y || (pts[i].y == pts[j].y && pts[i].x < pts[j].x))))\n tmp[k++] = pts[i++];\n else\n tmp[k++] = pts[j++];\n }\n // copia de volta\n for (int t = 0; t < k; ++t) pts[l + t] = tmp[t];\n\n // strip: |x - midx| <= sqrt(best)\n ld d = sqrtl(best);\n vector<Pt> strip;\n strip.reserve(k);\n for (int t = l; t < r; ++t)\n if (fabsl(pts[t].x - midx) <= d) strip.push_back(pts[t]);\n\n // compara vizinhos na ordenação por y (while (dy^2 < best))\n for (size_t a = 0; a < strip.size(); ++a) {\n for (size_t b = a + 1; b < strip.size(); ++b) {\n ld dy = strip[b].y - strip[a].y;\n if (dy*dy >= best) break;\n best = min(best, dist2(strip[a], strip[b]));\n }\n }\n return best;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n int n;\n if (!(cin >> n)) return 0;\n vector<Pt> pts(n);\n for (int i = 0; i < n; ++i) cin >> pts[i].x >> pts[i].y;\n\n // ordena por x, depois y para estabilidade\n sort(pts.begin(), pts.end(), [](const Pt& a, const Pt& b){\n if (a.x != b.x) return a.x < b.x;\n return a.y < b.y;\n });\n\n vector<Pt> tmp(n);\n ld best2 = closest_rec(pts, 0, n, tmp);\n ld ans = sqrtl(best2);\n\n cout.setf(std::ios::fixed); \n cout << setprecision(10) << (double)ans << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 12292, "score_of_the_acc": -0.6091, "final_rank": 14 }, { "submission_id": "aoj_CGL_5_A_10854438", "code_snippet": "#include<bits/stdc++.h>\n#define siz(x) int((x).size())\n#define all(x) std::begin(x),std::end(x)\n#define fi first\n#define se second\nusing namespace std;\nusing unt=unsigned;\nusing loli=long long;\nusing lolu=unsigned long long;\nusing pii=pair<int,int>;\nmt19937_64 rng(random_device{}());\nconstexpr double eps=1e-8;\ntemplate<typename any>inline any sqr(const any &x){return x*x;}\ninline int get_op(double x){if(fabs(x)<eps)return 0;return x>0?1:-1;}\ndouble det(array<double,3>a0,array<double,3>a1,array<double,3>a2){\n\tdouble sum=0;\n\tsum+=a0[0]*a1[1]*a2[2];\n\tsum+=a1[0]*a2[1]*a0[2];\n\tsum+=a2[0]*a0[1]*a1[2];\n\tsum-=a0[2]*a1[1]*a2[0];\n\tsum-=a0[1]*a1[0]*a2[2];\n\tsum-=a0[0]*a1[2]*a2[1];\n\treturn sum;\n}\nstruct bector{\n\tdouble x,y;\n\tbool operator<(const bector&t)const{return fabs(x-t.x)<eps?y<t.y:x<t.x;}\n\tbool operator==(const bector&t)const{return fabs(x-t.x)<eps&&fabs(y-t.y)<eps;}\n\tbector(double a=0,double b=0):x(a),y(b){}\n\tdouble operator~()const{return sqrt(x*x+y*y);}\n\tdouble operator*()const{return x*x+y*y;}\n\tfriend istream&operator>>(istream&a,bector&b){return a>>b.x>>b.y;}\n\tfriend ostream&operator<<(ostream&a,const bector&b){return a<<b.x<<' '<<b.y;}\n\tfriend bector operator+(const bector&a,const bector&b){return {a.x+b.x,a.y+b.y};}\n\tbector&operator+=(const bector&t){x+=t.x,y+=t.y;return *this;}\n\tfriend bector operator-(const bector&a,const bector&b){return {a.x-b.x,a.y-b.y};}\n\tbector&operator-=(const bector&t){x-=t.x,y-=t.y;return *this;}\n\tfriend bector operator*(const bector&a,double b){return {a.x*b,a.y*b};}\n\tfriend bector operator*(double b,const bector&a){return {a.x*b,a.y*b};}\n\tbector&operator*=(double t){x*=t,y*=t;return *this;}\n\tfriend bector operator/(const bector&a,double b){return {a.x/b,a.y/b};}\n\tbector&operator/=(double t){x/=t,y/=t;return *this;}\n\tfriend double operator*(const bector&a,const bector&b){return a.x*b.x+a.y*b.y;}\n\tfriend double operator/(const bector&a,const bector&b){return a.x*b.y-a.y*b.x;}\n\tbool frontis(const bector&t)const{auto r=*this*t;return get_op(r)>0;}\n\tbool backis(const bector&t)const{auto r=*this*t;return get_op(r)<0;}\n\tbool leftis(const bector&t)const{auto r=*this/t;return get_op(r)>0;}\n\tbool rightis(const bector&t)const{auto r=*this/t;return get_op(r)<0;}\n\tbool front1s(const bector&t)const{auto r=*this*t;return get_op(r)>=0;}\n\tbool back1s(const bector&t)const{auto r=*this*t;return get_op(r)<=0;}\n\tbool left1s(const bector&t)const{auto r=*this/t;return get_op(r)>=0;}\n\tbool right1s(const bector&t)const{auto r=*this/t;return get_op(r)<=0;}\n\tfriend double dis(const bector&a,const bector&b){return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}\n\tbector rot90()const{return {-y,x};}\n\tdouble arg()const{return atan2(y,x);}\n\tbector rotate(const bector&a,double r){\n\t\tauto u=a-*this;\n\t\treturn *this+bector{u.x*cos(r)-u.y*sin(r),u.x*sin(r)+u.y*cos(r)};\n\t}\n\tfriend double c0s(const bector&x,const bector&y){\n\t\t// 求 cos<x,y>\n\t\treturn x*y/~x/~y;\n\t}\n\tbector unit()const{\n\t\treturn (*this)/~(*this);\n\t}\n\tfriend bool operator&(const bector&a,const bector&b){return !get_op(a*b);}\n\tfriend bool operator|(const bector&a,const bector&b){return !get_op(a/b);}\n\tfriend double triarea(const bector&x,const bector&y,const bector&z){\n\t\treturn (y-x)/(z-x)/2;\n\t}\n};\nbector polar(double p,double r){return {cos(r)*p,sin(r)*p};}\nstruct segment{\n\tbector p1,p2;\n\tsegment(const bector&a={0,0},const bector&b={0,0}):p1(a),p2(b){};\n\tfriend istream&operator>>(istream&a,segment &b){return a>>b.p1>>b.p2;}\n\tfriend ostream&operator<<(ostream&a,const segment&b){return a<<b.p1<<' '<<b.p2;}\n\tfriend bool operator&(const segment&a,const segment&b){return !get_op((a.p2-a.p1)*(b.p2-b.p1));}\n\tfriend bool operator|(const segment&a,const segment&b){return !get_op((a.p2-a.p1)/(b.p2-b.p1));}\n\tbool leftis(const bector&t)const{return (p2-p1).leftis(t-p1);}\n\tbool rightis(const bector&t)const{return (p2-p1).rightis(t-p1);}\n\tbool left1s(const bector&t)const{return (p2-p1).left1s(t-p1);}\n\tbool right1s(const bector&t)const{return (p2-p1).right1s(t-p1);}\n\tbool check(const bector&t)const{\n\t\t// cerr<<left1s(t)<<' '<<right1s(t)<<'\\n';\n\t\treturn left1s(t)&&right1s(t);\n\t}\n\t// bool check(const bector&t)const{return left1s(t)&&right1s(t);}\n\tfriend bool banana(const segment&a,const segment&b){\n\t\t// 判断是否相交\n\t\tif(min(a.p1.x,a.p2.x)>max(b.p1.x,b.p2.x)||min(b.p1.x,b.p2.x)>max(a.p1.x,a.p2.x)||min(a.p1.y,a.p2.y)>max(b.p1.y,b.p2.y)||min(b.p1.y,b.p2.y)>max(a.p1.y,a.p2.y))return false;\n\t\treturn get_op(((a.p2-a.p1)/(b.p1-a.p1))*((a.p2-a.p1)/(b.p2-a.p1)))<=0&&get_op(((b.p2-b.p1)/(a.p1-b.p1))*((b.p2-b.p1)/(a.p2-b.p1)))<=0;\n\t}\n\tfriend bector focus(const segment&a,const segment&b){\n\t\t// 输入必须保证有交,输出交点\n\t\tbector v=a.p2-a.p1,w=b.p2-b.p1,u=a.p1-b.p1;\n\t\treturn a.p1+v*((w/u)/(v/w));\n\t}\n\tfriend double dis(const segment&a,const bector&b){\n\t\tif(a.p1==a.p2)return ~(b-a.p1);\n\t\tauto v1=a.p2-a.p1,v2=b-a.p1,v3=b-a.p2;\n\t\tif(v1.backis(v2))return ~v2;\n\t\tif(v1.frontis(v3))return ~v3;\n\t\treturn fabs(v1/v2)/~v1;\n\t}\n\tfriend double dis(const segment&a,const segment&b){\n\t\t// 求线段间最短距离\n\t\tif(banana(a,b))return 0;\n\t\treturn min({dis(a,b.p1),dis(a,b.p2),dis(b,a.p1),dis(b,a.p2)});\n\t}\n\tbector project(const bector&a)const{\n\t\t// 求点 a 在当前线段上的投影点坐标\n\t\tif(a==p1||a==p2)return a;\n\t\tauto u=p2-p1,v=a-p1;\n\t\treturn c0s(u,v)*(~v)*u.unit()+p1;\n\t}\n\tdouble pr0ject(const bector&a)const{\n\t\treturn dis(a,project(a));\n\t}\n\tbector reflect(const bector&a)const{\n\t\t// 求点 a 在当前线段上的对称点\n\t\treturn 2*project(a)-a;\n\t}\n\tsegment&sort(){if(p2<p1)std::swap(p1,p2);return *this;}\n};\nstruct circle{\n\tbector p;double r;\n\tcircle(const bector&a={0,0},double b=0):p(a),r(b){}\n\tcircle(bector p1,bector p2){\n\t\tp=(p1+p2)/2;\n\t\tr=dis(p1,p2)/2;\n\t}\n\tcircle(bector p1,bector p2,bector p3){\n\t\tp.x=det({*p1,p1.y,1},{*p2,p2.y,1},{*p3,p3.y,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tp.y=-det({*p1,p1.x,1},{*p2,p2.x,1},{*p3,p3.x,1})/2/det({p1.x,p1.y,1},{p2.x,p2.y,1},{p3.x,p3.y,1});\n\t\tr=dis(p,p1);\n\t}\n\tfriend istream&operator>>(istream&a,circle &b){return a>>b.p>>b.r;}\n\tfriend ostream&operator<<(ostream&a,const circle &b){return a<<b.p<<' '<<b.r;}\n\tbool check(bector t){\n\t\treturn dis(p,t)-r<=eps;\n\t}\n\tfriend segment focus(const circle &a,const segment&b){\n\t\tauto d=b.project(a.p),u=b.p2-b.p1,e=u/~u;\n\t\tauto t=sqrt(a.r*a.r-sqr(dis(d,a.p)));\n\t\treturn segment{d+e*t,d-e*t}.sort();\n\t}\n\tfriend segment focus(const circle &a,const circle &b){\n\t\tauto d=dis(a.p,b.p),l=acos((sqr(a.r)+sqr(d)-sqr(b.r))/(2*a.r*d)),t=(b.p-a.p).arg();\n\t\treturn segment{a.p+polar(a.r,t+l),a.p+polar(a.r,t-l)}.sort();\n\t}\n\tsegment tangent(const bector&a){\n\t\tauto u=a-p;\n\t\tauto l=acos(r/~u);\n\t\tu=u*r/~u;\n\t\treturn segment{p.rotate(p+u,+l),p.rotate(p+u,-l)}.sort();\n\t}\n};\nstruct points:vector<bector>{\n#define p (*this)\n\tpoints&read(istream&t,int n=-1){\n\t\tif(n==-1)cin>>n;\n\t\tp.resize(n);\n\t\tfor(int i=0;i<n;i++)t>>p[i];\n\t\treturn *this;\n\t}\n\tdouble area()const{\n\t\t// 无需满足多边形是凸的\n\t\tdouble ans=0;\n\t\tfor(int i=1;i<siz(p)-1;i++)ans+=(p[i]-p[0])/(p[i+1]-p[0]);\n\t\treturn ans/2;\n\t}\n\tpoints tobag(){\n\t\tsort(all(p));\n\t\terase(unique(all(p)),end());\n\t\tpoints b;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\twhile(siz(b)>1&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<=0)\n\t\t\t// while(siz(b)>1&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<0)\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(p[i]);\n\t\t}\n\t\tint o=siz(b);\n\t\tfor(int i=siz(p)-2;~i;i--){\n\t\t\twhile(siz(b)>o&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<=0)\n\t\t\t// while(siz(b)>o&&get_op((b.back()-b[siz(b)-2])/(p[i]-b[siz(b)-2]))<0)\n\t\t\t\tb.pop_back();\n\t\t\tb.push_back(p[i]);\n\t\t}\n\t\t// if(siz(p)>1)b.pop_back();\n\t\treturn b;\n\t}\n\tdouble xzqk()const{\n\t\tif(siz(p)==1)return 0;\n\t\tif(siz(p)==2)return dis(p[0],p[1]);\n\t\tif(siz(p)==3)return max({dis(p[0],p[1]),dis(p[0],p[2]),dis(p[1],p[2])});\n\t\tdouble ans=0;\n\t\tfor(int i=1,j=2;i<siz(p);i++){\n\t\t\twhile(get_op(triarea(p[i-1],p[i],p[j])-triarea(p[i-1],p[i],p[(j+1)%siz(p)]))<=0)\n\t\t\t\t(++j)%=siz(p);\n\t\t\tans=max({ans,dis(p[i-1],p[j]),dis(p[i],p[j])});\n\t\t}\n\t\treturn ans;\n\t}\n\tdouble kqzx(){\n\t\tsort(all(p));\n\t\tauto solve=[&](auto&&self,int l,int r){\n\t\t\tif(l==r)return 1e18;\n\t\t\tint mid=(l+r)/2;\n\t\t\tdouble ans=min(self(self,l,mid),self(self,mid+1,r));\n\t\t\tpoints b;\n\t\t\tfor(int i=l;i<=r;i++)if(fabs(p[mid].x-p[i].x)<=ans)b.push_back(p[i]);\n\t\t\tsort(all(b),[](const bector&x,const bector&y){\n\t\t\t\tif(x.y==y.y)return x.x<y.x;\n\t\t\t\treturn x.y<y.y;\n\t\t\t});\n\t\t\tfor(int i=0;i<siz(b);i++)for(int j=i+1;j<siz(b);j++){\n\t\t\t\tif(b[j].y-b[i].y>=ans)break;\n\t\t\t\tans=min(ans,dis(b[i],b[j]));\n\t\t\t}\n\t\t\treturn ans;\n\t\t};\n\t\treturn solve(solve,0,siz(p)-1);\n\t}\n\tcircle incircle(){\n\t\tassert(siz(p)==3);\n\t\tauto u=p[1]-p[0],v=p[2]-p[0];u=u/~u*~v;\n\t\tsegment l1{p[0],p[0]+u+v};\n\t\tu=p[2]-p[1],v=p[0]-p[1];u=u/~u*~v;\n\t\tsegment l2{p[1],p[1]+u+v};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(segment{p[0],p[1]},pp)};\n\t}\n\tcircle outcirce(){\n\t\tassert(siz(p)==3);\n\t\tauto u=p[1]-p[0],mid=(p[0]+p[1])/2;\n\t\tsegment l1{mid,mid+u.rot90()};\n\t\tu=p[2]-p[0],mid=(p[0]+p[2])/2;\n\t\tsegment l2{mid,mid+u.rot90()};\n\t\tauto pp=focus(l1,l2);\n\t\treturn circle{pp,dis(p[0],pp)};\n\t}\n\tint contains(bector t){\n\t\t// 无需满足多边形是凸的\n\t\t// 2表示包含,1表示在边上,0表示在外面\n\t\tbool res=false;\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tauto a=p[i]-t,b=p[(i+1)%siz(p)]-t;\n\t\t\tif(!a.leftis(b)&&!a.rightis(b)&&!a.frontis(b))return 1;\n\t\t\tif(a.y>b.y)std::swap(a,b);\n\t\t\tif(a.y<eps&&eps<b.y&&a.leftis(b))res=!res;\n\t\t}\n\t\treturn res?2:0;\n\t}\n\tpoints leftpoints(const segment&l)const{\n\t\tpoints b;\n\t\t// cerr<<\"check \"<<l<<'\\n';\n\t\tfor(int i=0;i<siz(p);i++){\n\t\t\tif(l.check(p[i]))b.push_back(p[i]);\n\t\t\telse if(l.rightis(p[(i-1+siz(p))%siz(p)])&&l.leftis(p[i])&&l.rightis(p[(i+1)%siz(p)])){\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i-1+siz(p))%siz(p)])));\n\t\t\t\tb.push_back(p[i]);\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i+1)%siz(p)])));\n\t\t\t}else if(l.leftis(p[i])&&l.rightis(p[(i+1)%siz(p)])){\n\t\t\t\tb.push_back(p[i]);\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i+1)%siz(p)])));\n\t\t\t}else if(l.leftis(p[i])&&l.rightis(p[(i-1+siz(p))%siz(p)])){\n\t\t\t\tb.push_back(focus(l,segment(p[i],p[(i-1+siz(p))%siz(p)])));\n\t\t\t\tb.push_back(p[i]);\n\t\t\t}else if(l.leftis(p[i]))b.push_back(p[i]);\n\t\t}\n\t\t// for(auto it:b)cout<<it<<'\\n';\n\t\t// cout<<\"===============\\n\";\n\t\treturn b;\n\t}\n#undef p\n};\ncircle mingenshin(points b){\n\tshuffle(all(b),rng);\n\tcircle ans;\n\tfor(int i=0;i<siz(b);i++)if(!ans.check(b[i])){\n\t\tans={b[i],0};\n\t\tfor(int j=0;j<i;j++)if(!ans.check(b[j])){\n\t\t\tans=circle(b[i],b[j]);\n\t\t\tfor(int k=0;k<j;k++)if(!ans.check(b[k])){\n\t\t\t\tans=circle(b[i],b[j],b[k]);\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\nsigned main(){\n//\tfreopen(\".in\",\"r\",stdin);\n//\tfreopen(\".out\",\"w\",stdout);\n\tstd::ios::sync_with_stdio(false);cin.tie(nullptr);\n\tcout<<setiosflags(ios::fixed)<<setprecision(10);\n\tpoints a;\n\ta.read(cin);\n\tcout<<a.kqzx();\n\treturn 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 7740, "score_of_the_acc": -0.2481, "final_rank": 4 }, { "submission_id": "aoj_CGL_5_A_10848625", "code_snippet": "#include<iostream>\n#include<iomanip>\n#include<cmath>\n#include<algorithm>\n#include<vector>\n\nusing namespace std;\n\nstruct point\n{\n double x, y;\n};\n\nbool cmp_x(const point& a, const point& b)\n{\n if(a.x != b.x) return a.x < b.x;\n else return a.y < b.y;\n}\n\nbool cmp_y(const point& a, const point& b)\n{\n if(a.y != b.y) return a.y < b.y;\n else return a.x < b.x;\n}\n\ndouble dist(point& a, point& b)\n{\n return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\ndouble dnc(vector<point>& half_space, vector<point>& half_space_y)\n{\n double min_dist = 1e9;\n point mid;\n vector<point> left, left_y, right, right_y, merge_y;\n\n if(half_space.size() < 2) return 1e9;\n\n mid = half_space[half_space.size() >> 1];\n for(int i = 0; i < half_space.size(); ++i)\n {\n if(half_space[i].x < mid.x) left.push_back(half_space[i]);\n else right.push_back(half_space[i]);\n if(half_space_y[i].x < mid.x) left_y.push_back(half_space_y[i]);\n else right_y.push_back(half_space_y[i]);\n }\n if(!left.empty()) min_dist = min(dnc(left, left_y), dnc(right, right_y));\n\n for(int i = 0; i < half_space_y.size(); ++i) if(fabs(half_space_y[i].x - mid.x) <= min_dist) merge_y.push_back(half_space_y[i]);\n for(int i = 0; i < merge_y.size(); ++i)\n {\n for(int j = i + 1; j < merge_y.size(); ++j)\n {\n if(merge_y[j].y - merge_y[i].y > min_dist) break;\n min_dist = min(min_dist, dist(merge_y[i], merge_y[j]));\n }\n }\n return min_dist;\n}\n\nint main()\n{\n int n;\n vector<point> space, space_y;\n cin >> n;\n for(int i = 0; i < n; ++i)\n {\n point now;\n cin >> now.x >> now.y;\n space.push_back(now);\n space_y.push_back(now);\n }\n sort(space.begin(), space.end(), cmp_x);\n sort(space_y.begin(), space_y.end(), cmp_y);\n cout << fixed << setprecision(7) << dnc(space, space_y) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 13396, "score_of_the_acc": -0.7609, "final_rank": 17 }, { "submission_id": "aoj_CGL_5_A_10843111", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nnamespace DBG\n{\n template <class T>\n void _dbg(const char *f, T t) { cerr << f << '=' << t << '\\n'; }\n template <class A, class... B>\n void _dbg(const char *f, A a, B... b)\n {\n while (*f != ',')\n cerr << *f++;\n cerr << '=' << a << \",\";\n _dbg(f + 1, b...);\n }\n template <typename Container>\n void _print(const char *f, const Container &v)\n {\n cerr << f << \" = [ \";\n for (const auto &x : v)\n cerr << x << \", \";\n cerr << \"]\\n\";\n }\n#define bug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n#define bugv(container) _print(#container, container)\n}\nusing namespace DBG;\n\nvoid _();\nint main()\n{\n ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n cout << fixed << setprecision(10);\n int T = 1;\n // cin >> T;\n while (T--)\n _();\n return 0;\n}\n\n#define int long long\n\nusing ld = long double;\nconst ld eps = 1e-9;\nconst ld PI = acos(-1);\n#define Pt Point<T>\n#define Pd Point<ld>\n#define Lt Line<T>\n#define Ld Line<ld>\n\nint sign(ld x) // 判符号\n{\n if (fabsl(x) < eps)\n return 0;\n else\n return x < 0 ? -1 : 1;\n}\nbool equal(ld x, ld y) { return !sign(x - y); } // 近似\nbool big(ld has, ld tar) { return sign(has - tar) > 0; }\n\n//////////////////////////////////////////////////////////////////////////// 点类\n\n// 点与向量\ntemplate <class T>\nstruct Point\n{\n T x, y;\n\n Point(T x = 0, T y = 0) : x(x), y(y) {} // 带参构造\n\n // 运算符重载\n Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }\n Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }\n Point operator*(T k) const { return Point(x * k, y * k); }\n Point operator/(T k) const { return Point(x / k, y / k); }\n\n friend bool operator<(Point a, Point b)\n {\n if (!equal(a.x, b.x))\n return a.x < b.x;\n return a.y < b.y;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return equal(a.x, b.x) && equal(a.y, b.y); } // 近似\n friend bool operator!=(Point a, Point b) { return !(a == b); }\n friend auto &operator>>(istream &is, Point &p) { return is >> p.x >> p.y; }\n friend auto &operator<<(ostream &os, Point p) { return os << \"(\" << p.x << \", \" << p.y << \")\"; }\n};\n\nld len(Point<ld> a) { return sqrtl(a.x * a.x + a.y * a.y); }; // 模长\nld dis(Point<ld> a, Point<ld> b) { return len(a - b); } // 两点距离\n\nld cross(Point<ld> a, Point<ld> b) { return a.x * b.y - a.y * b.x; } // 叉积 ab*sin 两点与原点三角形面积 判两点位置关系两侧\nld cross(Point<ld> p0, Point<ld> p1, Point<ld> p2) { return cross(p1 - p0, p2 - p0); }\nld dot(Point<ld> a, Point<ld> b) { return a.x * b.x + a.y * b.y; } // 点积 ab*cos 结合判两点象限位置关系\nld dot(Point<ld> p0, Point<ld> p1, Point<ld> p2) { return dot(p1 - p0, p2 - p0); }\nld angle(Point<ld> a, Point<ld> b) { return atan2(cross(a, b), dot(a, b)); } // 向量夹角[-pi, pi] 非负fabsl\n\nPoint<ld> standardize(Point<ld> h) // 转换为单位向量\n{\n ld l = len(h);\n if (sign(l) == 0)\n return {0, 0}; // 防止除零\n return h / l;\n}\nPd rotate(Pd p, ld rad) { return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)}; } // 向量旋转任意角度\n\nPd rotate90(Pd a) { return Point<ld>{-a.y, a.x}; } // 旋转90° 垂直向量\nld toDeg(ld x) { return x * 180 / PI; } // 弧度转角度\nld toArc(ld x) { return PI / 180 * x; } // 角度转弧度\nld angle(ld a, ld b, ld c) { return acos((a * a + b * b - c * c) / (2.0 * a * b)); } // 余弦定理 三边求角C弧度\n\n//////////////////////////////////////////////////////////////////////// 直线与线段\n\n// 直线\ntemplate <class T>\nstruct Line\n{\n Point<T> a, b;\n Line(Pt a_ = {}, Pt b_ = {}) : a(a_), b(b_) {}\n friend auto &operator<<(ostream &os, Line l) { return os << \"<\" << l.a << \", \" << l.b << \">\"; }\n};\nbool pointOnLineLeft(Pd p, Ld l) { return cross(l.b - l.a, p - l.a) > 0; } // 点在直线左侧\nbool onLine(Pd a, Pd b, Pd c) { return sign(cross(a - b, c - b)) == 0; } // 点是否在直线上(三点是否共线)ok\nbool onLine(Pd p, Ld l) { return onLine(p, l.a, l.b); }\n// 线段:点是否在线段上 ok\nbool pointOnSegment(Pd p, Ld l) { return fabsl(cross(l.a - p, l.b - p)) < eps && dot(l.a - p, l.b - p) <= 0; }\nbool Parallel(Pd p1, Pd p2) { return equal(0, cross(p1, p2)); } // 平行 ok\nbool Orthogonal(Pd p1, Pd p2) { return equal(0, dot(p1, p2)); } // 垂直 ok\nLd midSegment(Ld l) { return {(l.a + l.b) / 2, (l.a + l.b) / 2 + rotate90(l.a - l.b)}; } // 线段的中垂线\n\nld disPointToLine(Pd p, Ld l, bool isSegment = false) // 点到直线/线段的最近距离 ok\n{\n ld len_ab = dis(l.a, l.b);\n if (sign(len_ab) == 0)\n return dis(p, l.a);\n if (!isSegment)\n {\n ld ans = cross(p, l.a, l.b);\n return fabsl(ans) / dis(l.a, l.b); // 面积除以底边长\n }\n else\n {\n if (dot(p - l.a, l.b - l.a) <= 0)\n return dis(p, l.a);\n if (dot(p - l.b, l.a - l.b) <= 0)\n return dis(p, l.b);\n ld ans = cross(p, l.a, l.b);\n return fabsl(ans) / dis(l.a, l.b);\n }\n}\n\nPd lineIntersection(Ld l1, Ld l2, bool seg1 = false, bool seg2 = false) // 两直线/线段相交交点 ok\n{\n ld det = cross(l1.b - l1.a, l2.b - l2.a);\n if (sign(det) == 0) // 1. 平行或共线\n {\n if (sign(cross(l2.a - l1.a, l1.b - l1.a)) != 0) // 如果不共线 -> 平行\n return Pd(1e18, 1e18);\n\n if (pointOnSegment(l1.a, l2)) // 共线情况:检查端点是否重合/相连\n return l1.a;\n if (pointOnSegment(l1.b, l2))\n return l1.b;\n if (pointOnSegment(l2.a, l1))\n return l2.a;\n if (pointOnSegment(l2.b, l1))\n return l2.b;\n return Pd(1e18, 1e18); // 完全不相交\n }\n\n ld t = cross(l2.a - l1.a, l2.b - l2.a) / det; // 2. 一般情况,唯一交点 ✅\n Pd inter = l1.a + (l1.b - l1.a) * t;\n\n if ((seg1 && !pointOnSegment(inter, l1)) || (seg2 && !pointOnSegment(inter, l2)))\n return Pd(1e18, 1e18); // 不在线段上\n\n return inter;\n}\n\nPd project(Pd p, Ld l, bool isSegment = false) // 点在直线/线段上的投影点(垂足)ok\n{\n Pd h = l.b - l.a;\n ld r = dot(h, p - l.a) / (h.x * h.x + h.y * h.y);\n Pd pro = l.a + h * r;\n if (isSegment)\n {\n if (dot(pro - l.a, l.b - l.a) < 0)\n return l.a;\n if (dot(pro - l.b, l.a - l.b) < 0)\n return l.b;\n }\n return pro;\n}\n\n// ///////////////////////////////////////////////////////////////////////////////////////// 多边形\n\nusing Polygon = vector<Point<ld>>;\nld area(vector<Pd> P) // 任意多边形的面积 ok\n{\n int n = P.size();\n ld ans = 0;\n for (int i = 0; i < n; i++)\n {\n ans += cross(P[i], P[(i + 1) % n]);\n }\n return ans / 2.0;\n}\nint contains(Polygon g, Point<ld> p) // 点与多边形位置关系 内2 上1 外0 ok\n{\n int n = g.size();\n bool x = false;\n for (int i = 0; i < n; i++)\n {\n Point<ld> a = g[i] - p, b = g[(i + 1) % n] - p;\n if (abs(cross(a, b)) < eps && dot(a, b) < eps)\n return 1;\n if (a.y > b.y)\n swap(a, b);\n if (a.y < eps && eps < b.y && cross(a, b) > eps)\n x = !x;\n }\n return (x ? 2 : 0);\n}\nbool isConvexHull(Polygon p) // 是否为凸包 ok\n{\n int n = p.size();\n int same[2] = {};\n for (int i = 0; i < n; i++)\n {\n int l = (i + n - 1) % n, r = (i + 1) % n;\n if (sign(cross(p[l] - p[i], p[r] - p[i])) <= 0)\n same[0] = 1;\n else\n same[1] = 1;\n }\n return same[0] + same[1] < 2;\n}\n\nPolygon getHull(Polygon p) // 点集求凸包 <=不选共线点 <选共线点 ok\n{\n Polygon h, l;\n sort(p.begin(), p.end());\n p.erase(unique(p.begin(), p.end()), p.end());\n if (p.size() <= 1)\n return p;\n for (auto a : p)\n {\n while (h.size() > 1 && cross(a - h.back(), a - h[h.size() - 2]) <= 0) //\n h.pop_back();\n while (l.size() > 1 && cross(a - l.back(), a - l[l.size() - 2]) >= 0) //\n l.pop_back();\n l.push_back(a);\n h.push_back(a);\n }\n l.pop_back();\n reverse(h.begin(), h.end());\n h.pop_back();\n l.insert(l.end(), h.begin(), h.end());\n return l;\n}\n\nPolygon sortConvexHullCCW(Polygon h) // 将凸包点集按逆时针排序,从y最小(y相同则x最小)的点开始 ok\n{\n int pos = 0;\n for (int i = 0; i < h.size(); i++)\n {\n if (h[i].y < h[pos].y)\n pos = i;\n else if (h[i].y == h[pos].y)\n {\n if (h[i].x < h[pos].x)\n pos = i;\n }\n }\n rotate(h.begin(), h.begin() + pos, h.end());\n return h;\n}\n\nld diameter(Polygon h) // 旋转卡壳求凸包直径 ok\n{\n auto poly = h;\n if (poly.size() == 1)\n return 0;\n if (poly.size() == 2)\n return len(poly[1] - poly[0]);\n if (poly.size() == 3)\n return max({len(poly[1] - poly[0]), len(poly[2] - poly[1]), len(poly[0] - poly[2])});\n\n size_t cur = 0;\n ld ans = 0;\n for (size_t i = 0; i < poly.size(); i++)\n {\n size_t j = (i + 1) % poly.size();\n Line<ld> line(poly[i], poly[j]);\n while (disPointToLine(poly[cur], line) <= disPointToLine(poly[(cur + 1) % poly.size()], line))\n {\n cur = (cur + 1) % poly.size();\n }\n ans = max(ans, max(len(poly[i] - poly[cur]), len(poly[j] - poly[cur])));\n }\n return ans;\n}\n\nld ClosestPair(vector<Pd> &p, int l, int r) // 最近点对 先排序\n{\n if (l == r)\n return 1e18;\n if (l + 1 == r)\n return dis(p[l], p[r]);\n int mid = l + r >> 1;\n ld ans = min(ClosestPair(p, l, mid), ClosestPair(p, mid + 1, r));\n\n vector<Pd> b;\n for (int i = l; i <= r; i++)\n if (fabsl(p[i].x - p[mid].x) < ans)\n b.push_back(p[i]);\n\n sort(b.begin(), b.end(), [](Pd &e1, Pd &e2)\n { return e1.y <= e2.y; });\n int m = b.size();\n for (int i = 0; i < m; i++)\n for (int j = i + 1; j < m && dis(b[i], b[j]) < ans; j++)\n ans = min(ans, dis(b[i], b[j]));\n return ans;\n}\nvoid _()\n{\n int n;\n cin >> n;\n\n vector<Pd> p(n);\n for (auto &v : p)\n cin >> v;\n\n sort(p.begin(), p.end());\n ld ans = ClosestPair(p, 0, n - 1);\n cout << ans << '\\n';\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 12284, "score_of_the_acc": -0.6085, "final_rank": 13 }, { "submission_id": "aoj_CGL_5_A_10839125", "code_snippet": "#include<iostream>\n#include<iomanip>\n#include<cmath>\n#include<algorithm>\n#include<vector>\n\nusing namespace std;\n\nstruct point\n{\n double x, y;\n};\n\nbool cmp_x(const point& a, const point& b)\n{\n if(a.x != b.x) return a.x < b.x;\n else return a.y < b.y;\n}\n\nbool cmp_y(const point& a, const point& b)\n{\n if(a.y != b.y) return a.y < b.y;\n else return a.x < b.x;\n}\n\ndouble dist(point& a, point& b)\n{\n return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\ndouble dnc(vector<point>& half_space, vector<point>& half_space_y)\n{\n double min_dist = 1e9;\n point mid;\n vector<point> left, left_y, right, right_y, merge_y;\n\n if(half_space.size() < 2) return 1e9;\n\n mid = half_space[half_space.size() >> 1];\n for(int i = 0; i < half_space.size(); ++i)\n {\n if(half_space[i].x < mid.x) left.push_back(half_space[i]);\n else right.push_back(half_space[i]);\n if(half_space_y[i].x < mid.x) left_y.push_back(half_space_y[i]);\n else right_y.push_back(half_space_y[i]);\n }\n if(!left.empty()) min_dist = min(dnc(left, left_y), dnc(right, right_y));\n\n for(int i = 0; i < half_space_y.size(); ++i) if(fabs(half_space_y[i].x - mid.x) <= min_dist) merge_y.push_back(half_space_y[i]);\n for(int i = 0; i < merge_y.size(); ++i)\n {\n for(int j = i + 1; j < merge_y.size(); ++j)\n {\n if(merge_y[j].y - merge_y[i].y > min_dist) break;\n min_dist = min(min_dist, dist(merge_y[i], merge_y[j]));\n }\n }\n return min_dist;\n}\n\nint main()\n{\n int n;\n vector<point> space, space_y;\n cin >> n;\n for(int i = 0; i < n; ++i)\n {\n point now;\n cin >> now.x >> now.y;\n space.push_back(now);\n space_y.push_back(now);\n }\n sort(space.begin(), space.end(), cmp_x);\n sort(space_y.begin(), space_y.end(), cmp_y);\n cout << fixed << setprecision(7) << dnc(space, space_y) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 13356, "score_of_the_acc": -0.7579, "final_rank": 16 } ]
aoj_NTL_1_C_cpp
Least Common Multiple Find the least common multiple (LCM) of given n integers. Input n a 1 a 2 ... a n n is given in the first line. Then, n integers are given in the second line. Output Print the least common multiple of the given integers in a line. Constraints 2 ≤ n ≤ 10 1 ≤ a i ≤ 1000 Product of given integers a i ( i = 1, 2, ... n ) does not exceed 2 31 -1 Sample Input 1 3 3 4 6 Sample Output 1 12 Sample Input 2 4 1 2 3 5 Sample Output 2 30
[ { "submission_id": "aoj_NTL_1_C_8308574", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\nint main() {\n int n;\n cin >> n;\n \n vector<int> nums(n);\n cin >> nums[0];\n for (int i = 1; i < n; i++) {\n cin >> nums[i];\n int a = nums[i];\n int b = nums[i - 1];\n int f = a * b;\n \n while (1) {\n if (a > b) a = a - b;\n if (a < b) b = b - a;\n if (a == b) break;\n }\n f /= a;\n nums[i] = f;\n } \n cout << nums.back() << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 3132, "score_of_the_acc": -1.4573, "final_rank": 7 }, { "submission_id": "aoj_NTL_1_C_8300733", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\nint main(){\n\tint n,a,b;\n\tcin>>n;\n\tcin>>b;\n\tfor(int i=0;i<n-1;i++){\n\t\tcin>>a;\n\t\tint ans=a*b;\n\t\twhile(true){\n\t\t\tif(a>b)\n\t\t\t\ta-=b;\n\t\t\tif(a<b)\n\t\t\t\tb-=a;\n\t\t\tif(a==b)\n\t\t\t\tbreak;\n\t\t}\n\t\tans/=a;\n\t\tb=ans;\n\t}\n\tcout<<b<<endl;\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3136, "score_of_the_acc": -0.8623, "final_rank": 4 }, { "submission_id": "aoj_NTL_1_C_8298263", "code_snippet": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n \n vector<int> nums(n);\n cin >> nums[0];\n \n for (int i = 1; i < n; i++) {\n cin >> nums[i];\n int a = nums[i];\n int b = nums[i - 1];\n int f = a * b;\n \n while (1) {\n if (a > b) a = a - b;\n if (a < b) b = b - a;\n if (a == b) break;\n }\n \n f /= a;\n nums[i] = f;\n }\n \n cout << nums.back() << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 3136, "score_of_the_acc": -1.4623, "final_rank": 8 }, { "submission_id": "aoj_NTL_1_C_8298152", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main() {\n int n;\n cin >> n;\n vector<int> num(n);\n cin >> num[0];\n for (int i = 1; i < n; i++) {\n cin >> num[i];\n int a = num[i];\n int b = num[i - 1];\n int fin = a * b;\n while (1) {\n if (a > b) a = a - b;\n if (a < b) b = b - a;\n if (a == b) break;\n }\n fin /= a;\n num[i] = fin;\n }\n cout << num.back() << endl;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 3136, "score_of_the_acc": -1.4623, "final_rank": 8 }, { "submission_id": "aoj_NTL_1_C_8287178", "code_snippet": "#include<stdio.h>\nint main(){\nint n;\nscanf(\"%d\",&n);\nint a[n];\nfor(int i=0;i<n;i++){\n scanf(\"%d\",&a[i]);\n}\nint result=a[0];\nfor(int i=1;i<n;i++){\n int x=result,y=a[i];\n while(x!=y){\n if(x>y){\n x-=y;\n }else{\n y-=x;\n }\n }\n result=(a[i]*result)/x;\n}\nprintf(\"%d\\n\",result);\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2768, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_NTL_1_C_8287106", "code_snippet": "#include <stdio.h>\n\nint main() {\n int n;\n scanf(\"%d\", &n);\n\n int integers[n];\n for (int i = 0; i < n; i++) {\n scanf(\"%d\", &integers[i]);\n }\n\n int result = integers[0];\n for (int i = 1; i < n; i++) {\n int a = result, b = integers[i];\n while (a != b) (a > b) ? (a -= b) : (b -= a);\n result = (integers[i] * result) / a;\n }\n\n printf(\"%d\\n\", result);\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2768, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_NTL_1_C_8287104", "code_snippet": "#include <stdio.h>\n\nint main() {\n int n;\n scanf(\"%d\", &n);\n\n int integers[n];\n for (int i = 0; i < n; i++) {\n scanf(\"%d\", &integers[i]);\n }\n\n int result = integers[0];\n for (int i = 1; i < n; i++) {\n int a = result;\n int b = integers[i];\n\n // Calculate GCD without using a user-defined function\n while (a != b) {\n if (a > b) {\n a -= b;\n } else {\n b -= a;\n }\n }\n\n // Calculate LCM using GCD\n result = (integers[i] * result) / a;\n }\n\n printf(\"%d\\n\", result);\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2768, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_NTL_1_C_8283966", "code_snippet": "#include <iostream>\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int i,j,k,n;\n cin>>n;\n int ara[n];\n for(i=0;i<n;i++){\n cin>>ara[i];\n }\n sort(ara,ara+n);\n k=*max_element(ara,ara+n);\n for(j=k;;j+=k){\n int p=0;\n for(i=0;i<n;i++){\n if(j%ara[i]==0){\n p=1;\n }\n else{\n p=0;\n break;\n }\n }\n if(p==1){\n cout<<j<<endl;\n break;\n }\n }\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3180, "score_of_the_acc": -1.0176, "final_rank": 5 }, { "submission_id": "aoj_NTL_1_C_7043909", "code_snippet": "#include <iostream>\n\nusing namespace std;\n\nconst int N = 10;\n\nint main(){\n int n, num;\n int max = 0;\n int List_num[N];\n\n scanf(\"%d\", &n);\n\n /*配列の初期化*/\n for (int i = 0; i < N; i++){\n List_num[i] = 0;\n }\n\n /*配列の要素入力*/\n for (int i = 0; i < n; i++){\n scanf(\"%d\", &num);\n List_num[i] = (num);\n if (max < num){\n max = num;\n }\n }\n\n /*LCM導出*/\n int count = 1;\n int flag = 0;\n while(true){\n for (int i = 0; i < n; i++){\n if ((max*count) % List_num[i] != 0){\n //cout << max*count << \" : \" << List_num[i] << endl;\n count += 1;\n break;\n }\n else if(i == n-1){\n cout << max * count << endl;\n flag = 1;\n }\n }\n if (flag == 1) break;\n }\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3496, "score_of_the_acc": -1.3146, "final_rank": 6 }, { "submission_id": "aoj_NTL_1_C_6771986", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std ;\n#define MAX 1e9\n#define NIL -2000000002\n#define INF 2000000002\n#define MAXN 123456\ntypedef long long int ll;\nconst int debug = 0 ; \nconst int debug1 = 0 ; \n#define REP(i,n) for(int i=0; i<(int)n; i++)\n\nint gcd (int u , int v){\n if ( u<v) swap(u,v);\n if (v==0 ) {return u;}\n while ( u-v >=0) {\n u -= v ;\n } \n return gcd(v,u);\n}\n\nint lcm(int u,int v){\n int g = gcd(u,v);\n return g*(u/g)*(v/g); \n}\n\nint main() {\n int n;\n vector<int> v;\n int a;\n int res=0;\n scanf (\"%d\", &n);\n REP(i,n) {\n scanf (\"%d\", &a);\n v.push_back(a);\n }\n while (v.size()>=2) {\n int u = v.size();\n res = lcm(v.at(u-1),v.at(u-2)); \n v.pop_back();\n v.pop_back();\n v.push_back(res);\n }\n printf (\"%d\\n\",res);\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3564, "score_of_the_acc": -1.5, "final_rank": 10 } ]
aoj_NTL_1_A_cpp
Prime Factorization Factorize a given integer n . Input n An integer n is given in a line. Output Print the given integer n and : . Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a space before each prime factor. Constraints 2 ≤ n ≤ 10 9 Sample Input 1 12 Sample Output 1 12: 2 2 3 Sample Input 2 126 Sample Output 2 126: 2 3 3 7
[ { "submission_id": "aoj_NTL_1_A_10778330", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n int l = n;\n int i = 3;\n int flag = 0;\n cout << n << \":\";\n while (n % 2 == 0) {\n cout << \" 2\";\n n /= 2;\n }\n\n while(n != 1)\n {\n if(n%i == 0)\n {\n while(n%i==0)\n {\n cout << \" \" << i;\n n /= i;\n }\n }\n i+=2;\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 850, "memory_kb": 3440, "score_of_the_acc": -1.0091, "final_rank": 5 }, { "submission_id": "aoj_NTL_1_A_10738662", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n #define int long long\n int N;\n cin>>N;\n vector<int> A;\n int now=N;\n for(int i=2;i<=100000000;i++){\n while(now%i==0){\n now/=i;\n A.push_back(i);\n }\n }\n if(now!=1) A.push_back(now);\n cout<<N<<\": \";\n for(int i=0;i<A.size();i++){\n cout<<A[i]<<(i==A.size()-1?\"\":\" \");\n }\n cout<<endl;\n}", "accuracy": 1, "time_ms": 610, "memory_kb": 3460, "score_of_the_acc": -0.7238, "final_rank": 2 }, { "submission_id": "aoj_NTL_1_A_10351236", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/6/NTL/1/NTL_1_A\n// 2025年04月05日 23時04分10秒\n// https://onlinejudge.u-aizu.ac.jp/courses/library/6/NTL/1/NTL_1_A\n// 2025年04月05日 22時53分22秒\n#include <bits/stdc++.h>\n// #include <atcoder/all>\n// using namespace atcoder;\n// using mint = modint998244353;\n// using mint = modint1000000007;\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define rep(i, n) for (long long int i = 0; i < (n); ++i)\n#define rep2(i, k, n) for (long long int i = (k); i < (n); ++i)\nusing namespace std;\nusing ll = long long;\nusing vint = vector<int>;\nusing vll = vector<ll>;\nusing vvint = vector<vector<int>>;\nusing vvll = vector<vector<ll>>;\n\n// const ll INF = (ll)2e18+9;\nconst int INF = (int)2e9 + 7;\n\ntemplate <typename T>\nvoid chmin(T& a, T b) {\n a = min(a, b);\n}\ntemplate <typename T>\nvoid chmax(T& a, T b) {\n a = max(a, b);\n}\n\ntemplate <typename T>\nvoid print(vector<T> v) {\n int n = v.size();\n rep(i, n) {\n if (i == 0)\n cout << v[i];\n else\n cout << ' ' << v[i];\n }\n cout << endl;\n}\n\nvoid yesno(bool x) {\n cout << (x ? \"Yes\" : \"No\") << '\\n';\n}\n\nvoid solve();\n\nint main() {\n solve();\n return 0;\n}\n\n// prime, cnt\nvector<pair<ll, ll>> factor(ll n) {\n vector<pair<ll, ll>> ps;\n ll t = n;\n for (int i = 2; i * i <= n; i++) {\n if (t % i == 0) {\n ll cnt = 0;\n while (t % i == 0) {\n t /= i;\n cnt++;\n }\n ps.emplace_back(i, cnt);\n }\n }\n if (t > 1)\n ps.emplace_back(t, 1);\n\n return ps;\n}\n\n// https://qiita.com/drken/items/3beb679e54266f20ab63#4-%E6%B4%BB%E7%94%A8%E4%BE%8B-1-%E9%AB%98%E9%80%9F%E7%B4%A0%E5%9B%A0%E6%95%B0%E5%88%86%E8%A7%A3%E9%AB%98%E9%80%9F%E7%B4%84%E6%95%B0%E5%88%97%E6%8C%99\nstruct Sieve {\n vector<bool> isprime;\n\n // 整数 i を割り切る最小の素数\n vector<int> minfactor;\n\n Sieve(int N) : isprime(N + 1, true),\n minfactor(N + 1, -1) {\n isprime[1] = false;\n minfactor[1] = 1;\n\n for (int p = 2; p <= N; ++p) {\n // すでに合成数であるものはスキップする\n if (!isprime[p])\n continue;\n\n // p についての情報更新\n minfactor[p] = p;\n\n // p 以外の p の倍数から素数ラベルを剥奪\n for (int q = p * 2; q <= N; q += p) {\n // q は合成数なのでふるい落とす\n isprime[q] = false;\n\n // q は p で割り切れる旨を更新\n if (minfactor[q] == -1)\n minfactor[q] = p;\n }\n }\n }\n\n // 高速素因数分解\n // pair (素因子, 指数) の vector を返す\n vector<pair<ll, ll>> factorize(int n) {\n vector<pair<ll, ll>> res;\n while (n > 1) {\n int p = minfactor[n];\n int exp = 0;\n\n // n で割り切れる限り割る\n while (minfactor[n] == p) {\n n /= p;\n ++exp;\n }\n res.emplace_back(p, exp);\n }\n return res;\n }\n\n // 高速約数列挙\n vector<int> divisors(int n) {\n vector<int> res({1});\n\n // n を素因数分解 (メンバ関数使用)\n auto pf = factorize(n);\n\n // 約数列挙\n for (auto p : pf) {\n int s = (int)res.size();\n for (int i = 0; i < s; ++i) {\n int v = 1;\n for (int j = 0; j < p.second; ++j) {\n v *= p.first;\n res.push_back(res[i] * v);\n }\n }\n }\n return res;\n }\n};\n\nvoid solve() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n Sieve sieve((int)1e7);\n\n ll n;\n cin >> n;\n cout << n << \":\";\n\n vector<pair<ll, ll>> ps;\n if (n < (int)1e7) {\n ps = sieve.factorize(n);\n } else {\n ps = factor(n);\n }\n for (auto [x, cnt] : ps) {\n rep(i, cnt) {\n cout << ' ' << x;\n }\n }\n cout << endl;\n}", "accuracy": 1, "time_ms": 130, "memory_kb": 43712, "score_of_the_acc": -1.1429, "final_rank": 6 }, { "submission_id": "aoj_NTL_1_A_10351199", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/6/NTL/1/NTL_1_A\n// 2025年04月05日 22時53分22秒\n#include <bits/stdc++.h>\n// #include <atcoder/all>\n// using namespace atcoder;\n// using mint = modint998244353;\n// using mint = modint1000000007;\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define rep(i, n) for (long long int i = 0; i < (n); ++i)\n#define rep2(i, k, n) for (long long int i = (k); i < (n); ++i)\nusing namespace std;\nusing ll = long long;\nusing vint = vector<int>;\nusing vll = vector<ll>;\nusing vvint = vector<vector<int>>;\nusing vvll = vector<vector<ll>>;\n\n// const ll INF = (ll)2e18+9;\nconst int INF = (int)2e9 + 7;\n\ntemplate <typename T>\nvoid chmin(T& a, T b) {\n a = min(a, b);\n}\ntemplate <typename T>\nvoid chmax(T& a, T b) {\n a = max(a, b);\n}\n\ntemplate <typename T>\nvoid print(vector<T> v) {\n int n = v.size();\n rep(i, n) {\n if (i == 0)\n cout << v[i];\n else\n cout << ' ' << v[i];\n }\n cout << endl;\n}\n\nvoid yesno(bool x) {\n cout << (x ? \"Yes\" : \"No\") << '\\n';\n}\n\nvoid solve();\n\nint main() {\n solve();\n return 0;\n}\n\nvoid solve() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n vll sieve((int)1e6 + 5, -1);\n rep2(i, 2, (int)1e6 + 5) {\n for (ll j = i; j < (int)1e6 + 5; j += i) {\n if (sieve[j] < 0)\n sieve[j] = i;\n }\n }\n\n auto factor = [&](ll x) -> vector<pair<ll, ll>> {\n vector<pair<ll, ll>> ans;\n while (x > 1) {\n ll p = sieve[x];\n ll cnt = 0;\n while (x % p == 0) {\n cnt++;\n x /= p;\n }\n\n ans.push_back({p, cnt});\n }\n\n return ans;\n };\n\n ll n;\n cin >> n;\n if (n <= (ll)1e6) {\n auto v = factor(n);\n vll ans;\n for (auto [x, cnt] : v) {\n rep(i, cnt) ans.push_back(x);\n }\n sort(all(ans));\n cout << n << \": \";\n print(ans);\n } else {\n vector<pair<ll, ll>> ps;\n ll t = n;\n cout << n << \":\";\n for (int i = 2; i * i <= n; i++) {\n if (t % i == 0) {\n while (t % i == 0) {\n t /= i;\n cout << ' ' << i;\n }\n }\n }\n if (t > 1)\n cout << ' ' << t;\n cout << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 11240, "score_of_the_acc": -0.201, "final_rank": 1 }, { "submission_id": "aoj_NTL_1_A_10351196", "code_snippet": "// https://onlinejudge.u-aizu.ac.jp/courses/library/6/NTL/1/NTL_1_A\n// 2025年04月05日 22時53分22秒\n#include <bits/stdc++.h>\n// #include <atcoder/all>\n// using namespace atcoder;\n// using mint = modint998244353;\n// using mint = modint1000000007;\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define rep(i, n) for (long long int i = 0; i < (n); ++i)\n#define rep2(i, k, n) for (long long int i = (k); i < (n); ++i)\nusing namespace std;\nusing ll = long long;\nusing vint = vector<int>;\nusing vll = vector<ll>;\nusing vvint = vector<vector<int>>;\nusing vvll = vector<vector<ll>>;\n\n// const ll INF = (ll)2e18+9;\nconst int INF = (int)2e9 + 7;\n\ntemplate <typename T>\nvoid chmin(T& a, T b) {\n a = min(a, b);\n}\ntemplate <typename T>\nvoid chmax(T& a, T b) {\n a = max(a, b);\n}\n\ntemplate <typename T>\nvoid print(vector<T> v) {\n int n = v.size();\n rep(i, n) {\n if (i == 0)\n cout << v[i];\n else\n cout << ' ' << v[i];\n }\n cout << endl;\n}\n\nvoid yesno(bool x) {\n cout << (x ? \"Yes\" : \"No\") << '\\n';\n}\n\nvoid solve();\n\nint main() {\n solve();\n return 0;\n}\n\nvoid solve() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n\n vll sieve((int)1e6 + 5, -1);\n rep2(i, 2, (int)1e6 + 5) {\n for (ll j = i; j < (int)1e6 + 5; j += i) {\n if (sieve[j] < 0)\n sieve[j] = i;\n }\n }\n\n auto factor = [&](ll x) -> vector<pair<ll, ll>> {\n vector<pair<ll, ll>> ans;\n while (x > 1) {\n ll p = sieve[x];\n ll cnt = 0;\n while (x % p == 0) {\n cnt++;\n x /= p;\n }\n\n ans.push_back({p, cnt});\n }\n\n return ans;\n };\n\n ll n;\n cin >> n;\n if (n <= (ll)1e6) {\n auto v = factor(n);\n vll ans;\n for (auto [x, cnt] : v) {\n rep(i, cnt) ans.push_back(x);\n }\n sort(all(ans));\n cout << n << \": \";\n print(ans);\n } else {\n vector<pair<ll, ll>> ps;\n ll t = n;\n cout << n << \":\";\n for (int i = 2; i * i <= n; i++) {\n if (t % i == 0) {\n while (t % i == 0) {\n t /= i;\n cout << ' ' << i;\n }\n }\n }\n if (t)\n cout << ' ' << t;\n cout << endl;\n }\n}", "accuracy": 0.5833333333333334, "time_ms": 10, "memory_kb": 11240, "score_of_the_acc": -0.201, "final_rank": 7 }, { "submission_id": "aoj_NTL_1_A_10327035", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n\n cout << n << \":\";\n while (1) {\n if (n % 2) {\n break;\n } else {\n cout << \" \" << 2;\n n /= 2;\n }\n }\n if (n == 1) {\n cout << endl;\n return 0;\n }\n int i = 3;\n while (1) {\n if (n % i) {\n i += 2;\n } else {\n cout << \" \" << i;\n n = n / i;\n if (n == 1) break;\n }\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 650, "memory_kb": 3584, "score_of_the_acc": -0.7745, "final_rank": 4 }, { "submission_id": "aoj_NTL_1_A_10269514", "code_snippet": "#include <stdio.h>\nint main() {\n int n;\n scanf(\"%d\", &n);\n\n int i = 2;\n printf(\"%d:\",n);\n\n for (;;) {\n if (n == 1) {\n break;\n }\n if (n % i == 0) {\n n = n / i;\n printf(\" %d\",i);\n }\n else {\n if(i == 2){\n i++;\n }else{\n i += 2; \n }\n }\n\n }\n printf(\"\\n\");\n return 0;\n}", "accuracy": 1, "time_ms": 650, "memory_kb": 3072, "score_of_the_acc": -0.7619, "final_rank": 3 } ]
aoj_CGL_6_A_cpp
Segment Intersections: Manhattan Geometry For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them. Input In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format: $x_1 \; y_1 \; x_2 \; y_2$ The coordinates are given in integers. Output Print the number of intersections in a line. Constraints $1 \leq n \leq 100,000$ $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$ Two parallel segments never overlap or touch. The number of intersections $\leq 1,000,000$ Sample Input 1 6 2 2 2 5 1 3 5 3 4 1 4 4 5 2 7 2 6 1 6 3 6 5 6 7 Sample Output 1 3
[ { "submission_id": "aoj_CGL_6_A_11047895", "code_snippet": "// --- Start of include: ./../../akakoi_lib/template/template.cpp ---\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i,n) for(ll i=0;i<(ll)(n);++i)\nbool chmin(auto& a, auto b) {return a>b?a=b,1:0;}\nbool chmax(auto& a, auto b) {return a<b?a=b,1:0;}\n// int main() {\n// ios::sync_with_stdio(false);\n// cin.tie(0);\n// }\n// --- End of include: ./../../akakoi_lib/template/template.cpp ---\n// --- Start of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n/// @brief 幾何ライブラリ\nnamespace Geometry {\n using Real = long double;\n const Real EPS = 1e-9;\n\n bool almostEqual(Real a, Real b) { return abs(a - b) < EPS; }\n bool lessThan(Real a, Real b) { return a < b && !almostEqual(a, b); }\n bool greaterThan(Real a, Real b) { return a > b && !almostEqual(a, b); }\n bool lessThanOrEqual(Real a, Real b) { return a < b || almostEqual(a, b); }\n bool greaterThanOrEqual(Real a, Real b) { return a > b || almostEqual(a, b); }\n\n /// @brief 2次元平面上の位置ベクトル\n struct Point {\n Real x, y;\n Point() = default;\n Point(Real x, Real y) : x(x), y(y) {}\n\n Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); }\n Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); }\n Point operator*(Real k) const { return Point(x * k, y * k); }\n Point operator/(Real k) const { return Point(x / k, y / k); }\n\n /// @brief p との内積を返す\n Real dot(const Point& p) const { return x * p.x + y * p.y; }\n\n /// @brief p との外積を返す\n Real cross(const Point& p) const { return x * p.y - y * p.x; }\n\n /// @brief p1 と p2 を端点とするベクトルとの外積を返す\n Real cross(const Point& p1, const Point& p2) const { return (p1.x - x) * (p2.y - y) - (p1.y - y) * (p2.x - x); }\n\n /// @brief 2乗ノルムを返す\n Real norm() const { return x * x + y * y; }\n\n /// @brief ユークリッドノルムを返す\n Real abs() const { return sqrt(norm()); }\n\n /// @brief 偏角を返す\n Real arg() const { return atan2(y, x); }\n\n bool operator==(const Point& p) const { return almostEqual(x, p.x) && almostEqual(y, p.y); }\n friend istream& operator>>(istream& is, Point& p) { return is >> p.x >> p.y; }\n };\n\n /// @brief 直線\n struct Line {\n Point a, b;\n Line() = default;\n Line(const Point& _a, const Point& _b) : a(_a), b(_b) {}\n\n /// @brief 直線 Ax+By=C を定義する\n Line(const Real& A, const Real& B, const Real& C) {\n if (almostEqual(A, 0)) {\n assert(!almostEqual(B, 0));\n a = Point(0, C / B);\n b = Point(1, C / B);\n } else if (almostEqual(B, 0)) {\n a = Point(C / A, 0);\n b = Point(C / A, 1);\n } else if (almostEqual(C, 0)) {\n a = Point(0, C / B);\n b = Point(1, (C - A) / B);\n } else {\n a = Point(0, C / B);\n b = Point(C / A, 0);\n }\n }\n\n bool operator==(const Line& l) const { return a == l.a && b == l.b; }\n friend istream& operator>>(istream& is, Line& l) { return is >> l.a >> l.b; }\n };\n\n /// @brief 線分\n struct Segment : Line {\n Segment() = default;\n using Line::Line;\n };\n\n /// @brief 円\n struct Circle {\n Point center; ///< 中心\n Real r; ///< 半径\n\n Circle() = default;\n Circle(Real x, Real y, Real r) : center(x, y), r(r) {}\n Circle(Point _center, Real r) : center(_center), r(r) {}\n\n bool operator==(const Circle& C) const { return center == C.center && r == C.r; }\n friend istream& operator>>(istream& is, Circle& C) { return is >> C.center >> C.r; }\n };\n\n //-----------------------------------------------------------\n\n /// @brief 3点の進行方向\n enum Orientation {\n COUNTER_CLOCKWISE, ///< 反時計回り\n CLOCKWISE, ///< 時計回り\n ONLINE_BACK,\n ONLINE_FRONT,\n ON_SEGMENT\n };\n\n /// @brief 3点 p0, p1, p2 の進行方向を返す\n Orientation ccw(const Point& p0, const Point& p1, const Point& p2) {\n Point a = p1 - p0;\n Point b = p2 - p0;\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) return COUNTER_CLOCKWISE;\n if (lessThan(cross_product, 0)) return CLOCKWISE;\n if (lessThan(a.dot(b), 0)) return ONLINE_BACK;\n if (lessThan(a.norm(), b.norm())) return ONLINE_FRONT;\n return ON_SEGMENT;\n }\n\n string orientationToString(Orientation o) {\n switch (o) {\n case COUNTER_CLOCKWISE:\n return \"COUNTER_CLOCKWISE\";\n case CLOCKWISE:\n return \"CLOCKWISE\";\n case ONLINE_BACK:\n return \"ONLINE_BACK\";\n case ONLINE_FRONT:\n return \"ONLINE_FRONT\";\n case ON_SEGMENT:\n return \"ON_SEGMENT\";\n default:\n return \"UNKNOWN\";\n }\n }\n\n /// @brief ベクトル p の直線 p1, p2 への正射影ベクトルを返す\n Point projection(const Point& p1, const Point& p2, const Point& p) {\n Point base = p2 - p1;\n Real r = (p - p1).dot(base) / base.norm();\n return p1 + base * r;\n }\n\n /// @brief ベクトル p の直線 l への正射影ベクトルを返す\n Point projection(const Line& l, const Point& p) {\n Point base = l.b - l.a;\n Real r = (p - l.a).dot(base) / base.norm();\n return l.a + base * r;\n }\n\n /// @brief ベクトル p の直線 p1, p2 に対する鏡像ベクトルを返す\n Point reflection(const Point& p1, const Point& p2, const Point& p) {\n Point proj = projection(p1, p2, p);\n return proj * 2 - p;\n }\n\n /// @brief ベクトル p の直線 l に対する鏡像ベクトルを返す\n Point reflection(const Line& l, const Point& p) {\n Point proj = projection(l, p);\n return proj * 2 - p;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 直線の平行判定\n bool isParallel(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線の直交判定\n bool isOrthogonal(const Line& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分の平行判定\n bool isParallel(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分の直交判定\n bool isOrthogonal(const Segment& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 直線と線分の平行判定\n bool isParallel(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 直線と線分の直交判定\n bool isOrthogonal(const Line& l1, const Segment& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 線分と直線の平行判定\n bool isParallel(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).cross(l2.b - l2.a), 0); }\n /// @brief 線分と直線の直交判定\n bool isOrthogonal(const Segment& l1, const Line& l2) { return almostEqual((l1.b - l1.a).dot(l2.b - l2.a), 0); }\n /// @brief 点が直線上にあるか判定\n bool isPointOnLine(const Point& p, const Line& l) { return almostEqual((l.b - l.a).cross(p - l.a), 0.0); }\n\n /// @brief 点が線分上にあるか判定\n bool isPointOnSegment(const Point& p, const Segment& s) {\n return lessThanOrEqual(min(s.a.x, s.b.x), p.x) &&\n lessThanOrEqual(p.x, max(s.a.x, s.b.x)) &&\n lessThanOrEqual(min(s.a.y, s.b.y), p.y) &&\n lessThanOrEqual(p.y, max(s.a.y, s.b.y)) &&\n almostEqual((s.b - s.a).cross(p - s.a), 0.0);\n }\n\n /// @brief 直線の交差判定\n bool isIntersecting(const Segment& s1, const Segment& s2) {\n Point p0p1 = s1.b - s1.a, p0p2 = s2.a - s1.a, p0p3 = s2.b - s1.a, p2p3 = s2.b - s2.a, p2p0 = s1.a - s2.a, p2p1 = s1.b - s2.a;\n Real d1 = p0p1.cross(p0p2), d2 = p0p1.cross(p0p3), d3 = p2p3.cross(p2p0), d4 = p2p3.cross(p2p1);\n if (lessThan(d1 * d2, 0) && lessThan(d3 * d4, 0)) return true;\n if (almostEqual(d1, 0.0) && isPointOnSegment(s2.a, s1)) return true;\n if (almostEqual(d2, 0.0) && isPointOnSegment(s2.b, s1)) return true;\n if (almostEqual(d3, 0.0) && isPointOnSegment(s1.a, s2)) return true;\n if (almostEqual(d4, 0.0) && isPointOnSegment(s1.b, s2)) return true;\n return false;\n }\n\n /// @brief 線分の交点を返す\n Point getIntersection(const Segment& s1, const Segment& s2) {\n assert(isIntersecting(s1, s2));\n auto cross = [](Point p, Point q) { return p.x * q.y - p.y * q.x; };\n Point base = s2.b - s2.a;\n Real d1 = abs(cross(base, s1.a - s2.a));\n Real d2 = abs(cross(base, s1.b - s2.a));\n Real t = d1 / (d1 + d2);\n return s1.a + (s1.b - s1.a) * t;\n }\n\n /// @brief 点と線分の距離を返す\n Real distancePointToSegment(const Point& p, const Segment& s) {\n Point proj = projection(s.a, s.b, p);\n if (isPointOnSegment(proj, s))\n return (p - proj).abs();\n else\n return min((p - s.a).abs(), (p - s.b).abs());\n }\n\n /// @brief 線分と線分の距離を返す\n Real distanceSegmentToSegment(const Segment& s1, const Segment& s2) {\n if (isIntersecting(s1, s2)) return 0.0;\n return min({distancePointToSegment(s1.a, s2),\n distancePointToSegment(s1.b, s2),\n distancePointToSegment(s2.a, s1),\n distancePointToSegment(s2.b, s1)});\n }\n\n //-----------------------------------------------------------\n\n /// @brief 多角形の面積を返す\n Real getPolygonArea(const vector<Point>& points) {\n int n = points.size();\n Real area = 0.0;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n area += points[i].x * points[j].y;\n area -= points[i].y * points[j].x;\n }\n return abs(area) / 2.0;\n }\n\n /// @brief 多角形が凸か判定\n bool isConvex(const vector<Point>& points) {\n int n = points.size();\n bool has_positive = false, has_negative = false;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n int k = (i + 2) % n;\n Point a = points[j] - points[i];\n Point b = points[k] - points[j];\n Real cross_product = a.cross(b);\n if (greaterThan(cross_product, 0)) has_positive = true;\n if (lessThan(cross_product, 0)) has_negative = true;\n }\n return !(has_positive && has_negative);\n }\n\n /// @brief 点が凸多角形の辺上に存在するか判定\n bool isPointOnPolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n Segment s(a, b);\n if (isPointOnSegment(p, s)) return true;\n }\n return false;\n }\n\n /// @brief 点が多角形の内部に存在するか判定(辺上は含まない)\n bool isPointInsidePolygon(const vector<Point>& polygon, const Point& p) {\n int n = polygon.size();\n bool inPolygon = false;\n for (int i = 0; i < n; i++) {\n Point a = polygon[i];\n Point b = polygon[(i + 1) % n];\n if (greaterThan(a.y, b.y)) swap(a, b);\n if (lessThanOrEqual(a.y, p.y) && lessThan(p.y, b.y) && greaterThan((b - a).cross(p - a), 0)) inPolygon = !inPolygon;\n }\n return inPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 凸包を求める\n vector<Point> convexHull(vector<Point>& points, bool include_collinear = false) {\n int n = points.size();\n if (n <= 1) return points;\n sort(points.begin(), points.end(), [](const Point& l, const Point& r) -> bool {\n if (almostEqual(l.y, r.y)) return lessThan(l.x, r.x);\n return lessThan(l.y, r.y);\n });\n if (n == 2) return points;\n vector<Point> upper = {points[0], points[1]}, lower = {points[0], points[1]};\n for (int i = 2; i < n; i++) {\n while (upper.size() >= 2 && ccw(upper.end()[-2], upper.end()[-1], points[i]) != CLOCKWISE) {\n if (ccw(upper.end()[-2], upper.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n upper.pop_back();\n }\n upper.push_back(points[i]);\n while (lower.size() >= 2 && ccw(lower.end()[-2], lower.end()[-1], points[i]) != COUNTER_CLOCKWISE) {\n if (ccw(lower.end()[-2], lower.end()[-1], points[i]) == ONLINE_FRONT && include_collinear) break;\n lower.pop_back();\n }\n lower.push_back(points[i]);\n }\n reverse(upper.begin(), upper.end());\n upper.pop_back();\n lower.pop_back();\n lower.insert(lower.end(), upper.begin(), upper.end());\n return lower;\n }\n\n /// @brief 凸包の直径を求める\n Real convexHullDiameter(const vector<Point>& hull) {\n int n = hull.size();\n if (n == 1) return 0;\n int k = 1;\n Real max_dist = 0;\n for (int i = 0; i < n; i++) {\n while (true) {\n int j = (k + 1) % n;\n Point dist1 = hull[i] - hull[j], dist2 = hull[i] - hull[k];\n max_dist = max(max_dist, dist1.abs());\n max_dist = max(max_dist, dist2.abs());\n if (dist1.abs() > dist2.abs())\n k = j;\n else\n break;\n }\n Point dist = hull[i] - hull[k];\n max_dist = max(max_dist, dist.abs());\n }\n return max_dist;\n }\n\n /// @brief 凸包を直線で切断して左側を返す\n vector<Point> cutPolygon(const vector<Point>& g, const Line& l) {\n auto isLeft = [](const Point& p1, const Point& p2, const Point& p) -> bool { return (p2 - p1).cross(p - p1) > 0; };\n vector<Point> newPolygon;\n int n = g.size();\n for (int i = 0; i < n; i++) {\n const Point& cur = g[i];\n const Point& next = g[(i + 1) % n];\n if (isLeft(l.a, l.b, cur)) newPolygon.push_back(cur);\n if ((isLeft(l.a, l.b, cur) && !isLeft(l.a, l.b, next)) || (!isLeft(l.a, l.b, cur) && isLeft(l.a, l.b, next))) {\n Real A1 = (next - cur).cross(l.a - cur);\n Real A2 = (next - cur).cross(l.b - cur);\n Point intersection = l.a + (l.b - l.a) * (A1 / (A1 - A2));\n newPolygon.push_back(intersection);\n }\n }\n return newPolygon;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 最近点対の距離を求める\n /// @note points は x 座標でソートされている必要がある\n Real closestPair(vector<Point>& points, int l, int r) {\n if (r - l <= 1) return numeric_limits<Real>::max();\n int mid = (l + r) >> 1;\n Real x = points[mid].x;\n Real d = min(closestPair(points, l, mid), closestPair(points, mid, r));\n auto iti = points.begin(), itl = iti + l, itm = iti + mid, itr = iti + r;\n inplace_merge(itl, itm, itr, [](const Point& lhs, const Point& rhs) -> bool {\n return lessThan(lhs.y, rhs.y);\n });\n vector<Point> nearLine;\n for (int i = l; i < r; i++) {\n if (greaterThanOrEqual(fabs(points[i].x - x), d)) continue;\n int sz = nearLine.size();\n for (int j = sz - 1; j >= 0; j--) {\n Point dv = points[i] - nearLine[j];\n if (dv.y >= d) break;\n d = min(d, dv.abs());\n }\n nearLine.push_back(points[i]);\n }\n return d;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 線分の交差数を数える\n int countIntersections(vector<Segment> segments) {\n struct Event {\n Real x;\n int type; // 0:horizontal start,1:vertical,2:horizontal end\n Real y1, y2;\n Event(Real x, int type, Real y1, Real y2) : x(x), type(type), y1(y1), y2(y2) {}\n bool operator<(const Event& other) const {\n if (x == other.x) return type < other.type;\n return x < other.x;\n }\n };\n vector<Event> events;\n sort(segments.begin(), segments.end(), [](const Segment& lhs, const Segment& rhs) -> bool {\n return lessThan(min(lhs.a.x, lhs.b.x), min(rhs.a.x, rhs.b.x));\n });\n for (const auto& seg : segments) {\n if (seg.a.y == seg.b.y) {\n // Horizontal segment\n Real y = seg.a.y;\n Real x1 = min(seg.a.x, seg.b.x);\n Real x2 = max(seg.a.x, seg.b.x);\n events.emplace_back(x1, 0, y, y);\n events.emplace_back(x2, 2, y, y);\n } else {\n // Vertical segment\n Real x = seg.a.x;\n Real y1 = min(seg.a.y, seg.b.y);\n Real y2 = max(seg.a.y, seg.b.y);\n events.emplace_back(x, 1, y1, y2);\n }\n }\n sort(events.begin(), events.end());\n set<Real> activeSegments;\n int intersectionCount = 0;\n for (const auto& event : events) {\n if (event.type == 0) {\n // Add horizontal segment to active set\n activeSegments.insert(event.y1);\n } else if (event.type == 2) {\n // Remove horizontal segment from active set\n activeSegments.erase(event.y1);\n } else if (event.type == 1) {\n // Count intersections with vertical segment\n auto lower = activeSegments.lower_bound(event.y1);\n auto upper = activeSegments.upper_bound(event.y2);\n intersectionCount += distance(lower, upper);\n }\n }\n return intersectionCount;\n }\n\n //-----------------------------------------------------------\n\n /// @brief 2つの円の交点の個数を返す\n int countCirclesIntersection(const Circle& c1, const Circle& c2) {\n Real d =\n sqrt((c1.center.x - c2.center.x) * (c1.center.x - c2.center.x) +\n (c1.center.y - c2.center.y) * (c1.center.y - c2.center.y));\n Real r1 = c1.r, r2 = c2.r;\n if (greaterThan(d, r1 + r2))\n return 4;\n else if (almostEqual(d, r1 + r2))\n return 3;\n else if (greaterThan(d, fabs(r1 - r2)))\n return 2;\n else if (almostEqual(d, fabs(r1 - r2)))\n return 1;\n else\n return 0;\n }\n\n /// @brief 内接円を求める\n Circle getInCircle(const Point& A, const Point& B, const Point& C) {\n Real a = (B - C).abs();\n Real b = (A - C).abs();\n Real c = (A - B).abs();\n Real s = (a + b + c) / 2;\n Real area = sqrt(s * (s - a) * (s - b) * (s - c));\n Real r = area / s;\n Real cx = (a * A.x + b * B.x + c * C.x) / (a + b + c);\n Real cy = (a * A.y + b * B.y + c * C.y) / (a + b + c);\n return Circle{Point(cx, cy), r};\n }\n\n /// @brief 外接円を求める\n Circle getCircumCircle(const Point& A, const Point& B, const Point& C) {\n Real D = 2 * (A.x * (B.y - C.y) + B.x * (C.y - A.y) + C.x * (A.y - B.y));\n Real Ux = ((A.x * A.x + A.y * A.y) * (B.y - C.y) + (B.x * B.x + B.y * B.y) * (C.y - A.y) + (C.x * C.x + C.y * C.y) * (A.y - B.y)) / D;\n Real Uy = ((A.x * A.x + A.y * A.y) * (C.x - B.x) + (B.x * B.x + B.y * B.y) * (A.x - C.x) + (C.x * C.x + C.y * C.y) * (B.x - A.x)) / D;\n Point center(Ux, Uy);\n Real radius = (center - A).abs();\n return Circle{center, radius};\n }\n\n /// @brief 円と直線の交点を求める\n vector<Point> getCircleLineIntersection(const Circle& c, Point p1, Point p2) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real dx = p2.x - p1.x;\n Real dy = p2.y - p1.y;\n Real a = dx * dx + dy * dy;\n Real b = 2 * (dx * (p1.x - cx) + dy * (p1.y - cy));\n Real c_const = (p1.x - cx) * (p1.x - cx) + (p1.y - cy) * (p1.y - cy) - r * r;\n Real discriminant = b * b - 4 * a * c_const;\n vector<Point> intersections;\n if (almostEqual(discriminant, 0)) {\n Real t = -b / (2 * a);\n Real ix = p1.x + t * dx;\n Real iy = p1.y + t * dy;\n intersections.emplace_back(ix, iy);\n intersections.emplace_back(ix, iy);\n } else if (discriminant > 0) {\n Real sqrt_discriminant = sqrt(discriminant);\n Real t1 = (-b + sqrt_discriminant) / (2 * a);\n Real t2 = (-b - sqrt_discriminant) / (2 * a);\n Real ix1 = p1.x + t1 * dx;\n Real iy1 = p1.y + t1 * dy;\n Real ix2 = p1.x + t2 * dx;\n Real iy2 = p1.y + t2 * dy;\n intersections.emplace_back(ix1, iy1);\n intersections.emplace_back(ix2, iy2);\n }\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 2つの円の交点を求める\n vector<Point> getCirclesIntersect(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real d = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n if (d > r1 + r2 || d < abs(r1 - r2)) return {}; // No intersection\n Real a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);\n Real h = sqrt(r1 * r1 - a * a);\n Real x0 = x1 + a * (x2 - x1) / d;\n Real y0 = y1 + a * (y2 - y1) / d;\n Real rx = -(y2 - y1) * (h / d);\n Real ry = (x2 - x1) * (h / d);\n Point p1(x0 + rx, y0 + ry);\n Point p2(x0 - rx, y0 - ry);\n vector<Point> intersections;\n intersections.push_back(p1);\n intersections.push_back(p2);\n if (almostEqual(intersections[0].x, intersections[1].x)) {\n if (greaterThan(intersections[0].y, intersections[1].y)) swap(intersections[0], intersections[1]);\n } else if (greaterThan(intersections[0].x, intersections[1].x)) {\n swap(intersections[0], intersections[1]);\n }\n return intersections;\n }\n\n /// @brief 点から引ける円の接線の接点を求める\n vector<Point> getTangentLinesFromPoint(const Circle& c, const Point& p) {\n Real cx = c.center.x, cy = c.center.y, r = c.r;\n Real px = p.x, py = p.y;\n Real dx = px - cx;\n Real dy = py - cy;\n Real d = (p - c.center).abs();\n if (lessThan(d, r))\n return {}; // No tangents if the point is inside the circle\n else if (almostEqual(d, r))\n return {p};\n Real a = r * r / d;\n Real h = sqrt(r * r - a * a);\n Real cx1 = cx + a * dx / d;\n Real cy1 = cy + a * dy / d;\n vector<Point> tangents;\n tangents.emplace_back(cx1 + h * dy / d, cy1 - h * dx / d);\n tangents.emplace_back(cx1 - h * dy / d, cy1 + h * dx / d);\n if (almostEqual(tangents[0].x, tangents[1].x)) {\n if (greaterThan(tangents[0].y, tangents[1].y)) swap(tangents[0], tangents[1]);\n } else if (greaterThan(tangents[0].x, tangents[1].x)) {\n swap(tangents[0], tangents[1]);\n }\n return tangents;\n }\n\n /// @brief 2つの円の共通接線を求める\n vector<Segment> getCommonTangentsLine(const Circle& c1, const Circle& c2) {\n Real x1 = c1.center.x, y1 = c1.center.y, r1 = c1.r;\n Real x2 = c2.center.x, y2 = c2.center.y, r2 = c2.r;\n Real dx = x2 - x1;\n Real dy = y2 - y1;\n Real d = sqrt(dx * dx + dy * dy);\n vector<Segment> tangents;\n // Coincident circles(infinite tangents)\n if (almostEqual(d, 0) && almostEqual(r1, r2)) return tangents;\n // External tangents\n if (greaterThanOrEqual(d, r1 + r2)) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 + r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 + r2 * cos(a + sign * theta);\n Real cy2 = y2 + r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, r1 + r2)) break;\n }\n }\n // Internal tangents\n if (greaterThanOrEqual(d, fabs(r1 - r2))) {\n Real a = atan2(dy, dx);\n for (int sign : {-1, 1}) {\n Real theta = acos((r1 - r2) / d);\n Real cx1 = x1 + r1 * cos(a + sign * theta);\n Real cy1 = y1 + r1 * sin(a + sign * theta);\n Real cx2 = x2 - r2 * cos(a + sign * theta);\n Real cy2 = y2 - r2 * sin(a + sign * theta);\n tangents.emplace_back(Segment{Point(cx1, cy1), Point(cx2, cy2)});\n if (almostEqual(d, fabs(r1 - r2))) break;\n }\n }\n sort(tangents.begin(), tangents.end(), [&](const Segment& s1, const Segment& s2) {\n if (almostEqual(s1.a.x, s2.a.x))\n return lessThan(s1.a.y, s2.a.y);\n else\n return lessThan(s1.a.x, s2.a.x);\n });\n return tangents;\n }\n}\n// --- End of include: ./../../akakoi_lib/geometry/geometry.cpp ---\n\nusing namespace Geometry;\n\nvoid solve() {\n int n; cin >> n;\n vector<Segment> S(n);\n rep(i, n) {\n int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;\n S[i] = Segment(Point(x1, y1), Point(x2, y2));\n }\n cout << countIntersections(S) << endl;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout << fixed << setprecision(10);\n solve();\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 32300, "score_of_the_acc": -0.4579, "final_rank": 18 }, { "submission_id": "aoj_CGL_6_A_10912943", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#if __has_include(<atcoder/all>)\n#include <atcoder/all>\nusing namespace atcoder;\n#endif\n#ifndef ONLINE_JUDGE\n#define _GLIBCXX_DEBUG\n#include <iostream>\ntemplate <typename T, typename U>\nostream& operator<<(ostream& os, const pair<T, U>& p) {return os<<'(' <<p.first<<\", \"<<p.second<<')';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<T>& v) {os<<'[';for(auto it=v.begin();it!=v.end();++it){os<<*it; if(next(it)!=v.end()){os<<\", \";}}return os<<']';}\ntemplate <typename T>\nostream& operator<<(ostream& os, const vector<vector<T>>& vv) {os<<\"[\\n\";for(auto it=vv.begin();it!=vv.end();++it){os<<\" \"<<*it;if(next(it)!=vv.end()){os<<\",\\n\";}else{os<<\"\\n\";}}return os<<\"]\";}\n#define dump(x) cerr << #x << \" = \" << (x) << '\\n'\n#else\n#define dump(x) (void)0\n#endif\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\ntemplate<class T> using pq = priority_queue<T>;\ntemplate<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>;\n#define out(x) cout<<x<<'\\n'\n#define all(v) (v).begin(),(v).end()\n#define rall(v) (v).rbegin(),(v).rend()\n#define OVERLOAD_REP(_1,_2,_3,name,...) name\n#define REP1(i,n) for (auto i = std::decay_t<decltype(n)>{}; (i) < (n); ++(i))\n#define REP2(i, l, r) for (auto i = (l); (i) < (r); ++(i))\n#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)\ntemplate<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};\ntemplate<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};\nconst ll INF=(1LL<<60);\nconst ll mod=998244353;\nusing Graph = vector<vector<ll>>;\nusing Network = vector<vector<pair<ll,ll>>>;\nusing Grid = vector<string>;\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int dx2[8] = {1, 1, 1, 0, 0, -1, -1, -1};\nconst int dy2[8] = {1, 0, -1, 1, -1, 1, 0, -1};\n\n// #include \"../geo.hpp\"\n\n#pragma once\n\nusing D = long double;\nconst D EPS = 1e-12L;\nconst D PI = acosl(-1.0L);\nusing P2 = complex<D>;\nstruct L2{P2 a, b;};\nstruct S2{P2 a, b;};\nusing G2 = vector<P2>;\n\nint sgn(D x){return (x>EPS)-(x<-EPS);}\nint cmp(D a, D b){return sgn(a-b);}\nbool eq(D a, D b){return cmp(a, b)==0;}\nbool lt(D a, D b){return cmp(a, b)<0;}\nbool le(D a, D b){return cmp(a, b)<=0;}\nbool gt(D a, D b){return cmp(a, b)>0;}\nbool ge(D a, D b){return cmp(a, b)>=0;}\nbool eqP2(P2 a, P2 b){return eq(real(a), real(b)) && eq(imag(a), imag(b));}\nbool ltP2(P2 a, P2 b) {\n return lt(real(a), real(b)) || (eq(real(a), real(b)) && lt(imag(a), imag(b)));\n}\n\nD dot(P2 a, P2 b) {return real(conj(a)*b);}\nD cross(P2 a, P2 b) {return imag(conj(a)*b);}\nint ccw(P2 a, P2 b, P2 c) {\n b-=a; c-=a;\n auto cr=cross(b, c), dt=dot(b, c);\n if (cr > EPS) return +1; // counter clockwise\n if (cr < -EPS) return -1; // clockwise\n if (dt < -EPS) return +2; // c--a--b\n if (lt(norm(b), norm(c))) return -2; // a--b--c\n return 0; // a--c--b\n}\nint turn(P2 a, P2 b, P2 c) { return sgn(cross(b - a, c - a)); }\n\nP2 rot(P2 a, D th) { return a*polar<D>(1, th); }\nP2 rot90(P2 a) { return P2(-imag(a), real(a)); }\nbool ltP2Arg(P2 a, P2 b) {\n auto up = [](P2 p) { return (imag(p) > 0 || (eq(imag(p), 0) && ge(real(p), 0))); };\n if (up(a) != up(b)) return up(a);\n if (!eq(cross(a, b), 0)) return cross(a, b) > 0;\n return lt(norm(a), norm(b));\n}\n\ninline void rd(P2& p) {D x, y; cin>>x>>y; p = P2(x, y);}\n#define setp(n) cout<<setprecision(n)<<fixed\ninline void pr(const P2& p) {setp(12); cout<<real(p)<<' '<<imag(p)<<'\\n';}\n\n// ----------------------------------------------------------------------------------\n\nP2 proj(L2 l, P2 p) { P2 a=p-l.a, b=l.b-l.a; return l.a+b*dot(a, b)/norm(b);}\nP2 refl(L2 l, P2 p) { return proj(l, p)*2.0L - p; }\nbool isParallel(L2 l, L2 m){ return eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isPerp(L2 l, L2 m){ return eq(dot(l.a-l.b, m.a-m.b), 0); }\n\nbool isLL(L2 l, L2 m){ return !eq(cross(l.a-l.b, m.a-m.b), 0); }\nbool isLS(L2 l, S2 s){ return turn(l.a, l.b, s.a)*turn(l.a, l.b, s.b)<=0; }\nbool isSS(S2 s, S2 t) {\n return\n ccw(s.a,s.b,t.a)*ccw(s.a,s.b,t.b) <= 0 &&\n ccw(t.a,t.b,s.a)*ccw(t.a,t.b,s.b) <= 0;\n}\n\nP2 cpLL(L2 l, L2 m) {\n P2 a=l.b-l.a, b=m.b-m.a;\n D d=cross(a, b);\n if (eq(d, 0)) return P2(INF, INF); // parallel\n return l.a + a*cross(m.b-l.a,b)/d;\n}\n\nD distLP(L2 l, P2 p) { return abs(cross(l.b-l.a, p-l.a))/abs(l.b-l.a); }\nD distSP(S2 s, P2 p) {\n P2 a=s.a, b=s.b;\n if (lt(dot(b-a, p-a), 0)) return abs(p-a);\n if (lt(dot(a-b, p-b), 0)) return abs(p-b);\n return distLP({a,b}, p);\n}\nD distSS(S2 s, S2 t) {\n if (isSS(s, t)) return 0;\n return min({distSP(s, t.a), distSP(s, t.b), distSP(t, s.a), distSP(t, s.b)});\n}\n\nD area(G2 g) {\n D s=0;\n int n=g.size();\n rep(i, n) s+=cross(g[i], g[(i+1)%n]);\n return s/2.0L;\n}\n\nbool isConvex(G2 g) {\n int n=g.size();\n if (n < 3) return false;\n int dir = 0;\n rep(i,n){\n int s = turn(g[i], g[(i+1)%n], g[(i+2)%n]);\n if (s == 0) return false; // -> continue : allows three points on a line\n if (dir == 0) dir = s;\n else if (dir*s < 0) return false;\n }\n return true;\n}\n\nint inG(G2 g, P2 p) {\n bool in=false;\n int n=g.size();\n rep(i, n) {\n P2 a=g[i], b=g[(i+1)%n];\n if (ccw(a, b, p) == 0) return 2; // on boundary\n if (a.imag() > b.imag()) swap(a, b);\n if (le(a.imag(), p.imag()) && lt(p.imag(), b.imag()) && turn(a, b, p) > 0) in=!in;\n }\n return in ? 1 : 0; // inside : outside\n}\n\nG2 hull(G2 g) {\n sort(all(g), ltP2);\n g.erase(unique(all(g), eqP2), g.end());\n if (g.size()<=1) return g;\n G2 lo, up;\n for (auto &p:g) {\n while (lo.size()>=2 && turn(lo[lo.size()-2], lo.back(), p)<=0) lo.pop_back(); //-> turn()<0 : allow three points on a line\n lo.push_back(p);\n }\n reverse(all(g));\n for (auto &p:g) {\n while (up.size()>=2 && turn(up[up.size()-2], up.back(), p)<=0) up.pop_back(); // -> turn()<0 : allow three points on a line\n up.push_back(p);\n }\n lo.pop_back(); up.pop_back();\n lo.insert(lo.end(), all(up));\n return lo;\n}\n\npair<P2, P2> diameter(const G2& h) {\n int n=h.size();\n if(n==0) return {P2(0,0), P2(0,0)};\n if(n==1) return {h[0], h[0]};\n auto area2=[&](int i, int j, int k) {return abs(cross(h[j]-h[i], h[k]-h[i]));};\n D maxd=0;\n pair<P2, P2> res={h[0], h[0]};\n int j=1;\n rep(i, n) {\n int ni=(i+1)%n;\n while (gt(area2(i, ni, (j+1)%n), area2(i, ni, j))) j=(j+1)%n;\n if (gt(abs(h[i]-h[j]), maxd)) maxd=abs(h[i]-h[j]), res={h[i], h[j]};\n if (gt(abs(h[ni]-h[j]), maxd)) maxd=abs(h[ni]-h[j]), res={h[ni], h[j]};\n }\n return res;\n}\n\n// int inConvex(G2 h, P2 p) {\n// int n=h.size();\n// if (n==0) return 0;\n// if (n==1) return eqP2(h[0], p) ? 2 : 0;\n// if (n==2) return ccw(h[0], h[1], p)==0 && le(abs(h[0]-p)+abs(h[1]-p), abs(h[0]-h[1])) ? 2 : 0;\n// int left=1, right=n-1;\n// while (right-left>1) {\n// int mid=(left+right)/2;\n// if (turn(h[0], h[mid], p)<0) right=mid;\n// else left=mid;\n// }\n// if (turn(h[0], h[left], p)<0) return 0;\n// if (turn(h[left], h[right%n], p)<0) return 0;\n// if (turn(h[right%n], h[0], p)<0) return 0;\n// if (turn(h[0], h[left], p)==0 || turn(h[left], h[right%n], p)==0 || turn(h[right%n], h[0], p)==0) return 2;\n// return 1;\n// }\n\nG2 cutConvex(G2 h, L2 l) {\n int n=h.size();\n G2 res;\n if (n==0) return res;\n auto inside=[&](P2 p){ return turn(l.a, l.b, p) >= 0; };\n rep(i, n) {\n P2 a=h[i], b=h[(i+1)%n];\n bool ina=inside(a), inb=inside(b);\n if (ina&&inb) res.push_back(b);\n else if (ina&&!inb) {\n res.push_back(proj({a,b}, l.a));\n }\n else if (!ina&&inb) {\n res.push_back(proj({a,b}, l.a));\n res.push_back(b);\n }\n }\n return res;\n}\n\n\npair<P2, P2> closestPair(G2 g) {\n auto ps = g;\n int n=ps.size();\n if (n < 2) return {P2(0,0), P2(0,0)};\n sort(all(ps), ltP2);\n D mind = norm(ps[0]-ps[1]);\n pair<P2, P2> res = {ps[0], ps[1]};\n set<pair<D,int>> box;\n int j=0;\n rep(i, n) {\n D xi=real(ps[i]), yi=imag(ps[i]);\n D rad = sqrtl(mind);\n while (j<i && gt(xi - real(ps[j]), rad)) {\n box.erase({imag(ps[j]), j});\n j++;\n }\n auto it = box.lower_bound({yi - rad, -1});\n for (; it != box.end() && le(it->first, yi + rad); ++it) {\n int k = it->second;\n D d = norm(ps[i]-ps[k]);\n if (lt(d, mind)) mind=d, res={ps[i], ps[k]}, rad = sqrtl(mind);\n }\n box.insert({yi, i});\n }\n return res;\n}\n\n\nstruct C2 { P2 o; D r; };\n\nC2 makeC2(P2 a, P2 b) {\n return C2{(a+b)/D(2), abs(a-b)/D(2)};\n}\nC2 makeC2(P2 a, P2 b, P2 c) {\n P2 B=b-a, C=c-a;\n D d=2*cross(B, C);\n if (eq(d, 0)) {\n D ab=norm(B), bc=norm(b-c), ca=norm(c-a);\n if (le(ab, bc) && le(ab, ca)) return makeC2(a, b);\n if (le(bc, ca)) return makeC2(b, c);\n return makeC2(c, a);\n }\n P2 o=a+(rot90(B)*norm(C)-rot90(C)*norm(B))/d;\n return C2{o, abs(o-a)};\n}\n\nC2 incircle(P2 a, P2 b, P2 c) {\n D ab=abs(b-a), bc=abs(c-b), ca=abs(a-c);\n P2 o=(a*bc+b*ca+c*ab)/(ab+bc+ca);\n D r=abs(cross(b-a, o-a))/abs(b-a);\n return C2{o, r};\n}\n\nvector<P2> cpCL(L2 l, C2 c) {\n vector<P2> res;\n P2 a=l.a-c.o, d=l.b-l.a;\n D A=norm(d), B=2*dot(a, d), C=norm(a)-c.r*c.r;\n D Dlt=B*B-4*A*C;\n if (lt(Dlt, 0)) return res;\n D s = le(Dlt, 0) ? 0 : sqrtl(max<D>(0, Dlt));\n D t1 = (-B - s)/(2*A), t2 = (-B + s)/(2*A);\n res.push_back(c.o + a + d*t1);\n if (gt(Dlt, 0)) res.push_back(c.o + a + d*t2);\n return res;\n}\n\nvector<P2> cpCC(C2 c1, C2 c2) {\n vector<P2> res;\n P2 d=c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n D a=(c1.r*c1.r-c2.r*c2.r+L*L)/(2*L), h2=c1.r*c1.r-a*a;\n if (lt(h2, 0)) return res;\n P2 m=c1.o+d*(a/L), n=rot90(d)*( (lt(h2, 0) ? 0 : sqrtl(max<D>(0, h2))/L) );\n res.push_back(m-n);\n if (gt(h2, 0)) res.push_back(m+n);\n return res;\n}\n\nD isaCC(C2 c1, C2 c2) {\n D d=abs(c1.o-c2.o), r1=c1.r, r2=c2.r;\n if (ge(d, r1+r2)) return 0;\n if (le(d, abs(r1-r2))) {\n D r=min(r1, r2);\n return PI*r*r;\n }\n auto f = [&] (D z) { return max<D>(-1, min<D>(1, z)); };\n D a = 2*acosl(f((d*d+r1*r1-r2*r2)/(2*d*r1)));\n D b = 2*acosl(f((d*d+r2*r2-r1*r1)/(2*d*r2)));\n return 0.5L*(r1*r1*(a-sinl(a)) + r2*r2*(b-sinl(b)));\n}\n\nvector<L2> tangCP(C2 c, P2 p) {\n vector<L2> res;\n P2 v = p - c.o;\n D d2 = norm(v), r2 = c.r*c.r;\n if (lt(d2, r2)) return res;\n if (eq(d2, r2)) {\n res.push_back({c.o+v*(r2/d2), p});\n return res;\n }\n D h = c.r*sqrtl(max<D>(0, d2 - r2));\n P2 n1 = (v*r2 - rot90(v)*h)/d2;\n P2 n2 = (v*r2 + rot90(v)*h)/d2;\n res.push_back({c.o+n1, p});\n res.push_back({c.o+n2, p});\n return res;\n}\n\nvector<L2> tangCC(C2 c1, C2 c2) {\n vector<L2> res;\n P2 d = c2.o-c1.o;\n D L=abs(d);\n if (eq(L, 0)) return res;\n P2 e = d/L;\n auto add = [&] (int s) {\n D c=(s*c2.r - c1.r)/L;\n if (gt(c*c, 1)) return;\n D s2 = max<D>(0, 1 - c*c);\n if (eq(s2, 0)) {\n P2 n = e*c;\n res.push_back({c1.o-n*c1.r, c2.o-n*c2.r});\n } else {\n D s = sqrtl(s2);\n P2 n1 = e*c + rot90(e)*s;\n P2 n2 = e*c - rot90(e)*s;\n res.push_back({c1.o-n1*c1.r, c2.o-n1*c2.r});\n res.push_back({c1.o-n2*c1.r, c2.o-n2*c2.r});\n }\n };\n add(+1); // external\n add(-1); // internal\n return res;\n}\n\nC2 mec(G2 ps) {\n auto inC2=[&](C2 c, P2 p){ return le(abs(c.o - p), c.r); };\n mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n shuffle(all(ps), rng);\n int n=ps.size();\n if(n==0) return C2{P2(0,0), 0};\n C2 c{ps[0], 0};\n rep(i, n) {\n if (inC2(c, ps[i])) continue;\n c={ps[i], 0};\n rep(j, i) {\n if (inC2(c, ps[j])) continue;\n c=makeC2(ps[i], ps[j]);\n rep(k, j) {\n if (inC2(c, ps[k])) continue;\n c=makeC2(ps[i], ps[j], ps[k]);\n }\n }\n }\n return c;\n}\n\nvector<P2> cpSegs(vector<S2> ss) {\n struct E { D x; int t; D y, y1, y2; }; // t: 0=add(H), 1=query(V), 2=remove(H)\n vector<E> es; es.reserve(ss.size()*2);\n\n for(auto s: ss) {\n if (eq(s.a.imag(), s.b.imag())) {\n if (gt(s.a.real(), s.b.real())) swap(s.a, s.b);\n es.push_back({s.a.real(), 0, s.a.imag(), 0, 0});\n es.push_back({s.b.real(), 2, s.a.imag(), 0, 0});\n } else {\n if (gt(s.a.imag(), s.b.imag())) swap(s.a, s.b);\n es.push_back({s.a.real(), 1, 0, s.a.imag(), s.b.imag()});\n }\n }\n\n sort(all(es), [](E a, E b) {\n if (!eq(a.x, b.x)) return lt(a.x, b.x);\n return a.t < b.t;\n });\n\n multiset<D> active;\n vector<P2> res; res.reserve(ss.size());\n for (auto e : es) {\n if (e.t == 0) { // add\n active.insert(e.y);\n } else if (e.t == 2) { // remove\n auto it = active.find(e.y);\n if (it != active.end()) active.erase(it);\n } else { // query\n for (auto it = active.lower_bound(e.y1); it != active.end() && le(*it, e.y2); ++it) {\n res.push_back(P2(e.x, *it));\n }\n }\n }\n\n sort(all(res), ltP2);\n res.erase(unique(all(res), eqP2), res.end());\n return res;\n}\n\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_A\nvoid Projection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(proj(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_B\nvoid Reflection() {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n pr(refl(l, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_1_C\nvoid CounterClockwise() {\n P2 p0, p1;\n rd(p0); rd(p1);\n ll q; cin>>q;\n while(q--) {\n P2 p; rd(p);\n int res = ccw(p0, p1, p);\n if (res == +1) out(\"COUNTER_CLOCKWISE\");\n else if (res == -1) out(\"CLOCKWISE\");\n else if (res == +2) out(\"ONLINE_BACK\");\n else if (res == -2) out(\"ONLINE_FRONT\");\n else out(\"ON_SEGMENT\");\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/1/CGL_2_A\nvoid ParallelOrthogonal() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n if (isParallel({p1, p2}, {p3, p4})) out(2);\n else if(isPerp({p1, p2}, {p3, p4})) out(1);\n else out(0);\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_B\nvoid IntersectionSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n out(isSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_C\nvoid CrossPointSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n L2 s1 = {p1, p2}, s2 = {p3, p4};\n pr(cpLL(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/2/CGL_2_D\nvoid DistanceSS() {\n ll q;cin>>q;\n while(q--) {\n P2 p1, p2, p3, p4;\n rd(p1); rd(p2); rd(p3); rd(p4);\n S2 s1 = {p1, p2}, s2 = {p3, p4};\n setp(12);\n out(distSS(s1, s2));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_A\nvoid Area() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n setp(12);\n out(area(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_B\nvoid IsConvex() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n out(isConvex(g));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/3/CGL_3_C\nvoid PolygonPointContainment() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 p; rd(p);\n out(inG(g, p));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_A\nvoid ConvexHull() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n G2 h = hull(g);\n out(h.size());\n rep(i, h.size()) pr(h[i]);\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_B\nvoid DiameterOfConvexPolygon() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = diameter(g);\n setp(12);\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/4/CGL_4_C\nvoid ConvexCut() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n G2 h = cutConvex(g, l);\n setp(12);\n out(area(h));\n }\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_A\nvoid ClosestPair() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [p1, p2] = closestPair(g);\n setp(12);\n out(abs(p1 - p2));\n}\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/5/CGL_5_B\nvoid MinimumEnclosingCircle() {\n ll n;cin>>n;\n G2 g(n);\n rep(i, n) rd(g[i]);\n auto [c, r] = mec(g);\n pr(c);\n setp(12);\n out(r);\n}\n\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/6/CGL_6_A\nvoid SegmentIntersections() {\n ll n;cin>>n;\n vector<S2> seg(n);\n rep(i, n) {\n P2 a, b; rd(a); rd(b);\n seg[i] = {a, b};\n }\n out(cpSegs(seg).size());\n}\n\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_A\nvoid IntersectionOfCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n out(tangCC(c1, c2).size());\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_B\nvoid IncircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [ic, ir] = incircle(a, b, c);\n pr(ic);\n setp(12);\n out(ir);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_C\nvoid CircumscribedCircleOfTriangle() {\n P2 a, b, c; rd(a); rd(b); rd(c);\n auto [cc, cr] = makeC2(a, b, c);\n pr(cc);\n setp(12);\n out(cr);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_D\nvoid CrossPointsCL() {\n P2 c; D r;\n rd(c); cin>>r;\n ll q;cin>>q;\n while(q--) {\n P2 a, b; rd(a); rd(b);\n L2 l = {a, b};\n auto ps = cpCL(l, {c, r});\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n }\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_E\nvoid CrossPointsCC() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ps = cpCC(c1, c2);\n sort(all(ps), ltP2);\n pr(ps[0]);\n pr(ps[(ps.size()-1)]);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_F\nvoid TangentToCircle() {\n P2 p, c; D r;\n rd(p);\n rd(c); cin>>r;\n C2 c1={c, r};\n auto ls = tangCP(c1, p);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_G\nvoid CommonTangent() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n auto ls = tangCC(c1, c2);\n vector<P2> ps;\n for (auto l : ls) {\n ps.push_back(l.a);\n }\n sort(all(ps), ltP2);\n for (auto p : ps) pr(p);\n}\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_H\n// void IntersectionCP() {\n// ll n;cin>>n;\n// D r; cin>>r;\n// C2 c = {P2(0, 0), r};\n// G2 g(n);\n// rep(i, n) rd(g[i]);\n// out(isaCP(c, g));\n// }\n\n// // https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_I\nvoid AreaOfIntersectionBetweenTwoCircles() {\n P2 o1, o2; D r1, r2;\n rd(o1); cin>>r1;\n rd(o2); cin>>r2;\n C2 c1={o1, r1}, c2={o2, r2};\n setp(12);\n out(isaCC(c1, c2));\n}\n\nint main() {\n cin.tie(0);\n ios_base::sync_with_stdio(false);\n\n // Projection();\n // Reflection();\n // CounterClockwise();\n\n // ParallelOrthogonal();\n // IntersectionSS();\n // CrossPointSS();\n // DistanceSS();\n\n // Area();\n // IsConvex();\n // PolygonPointContainment();\n\n // ConvexHull();\n // DiameterOfConvexPolygon();\n // ConvexCut();\n\n // ClosestPair();\n // MinimumEnclosingCircle();\n\n SegmentIntersections();\n\n // IntersectionOfCircles();\n // IncircleOfTriangle();\n // CircumscribedCircleOfTriangle();\n // CrossPointsCL();\n // CrossPointsCC();\n // TangentToCircle();\n // CommonTangent();\n // IntersectionCP();\n // AreaOfIntersectionBetweenTwoCircles();\n return 0;\n}", "accuracy": 1, "time_ms": 220, "memory_kb": 71532, "score_of_the_acc": -1.4419, "final_rank": 20 }, { "submission_id": "aoj_CGL_6_A_10906497", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <climits>\n#include <unordered_map>\n#include <queue>\n#include <deque>\n#include <math.h>\n#include <limits.h>\n#include <set>\n#include <stack>\n#include <map>\n#include <bits/stdc++.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <cmath>\n#define Lt Line<T>\n#define Pt Point<T>\n#define ll long long\n\n\n\n//#define double long double\nusing namespace std;\n\n\nconst ll N=2e4+10,M=1e6+10,MOD=998244353;\n\ntypedef std::pair<ll,ll> pii;\ntypedef std::pair<ll,std::pair<ll,ll> > piii;\n\n\n//ll n,m;\n\nusing ld = long double;\nconst ld PI = acos(-1);\nconst ld EPS = 1e-7;\nconst ld INF = numeric_limits<ld>::max();\n#define cc(x) cout << fixed << setprecision(x);\n\nld fgcd(ld x, ld y) { // 实数域gcd\n return abs(y) < EPS ? abs(x) : fgcd(y, fmod(x, y));\n}\ntemplate<class T, class S> bool equal(T x, S y) {\n return -EPS < x - y && x - y < EPS;\n}\ntemplate<class T> int sign(T x) {\n if (-EPS < x && x < EPS) return 0;\n return x < 0 ? -1 : 1;\n}\n\n\n\ntemplate<class T> struct Point { // 在C++17下使用 emplace_back 绑定可能会导致CE!\n T x, y;\n Point(T x_ = 0, T y_ = 0) : x(x_), y(y_) {} // 初始化\n template<class U> operator Point<U>() { // 自动类型匹配\n return Point<U>(U(x), U(y));\n }\n Point &operator+=(Point p) & { return x += p.x, y += p.y, *this; }\n Point &operator+=(T t) & { return x += t, y += t, *this; }\n Point &operator-=(Point p) & { return x -= p.x, y -= p.y, *this; }\n Point &operator-=(T t) & { return x -= t, y -= t, *this; }\n Point &operator*=(T t) & { return x *= t, y *= t, *this; }\n Point &operator/=(T t) & { return x /= t, y /= t, *this; }\n Point operator-() const { return Point(-x, -y); }\n friend Point operator+(Point a, Point b) { return a += b; }\n friend Point operator+(Point a, T b) { return a += b; }\n friend Point operator-(Point a, Point b) { return a -= b; }\n friend Point operator-(Point a, T b) { return a -= b; }\n friend Point operator*(Point a, T b) { return a *= b; }\n friend Point operator*(T a, Point b) { return b *= a; }\n friend Point operator/(Point a, T b) { return a /= b; }\n friend bool operator<(Point a, Point b) {\n return equal(a.x, b.x) ? a.y < b.y - EPS : a.x < b.x - EPS;\n }\n friend bool operator>(Point a, Point b) { return b < a; }\n friend bool operator==(Point a, Point b) { return !(a < b) && !(b < a); }\n friend bool operator!=(Point a, Point b) { return a < b || b < a; }\n friend auto &operator>>(istream &is, Point &p) {\n return is >> p.x >> p.y;\n }\n friend auto &operator<<(ostream &os, Point p) {\n return os << \"(\" << p.x << \", \" << p.y << \")\";\n }\n};\ntemplate<class T> struct Line {\n Point<T> a, b;\n Line(Point<T> a_ = Point<T>(), Point<T> b_ = Point<T>()) : a(a_), b(b_) {}\n template<class U> operator Line<U>() { // 自动类型匹配\n return Line<U>(Point<U>(a), Point<U>(b));\n }\n friend auto &operator<<(ostream &os, Line l) {\n return os << \"<\" << l.a << \", \" << l.b << \">\";\n }\n};\n\nusing Pd = Point<ld>;\nusing Ld = Line<ld>;\n\ntemplate<class T> T cross(Point<T> a, Point<T> b) { // 叉乘\n return a.x * b.y - a.y * b.x;\n}\ntemplate<class T> T cross(Point<T> p1, Point<T> p2, Point<T> p0) { // 叉乘 (p1 - p0) x (p2 - p0);\n return cross(p1 - p0, p2 - p0);\n}\n\ntemplate<class T> T dot(Point<T> a, Point<T> b) { // 点乘\n return a.x * b.x + a.y * b.y;\n}\ntemplate<class T> T dot(Point<T> p1, Point<T> p2, Point<T> p0) { // 点乘 (p1 - p0) * (p2 - p0);\n return dot(p1 - p0, p2 - p0);\n}\n\ntemplate <class T> ld dis(T x1, T y1, T x2, T y2) {\n ld val = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n return sqrt(val);\n}\ntemplate <class T> ld dis(Point<T> a, Point<T> b) {\n return dis(a.x, a.y, b.x, b.y);\n}\n\ntemplate<class T> Point<T> rotate(Point<T> p1, Point<T> p2) { // 旋转\n Point<T> vec = p1 - p2;\n return {-vec.y, vec.x};\n}\n\nPoint<ld> rotate(Point<ld> p, ld rad) {\n return {p.x * cos(rad) - p.y * sin(rad), p.x * sin(rad) + p.y * cos(rad)};\n}\n\nPoint<ld> rotate(Point<ld> a, Point<ld> b, ld rad) {\n ld x = (a.x - b.x) * cos(rad) + (a.y - b.y) * sin(rad) + b.x;\n ld y = (b.x - a.x) * sin(rad) + (a.y - b.y) * cos(rad) + b.y;\n return {x, y};\n}\n\ntemplate<class T> bool onLine(Point<T> a, Point<T> b, Point<T> c) {\n return sign(cross(b, a, c)) == 0;\n}\ntemplate<class T> bool onLine(Point<T> p, Line<T> l) {\n return onLine(p, l.a, l.b);\n}\n\ntemplate<class T> bool lineParallel(Line<T> p1, Line<T> p2) {\n return sign(cross(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool lineVertical(Line<T> p1, Line<T> p2) {\n return sign(dot(p1.a - p1.b, p2.a - p2.b)) == 0;\n}\ntemplate<class T> bool same(Line<T> l1, Line<T> l2) {\n return lineParallel(Line{l1.a, l2.b}, {l1.b, l2.a}) &&\n lineParallel(Line{l1.a, l2.a}, {l1.b, l2.b}) && lineParallel(l1, l2);\n}\n\ntemplate<class T> ld disPointToLine(Point<T> p, Line<T> l) {\n ld ans = cross(p, l.a, l.b);\n return abs(ans) / dis(l.a, l.b); // 面积除以底边长\n}\n\ntemplate<class T> bool pointOnSegment(Point<T> p, Line<T> l) { // 端点也算作在直线上\n return sign(cross(p, l.a, l.b)) == 0 && min(l.a.x, l.b.x) <= p.x && p.x <= max(l.a.x, l.b.x) &&\n min(l.a.y, l.b.y) <= p.y && p.y <= max(l.a.y, l.b.y);\n}\n\ntemplate<class T> bool segmentIntersection(Line<T> l1, Line<T> l2) {\n auto [s1, e1] = l1;\n auto [s2, e2] = l2;\n auto A = max(s1.x, e1.x), AA = min(s1.x, e1.x);\n auto B = max(s1.y, e1.y), BB = min(s1.y, e1.y);\n auto C = max(s2.x, e2.x), CC = min(s2.x, e2.x);\n auto D = max(s2.y, e2.y), DD = min(s2.y, e2.y);\n return A >= CC && B >= DD && C >= AA && D >= BB &&\n sign(cross(s1, s2, e1) * cross(s1, e1, e2)) == 1 &&\n sign(cross(s2, s1, e2) * cross(s2, e2, e1)) == 1;\n}//其中重叠、相交于端点均视为不相交。\n\nPd lineIntersection(Ld l1, Ld l2) {\n ld val = cross(l2.b - l2.a, l1.a - l2.a) / cross(l2.b - l2.a, l1.a - l1.b);\n return l1.a + (l1.b - l1.a) * val;\n}\n\npair<Pd, ld> pointToLine(Pd p, Ld l) {\n Pd ans = lineIntersection({p, p + rotate(l.a, l.b)}, l);\n return {ans, dis(p, ans)};\n}\n\npair<Pd, ld> pointToSegment(Pd p, Ld l) {\n if (sign(dot(p, l.b, l.a)) == -1) { // 特判到两端点的距离\n return {l.a, dis(p, l.a)};\n } else if (sign(dot(p, l.a, l.b)) == -1) {\n return {l.b, dis(p, l.b)};\n }\n return pointToLine(p, l);\n}\n\nld DisSegToSeg(Ld l1,Ld l2)\n{\n // if(lineParallel(l1,l2)) \n // {\n // auto [t1,ans1]=pointToSegment(l1.a,l2);\n // return ans1;\n // }\n if(segmentIntersection(l1,l2)) return 0.0;\n auto [t1,ans1]=pointToSegment(l1.a,l2);\n auto [t2,ans2]=pointToSegment(l1.b,l2);\n auto [t3,ans3]=pointToSegment(l2.a,l1);\n auto [t4,ans4]=pointToSegment(l2.b,l1);\n //cout<<ans1<<' '<<ans2<<' '<<ans3<<' '<<ans4<<'\\n';\n return min(min(ans1,ans2),min(ans3,ans4));\n}\n\ntemplate<class T> ld area(vector<Point<T>> P) {\n int n = P.size();\n ld ans = 0;\n for (int i = 0; i < n; i++) {\n ans += cross(P[i], P[(i + 1) % n]);\n }\n return ans / 2.0;\n}\n\ntemplate<class T> vector<Point<T>> staticConvexHull(vector<Point<T>> A, int flag = 1) {\n int n = A.size();\n if (n <= 2) { // 特判\n return A;\n }\n vector<Point<T>> ans(n * 2);\n sort(A.begin(), A.end());\n int now = -1;\n for (int i = 0; i < n; i++) { // 维护下凸包\n while (now > 0 && cross(A[i], ans[now], ans[now - 1]) < 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n int pre = now;\n for (int i = n - 2; i >= 0; i--) { // 维护上凸包\n while (now > pre && cross(A[i], ans[now], ans[now - 1]) <= 0) {\n now--;\n }\n ans[++now] = A[i];\n }\n ans.resize(now);\n sort(ans.begin(),ans.end());\n ans.erase(unique(ans.begin(),ans.end()),ans.end());\n return ans;\n}\n\n\n\ntemplate<class T> T sqr(T x) {\n return x * x;\n}\n\ntemplate<class T> T disEx(Pt a1,Pt a2)\n{\n return (a1.x-a2.x)*(a1.x-a2.x)+(a1.y-a2.y)*(a1.y-a2.y);\n}\n\n// 计算最小包围圆(最小圆覆盖)\n// 输入:点集的迭代器范围 [left, right),随机种子 seed\n// 输出:pair<圆心, 半径平方>\ntemplate <class T>\nstd::pair<Point<T>, ld> min_ball(vector<Pt> A, int seed = 1333) {\n \n const int n = A.size(); // 点的数量\n\n assert(n >= 1); // 至少需要1个点\n \n // 特殊情况处理:只有1个点\n if (n == 1) {\n return {A[0], ld(0)}; // 圆就是点本身,半径为0\n }\n\n // 随机数生成器\n std::mt19937 mt(seed);\n // 随机打乱点集顺序 - 这是保证O(n)期望时间复杂度的关键\n std::shuffle(A.begin(), A.end(), mt);\n\n vector<Pt> &ps=A;\n\n using circle = std::pair<Pt, ld>; // 圆类型:圆心 + 半径平方\n\n // 通过三个点构造圆的lambda函数\n auto make_circle_3 = [](const Pt &a, const Pt &b, const Pt &c) -> circle {\n // 使用三角形外心公式计算圆心\n ld A = disEx(b , c), // |BC|²\n B = disEx(c , a), // |CA|² \n C = disEx(a , b), // |AB|²\n S = cross(b - a, c - a); // 三角形面积的2倍\n \n // 外心坐标公式(重心坐标形式)\n Pt p = (A * (B + C - A) * a + B * (C + A - B) * b + C * (A + B - C) * c) / (4 * S * S);\n ld r2 = disEx(p , a); // 半径的平方\n return {p, r2};\n };\n\n // 通过两个点构造圆的lambda函数(以两点为直径的圆)\n auto make_circle_2 = [](const Pt &a, const Pt &b) -> circle {\n Pt c = (a + b) / (ld)2; // 圆心为两点中点\n ld r2 = disEx(a , c); // 半径平方\n return {c, r2};\n };\n\n // 判断点是否在圆内的lambda函数\n auto in_circle = [](const Pt &a, const circle &c) -> bool {\n // 判断点到圆心的距离平方是否 <= 半径平方 + 容误差\n return disEx(a , c.first) <= c.second + EPS;\n };\n\n // 初始化:用前两个点构造初始圆\n circle c = make_circle_2(ps[0], ps[1]);\n\n // 主循环:逐个处理剩余的点\n for (int i = 2; i < n; ++i) {\n // 如果当前点不在当前圆内,需要更新圆\n if (!in_circle(ps[i], c)) {\n // MiniDiscWithPoint: 新圆必须包含当前点ps[i]\n c = make_circle_2(ps[0], ps[i]); // 初始尝试:用第一个点和当前点构造圆\n \n // 检查前面的点是否都在新圆内\n for (int j = 1; j < i; ++j) {\n if (!in_circle(ps[j], c)) {\n // MiniDiscWith2Points: 新圆必须包含ps[i]和ps[j]\n c = make_circle_2(ps[i], ps[j]); // 用当前两个点构造圆\n \n // 检查更前面的点\n for (int k = 0; k < j; ++k) {\n if (!in_circle(ps[k], c)) {\n // 三个点确定唯一圆\n c = make_circle_3(ps[i], ps[j], ps[k]);\n }\n }\n }\n }\n }\n // 如果当前点在圆内,直接跳过(概率O(1/k),这是算法高效的关键)\n }\n return c;\n}\n\ntuple<int, Pd, Pd> circleIntersection(Pd p1, ld r1, Pd p2, ld r2) {\n ld x1 = p1.x, x2 = p2.x, y1 = p1.y, y2 = p2.y;\n ld d = dis(p1, p2);\n \n // 检查圆的位置关系\n if (sign(d) == 0) { // 同心圆\n if (sign(r1 - r2) == 0) return {4, {}, {}}; // 重合\n else return {0, {}, {}}; // 内含\n }\n \n if (sign(d - (r1 + r2)) == 1) { // 相离\n return {0, {}, {}};\n } else if (sign(abs(r1 - r2) - d) == 1) { // 内含\n return {0, {}, {}};\n }\n \n // 计算交点\n ld dx = x2 - x1, dy = y2 - y1;\n ld a = (r1*r1 - r2*r2 + d*d) / (2*d);\n ld h = sqrt(r1*r1 - a*a);\n \n // 中点\n ld xm = x1 + a * dx / d;\n ld ym = y1 + a * dy / d;\n \n // 垂直方向的偏移量\n ld xoff = -h * dy / d;\n ld yoff = h * dx / d;\n \n Pd ans1 = {xm + xoff, ym + yoff};\n Pd ans2 = {xm - xoff, ym - yoff};\n \n if (sign(dis(ans1, ans2)) == 0) { // 相切,一个交点\n return {2, ans1, ans1};\n } else { // 相交,两个交点\n return {3, ans1, ans2};\n }\n}\n\ntemplate<class T> Lt midSegment(Lt l) {\n Pt mid = (l.a + l.b) / 2; // 线段中点\n return {mid, mid + rotate(l.a, l.b)};\n}\n\ntuple<int, Pd, ld> getCircle(Pd A, Pd B, Pd C) {\n if (onLine(A, B, C)) { // 特判三点共线\n return {0, {}, 0};\n }\n Ld l1 = midSegment(Line{A, B});\n Ld l2 = midSegment(Line{A, C});\n Pd O = lineIntersection(l1, l2);\n return {1, O, dis(A, O)};\n}\n\npair<Pd,ld> getIncircle(Pd A,Pd B,Pd C)\n{\n ld AB=dis(A,B);\n ld AC=dis(A,C);\n ld BC=dis(B,C);\n Pd ans((AB*C.x+AC*B.x+BC*A.x)/(AB+AC+BC),(AB*C.y+AC*B.y+BC*A.y)/(AB+AC+BC));\n ld ans1=cross(A,B,C)/(AB+AC+BC);\n return {ans,max(ans1,-ans1)};\n}\n\nPd project(Pd p, Ld l) { // 投影\n Pd vec = l.b - l.a;\n ld r = dot(vec, p - l.a) / (vec.x * vec.x + vec.y * vec.y);\n return l.a + vec * r;\n}\n\nPoint<ld> standardize(Point<ld> vec) { // 转换为单位向量\n return vec / sqrt(vec.x * vec.x + vec.y * vec.y);\n}\n\ntuple<int, Pd, Pd> lineCircleCross(Ld l, Pd o, ld r) {\n Pd P = project(o, l);\n ld d = dis(P, o), tmp = r * r - d * d;\n if (sign(tmp) == -1) {\n return {0, {}, {}};\n } else if (sign(tmp) == 0) {\n return {1, P, {}};\n }\n Pd vec = standardize(l.b - l.a) * sqrt(tmp);\n return {2, P + vec, P - vec};\n}\n\nPoint<ld> getPoint(Point<ld> p, ld r, ld rad) {\n return {p.x + cos(rad) * r, p.y + sin(rad) * r};\n}\n\npair<int, vector<Point<ld>>> tangent(Point<ld> p, Point<ld> A, ld r) {\n vector<Point<ld>> ans;\n ld d = dis(p, A);\n \n if (sign(d - r) < 0) {\n // 点在圆内,无切线\n return {0, {}};\n } else if (sign(d - r) == 0) {\n // 点在圆上,只有一条切线\n // 切点就是p本身\n ans.push_back(p);\n return {1, ans};\n } else {\n // 点在圆外,有两条切线\n Point<ld> u = A - p;\n \n // 使用圆心和半径计算\n // 计算圆心到切点的方向角\n ld alpha = atan2(u.y, u.x);\n ld beta = asin(r / d);\n \n Point<ld> t1_alt = getPoint(A, r, alpha + beta + M_PI_2);\n Point<ld> t2_alt = getPoint(A, r, alpha - beta - M_PI_2);\n \n ans.push_back(t1_alt);\n ans.push_back(t2_alt);\n \n return {2, ans};\n }\n}\n\ntuple<int, vector<Point<ld>>, vector<Point<ld>>> tangent(Point<ld> A, ld Ar, Point<ld> B, ld Br) {\n vector<Point<ld>> a, b; // 储存切点\n if (Ar < Br) {\n swap(Ar, Br);\n swap(A, B);\n swap(a, b);\n }\n int d = disEx(A, B), dif = Ar - Br, sum = Ar + Br;\n if (d < dif * dif) { // 内含,无\n return {0, {}, {}};\n }\n ld base = atan2(B.y - A.y, B.x - A.x);\n if (d == 0 && Ar == Br) { // 完全重合,无数条外公切线\n return {-1, {}, {}};\n }\n if (d == dif * dif) { // 内切,1条外公切线\n a.push_back(getPoint(A, Ar, base));\n b.push_back(getPoint(B, Br, base));\n return {1, a, b};\n }\n ld ang = acos(dif / sqrt(d));\n a.push_back(getPoint(A, Ar, base + ang)); // 保底2条外公切线\n a.push_back(getPoint(A, Ar, base - ang));\n b.push_back(getPoint(B, Br, base + ang));\n b.push_back(getPoint(B, Br, base - ang));\n if (d == sum * sum) { // 外切,多1条内公切线\n a.push_back(getPoint(A, Ar, base));\n b.push_back(getPoint(B, Br, base + PI));\n } else if (d > sum * sum) { // 相离,多2条内公切线\n ang = acos(sum / sqrt(d));\n a.push_back(getPoint(A, Ar, base + ang));\n a.push_back(getPoint(A, Ar, base - ang));\n b.push_back(getPoint(B, Br, base + ang + PI));\n b.push_back(getPoint(B, Br, base - ang + PI));\n }\n return {a.size(), a, b};\n}\n\nld angle(ld a, ld b, ld c) { // 余弦定理\n ld val = acos((a * a + b * b - c * c) / (2.0 * a * b)); // 计算弧度\n return val;\n}\n\nld circleIntersectionArea(Pd p1, ld r1, Pd p2, ld r2) {\n ld x1 = p1.x, x2 = p2.x, y1 = p1.y, y2 = p2.y, d = dis(p1, p2);\n if (sign(abs(r1 - r2) - d) >= 0) {\n return PI * min(r1 * r1, r2 * r2);\n } else if (sign(r1 + r2 - d) == -1) {\n return 0;\n }\n ld theta1 = angle(r1, dis(p1, p2), r2);\n ld area1 = r1 * r1 * (theta1 - sin(theta1 * 2) / 2);\n ld theta2 = angle(r2, dis(p1, p2), r1);\n ld area2 = r2 * r2 * (theta2 - sin(theta2 * 2) / 2);\n return area1 + area2;\n}\n\ntemplate <class T> struct ManPoint\n{\n Pt Now;\n int Type;\n Pt Ne;\n ManPoint (){};\n ManPoint (Pt A,Pt B)\n {\n Now=A; Ne=B;\n if(A.y==B.y) Type=((A.x<B.x)?2:3);\n else Type=((A.y<B.y)?1:4);\n }\n friend bool operator < (ManPoint A,ManPoint B)\n {\n if(A.Now.y==B.Now.y) return A.Type<B.Type;\n return A.Now.y<B.Now.y;\n }\n friend bool operator > (ManPoint A,ManPoint B) {return B<A;}\n};\n\ntemplate <class T> ll ManhattanIn(vector<Line<T>> A)\n{\n vector<ManPoint<T>> MP;\n for(auto [x,y]:A)\n {\n ManPoint x1(x,y),y1(y,x);\n MP.push_back(x1); MP.push_back(y1);\n }\n set<T> S;\n sort(MP.begin(),MP.end());\n ll ans=0;\n for(auto Mpo:MP)\n {\n if(Mpo.Type==1) S.insert(Mpo.Now.x);\n else if(Mpo.Type==2) \n {\n auto LE=(lower_bound(S.begin(),S.end(),Mpo.Now.x));\n auto RI=(upper_bound(S.begin(),S.end(),Mpo.Ne.x));\n ans+=distance(LE,RI);\n }\n else if(Mpo.Type==4) S.erase(Mpo.Now.x);\n }\n return ans;\n}\n\n\n\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(0);\n\n int n; cin>>n;\n vector<Line<ll>> z(n);\n \n for(int i=0;i<n;i++)\n {\n Point<ll> a,b; cin>>a>>b;\n z[i]={a,b};\n }\n \n cout<<ManhattanIn(z)<<'\\n';\n \n return 0;\n}", "accuracy": 1, "time_ms": 460, "memory_kb": 21784, "score_of_the_acc": -1.1946, "final_rank": 19 }, { "submission_id": "aoj_CGL_6_A_10900713", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define endl '\\n'\n\n\n#define maxn 200010\nint n,m,cnt,ans,Hash[maxn],tr[maxn];\nstruct Point{\n int x,y;\n bool operator <(Point p){\n if(x!=p.x)return x<p.x;\n return y<p.y;\n }\n};Point p[maxn];\nstruct seg{\n int k,x,y,r;\n bool operator<(seg s){\n if(y==s.y)return k>s.k;\n return y<s.y;\n }\n};seg s[maxn];\n\nint find(int x){\n return lower_bound(Hash+1,Hash+1+m,x)-Hash;\n}\nvoid insert(int k,int l,int r,int t){\n if(!k){\n s[++cnt].x=find(l);\n s[cnt].r = find(r);\n s[cnt].y = t;\n s[cnt].k = 0;\n }else{\n s[++cnt].x=find(t);s[cnt].y=l;s[cnt].k=1;//从底端入\n s[++cnt].x=find(t);s[cnt].y=r;s[cnt].k=-1;//从上端出\n }\n}\nvoid update(int x,int y){\n while(x<2e5){\n tr[x]+=y;\n x+=x&(-x);\n }\n}\nint ask(int x){\n int s = 0;\n while(x){\n s+=tr[x];\n x-=x&(-x);\n }\n\n return s;\n}\n\nsigned main(){\n cin>>n;\n for(int i =1;i<=2*n;i++){\n cin>>p[i].x>>p[i].y;\n Hash[i]=p[i].x;\n }\n sort(Hash+1,Hash+2*n+1);\n m = unique(Hash+1,Hash+2*n+1)-(Hash+1);\n for(int i=1;i<=2*n;i+=2){\n if(p[i].x==p[i+1].x){//垂直,k=1\n if(p[i].y>p[i+1].y)swap(p[i],p[i+1]);\n insert(1,p[i].y,p[i+1].y,p[i].x);\n }else{\n if(p[i].x>p[i+1].x)swap(p[i],p[i+1]);\n insert(0,p[i].x,p[i+1].x,p[i].y);\n }\n }\n\n sort(s+1,s+cnt+1);\n for(int i =1;i<=cnt;i++){\n if(!s[i].k)ans+=ask(s[i].r)-ask(s[i].x-1);\n else update(s[i].x,s[i].k);\n }\n cout<<ans<<endl;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 15856, "score_of_the_acc": -0.2149, "final_rank": 13 }, { "submission_id": "aoj_CGL_6_A_10851587", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <set>\n\n#define EPS (1e-10)\n#define equals(a, b) (fabs((a) - (b)) < EPS)\n\nusing namespace std;\n\nstatic const int COUNTER_CLOCKWISE = 1;\nstatic const int CLOCKWISE = -1;\nstatic const int ONLINE_BACK = 2;\nstatic const int ONLINE_FRONT = -2;\nstatic const int ON_SEGMENT = 0;\n\nstruct Point {\n double x, y;\n Point() {}\n Point(double _x, double _y) : x(_x), y(_y) {}\n\n Point operator + (Point p) { return Point(x+p.x, y+p.y); }\n Point operator - (Point p) { return Point(x-p.x, y-p.y); }\n Point operator * (double a) { return Point(x*a, y*a); }\n Point operator / (double a) { return Point(x/a, y/a); }\n\n double abs() { return sqrt(norm()); }\n double norm() { return x * x + y * y; }\n\n bool operator < (const Point &p) const {\n return x != p.x ? x < p.x : y < p.y;\n }\n\n bool operator == (const Point &p) const {\n return equals(x, p.x) && equals(y, p.y);\n }\n};\n\ntypedef Point Vector;\ntypedef vector<Point> Polygon;\n\nstruct Segment {\n Point p1, p2;\n Segment(Point _p1 = Point(), Point _p2 = Point()) : p1(_p1), p2(_p2) {}\n};\n\ntypedef Segment Line;\n\n\nstruct Circle {\n Point c;\n double r;\n Circle(Point _c = Point(), double _r = 0.0) : c(_c), r(_r) {}\n};\n\ndouble dot(Vector a, Vector b) {\n return a.x * b.x + a.y * b.y;\n}\n\ndouble cross(Vector a, Vector b) {\n return a.x * b.y - a.y * b.x;\n}\n\nbool isOrthogonal(Vector a, Vector b) {\n return equals(dot(a, b), 0.0);\n}\n\nbool isOrthogonal(Point a1, Point a2, Point b1, Point b2) {\n return isOrthogonal(a1-a2, b1-b2);\n}\n\nbool isOrthogonal(Segment s1, Segment s2) {\n return equals(dot(s1.p2-s1.p1, s2.p2-s2.p1), 0.0);\n}\n\nbool isParallel(Vector a, Vector b) {\n return equals(cross(a, b), 0.0);\n}\n\nbool isParallel(Point a1, Point a2, Point b1, Point b2) {\n return isParallel(a1-a2, b1-b2);\n}\n\nbool isParallel(Segment s1, Segment s2) {\n return equals(cross(s1.p2-s1.p1, s2.p2-s2.p1), 0.0);\n}\n\nPoint project(Segment s, Point p) {\n Vector base = s.p2 - s.p1;\n double r = dot(p - s.p1, base) / base.norm();\n return s.p1 + base * r;\n}\n\nPoint reflect(Segment s, Point p) {\n return p + (project(s, p) - p) * 2.0;\n}\n\nPoint getCrossPoint(Segment s1, Segment s2) {\n Vector base = s2.p2 - s2.p1;\n double d1 = fabs(cross(base, s1.p1 - s2.p1));\n double d2 = fabs(cross(base, s1.p2 - s2.p1));\n double t = d1 / (d1 + d2);\n return s1.p1 + (s1.p2 - s1.p1) * t;\n}\n\nint ccw(Point p0, Point p1, Point p2) {\n Vector a = p1 - p0;\n Vector b = p2 - p0;\n if (cross(a, b) > EPS) return COUNTER_CLOCKWISE;\n if (cross(a, b) < -EPS) return CLOCKWISE;\n if (dot(a, b) < -EPS) return ONLINE_BACK;\n if (a.norm() < b.norm()) return ONLINE_FRONT;\n\n return ON_SEGMENT;\n}\n\nbool intersect(Point p1, Point p2, Point p3, Point p4) {\n return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 && \n ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0);\n}\n\nbool intersect(Segment s1, Segment s2) {\n return intersect(s1.p1, s1.p2, s2.p1, s2.p2);\n}\n\ndouble getDistanceLP(Line l, Point p);\nbool intersect(Circle c, Line l) {\n double d = getDistanceLP(l, c.c);\n return d < c.r || equals(d, c.r);\n}\n\ndouble getDistance(Point a, Point b);\nbool intersect(Circle c1, Circle c2) {\n double d = getDistance(c1.c, c2.c);\n return (d < c1.r + c2.r || (equals(d, c1.r + c2.r)));\n}\n\ndouble getDistance(Point a, Point b) {\n return (a-b).abs();\n}\n\ndouble getDistanceLP(Line l, Point p) {\n return abs(cross(l.p2-l.p1, p-l.p1) / (l.p2-l.p1).abs());\n}\n\n\ndouble getDistanceSP(Segment s, Point p) {\n if (dot(s.p2-s.p1, p-s.p1) < 0.0) return (p-s.p1).abs();\n if (dot(s.p1-s.p2, p-s.p2) < 0.0) return (p-s.p2).abs();\n return getDistanceLP(s, p);\n}\n\ndouble getDistance(Segment s1, Segment s2) {\n if (intersect(s1, s2)) return 0.0;\n return min(min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)),\n min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2)));\n}\n\npair<Point, Point> getCrossPoints(Circle c, Line l) {\n assert(intersect(c, l));\n Vector pr = project(l, c.c);\n Vector e = (l.p2 - l.p1) / (l.p2 - l.p1).abs();\n double base = sqrt(c.r * c.r - (pr - c.c).norm());\n return make_pair(pr + e * base, pr - e * base);\n}\n\ndouble arg(Vector p) { return atan2(p.y, p.x); }\nVector polar(double a, double r) { return Point(cos(r) * a, sin(r) * a); }\n\npair<Point, Point> getCrossPoints(Circle c1, Circle c2) {\n assert(intersect(c1, c2));\n double d = (c1.c - c2.c).abs();\n double a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));\n double t = arg(c2.c - c1.c);\n return make_pair(c1.c + polar(c1.r, t + a), c1.c + polar(c1.r, t - a));\n}\n\nint contains(Polygon &g, Point p) {\n int n = g.size();\n bool x = false;\n for (int i = 0; i < n; i++) {\n Point a = g[i] - p, b = g[(i + 1) % n] - p;\n if (fabs(cross(a, b)) < EPS && dot(a, b) < EPS) return 1;\n if (a.y > b.y) swap(a, b);\n if (a.y < EPS && EPS < b.y && cross(a, b) > EPS) x = !x;\n }\n return (x ? 2 : 0);\n}\n\nPolygon andrewScan(Polygon s) {\n Polygon u, l;\n if (s.size() < 3) return s;\n sort(s.begin(), s.end());\n u.push_back(s[0]);\n u.push_back(s[1]);\n l.push_back(s[s.size() - 1]);\n l.push_back(s[s.size() - 2]);\n\n for (int i = 2; i < s.size(); i++) {\n for (int n = u.size(); n >= 2 && ccw(u[n-2], u[n-1], s[i]) == COUNTER_CLOCKWISE; n--) {\n u.pop_back();\n }\n u.push_back(s[i]);\n }\n for (int i = s.size() - 3; i >= 0; i--) {\n for (int n = l.size(); n >= 2 && ccw(l[n-2], l[n-1], s[i]) == COUNTER_CLOCKWISE; n--) {\n l.pop_back();\n }\n l.push_back(s[i]);\n }\n reverse(l.begin(), l.end());\n for (int i = u.size() - 2; i >= 1; i--) l.push_back(u[i]);\n return l;\n}\n\n#define BOTTOM 0\n#define LEFT 1\n#define RIGHT 2\n#define TOP 3\n\nstruct EndPoint {\n Point p;\n int seg, st;\n EndPoint() {}\n EndPoint(Point _p, int _seg, int _st) : p(_p), seg(_seg), st(_st) {}\n\n bool operator < (const EndPoint &ep) const {\n if (p.y == ep.p.y) {\n return st < ep.st;\n } else return p.y < ep.p.y;\n }\n};\n\nEndPoint EP[2 * 100000];\n\nint manhattanIntersection(vector<Segment> S) {\n int n = S.size();\n for (int i = 0, k = 0; i < n; i++) {\n if (S[i].p1.y == S[i].p2.y) {\n if (S[i].p1.x > S[i].p2.x) swap(S[i].p1, S[i].p2);\n } else if (S[i].p1.y > S[i].p2.y) swap(S[i].p1, S[i].p2);\n \n if (S[i].p1.y == S[i].p2.y) {\n EP[k++] = EndPoint(S[i].p1, i, LEFT);\n EP[k++] = EndPoint(S[i].p2, i, RIGHT);\n } else {\n EP[k++] = EndPoint(S[i].p1, i, BOTTOM);\n EP[k++] = EndPoint(S[i].p2, i, TOP);\n }\n }\n\n sort(EP, EP + (2 * n));\n\n set<int> BT;\n BT.insert(1000000001);\n int cnt = 0;\n for (int i = 0; i < 2 * n; i++) {\n if (EP[i].st == TOP) {\n BT.erase(EP[i].p.x);\n } else if (EP[i].st == BOTTOM) {\n BT.insert(EP[i].p.x);\n } else if (EP[i].st == LEFT) {\n set<int>::iterator b = BT.lower_bound(S[EP[i].seg].p1.x);\n set<int>::iterator e = BT.upper_bound(S[EP[i].seg].p2.x);\n cnt += distance(b, e);\n }\n }\n return cnt;\n}\n\nint main() {\n int N;\n scanf(\"%d\", &N);\n vector<Segment> S;\n while (N--) {\n double x1, y1, x2, y2;\n scanf(\"%lf %lf %lf %lf\", &x1, &y1, &x2, &y2);\n Segment seg = Segment(Point(x1, y1), Point(x2, y2));\n S.push_back(seg);\n }\n printf(\"%d\\n\", manhattanIntersection(S));\n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 16712, "score_of_the_acc": -0.2055, "final_rank": 11 }, { "submission_id": "aoj_CGL_6_A_10843500", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n vector<tuple<int, int, int, int>> points;\n for (int i = 0; i < n; i++)\n {\n int x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n if (x1 == x2)\n {\n if (y1 > y2)\n {\n swap(y1, y2);\n }\n //下の端点\n points.push_back( make_tuple(y1, 0, x1, x2) );\n //上の端点\n points.push_back( make_tuple(y2, 2, x1, x2) );\n }\n else\n {\n if (x1 > x2)\n {\n swap(x1, x2);\n }\n //水平線分\n points.push_back( make_tuple( y1, 1, x1, x2 ) );\n }\n }\n\n sort( points.begin(), points.end() );\n set<int> T;\n\n int ans = 0;\n\n for (int i = 0; i < points.size(); i++)\n {\n auto p = points[i];\n if ( get<1>(p) == 0 ) T.insert(get<2>(p));\n else if ( get<1>(p) == 2 ) T.erase(get<2>(p));\n else\n {\n auto l = T.lower_bound(get<2>(p));\n auto r = T.upper_bound(get<3>(p));\n ans += distance(l, r);\n }\n }\n\n cout << ans << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 9764, "score_of_the_acc": -0.1163, "final_rank": 5 }, { "submission_id": "aoj_CGL_6_A_10766576", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 4e5 + 5;\ntypedef long long ll;\n// 空间开16倍!\n\nstruct node \n{\n int l, r, cl, cr, f, w;\n}p[N * 4];\n\nstruct edgex\n{\n int l, r, y;\n}ax[N * 4];\n\nstruct edgey\n{\n int x, y, flag;\n}ay[N * 4];\n\nint n, m, mx, cnt, px[N];\n\nvoid build(int id, int L, int R)\n{\n p[id].l = L;\n p[id].r = R;\n p[id].w = p[id].f = 0;\n if(L == R)\n {\n p[id].cl = px[L];\n p[id].cr = px[R];\n return;\n }\n int mid = (L + R) / 2;\n build(id * 2, L, mid);\n build(id * 2 + 1, mid + 1, R);\n p[id].cl = p[id * 2].cl;\n p[id].cr = p[id * 2 + 1].cr;\n}\n\nvoid update(int id, int L, int x)\n{\n if(L == p[id].cl && L == p[id].cr)\n {\n p[id].w += x;\n p[id].f += x;\n return;\n }\n\n if(p[id * 2].cr >= L)\n\t\tupdate(id * 2, L, x);\n\telse\n \tupdate(id * 2 + 1, L, x);\n p[id].w = p[id * 2].w + p[id * 2 + 1].w;\n}\n\nint query(int id, int L, int R)\n{\n //cout << id << ' ' << p[id].cl << ' '<< p[id].cr << endl;\n if(L <= p[id].cl && p[id].cr <= R)\n return p[id].w;\n int res = 0;\n if(p[id * 2].cr >= L)\n res += query(id * 2, L, R);\n if(p[id * 2 + 1].cl <= R)\n res += query(id * 2 + 1, L, R);\n return res;\n}\n\nbool cmpy(edgey b, edgey c)\n{\n return b.y < c.y;\n}\n\nbool cmpx(edgex b, edgex c)\n{\n return b.y < c.y;\n}\n\nint main()\n{\n scanf(\"%d\", &n);\n int xa, ya, xb, yb;\n for(int i = 1; i <= n; i ++)\n {\n scanf(\"%d%d%d%d\", &xa, &ya, &xb, &yb);\n if(xa == xb)\n {\n ay[++ m].x = xa;\n ay[m].y = min(ya, yb);\n ay[m].flag = 1;\n ay[++ m].x = xa;\n ay[m].y = max(ya, yb) + 1;\n ay[m].flag = -1;\n px[++cnt] = xa;\n }\n else\n {\n px[++cnt] = ax[++ mx].l = min(xa, xb);\n ax[mx].y = ya;\n px[++cnt] = ax[mx].r = max(xa, xb);\n }\n }\n\n sort(px + 1, px + cnt + 1);\n int tot = unique(px + 1, px + cnt + 1) - px - 1;\n // for(int i = 1; i <= tot; i ++)\n // cout << px[i] << ' ';\n // cout <<\"tot = \"<< tot << endl;\n\tbuild(1, 1, tot);\n sort(ax + 1, ax + mx + 1, cmpx);\n sort(ay + 1, ay + m + 1, cmpy);\n \n ll ans = 0;\n int idx = 1;\n for(int i = 1; i <= mx; i ++)\n {\n while(ay[idx].y <= ax[i].y)\n {\n //cout << \"update = \" << ay[idx].x << endl;\n update(1, ay[idx].x, ay[idx].flag);\n idx ++;\n }\n //cout << \"query = \" << ax[i].l << ' ' << ax[i].r << endl;\n ans += query(1, ax[i].l, ax[i].r);\n }\n\n printf(\"%lld\\n\", ans);\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 16492, "score_of_the_acc": -0.1322, "final_rank": 8 }, { "submission_id": "aoj_CGL_6_A_10749927", "code_snippet": "#include <bits/stdc++.h>\n\n// https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/6/CGL_6_A\n// 给定 n 条和 X 轴和 Y 轴平行的直线, 求它们之间的交点个数\n// from: cpp.json\n#define INF 8e18\n#define int long long\nusing namespace std;\n\ntemplate <typename T>\nstruct Fenwick {\n int n;\n std::vector<T> a;\n \n Fenwick(int n_ = 0) {\n init(n_);\n }\n \n void init(int n_) {\n n = n_;\n a.assign(n + 1, T{});\n }\n \n void add(int x, const T &v) {\n for (int i = x; i <= n; i += i & -i) {\n a[i] += v;\n }\n }\n \n T sum(int x) {\n T ans{};\n for (int i = x; i > 0; i -= i & -i) {\n ans = ans + a[i];\n }\n return ans;\n }\n \n T rangeSum(int l, int r) {\n if (l > r) return T{};\n return sum(r) - sum(l - 1);\n }\n \n // 前缀和不超过给定值的最小位置的查询\n int select(const T &k) {\n int x = 0;\n T cur{};\n for (int i = 1 << std::__lg(n); i; i /= 2) {\n if (x + i <= n && cur + a[x + i] <= k) {\n x += i;\n cur = cur + a[x];\n }\n }\n return x;\n }\n};\n\nstruct Event {\n int x, type, y1, y2; \n};\n\nvoid solve() {\n int n;\n cin >> n;\n\n vector<tuple<int, int, int, int>> seg(n);\n vector<int> ys;\n\n for (int i = 0; i < n; i++) {\n int x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n if (x1 > x2) {\n swap(x1, x2);\n }\n if (y1 > y2) {\n swap(y1, y2);\n }\n seg[i] = {x1, y1, x2, y2};\n ys.push_back(y1);\n ys.push_back(y2);\n }\n\n ranges::sort(ys);\n ys.erase(unique(ys.begin(), ys.end()), ys.end());\n\n auto getY = [&](int y) -> int {\n return lower_bound(ys.begin(), ys.end(), y) - ys.begin() + 1;\n };\n\n int m = ys.size();\n\n vector<Event> e;\n for (auto [x1, y1, x2, y2] : seg) {\n if (y1 == y2) {\n int Y = getY(y1);\n e.push_back({x1, 0, Y, 0});\n e.push_back({x2 + 1, 1, Y, 0});\n } else {\n int Y1 = getY(y1);\n int Y2 = getY(y2);\n e.push_back({x1, 2, Y1, Y2});\n }\n }\n\n sort(e.begin(), e.end(), [&](auto &a, auto &b) {\n if (a.x != b.x) {\n return a.x < b.x;\n }\n return a.type < b.type;\n });\n\n Fenwick<int> bit(m + 1);\n int ans = 0;\n for (auto &E : e) {\n if (E.type == 0) {\n bit.add(E.y1, 1);\n } else if (E.type == 1) {\n bit.add(E.y1, -1);\n } else {\n ans += bit.rangeSum(E.y1, E.y2);\n }\n } \n\n cout << ans << '\\n';\n}\n\nsigned main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 17424, "score_of_the_acc": -0.124, "final_rank": 6 }, { "submission_id": "aoj_CGL_6_A_10749902", "code_snippet": "#include <bits/stdc++.h>\n\n// \n// from: cpp.json\n#define INF 8e18\n#define int long long\nusing namespace std;\n\ntemplate<class T>\nstruct Point {\n T x; \n T y; \n\n Point(const T &x_ = 0, const T &y_ = 0) : x(x_), y(y_) {}\n\n template<class U>\n operator Point<U>() {\n return Point<U>(U(x), U(y));\n }\n\n Point &operator+=(const Point &p) & {\n x += p.x;\n y += p.y;\n return *this;\n }\n \n Point &operator-=(const Point &p) & {\n x -= p.x;\n y -= p.y;\n return *this;\n }\n \n Point &operator*=(const T &v) & {\n x *= v;\n y *= v;\n return *this;\n }\n \n Point &operator/=(const T &v) & {\n x /= v;\n y /= v;\n return *this;\n }\n \n Point operator-() const {\n return Point(-x, -y);\n }\n \n friend Point operator+(Point a, const Point &b) {\n return a += b;\n }\n \n friend Point operator-(Point a, const Point &b) {\n return a -= b;\n }\n \n friend Point operator*(Point a, const T &b) {\n return a *= b;\n }\n \n friend Point operator/(Point a, const T &b) {\n return a /= b;\n }\n \n friend Point operator*(const T &a, Point b) {\n return b *= a;\n }\n \n friend bool operator==(const Point &a, const Point &b) {\n return a.x == b.x && a.y == b.y;\n }\n \n friend std::istream &operator>>(std::istream &is, Point &p) {\n return is >> p.x >> p.y;\n }\n \n friend std::ostream &operator<<(std::ostream &os, const Point &p) {\n return os << \"(\" << p.x << \", \" << p.y << \")\";\n }\n};\n\ntemplate<class T>\nstruct Line {\n Point<T> a; \n Point<T> b; \n Line(const Point<T> &a_ = Point<T>(), const Point<T> &b_ = Point<T>()) : a(a_), b(b_) {}\n};\n\n/*\n 计算向量 a 和 b 的点积(内积)\n dot(a, b) = a.x*b.x + a.y*b.y\n*/\ntemplate<class T>\nT dot(const Point<T> &a, const Point<T> &b) {\n return a.x * b.x + a.y * b.y;\n}\n\n/*\n 计算向量 a 和 b 的叉积(2D 向量的“伪叉积”)\n cross(a, b) = a.x*b.y - a.y*b.x\n 正值表示 b 在 a 的逆时针方向,负值表示顺时针方向\n*/\ntemplate<class T>\nT cross(const Point<T> &a, const Point<T> &b) {\n return a.x * b.y - a.y * b.x;\n}\n\n/*\n 计算点 p 的平方模:|p|^2 = dot(p, p)\n*/\ntemplate<class T>\nT square(const Point<T> &p) {\n return dot(p, p);\n}\n\n/*\n 计算点 p 的长度(欧几里得范数),返回 double\n*/\ntemplate<class T>\ndouble length(const Point<T> &p) {\n return std::sqrt(square(p));\n}\n\n/*\n 计算线段 l 的长度\n 通过端点之差的长度来计算\n*/\ntemplate<class T>\ndouble length(const Line<T> &l) {\n return length(l.a - l.b);\n}\n\n/*\n 将向量 p 归一化:返回单位向量 p/|p|\n 注意:调用者需保证 p != (0,0)\n*/\ntemplate<class T>\nPoint<T> normalize(const Point<T> &p) {\n return p / length(p);\n}\n\n/*\n 判断两条直线(线段) l1, l2 是否平行\n 平行当且仅当方向向量叉积为 0\n*/\ntemplate<class T>\nbool parallel(const Line<T> &l1, const Line<T> &l2) {\n return cross(l1.b - l1.a, l2.b - l2.a) == 0;\n}\n\n/*\n 计算两点 a, b 之间的距离,等价于 |a - b|\n*/\ntemplate<class T>\ndouble distance(const Point<T> &a, const Point<T> &b) {\n return length(a - b);\n}\n\nusing LD = long double; \nusing P = Point<LD>; \n\nconstexpr LD eps = 0; \n\ntemplate <typename T>\nstruct Fenwick {\n int n;\n std::vector<T> a;\n \n Fenwick(int n_ = 0) {\n init(n_);\n }\n \n void init(int n_) {\n n = n_;\n a.assign(n + 1, T{});\n }\n \n void add(int x, const T &v) {\n for (int i = x; i <= n; i += i & -i) {\n a[i] += v;\n }\n }\n \n T sum(int x) {\n T ans{};\n for (int i = x; i > 0; i -= i & -i) {\n ans = ans + a[i];\n }\n return ans;\n }\n \n T rangeSum(int l, int r) {\n if (l > r) return T{};\n return sum(r) - sum(l - 1);\n }\n \n // 前缀和不超过给定值的最小位置的查询\n int select(const T &k) {\n int x = 0;\n T cur{};\n for (int i = 1 << std::__lg(n); i; i /= 2) {\n if (x + i <= n && cur + a[x + i] <= k) {\n x += i;\n cur = cur + a[x];\n }\n }\n return x;\n }\n};\n\nstruct Event {\n int x, type, y1, y2; \n};\n\nvoid solve() {\n int n;\n cin >> n;\n\n vector<tuple<int, int, int, int>> seg(n);\n vector<int> ys;\n\n for (int i = 0; i < n; i++) {\n int x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n if (x1 > x2) {\n swap(x1, x2);\n }\n if (y1 > y2) {\n swap(y1, y2);\n }\n seg[i] = {x1, y1, x2, y2};\n ys.push_back(y1);\n ys.push_back(y2);\n }\n\n ranges::sort(ys);\n ys.erase(unique(ys.begin(), ys.end()), ys.end());\n\n auto getY = [&](int y) -> int {\n return lower_bound(ys.begin(), ys.end(), y) - ys.begin() + 1;\n };\n\n int m = ys.size();\n\n vector<Event> e;\n for (auto [x1, y1, x2, y2] : seg) {\n if (y1 == y2) {\n int Y = getY(y1);\n e.push_back({x1, 0, Y, 0});\n e.push_back({x2 + 1, 1, Y, 0});\n } else {\n int Y1 = getY(y1);\n int Y2 = getY(y2);\n e.push_back({x1, 2, Y1, Y2});\n }\n }\n\n sort(e.begin(), e.end(), [&](auto &a, auto &b) {\n if (a.x != b.x) {\n return a.x < b.x;\n }\n return a.type < b.type;\n });\n\n Fenwick<int> bit(m + 1);\n int ans = 0;\n for (auto &E : e) {\n if (E.type == 0) {\n bit.add(E.y1, 1);\n } else if (E.type == 1) {\n bit.add(E.y1, -1);\n } else {\n ans += bit.rangeSum(E.y1, E.y2);\n }\n } \n\n cout << ans << '\\n';\n}\n\nsigned main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 16652, "score_of_the_acc": -0.1115, "final_rank": 4 }, { "submission_id": "aoj_CGL_6_A_10749888", "code_snippet": "#include <bits/stdc++.h>\n\n// \n// from: cpp.json\n#define INF 8e18\n#define int long long\nusing namespace std;\n\ntemplate<class T>\nstruct Point {\n T x; \n T y; \n\n Point(const T &x_ = 0, const T &y_ = 0) : x(x_), y(y_) {}\n\n template<class U>\n operator Point<U>() {\n return Point<U>(U(x), U(y));\n }\n\n Point &operator+=(const Point &p) & {\n x += p.x;\n y += p.y;\n return *this;\n }\n \n Point &operator-=(const Point &p) & {\n x -= p.x;\n y -= p.y;\n return *this;\n }\n \n Point &operator*=(const T &v) & {\n x *= v;\n y *= v;\n return *this;\n }\n \n Point &operator/=(const T &v) & {\n x /= v;\n y /= v;\n return *this;\n }\n \n Point operator-() const {\n return Point(-x, -y);\n }\n \n friend Point operator+(Point a, const Point &b) {\n return a += b;\n }\n \n friend Point operator-(Point a, const Point &b) {\n return a -= b;\n }\n \n friend Point operator*(Point a, const T &b) {\n return a *= b;\n }\n \n friend Point operator/(Point a, const T &b) {\n return a /= b;\n }\n \n friend Point operator*(const T &a, Point b) {\n return b *= a;\n }\n \n friend bool operator==(const Point &a, const Point &b) {\n return a.x == b.x && a.y == b.y;\n }\n \n friend std::istream &operator>>(std::istream &is, Point &p) {\n return is >> p.x >> p.y;\n }\n \n friend std::ostream &operator<<(std::ostream &os, const Point &p) {\n return os << \"(\" << p.x << \", \" << p.y << \")\";\n }\n};\n\ntemplate<class T>\nstruct Line {\n Point<T> a; \n Point<T> b; \n Line(const Point<T> &a_ = Point<T>(), const Point<T> &b_ = Point<T>()) : a(a_), b(b_) {}\n};\n\n/*\n 计算向量 a 和 b 的点积(内积)\n dot(a, b) = a.x*b.x + a.y*b.y\n*/\ntemplate<class T>\nT dot(const Point<T> &a, const Point<T> &b) {\n return a.x * b.x + a.y * b.y;\n}\n\n/*\n 计算向量 a 和 b 的叉积(2D 向量的“伪叉积”)\n cross(a, b) = a.x*b.y - a.y*b.x\n 正值表示 b 在 a 的逆时针方向,负值表示顺时针方向\n*/\ntemplate<class T>\nT cross(const Point<T> &a, const Point<T> &b) {\n return a.x * b.y - a.y * b.x;\n}\n\n/*\n 计算点 p 的平方模:|p|^2 = dot(p, p)\n*/\ntemplate<class T>\nT square(const Point<T> &p) {\n return dot(p, p);\n}\n\n/*\n 计算点 p 的长度(欧几里得范数),返回 double\n*/\ntemplate<class T>\ndouble length(const Point<T> &p) {\n return std::sqrt(square(p));\n}\n\n/*\n 计算线段 l 的长度\n 通过端点之差的长度来计算\n*/\ntemplate<class T>\ndouble length(const Line<T> &l) {\n return length(l.a - l.b);\n}\n\n/*\n 将向量 p 归一化:返回单位向量 p/|p|\n 注意:调用者需保证 p != (0,0)\n*/\ntemplate<class T>\nPoint<T> normalize(const Point<T> &p) {\n return p / length(p);\n}\n\n/*\n 判断两条直线(线段) l1, l2 是否平行\n 平行当且仅当方向向量叉积为 0\n*/\ntemplate<class T>\nbool parallel(const Line<T> &l1, const Line<T> &l2) {\n return cross(l1.b - l1.a, l2.b - l2.a) == 0;\n}\n\n/*\n 计算两点 a, b 之间的距离,等价于 |a - b|\n*/\ntemplate<class T>\ndouble distance(const Point<T> &a, const Point<T> &b) {\n return length(a - b);\n}\n\nusing LD = long double; \nusing P = Point<LD>; \n\nconstexpr LD eps = 0; \n\ntemplate<typename T>\nstruct Fenwick {\n int n;\n vector<T> a;\n Fenwick(int _n = 0) { init(_n); }\n void init(int _n) {\n n = _n;\n a.assign(n+1, T{}); \n }\n void add(int x, const T &v) {\n for (int i = x; i <= n; i += i & -i)\n a[i] += v;\n }\n T sum(int x) const {\n T s = T{};\n for (int i = x; i > 0; i -= i & -i)\n s += a[i];\n return s;\n }\n T rangeSum(int l, int r) const {\n if (l > r) return T{};\n return sum(r) - sum(l - 1);\n }\n};\n\nstruct Event {\n int x, type, y1, y2; \n};\n\nvoid solve() {\n int n;\n cin >> n;\n\n vector<tuple<int, int, int, int>> seg(n);\n vector<int> ys;\n\n for (int i = 0; i < n; i++) {\n int x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n if (x1 > x2) {\n swap(x1, x2);\n }\n if (y1 > y2) {\n swap(y1, y2);\n }\n seg[i] = {x1, y1, x2, y2};\n ys.push_back(y1);\n ys.push_back(y2);\n }\n\n ranges::sort(ys);\n ys.erase(unique(ys.begin(), ys.end()), ys.end());\n\n auto getY = [&](int y) -> int {\n return lower_bound(ys.begin(), ys.end(), y) - ys.begin() + 1;\n };\n\n int m = ys.size();\n\n vector<Event> e;\n for (auto [x1, y1, x2, y2] : seg) {\n if (y1 == y2) {\n int Y = getY(y1);\n e.push_back({x1, 0, Y, 0});\n e.push_back({x2 + 1, 1, Y, 0});\n } else {\n int Y1 = getY(y1);\n int Y2 = getY(y2);\n e.push_back({x1, 2, Y1, Y2});\n }\n }\n\n sort(e.begin(), e.end(), [&](auto &a, auto &b) {\n if (a.x != b.x) {\n return a.x < b.x;\n }\n return a.type < b.type;\n });\n\n Fenwick<int> bit(m + 1);\n int ans = 0;\n for (auto &E : e) {\n if (E.type == 0) {\n bit.add(E.y1, 1);\n } else if (E.type == 1) {\n bit.add(E.y1, -1);\n } else {\n ans += bit.rangeSum(E.y1, E.y2);\n }\n } \n\n cout << ans << '\\n';\n}\n\nsigned main() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n\n solve();\n\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 17684, "score_of_the_acc": -0.1282, "final_rank": 7 }, { "submission_id": "aoj_CGL_6_A_10737993", "code_snippet": "#include<iostream>\n#include<fstream>\n#include<iomanip>\n#include<cmath>\n#include<vector>\n#include<list>\n#include<stack>\n#include<queue>\n#include<deque>\n#include<string>\n#include<bitset>\n#include<algorithm>\n#include<ctime>\n#include<cstdarg>\n#include<assert.h>\n#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<map>\n#include<assert.h>\n#include<set>\nusing namespace std;\ntypedef long long ll;\n#define eps (1e-10)\n#define equals(a,b) (fabs((a)-(b))<eps)\nclass Point\n{\npublic:\n double x,y;\n Point(double x=0,double y=0):x(x),y(y) {}\n Point operator + (Point p)\n {\n return Point(x+p.x,y+p.y);\n }\n Point operator - (Point p)\n {\n return Point(x-p.x,y-p.y);\n }\n Point operator * (double a)\n {\n return Point(x*a,y*a);\n }\n Point operator / (double a)\n {\n return Point(x/a,y/a);\n }\n double norm()\n {\n return x*x+y*y;\n }\n double abs()\n {\n return sqrt(norm());\n }\n bool operator < (const Point &p)const\n {\n return x!=p.x? x<p.x:y<p.y;\n }\n bool operator == (const Point &p)const\n {\n return fabs(x-p.x)<eps&&fabs(y-p.y)<eps;\n }\n};\ntypedef Point Vector;\nstruct Segment\n{\n Point p1,p2;\n};\ntypedef Segment Line;\nclass Circle\n{\npublic:\n Point c;\n double r;\n Circle(Point c=Point(),double r=0.0):c(c),r(r) {}\n};\ndouble dot(Vector a,Vector b)//内积\n{\n return a.x*b.x+a.y*b.y;\n}\ndouble cross(Vector a,Vector b)//外积\n{\n return a.x*b.y-a.y*b.x;\n}\nbool isOrthogonal(Vector a,Vector b)//是否正交\n{\n return equals(dot(a,b),0.0);\n}\nbool isOrthogonal(Point a1,Point a2,Point b1,Point b2)//是否正交\n{\n return isOrthogonal(a1-a2,b1-b2);\n}\nbool isOrthogonal(Segment s1,Segment s2)//是否正交\n{\n return equals(dot(s1.p2-s1.p1,s2.p2-s2.p1),0.0);\n}\nbool isParallel(Vector a,Vector b)//是否平行\n{\n return equals(cross(a,b),0.0);\n}\nbool isParallel(Point a1,Point a2,Point b1,Point b2)//是否平行\n{\n return isParallel(a1-a2,b1-b2);\n}\nbool isParallel(Segment s1,Segment s2)//是否平行\n{\n return equals(cross(s1.p2-s1.p1,s2.p2-s2.p1),0.0);\n}\nPoint project(Segment s,Point p)//点p在线段上的投影\n{\n Vector base=s.p2-s.p1;\n double r=dot(p-s.p1,base)/base.norm();\n return s.p1+base*r;\n}\nPoint reflect(Segment s,Point p)//映像,p关于s的对称点\n{\n return p+(project(s,p)-p)*2.0;\n}\ndouble getDistance(Point a,Point b)//点与点之间的距离\n{\n return (a-b).abs();\n}\ndouble getDistanceLP(Line l,Point p)//点与线之间的距离\n{\n return abs(cross(l.p2-l.p1,p-l.p1)/(l.p2-l.p1).abs());\n}\ndouble getDistanceSP(Segment s,Point p)//点与线段之间的距离\n{\n if (dot(s.p2-s.p1,p-s.p1)<0.0)return (p-s.p1).abs();\n if (dot(s.p1-s.p2,p-s.p2)<0.0)return (p-s.p2).abs();\n return getDistanceLP(s,p);\n}\nbool intersect(Segment s1,Segment s2);//线段是否相交\ndouble getDistance(Segment s1,Segment s2)//线段与线段之间的距离\n{\n if (intersect(s1,s2))return 0.0;\n return min(min(getDistanceSP(s1,s2.p1),getDistanceSP(s1,s2.p2)),\n min(getDistanceSP(s2,s1.p1),getDistanceSP(s2,s1.p2)));\n}\nstatic const int COUNTER_CLOCKWISE=1;//p2在p0->p1的逆时针\nstatic const int CLOCKWISE=-1;//p2在p0->p1的顺时针\nstatic const int ONLINE_BACK=2;//共线p2->p0->p1\nstatic const int ONLINE_FRONT=-2;//共线p0->p1->p2\nstatic const int ON_SEGMENT=0;//共线p0->p2->p1\nint ccw(Point p0,Point p1,Point p2)\n{\n Vector a=p1-p0;\n Vector b=p2-p0;\n if (cross(a,b)>eps)return COUNTER_CLOCKWISE;\n if (cross(a,b)<-eps)return CLOCKWISE;\n if (dot(a,b)<-eps)return ONLINE_BACK;\n if (a.norm()<b.norm())return ONLINE_FRONT;\n return ON_SEGMENT;\n}\nbool intersect(Point p1,Point p2,Point p3,Point p4)//线段p1p2,p3p4是否相交\n{\n return (ccw(p1,p2,p3)*ccw(p1,p2,p4)<=0&&\n ccw(p3,p4,p1)*ccw(p3,p4,p2)<=0);\n}\nbool intersect(Segment s1,Segment s2)//线段与线段是否相交\n{\n return intersect(s1.p1,s1.p2,s2.p1,s2.p2);\n}\nbool intersect(Circle c,Line l)//圆与线是否相交//自己写的\n{\n return c.r>=getDistanceLP(l,c.c);\n}\nbool intersect(Circle c1,Circle c2)//圆与圆是否相交//自己写的\n{\n return c1.r+c2.r>=getDistance(c1.c,c2.c);\n}\nPoint getCrossPoint(Segment s1,Segment s2)//线段的交点\n{\n Vector base=s2.p2-s2.p1;\n double d1=abs(cross(base,s1.p1-s2.p1));\n double d2=abs(cross(base,s1.p2-s2.p1));\n double t=d1/(d1+d2);\n return s1.p1+(s1.p2-s1.p1)*t;\n}\npair<Point,Point> getCrossPoint(Circle c,Line l)\n{\n assert(intersect(c,l));\n Vector pr=project(l,c.c);\n Vector e=(l.p2-l.p1)/(l.p2-l.p1).abs();\n double base=sqrt(c.r*c.r-(pr-c.c).norm());\n return make_pair(pr+e*base,pr-e*base);\n}\ndouble arg(Vector p)\n{\n return atan2(p.y,p.x);\n}\nVector polar(double a,double r)\n{\n return Point(cos(r)*a,sin(r)*a);\n}\npair<Point,Point> getCrossPoint(Circle c1,Circle c2)\n{\n assert(intersect(c1,c2));\n double d=(c1.c-c2.c).abs();\n double a=acos((c1.r*c1.r+d*d-c2.r*c2.r)/(2*c1.r*d));\n double t=arg(c2.c-c1.c);\n return make_pair(c1.c+polar(c1.r,t+a),c1.c+polar(c1.r,t-a));\n}\ntypedef vector<Point> Polygon;\nstatic const int IN=2;\nstatic const int ON=1;\nstatic const int OUT=0;\nint contains(Polygon g,Point p)//点与多边形的位置\n{\n int n=g.size();\n bool x=false;\n for (int i=0; i<n; ++i)\n {\n Point a=g[i]-p,b=g[(i+1)%n]-p;\n if (abs(cross(a,b))<eps&&dot(a,b)<eps)return 1;\n if (a.y>b.y)swap(a,b);\n if (a.y<eps&&eps<b.y&&cross(a,b)>eps)x=!x;\n }\n return (x? 2:0);\n}\nPolygon andrewScan(Polygon s)//安德鲁算法求凸包\n{\n Polygon u,l;\n if (s.size()<3)return s;\n sort(s.begin(),s.end());\n u.push_back(s[0]);\n u.push_back(s[1]);\n l.push_back(s[s.size()-1]);\n l.push_back(s[s.size()-2]);\n for (int i=2; i<s.size(); ++i)\n {\n for (int n=u.size(); n>=2&&ccw(u[n-2],u[n-1],s[i])==COUNTER_CLOCKWISE; --n)//书上改之前!=CLOCKWISE,这样会把同一条线上的点给去掉\n u.pop_back();\n u.push_back(s[i]);\n }\n for (int i=s.size()-3; i>=0; --i)\n {\n for (int n=l.size(); n>=2&&ccw(l[n-2],l[n-1],s[i])==COUNTER_CLOCKWISE; --n)//书上改之前!=CLOCKWISE,这样会把同一条线上的点给去掉\n l.pop_back();\n l.push_back(s[i]);\n }\n reverse(l.begin(),l.end());\n for (int i=u.size()-2; i>=1; --i)\n l.push_back(u[i]);\n return l;\n}\n//端点种类\n#define BOTTOM 0\n#define LEFT 1\n#define RIGHT 2\n#define TOP 3\nclass EndPoint\n{\npublic:\n Point p;\n int seg,st;//线段id,端点种类\n EndPoint() {}\n EndPoint(Point p,int seg,int st):p(p),seg(seg),st(st) {}\n bool operator < (const EndPoint &ep)const\n {\n return p.y==ep.p.y? st<ep.st:p.y<ep.p.y;\n }\n};\nEndPoint EP[2*100000];\nint manhattanIntersection(vector<Segment> S)\n{\n int n=S.size();\n for (int i=0,k=0; i<n; ++i) //调整端点使得p1p2左小右大\n {\n if (S[i].p1.y==S[i].p2.y)\n {\n if (S[i].p1.x>S[i].p2.x)swap(S[i].p1,S[i].p2);\n }\n else if (S[i].p1.y>S[i].p2.y)swap(S[i].p1,S[i].p2);\n\n if (S[i].p1.y==S[i].p2.y)//添加水平\n {\n EP[k++]=EndPoint(S[i].p1,i,LEFT);\n EP[k++]=EndPoint(S[i].p2,i,RIGHT);\n }\n else//添加垂直\n {\n EP[k++]=EndPoint(S[i].p1,i,BOTTOM);\n EP[k++]=EndPoint(S[i].p2,i,TOP);\n }\n }\n sort(EP,EP+2*n);//按y升序排列\n\n set<int>BST;\n BST.insert(1000000001);\n int cnt=0;\n for (int i=0; i<2*n; ++i)\n if (EP[i].st==TOP)//删除上端\n BST.erase(EP[i].p.x);\n else if (EP[i].st==BOTTOM)//删除下端\n BST.insert(EP[i].p.x);\n else if (EP[i].st==LEFT)\n {\n set<int>::iterator b=BST.lower_bound(S[EP[i].seg].p1.x);\n set<int>::iterator e=BST.upper_bound(S[EP[i].seg].p2.x);\n cnt+=distance(b,e);\n }\n return cnt;\n}\nint n;\nSegment s;\nvector<Segment>v;\nint main()\n{\n cin>>n;\n for (int i=0; i<n; ++i)\n {\n cin>>s.p1.x>>s.p1.y>>s.p2.x>>s.p2.y;\n v.push_back(s);\n }\n cout<<manhattanIntersection(v)<<\"\\n\";\n}", "accuracy": 1, "time_ms": 120, "memory_kb": 17096, "score_of_the_acc": -0.328, "final_rank": 17 }, { "submission_id": "aoj_CGL_6_A_10737989", "code_snippet": "#include <bits/stdc++.h>\n#define lo(i, n, m) for (int i = n; i < m; i++)\n#define loe(i, n, m) for (int i = n; i <= m; i++)\n#define mk make_pair\nusing namespace std;\ntypedef pair<int, int> Point;\nstruct Node {\n Point s, t;\n int id; \n Node (const Point &ns = Point(0, 0), const Point &nt = Point(0, 0), int nid = 0) : s(ns), t(nt), id(nid) {}\n bool operator < (const Node &n) const {\n if (s.first != n.s.first) return s.first < n.s.first;\n return id < n.id;\n } \n};\nconst int LIM = 3e5 + 10; \nint cur;\nNode d[LIM];\nint main(void) {\n ios::sync_with_stdio(false);\n cin.tie(NULL), cout.tie(NULL);\n int n;\n cin >> n;\n lo(i, 0, n) {\n Point s, t;\n cin >> s.first >> s.second >> t.first >> t.second;\n if (s.first != t.first) {\n if (s.first < t.first) {\n d[cur++] = Node(s, mk(0, 0), 1); \n d[cur++] = Node(t, mk(0, 0), 3); \n } else {\n d[cur++] = Node(t, mk(0, 0), 1); \n d[cur++] = Node(s, mk(0, 0), 3); \n }\n } else d[cur++] = Node(s, t, 2); \n } \n sort(d, d + cur);\n set<int> act;\n int ans = 0;\n lo(i, 0, cur) {\n if (d[i].id == 1) {\n act.insert(d[i].s.second);\n } else if (d[i].id == 2) {\n set<int>::iterator ite = act.lower_bound(min(d[i].s.second, d[i].t.second));\n for (; ite != act.end() && *ite <= max(d[i].s.second, d[i].t.second); ite++, ans++);\n } else {\n act.erase(act.find(d[i].s.second));\n }\n }\n cout << ans<<\"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 12128, "score_of_the_acc": -0.108, "final_rank": 3 }, { "submission_id": "aoj_CGL_6_A_10737988", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <set>\nusing namespace std;\n#define EPS (1e-10)\n#define equals(a,b) (fabs((a) - (b)) < EPS)\n\n// 点类\nclass Point {\npublic :\n double x, y;\n Point() {};\n Point(double x, double y) :x(x), y(y) {}\n\n Point operator + (Point p) { return Point(x + p.x, y + p.y); }\n Point operator - (Point p) { return Point(x - p.x, y - p.y); }\n Point operator * (double a) { return Point(x * a, y * a); }\n Point operator / (double a) { return Point(x / a, y / a); }\n\n bool operator < (const Point &p) const {\n return x != p.x ? x < p.x : y < p.y;\n }\n\n bool operator == (const Point &p) const {\n return fabs(x - p.x) < EPS && fabs(y - p.y) < EPS;\n }\n};\n// 线段类\nclass Segment {\npublic:\n Point p1, p2;\n Segment() {};\n Segment(Point p1, Point p2) :p1(p1), p2(p2) {};\n};\n\n#define BOTTOM 0\n#define LEFT 1\n#define RIGHT 2\n#define TOP 3\n\nclass EndPoint {\npublic :\n Point p;\n int seg, st; // 线段的ID,端点的种类\n EndPoint() {}\n EndPoint(Point p, int seg, int st) :p(p), seg(seg), st(st) {}\n\n bool operator < (const EndPoint &ep) const {\n // 按y坐标升序排序\n if (p.y == ep.p.y) {\n return st < ep.st;\n }else {\n return p.y < ep.p.y;\n }\n }\n\n};\nEndPoint EP[2 * 1000010];\n\n// 线段相交问题,曼哈顿几何\nint manhattanIntersection(vector<Segment> S) {\n int n = S.size();\n //按照端点的y坐标升序排序\n sort(EP, EP + (2 * n));\n\n set<int> BT; \n BT.insert(10000000001); \n int cnt = 0;\n\n for (int i = 0; i < 2 * n; i++) {\n if (EP[i].st == TOP)\n BT.erase(EP[i].p.x); //删除上端点\n else if (EP[i].st == BOTTOM)\n BT.insert(EP[i].p.x);\n else if (EP[i].st == LEFT) {\n set<int>::iterator b = BT.lower_bound(S[EP[i].seg].p1.x);\n set<int>::iterator e = BT.upper_bound(S[EP[i].seg].p2.x);\n\n // 加上b到e距离\n cnt += distance(b, e);\n }\n\n }\n return cnt;\n}\nint main() {\n vector<Segment> S;\n Segment seg;\n int n , k = 0;\n scanf(\"%d\", &n);\n for (int i = 0; i < n; i++) {\n scanf(\"%lf %lf %lf %lf\", &seg.p1.x, &seg.p1.y, &seg.p2.x, &seg.p2.y);\n //调整端点p1、p2,保证左小右大\n if (seg.p1.y == seg.p2.y) {\n if (seg.p1.x > seg.p2.x)\n swap(seg.p1, seg.p2);\n }\n else if (seg.p1.y > seg.p2.y) {\n swap(seg.p1, seg.p2);\n }\n\n // 将水平线段添加到端点列表\n if (seg.p1.y == seg.p2.y) {\n EP[k++] = EndPoint(seg.p1, i, LEFT);\n EP[k++] = EndPoint(seg.p2, i, RIGHT);\n }\n else { // 将垂直线段添加到端点列表\n EP[k++] = EndPoint(seg.p1, i, BOTTOM);\n EP[k++] = EndPoint(seg.p2, i, TOP);\n }\n S.push_back(seg);\n }\n\n printf(\"%d\\n\", manhattanIntersection(S));\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 18284, "score_of_the_acc": -0.2077, "final_rank": 12 }, { "submission_id": "aoj_CGL_6_A_10737987", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <set>\nusing namespace std;\n#define EPS (1e-10)\n#define equals(a,b) (fabs((a) - (b)) < EPS)\n\n// 点类\nclass Point {\npublic :\n double x, y;\n Point() {};\n Point(double x, double y) :x(x), y(y) {}\n\n Point operator + (Point p) { return Point(x + p.x, y + p.y); }\n Point operator - (Point p) { return Point(x - p.x, y - p.y); }\n Point operator * (double a) { return Point(x * a, y * a); }\n Point operator / (double a) { return Point(x / a, y / a); }\n\n bool operator < (const Point &p) const {\n return x != p.x ? x < p.x : y < p.y;\n }\n\n bool operator == (const Point &p) const {\n return fabs(x - p.x) < EPS && fabs(y - p.y) < EPS;\n }\n};\n// 线段类\nclass Segment {\npublic:\n Point p1, p2;\n Segment() {};\n Segment(Point p1, Point p2) :p1(p1), p2(p2) {};\n};\n\n#define BOTTOM 0\n#define LEFT 1\n#define RIGHT 2\n#define TOP 3\n\nclass EndPoint {\npublic :\n Point p;\n int seg, st; // 线段的ID,端点的种类\n EndPoint() {}\n EndPoint(Point p, int seg, int st) :p(p), seg(seg), st(st) {}\n\n bool operator < (const EndPoint &ep) const {\n // 按y坐标升序排序\n if (p.y == ep.p.y) {\n return st < ep.st;\n }else {\n return p.y < ep.p.y;\n }\n }\n\n};\nEndPoint EP[2 * 1000010];\n\n// 线段相交问题,曼哈顿几何\nint manhattanIntersection(vector<Segment> S) {\n int n = S.size();\n //按照端点的y坐标升序排序\n sort(EP, EP + (2 * n));\n\n set<int> BT; // 二叉搜索树\n BT.insert(10000000001); // 设置标记\n int cnt = 0;\n\n for (int i = 0; i < 2 * n; i++) {\n if (EP[i].st == TOP)\n BT.erase(EP[i].p.x); //删除上端点\n else if (EP[i].st == BOTTOM)\n BT.insert(EP[i].p.x);\n else if (EP[i].st == LEFT) {\n set<int>::iterator b = BT.lower_bound(S[EP[i].seg].p1.x);\n set<int>::iterator e = BT.upper_bound(S[EP[i].seg].p2.x);\n\n // 加上b到e距离\n cnt += distance(b, e);\n }\n\n }\n return cnt;\n}\nint main() {\n vector<Segment> S;\n Segment seg;\n int n , k = 0;\n scanf(\"%d\", &n);\n for (int i = 0; i < n; i++) {\n scanf(\"%lf %lf %lf %lf\", &seg.p1.x, &seg.p1.y, &seg.p2.x, &seg.p2.y);\n //调整端点p1、p2,保证左小右大\n if (seg.p1.y == seg.p2.y) {\n if (seg.p1.x > seg.p2.x)\n swap(seg.p1, seg.p2);\n }\n else if (seg.p1.y > seg.p2.y) {\n swap(seg.p1, seg.p2);\n }\n\n // 将水平线段添加到端点列表\n if (seg.p1.y == seg.p2.y) {\n EP[k++] = EndPoint(seg.p1, i, LEFT);\n EP[k++] = EndPoint(seg.p2, i, RIGHT);\n }\n else { // 将垂直线段添加到端点列表\n EP[k++] = EndPoint(seg.p1, i, BOTTOM);\n EP[k++] = EndPoint(seg.p2, i, TOP);\n }\n S.push_back(seg);\n }\n\n printf(\"%d\\n\", manhattanIntersection(S));\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 19132, "score_of_the_acc": -0.2214, "final_rank": 14 }, { "submission_id": "aoj_CGL_6_A_10737979", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int maxn=1e6+50;//注意修改大小\nconst double eps=1e-8;\nconst double PI=acos(1.0);\nconst double INF=1e9;//无穷大,视情况修改\n#define sgn2(x) ((x)>eps?1:((x)<-eps?2:0))//x>0:1;x<0:2;x=0:0.\n#define zero(x) (((x)>0?(x):-(x))<eps)//x=0返回1,否则返回0\nlong long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}\nll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}\n\n\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//---------------------------------------------------点------------------------------------------------------------------------------//\n//-----------------------------------------------------------------------------------------------------------------------------------//\ninline double R_to_D(double rad){ return 180/PI*rad; }//弧度转角度\ninline double D_to_R(double D){ return PI/180*D; }//角度转弧度\nint sgn(double x){\n if(fabs(x) < eps)return 0;//x==0\n if(x < 0)return -1;//x<0\n return 1;//x>0\n}//!三态函数sgn用于判断相等,减少精度误差问题\nstruct Point{\n double x, y;\n Point(double x = 0, double y = 0):x(x), y(y){}//构造函数\n};\ntypedef Point Vector;//!注意区分点和向量\ntypedef vector<Point> Polygon;//定义多边形:即多个Point顺序组成的\nVector operator + (Vector A, Vector B){return Vector(A.x + B.x, A.y + B.y);}//向量 + 向量 = 向量,点 + 向量 = 向量\nVector operator - (Point A, Point B){return Vector(A.x - B.x, A.y - B.y);}//点 - 点 = 向量(向量AB = B - A)\nVector operator * (Vector A, double p){return Vector(A.x * p, A.y * p);}//向量 * 数 = 向量\nVector operator / (Vector A, double p){return Vector(A.x / p, A.y / p);}//!向量 / 数= 向量\nbool operator < (const Point& A, const Point& B) {return A.x < B.x || (A.x == B.x && A.y < B. y);}//点or向量 的比较函数(优先横向排序)\nbool operator == (const Point& A, const Point& B){return !sgn(A.x - B.x) && !sgn(A.y - B.y);}//点or向量 的相等函数\ndouble Polar_angle(Vector A){return atan2(A.y, A.x);}//求极角:在极坐标系中,平面上任何一点到极点的连线和极轴的夹角叫做极角。单位弧度rad\ndouble Dot(Vector A, Vector B){return A.x * B.x + A.y * B.y;}//点积(满足交换律):a·b=|a||b|cos<a,b> A.x*B.x+A.y*B.y;\ndouble Cross(Vector A, Vector B){return A.x * B.y - B.x * A.y;}//向量的叉积(不满足交换律):等于两向量有向面积的二倍(若B在A的逆时针方向,则为正值;顺时针则为负值;共线则为0).cross(x, y) = -cross(y, x)\ndouble LeftTest_Point(Point A, Point B, Point C){return Cross(B - A, C - B);}//判断向量BC是不是向AB的逆时针方向(左边)转(ToLeftTest);也可看作一个点C是否在向量AB的左边:是则>0,不是则<0,共线则=0\ndouble LeftTest_Vector(Vector A, Vector B){return Cross(A,B);}//判断向量B是不是向量A的逆时针方向(左边):是则>0,不是则<0,共线则=0\ndouble Length(Vector A){return sqrt(Dot(A, A));}//取模\ndouble Angle(Vector A, Vector B){return acos(Dot(A, B) / Length(A) / Length(B));}//计算两向量夹角(Angle),返回值为弧度制下的夹角\ndouble Area2(Point A, Point B, Point C){return Cross(B - A, C - A);}//交点为A的两个向量AB和AC,然后求这两个向量的叉积(叉乘),ABxAC=平行四边形的面积\ndouble Dist(Point A,Point B){return sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));}\nVector Normal(Vector A) {double L = Length(A);return Vector(-A.y / L, A.x / L);}//向量A的法向量:向量A逆时针旋转九十度之后的单位向量\nVector Format(Vector A) {double L = Length(A);return Vector(A.x / L,A.y / L);}//向量A的单位向量化\nVector Rotate(Vector A, double rad){return Vector(A.x*cos(rad)-A.y*sin(rad),A.x*sin(rad)+A.y*cos(rad));}//向量A逆时针旋转后的向量:x'=xcosa -ysina, y'= xsina+ycosa,rad:弧度且为逆时针旋转的角\nPoint Turn_B(Point A, Point B, double rad){\n double x = (A.x-B.x) * cos(rad) + (A.y-B.y) * sin(rad) + B.x;\n double y = - (A.x-B.x) * sin(rad) + (A.y-B.y) * cos(rad) + B.y; \n return Point(x,y);\n}//将点A绕点B顺时针旋转rad(弧度)\n\n\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//---------------------------------------------------直线----------------------------------------------------------------------------//\n//-----------------------------------------------------------------------------------------------------------------------------------//\nstruct Line{\n Vector v;//方向向量。左边就是对应的半平面\n Point p;//直线上任意一点\n Line(Vector v, Point p):v(v), p(p) {}\n //如果需要使用极角就使用下面的代码,主要注释上面一行\n // double deg;//极角\n // Line(Vector v,Point p):p(p), v(v){deg = atan2(v.y, v.x);}\n // bool operator < (const Line& L)const {//排序时使用的比较运算符 由x正向逆时针到x正向\n // return deg < L.deg;\n // }\n};//直线定义:P'=P+v*t\nstruct Segment {\n Point p1, p2;\n\tSegment() {};\n\tSegment(Point p1, Point p2) :p1(p1), p2(p2) {};\n};//线段定义:两个端点\nint Relation(Point A, Point B, Point C){int c = sgn(Cross((B - A), (C - A)));if(c < 0) return 1;else if(c > 0) return -1;return 0;}//点C和直线AB关系:1在左侧;-1在右侧;0在直线上.\nPoint Get_line_intersection(Point P,Vector V,Point Q,Vector W){\n Vector U = P - Q;double t = Cross(W, U) / Cross(V, W);return P + V * t;\n}//两直线交点:(直线AB:A+tv(v为向量AB,t为参数,A为起点)).调用前要确保两直线p + tv和Q + tw之间有唯一交点,当且仅当Corss(v, w) != 0;(t是参数)\ndouble Distance_point_to_line(Point P, Point A, Point B){Vector v1 = B - A, v2 = P - A;return fabs(Cross(v1, v2) / Length(v1));}//如果不取绝对值,那么得到的是有向距离}//点P到直线AB的距离\ndouble Distance_point_to_segment(Point P, Point A, Point B)\n{\n if(A == B) return Length(P - A);//(如果重合那么就是两个点之间的距离,直接转成向量求距离即可)\n Vector v1 = B - A, v2 = P - A, v3 = P - B;\n if(sgn(Dot(v1, v2)) < 0) return Length(v2);//A点左边\n if(sgn(Dot(v1, v3)) > 0)return Length(v3);//B点右边\n return fabs(Cross(v1, v2) / Length(v1));//垂线的距离\n}//点P到线段AB的距离:垂线距离或者PA或者PB距离\nbool OnSegment(Point P, Point A, Point B){return sgn(Cross(A-P, B-P)) == 0 && sgn(Dot(A-P, B-P)) <= 0;}//判断点p是否在线段AB上(包含端点AB,如果不包含AB则<=改为<)\nbool Segment_proper_intersection(Point a1, Point a2, Point b1, Point b2){\n double c1 = Cross(a2-a1, b1-a1), c2 = Cross(a2-a1, b2-a1);double c3 = Cross(b2-b1, a1-b1), c4 = Cross(b2-b1, a2-b1);\n //if判断控制是否允许线段在端点处相交,根据需要添加\n if(!sgn(c1) || !sgn(c2) || !sgn(c3) || !sgn(c4)){\n bool f1 = OnSegment(b1, a1, a2), f2 = OnSegment(b2, a1, a2), f3 = OnSegment(a1, b1, b2), f4 = OnSegment(a2, b1, b2);\n bool f = (f1|f2|f3|f4);\n return f;\n }\n return (sgn(c1)*sgn(c2) < 0 && sgn(c3)*sgn(c4) < 0);\n}//判断线段a1a2与b1b2是否相交(if控制端点相交)\nPoint Get_line_projection(Point P, Point A, Point B){Vector v = B - A;return A + v * (Dot(v, P - A) / Dot(v, v));}//求点P在直线AB上的投影点\nPoint FootPoint(Point P, Point A, Point B){\n Vector x = P - A, y = P - B, z = B - A;\n double len1 = Dot(x, z) / Length(z), len2 = - 1.0 * Dot(y, z) / Length(z);//分别计算AP,BP在AB,BA上的投影\n return A + z * (len1 / (len1 + len2));//点A加上向量AF\n}//求点P到直线AB的垂足\nPoint Symmetry_PL(Point P, Point A, Point B){return P + (FootPoint(P, A, B) - P) * 2; }//求点P到直线AB的对称点\n// 线段相交问题,曼哈顿几何\nstruct EndPoint{\n Point p;\n int seg, st; // 线段的ID,端点的种类:BOTTOM 0、LEFT 1、RIGHT 2、TOP 3\n EndPoint() {}\n EndPoint(Point p, int seg, int st) :p(p), seg(seg), st(st) {}\n bool operator < (const EndPoint &ep) const {// 按y坐标升序排序\n if (p.y == ep.p.y) return st < ep.st;\n else return p.y < ep.p.y;\n }\n};// 用于求平面内线段交点个数\nint manhattanIntersection(vector<Segment>S) {\n vector<EndPoint>EP;\n\tint n = S.size();\n\tfor (int i = 0; i < n; i++) {//调整端点p1、p2,保证左小右大\n\t\tif (S[i].p1.y == S[i].p2.y) {\n\t\t\tif(S[i].p1.x > S[i].p2.x){\n swap(S[i].p1, S[i].p2);\n }\n\t\t}else if(S[i].p1.y > S[i].p2.y){\n\t\t\tswap(S[i].p1, S[i].p2);\n\t\t}\n\t\tif (S[i].p1.y == S[i].p2.y) {// 将水平线段添加到端点列表\n\t\t\tEP.push_back(EndPoint(S[i].p1, i, 1));\n\t\t\tEP.push_back(EndPoint(S[i].p2, i, 2));\n\t\t}else { // 将垂直线段添加到端点列表\n\t\t\tEP.push_back(EndPoint(S[i].p1, i, 0));\n\t\t\tEP.push_back(EndPoint(S[i].p2, i, 3));\n\t\t}\n\t}\n\tsort(EP.begin(),EP.end());//按照端点的y坐标升序排序\n\tset<int> BT;\t\t\t// 二叉搜索树\n\tBT.insert(10000000001); // 设置标记\n\tint cnt = 0;\n\tfor (int i = 0; i < 2 * n; i++) {\n\t\tif (EP[i].st == 3){\n BT.erase(EP[i].p.x); //删除上端点\n }\n\t\telse if (EP[i].st == 0){\n BT.insert(EP[i].p.x);\n }\n\t\telse if (EP[i].st == 1) {\n\t\t\tset<int>::iterator b = BT.lower_bound(S[EP[i].seg].p1.x);\n\t\t\tset<int>::iterator e = BT.upper_bound(S[EP[i].seg].p2.x);\n\t\t\tcnt += distance(b, e);// 加上b到e距离\n\t\t}\n\t}\n\treturn cnt;\n}\n\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//---------------------------------------------------多边形----------------------------------------------------------------------------//\n//-----------------------------------------------------------------------------------------------------------------------------------//\n//外心:三边中垂线交点,到三角形三个顶点距离相同(外接圆圆心)\n//内心:角平分线的交点,到三角形三边的距离相同(内切圆圆心)\n//垂心:三条垂线的交点\n//重心:三条中线的交点,到三角形三顶点距离的平方和最小的点,三角形内到三边距离之积最大的点(x=(x1+x2+x3),y=(y1+y2+y3))\ndouble Convex_polygon_area(Point* p, int n){//逆时针储存所有顶点,下标从0开始\n double area = 0;for(int i = 1; i <= n - 2; ++ i)area += Cross(p[i] - p[0], p[i + 1] - p[0]);return area / 2;//return fabs(area / 2);//不加的话求的是有向面积,逆时针为正,顺时针为负\n}//求凸多边形的有向面积\ndouble Polygon_area(Point* p, int n){//逆时针储存所有顶点,下标从0开始\n double area = 0;for(int i = 1; i <= n - 2; ++ i)area += Cross(p[i] - p[0], p[i + 1] - p[0]);return area / 2;\n}//求非凸多边形的有向面积\nint is_point_in_polygon(Point p, Point* poly,int n){//待判断的点和该多边形的所有点的合集\n int wn = 0;\n for(int i = 0; i < n; ++i){\n if(OnSegment(p, poly[i], poly[(i+1)%n])) return -1;\n int k = sgn(Cross(poly[(i+1)%n] - poly[i], p - poly[i])),d1 = sgn(poly[i].y - p.y),d2 = sgn(poly[(i+1)%n].y - p.y);\n if(k > 0 && d1 <= 0 && d2 > 0) wn++;\n if(k < 0 && d2 <= 0 && d1 > 0) wn--;\n }\n if(wn != 0)return 1;\n return 0;\n}//判断点P是否在多边形内,若点在多边形内返回1,在多边形外部返回0,在多边形上返回-1\n//判断点P是否在凸多边形内,只需要判断点P是否在所有边的左边(按逆时针顺序排列的顶点集)可以使用LeftTest_Point\nint is_convex(Point* p,int n){int s[3]={1,1,1};for(int i=0;i<n&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],p[(i+2)%n]-p[i]))]=0;return s[1]|s[2];}//判定凸多边形,允许相邻边共线.顶点按顺时针或逆时针给出\nint is_convex_v2(Point* p,int n){int s[3]={1,1,1};for (int i=0;i<n&&s[0]&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],p[(i+2)%n]-p[i]))]=0;return s[0]&&s[1]|s[2];}//判定凸多边形,不允许相邻边共线.顺时针或逆时针给出\nint inside_convex(Point q,Point* p,int n){int s[3]={1,1,1};for (int i=0;i<n&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],q-p[i]))]=0;return s[1]|s[2];}//判点q在凸多边形内或边上,顶点按顺时针或逆时针给出\nint inside_convex_v2(Point q,Point* p,int n){int s[3]={1,1,1};for (int i=0;i<n&&s[0]&&s[1]|s[2];i++)s[sgn2(Cross(p[(i+1)%n]-p[i],q-p[i]))]=0;return s[0]&&s[1]|s[2];}//判点q在凸多边形内,顶点按顺时针或逆时针给出,在多边形边上返回0\nint inside_polygon(Point q,Point* p,int n,int on_edge=1){//on_edge表示点在多边形边上时的返回值,默认为1\n\tPoint q2;int i=0,count=0;\n const int offset=10000;//offset为多边形坐标上限,根据题意修改\n\twhile (i<n){\n for (count=i=0,q2.x=rand()+offset,q2.y=rand()+offset;i<n;i++){\n if (zero(Cross(q-p[(i+1)%n],p[i]-p[(i+1)%n]))&&(p[i].x-q.x)*(p[(i+1)%n].x-q.x)<eps&&(p[i].y-q.y)*(p[(i+1)%n].y-q.y)<eps)return on_edge;\n\t\t\telse if (zero(Cross(q-p[i],q2-p[i])))break;\n\t\t\telse if (Cross(q-q2,p[i]-q2)*Cross(q-q2,p[(i+1)%n]-q2)<-eps&&Cross(p[i]-p[(i+1)%n],q-p[(i+1)%n])*Cross(p[i]-p[(i+1)%n],q2-p[(i+1)%n])<-eps)count++;\n }\n }\n if(count&1)return 2;return 0;\n}//判点在任意多边形内,顶点按顺时针或逆时针给出.点q在多边形内则为2,在边上则为1(可以修改on_edge),在外则为0\n\nint opposite_side(Point p1,Point p2,Point l1,Point l2){return Cross(l1-l2,p1-l2)*Cross(l1-l2,p2-l2)<-eps;}\nint dot_online_in(Point p,Point l1,Point l2){return zero(Cross(p-l2,l1-l2))&&(l1.x-p.x)*(l2.x-p.x)<eps&&(l1.y-p.y)*(l2.y-p.y)<eps;}\nint inside_polygon(Point l1,Point l2,Point* p,int n){\n const int MAXN=1000;//注意根据n的范围进行修改\n\tPoint t[MAXN],tt;int i,j,k=0;\n\tif (!inside_polygon(l1,p,n)||!inside_polygon(l2,p,n))return 0;\n\tfor (i=0;i<n;i++){\n if (opposite_side(l1,l2,p[i],p[(i+1)%n])&&opposite_side(p[i],p[(i+1)%n],l1,l2))return 0;\n\t\telse if (dot_online_in(l1,p[i],p[(i+1)%n]))t[k++]=l1;\n\t\telse if (dot_online_in(l2,p[i],p[(i+1)%n]))t[k++]=l2;\n\t\telse if (dot_online_in(p[i],l1,l2))t[k++]=p[i];\n }\n\tfor (i=0;i<k;i++){\n for (j=i+1;j<k;j++){\n\t\t\ttt.x=(t[i].x+t[j].x)/2;tt.y=(t[i].y+t[j].y)/2;\n\t\t\tif(!inside_polygon(tt,p,n))return 0;\t\t\t\n\t\t}\n }\t\n\treturn 1;\n}//判线段l1l2在任意多边形内,顶点按顺时针或逆时针给出,与边界相交或在内部返回1,否则返回0\nPoint Polygon_center(Point *p, int n) {\n Point ans(0, 0);\n if(Polygon_area(p, n) == 0)return ans;\n for (int i = 0; i < n; i++)ans = ans + (p[i] + p[(i + 1) % n]) * Cross(p[i], p[(i + 1) % n]); //面积有正负\n return ans / Polygon_area(p, n) / 6.;\n}//多边形重心,将多边形三角剖分,算出每个三角形重心(三角形重心是3点坐标平均值)对每个三角形有向面积求加权平均值\nbool cmp_ConvexHull(Point A,Point B){return A.y < B.y || (A.y == B.y && A.x < B. x);}//竖向排序,默认从下左角开始逆时针输出\nint ConvexHull(Point* p, int n, Point* ch){//下标都是从0开始,ch按照逆时针存储的\n sort(p, p + n);int m = 0;\n for(int i = 0; i < n;i++){//下凸包\n //如果叉积<=0说明新边斜率小说明已经不是凸包边了,赶紧踢走\n while(m > 1 && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0)m -- ;\n ch[m ++ ] = p[i];//<=:一条边有两给端点;<:边上可以有多个输入点 注意根据题意进行修改(求凸包直径的时候是<=)\n }\n int k = m;\n for(int i = n - 2; i >= 0;i--){//上凸包\n while(m > k && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0)m -- ;\n ch[m ++ ] = p[i];//<=:一条边有两给端点;<:边上可以有多个输入点 注意根据题意进行修改(求凸包直径的时候是<=)\n }\n if(n > 1) m -- ;return m;//返回凸包顶点个数\n}//计算凸包,输入点数组p.输出点数组ch.输入不能有重复的点,函数执行完后的输入点的顺序将被破坏(因为要排序,可以加一个数组存原来的id)\ndouble Rotating_calipers(Point* con,int n){//传入最小凸包的点数组\n int op = 1;double ans = 0;\n for(int i = 0; i < n; ++ i){\n while(Cross((con[i] - con[op]), (con[i + 1] - con[i])) < Cross((con[i] - con[op + 1]), (con[i + 1] - con[i])))op = (op + 1) % n;//(写成<=会被两个点的数据卡掉,所以必须写成<)\n ans = max(ans, max(Dot(con[i] - con[op],con[i] - con[op]), Dot(con[i + 1] - con[op],con[i + 1] - con[op])));\n }\n return ans;\n}//旋转卡壳,返回凸包的直径的平方\nPolygon CutPolygon(Polygon poly,const Point& a,const Point& b) {//poly中的点从0开始\n Polygon newpoly;int n=poly.size();\n for(int i=0; i<n; i++){\n Point c=poly[i],d=poly[(i+1)%n];\n if(sgn(Cross(b-a,c-a))>=0)newpoly.push_back(c);//有向直线的左侧所有点(包括交点)\n if(sgn(Cross(b-a,c-d))!=0){\n Point ip=Get_line_intersection(a,b-a,c,d-c);\n if(OnSegment(ip,c,d))newpoly.push_back(ip);\n }\n }\n return newpoly;\n}//有向直线ab切割多边形,返回有向直线的左侧所有点,包括了直线ab和多边形的交点 \ndouble Divide_Conquer(Point* a,Point* b,int l,int r){//a是原数组,原数组需要以x从左到右进行排序,即对Point数组进行最基本的排序(<)\n if(l==r)return INF;//注意修改无穷大的值,视情况而定\n if(l+1==r)return Dist(a[l],a[r]);\n int mid=(l+r)>>1;\n double ans=min(Divide_Conquer(a,b,l,mid),Divide_Conquer(a,b,mid+1,r));\n int len=0;\n for(int i=l;i<=r;i++)if(fabs(a[mid].x-a[i].x)<=ans)b[len++]=a[i];\n sort(b,b+len,cmp_ConvexHull);\n for(int i=0;i<len;i++){\n for(int j=i+1;j<len;j++){\n if(b[j].y-b[i].y>ans)break;\n ans=min(ans,Dist(b[i],b[j]));\n }\n }\n return ans;\n}//平面最近点对:n个点中最近的两个点的距离.O(nlogn)\nint n,T;\nint main(){\n ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n vector<Segment>s;\n cin>>n;\n for(int i=0;i<n;i++){\n Segment a;\n cin>>a.p1.x>>a.p1.y>>a.p2.x>>a.p2.y;\n s.push_back(a);\n }\n cout<<manhattanIntersection(s)<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 20216, "score_of_the_acc": -0.2855, "final_rank": 15 }, { "submission_id": "aoj_CGL_6_A_10691325", "code_snippet": "// #define ENABLE_TUPLE_OPS_\n#define DISABLE_PRAGMA_\n#ifndef DISABLE_PRAGMA_\n#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops,fast-math\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native\")\n#endif\n\n#include <bits/stdc++.h>\n#ifdef __GNUG__\n// #include <bits/extc++.h>\n#endif\n\n\ntemplate <class Tp>\nusing pi = std::pair<Tp, Tp>;\ntemplate <class Tp>\nusing pi3 = std::tuple<Tp, Tp, Tp>;\ntemplate <class Tp>\nusing pi4 = std::tuple<Tp, Tp, Tp, Tp>;\ntemplate <class Tp>\nusing vc = std::vector<Tp>;\ntemplate <class Tp>\nusing vvc = std::vector<std::vector<Tp>>;\ntemplate <class Tp>\nusing pq = std::priority_queue<Tp>;\ntemplate <class Tp>\nusing pqg = std::priority_queue<Tp, std::vector<Tp>, std::greater<Tp>>;\ntemplate <class Tp>\nusing hset = std::unordered_set<Tp>;\ntemplate <class Key, class Tp, class Hash = std::hash<Key>>\nusing hmap = std::unordered_map<Key, Tp, Hash>;\n\n\nusing i32 = int32_t;\nusing u32 = uint32_t;\nusing i64 = int64_t;\nusing u64 = uint64_t;\nusing i128 = __int128_t;\nusing u128 = __uint128_t;\n\nusing compi = std::complex<int>;\nusing compi64 = std::complex<i64>;\nusing compd = std::complex<double>;\nusing pii = pi<int>;\nusing pii64 = pi<i64>;\nusing pi3i = pi3<int>;\nusing pi3i64 = pi3<i64>;\nusing pi4i = pi4<int>;\nusing pi4i64 = pi4<i64>;\n\n\n#define for_(i, l, r, vars...) for (decltype(l + r) i = (l), i##end = (r), ##vars; i <= i##end; ++i)\n#define for_step_(i, l, r, s, vars...) for (decltype(l + r) i = (l), i##end = (r), ##vars; i <= i##end; i += s)\n#define rfor_(i, r, l, vars...) for (make_signed_t<decltype(r - l)> i = (r), i##end = (l), ##vars; i >= i##end; --i)\n#define rfor_step_(i, r, l, s, vars...) for (make_signed_t<decltype(r - l)> i = (r), i##end = (l), ##vars; i >= i##end; i -= s)\n#define foreach_val_(i, container) for (auto i : (container))\n#define foreach_ref_(i, container) for (auto &i : (container))\n#define foreach_cref_(i, container) for (const auto &i : (container))\n#define foreach_rref_(i, container) for (auto &&i : (container))\n#define foreach_binding_(container, vars...) for (auto &&[vars] : container)\n#define foreach_iter_(it, container) for (auto it = (container).begin(); it != (container).end(); ++it)\n#define foreach_iter_range_(it, container, l, r) for (auto it = (container).begin() + (l); it != (container).begin() + (r); ++it)\n#define foreach_riter_(it, container) for (auto it = (container).rbegin(); it != (container).rend(); ++it)\n#define foreach_riter_range_(it, container, l, r) for (auto it = (container).rbegin() + (l); it != (container).rbegin() + (r); ++it)\n#define ins_(a) std::inserter((a), (a).begin())\n#define all_(a) (a).begin(), (a).end()\n#define rall_(a) (a).rbegin(), (a).rend()\n#define range_(a, l, r) ((a).begin() + (l)), ((a).begin() + (r))\n#define rrange_(a, l, r) ((a).rbegin() + (l)), ((a).rbegin() + (r))\n#define set_nul_(a) memset(a, 0, sizeof(a))\n#define set_inf_(a) memset(a, 0x3f, sizeof(a))\n#define set_nul_n_(a, n) memset(a, 0, sizeof(*(a)) * (n))\n#define set_inf_n_(a, n) memset(a, 0x3f, sizeof(*(a)) * (n))\n#define run_exec_(expressions, post_process) \\\n { \\\n expressions; \\\n post_process; \\\n }\n#define run_exit_(expressions) run_exec_(expressions, exit(0))\n#define run_return_(expressions, val) run_exec_(expressions, return val)\n#define run_return_void_(expressions) run_exec_(expressions, return )\n#define run_break_(expressions) run_exec_(expressions, break)\n#define run_continue_(expressions) run_exec_(expressions, continue)\n#define read_var_(type, name) \\\n type name; \\\n std::cin >> name\n#define read_container_(type, name, size) \\\n type name(size); \\\n foreach_ref_(i, name) std::cin >> i\n\n\ntemplate <class Tp>\nconstexpr auto chkmin(Tp &a, Tp b) -> bool { return b < a ? a = b, true : false; };\ntemplate <class Tp>\nconstexpr auto chkmax(Tp &a, Tp b) -> bool { return a < b ? a = b, true : false; };\ntemplate <class Tp, class Pred>\ninline Tp binary_search(Pred check, Tp ok, Tp ng) {\n assert(check(ok));\n while (std::abs(ok - ng) > 1) {\n Tp x = (ng + ok) / 2;\n (check(x) ? ok : ng) = x;\n }\n return ok;\n}\ntemplate <class Tp, class Pred, std::enable_if_t<std::is_floating_point_v<Tp>> * = nullptr>\ninline Tp binary_search_real(Pred check, Tp ok, Tp ng, Tp eps) {\n assert(check(ok));\n while (std::abs(ok - ng) > eps) {\n Tp x = (ng + ok) / 2;\n (check(x) ? ok : ng) = x;\n }\n return (ng + ok) / 2;\n}\ntemplate <class Tp>\ninline auto discretization(Tp &var) -> Tp {\n Tp d__(var);\n std::sort(d__.begin(), d__.end());\n d__.erase(std::unique(d__.begin(), d__.end()), d__.end());\n for (auto &i : var) i = std::distance(d__.begin(), std::lower_bound(d__.begin(), d__.end(), i));\n return d__;\n};\ntemplate <class Tp>\nconstexpr auto ispow2(Tp i) -> bool { return i && (i & -i) == i; }\n\n#ifdef ENABLE_TUPLE_OPS_\n\n// <https://tifa-233.xyz/archives/draft-019/>\n#define TPL_SIZE_(Tuple) std::tuple_size_v<std::remove_reference_t<Tuple>>\n\nnamespace tuple_detail_ {\ntemplate <std::size_t Begin, class Tuple, std::size_t... Is>\nconstexpr auto subtuple_impl_(Tuple &&t, std::index_sequence<Is...>) { return std::make_tuple(std::get<Is + Begin>(t)...); }\ntemplate <class Tuple, class BinOp, std::size_t... Is>\nconstexpr auto apply2_impl_(BinOp &&f, Tuple &&lhs, Tuple &&rhs, std::index_sequence<Is...>) { return std::make_tuple(std::forward<BinOp>(f)(std::get<Is>(lhs), std::get<Is>(rhs))...); }\n} // namespace tuple_detail_\n\n\ntemplate <std::size_t Begin, std::size_t Len, class Tuple>\nconstexpr auto subtuple(Tuple &&t) {\n static_assert(Begin <= TPL_SIZE_(Tuple) && Len <= TPL_SIZE_(Tuple) && Begin + Len <= TPL_SIZE_(Tuple), \"Out of range\");\n return tuple_detail_::subtuple_impl_<Begin>(t, std::make_index_sequence<Len>());\n}\n\ntemplate <std::size_t Pos, class Tp, class Tuple>\nconstexpr auto tuple_push(Tp &&v, Tuple &&t) {\n static_assert(TPL_SIZE_(Tuple) > 0, \"Pop from empty tuple\");\n return std::tuple_cat(subtuple<0, Pos>(t), std::make_tuple(v), subtuple<Pos, TPL_SIZE_(Tuple) - Pos>(t));\n}\ntemplate <class Tp, class Tuple>\nconstexpr auto tuple_push_front(Tp &&v, Tuple &&t) { return tuple_push<0>(v, t); }\ntemplate <class Tp, class Tuple>\nconstexpr auto tuple_push_back(Tp &&v, Tuple &&t) { return tuple_push<TPL_SIZE_(Tuple)>(v, t); }\n\n\ntemplate <std::size_t Pos, class Tuple>\nconstexpr auto tuple_pop(Tuple &&t) {\n static_assert(TPL_SIZE_(Tuple) > 0, \"Pop from empty tuple\");\n return std::tuple_cat(subtuple<0, Pos>(t), subtuple<Pos + 1, TPL_SIZE_(Tuple) - Pos - 1>(t));\n}\ntemplate <class Tuple>\nconstexpr auto tuple_pop_front(Tuple &&t) { return tuple_pop<0>(t); }\ntemplate <class Tuple>\nconstexpr auto tuple_pop_back(Tuple &&t) { return tuple_pop<TPL_SIZE_(Tuple) - 1>(t); }\n\ntemplate <class Tuple, class BinOp>\nconstexpr auto apply2(BinOp &&f, Tuple &&lhs, Tuple &&rhs) { return tuple_detail_::apply2_impl_(f, lhs, rhs, std::make_index_sequence<TPL_SIZE_(Tuple)>()); }\n\n#define OO_PT_(op) \\\n template <class Tp, class Up> \\\n constexpr auto operator op(std::pair<Tp, Up> lhs, const std::pair<Tp, Up> &rhs) { return {lhs.first op rhs.first, lhs.second op rhs.second}; } \\\n template <class... Ts> \\\n constexpr auto operator op(std::tuple<Ts...> const &lhs, std::tuple<Ts...> const &rhs) { \\\n return apply2([](auto &&l, auto &&r) { return l op r; }, lhs, rhs); \\\n }\n#define OO_PTEQ_(op) \\\n OO_PT_(op) \\\n template <class Tp, class Up> \\\n constexpr std::pair<Tp, Up> &operator op##=(std::pair<Tp, Up> &lhs, const std::pair<Tp, Up> &rhs) { \\\n lhs.first op## = rhs.first; \\\n lhs.second op## = rhs.second; \\\n return lhs; \\\n } \\\n template <class... Ts> \\\n constexpr auto operator op##=(std::tuple<Ts...> &lhs, const std::tuple<Ts...> &rhs) { return lhs = lhs op rhs; }\n\nOO_PTEQ_(+)\nOO_PTEQ_(-)\nOO_PTEQ_(*)\nOO_PTEQ_(/)\nOO_PTEQ_(%)\nOO_PTEQ_(&)\nOO_PTEQ_(|)\nOO_PTEQ_(^)\nOO_PTEQ_(<<)\nOO_PTEQ_(>>)\nOO_PT_(==)\nOO_PT_(!=)\nOO_PT_(<)\nOO_PT_(<=)\nOO_PT_(>)\nOO_PT_(>=)\n\n#undef OO_PT_\n#undef TPL_SIZE_\n\n\ntemplate <class Tp, class Up>\nstd::istream &operator>>(std::istream &is, std::pair<Tp, Up> &p) { return is >> p.first >> p.second; }\ntemplate <class Tp, class Up>\nstd::ostream &operator<<(std::ostream &os, const std::pair<Tp, Up> &p) {\n#ifdef LOCAL_\n if (&os == &std::cerr)\n return os << '<' << p.first << \", \" << p.second << '>';\n else\n#endif\n return os << p.first << ' ' << p.second;\n}\n\ntemplate <typename... Ts>\nstd::istream &operator>>(std::istream &is, std::tuple<Ts...> &p) {\n std::apply([&](Ts &...targs) { ((is >> targs), ...); }, p);\n return is;\n}\ntemplate <typename... Ts>\nstd::ostream &operator<<(std::ostream &os, const std::tuple<Ts...> &p) {\n std::apply(\n [&](Ts const &...targs) {\n std::size_t n{0};\n#ifdef LOCAL_\n if (&os == &std::cerr) os << '(';\n if (&os == &std::cerr)\n ((os << targs << (++n != sizeof...(Ts) ? \", \" : \"\")), ...);\n else\n#endif\n ((os << targs << (++n != sizeof...(Ts) ? \" \" : \"\")), ...);\n#ifdef LOCAL_\n if (&os == &std::cerr) os << ')';\n#endif\n },\n p);\n return os;\n}\n\n#endif\n\ntemplate <class Ct, std::enable_if_t<std::is_same_v<decltype(std::declval<Ct>().begin()), typename Ct::iterator> && std::is_same_v<decltype(std::declval<Ct>().end()), typename Ct::iterator>> * = nullptr>\nstd::ostream &operator<<(std::ostream &os, const Ct &x) {\n#ifdef LOCAL_\n if (&os == &std::cerr) os << '[';\n if (&os == &std::cerr)\n for (auto it = x.begin(); it != x.end() - 1; ++it) os << *it << \", \";\n else\n#endif\n for (auto it = x.begin(); it != x.end() - 1; ++it) os << *it << ' ';\n os << x.back();\n#ifdef LOCAL_\n if (&os == &std::cerr) os << ']';\n#endif\n return os;\n}\n\n\ntemplate <class Tp>\ninline void debug(Tp x) {\n#ifdef LOCAL_\n std::cerr << x << std::endl;\n#endif\n}\ntemplate <class Tp, class... Ts>\ninline void debug(Tp x, Ts... args) {\n#ifdef LOCAL_\n std::cerr << x << ' ';\n debug(args...);\n#endif\n}\n#define debug_line_ (std::cerr << __LINE__ << ' ' << __FUNCTION__ << std::endl)\n#define debug_withname_(var) debug(#var, var)\n\n\nconst u32 OFFSET = 5;\nconst u32 N = 5e5 + OFFSET;\nconst u32 M = 2e5 + OFFSET;\nconst u32 K = 21;\nconst u32 MOD = 1e9 + 7;\nconst double EPS = 1e-6;\nconst i32 INF = 0x3f3f3f3f;\nconst i64 INF64 = 0x3f3f3f3f3f3f3f3f;\nconst double PI = acos(-1.0);\nconst pii DIR4[4] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};\nconst pii DIR8[8] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};\nconst std::string RES_YN[2] = {\"NO\", \"YES\"};\nconst std::string RES_Yn[2] = {\"No\", \"Yes\"};\nconst std::string RES_yn[2] = {\"no\", \"yes\"};\nconst std::string RES_POSS[2] = {\"IMPOSSIBLE\", \"POSSIBLE\"};\nconst std::string RES_Poss[2] = {\"Impossible\", \"Possible\"};\nconst std::string RES_poss[2] = {\"impossible\", \"possible\"};\n// const int64_t EXP10[10] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};\n// const int64_t FACT[11] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800};\n\ntemplate <size_t N_>\nconstexpr int64_t EXP10_impl_() { return EXP10_impl_<N_ - 1>() * 10; }\ntemplate <>\nconstexpr int64_t EXP10_impl_<0>() { return 1; }\ntemplate <size_t N_>\nconstexpr int64_t EXP10 = EXP10_impl_<N_>();\n\ntemplate <size_t N_>\nconstexpr int64_t FACT10_impl_() { return FACT10_impl_<N_ - 1>() * N_; }\ntemplate <>\nconstexpr int64_t FACT10_impl_<0>() { return 1; }\ntemplate <size_t N_>\nconstexpr int64_t FACT = FACT10_impl_<N_>();\n\n\nusing namespace std;\nconst auto STATIC__ = []() {\n return 0;\n}();\n\n// #define MULTI_CASES\ninline auto solve([[maybe_unused]] int t_ = 0) -> void {\n vc<pi4i> vp4;\n read_var_(int, n);\n for_(i, 1, n, ax, ay, bx, by) {\n cin >> ax >> ay >> bx >> by;\n if (ax > bx) swap(ax, bx);\n if (ay > by) swap(ay, by);\n if (ax == bx) run_continue_(vp4.emplace_back(ax, 0, ay, by));\n vp4.emplace_back(ax, -1, ay, 0);\n vp4.emplace_back(bx, 1, by, 0);\n }\n sort(all_(vp4));\n i64 ans = 0;\n set<int> s;\n for (auto &&x : vp4) {\n if (get<1>(x) == -1) run_continue_(s.insert(get<2>(x)));\n if (get<1>(x) == 1) run_continue_(s.erase(get<2>(x)));\n ans += distance(s.lower_bound(get<2>(x)), s.upper_bound(get<3>(x)));\n }\n cout << ans << '\\n';\n}\n\nint main() {\n#ifdef LOCAL_\n auto CLOCK_ST_ = std::chrono::high_resolution_clock::now();\n#endif\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n int i_ = STATIC__;\n // cout << fixed << setprecision(12);\n std::cerr << boolalpha << fixed << setprecision(12);\n\n#ifdef MULTI_CASES\n int t_ = 0;\n std::cin >> t_;\n for (i_ = 1; i_ <= t_; ++i_)\n#endif\n debug(\"Case\", i_), solve(i_);\n#ifdef LOCAL_\n auto CLOCK_ED_ = std::chrono::high_resolution_clock::now();\n std::clog << \"\\n---\\n\"\n << \"Time used: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(CLOCK_ED_ - CLOCK_ST_).count() * 1e-6l << \" ms\" << std::endl;\n#endif\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 9860, "score_of_the_acc": -0.0481, "final_rank": 1 }, { "submission_id": "aoj_CGL_6_A_10505950", "code_snippet": "#include <bits/stdc++.h>\n#define init(x) memset (x,0,sizeof (x))\n#define ll long long\n#define ull unsigned long long\n#define INF 0x3f3f3f3f\n#define pii pair <int,int>\nusing namespace std;\nconst int MAX = 3e5 + 5;\nconst int MOD = 1e9 + 7;\ninline int read ();\nstruct point {int x,y;};\nstruct seg\n{\n point A,B;int op;\n seg (point A,point B,int op) : A (A),B (B),op (op) {}\n bool operator < (const seg &p)\n {\n if (A.y != p.A.y) return A.y < p.A.y;\n else return op != p.op ? op < p.op : A.x < p.A.x;\n }\n};\nint n;ll ans,tree[MAX << 2];\nvoid modify (int cur,int l,int r,int x,int v)\n{\n if (l == r) {tree[cur] += v;return ;}\n int mid = (l + r) >> 1;\n if (x <= mid) modify (cur << 1,l,mid,x,v);\n else modify (cur << 1 | 1,mid + 1,r,x,v);\n tree[cur] = tree[cur << 1] + tree[cur << 1 | 1];\n}\nll query (int cur,int l,int r,int x,int y)\n{\n if (x <= l && y >= r) return tree[cur];\n int mid = (l + r) >> 1;ll res = 0;\n if (x <= mid) res += query (cur << 1,l,mid,x,y);\n if (y > mid) res += query (cur << 1 | 1,mid + 1,r,x,y);\n return res;\n}\nint main ()\n{\n n = read ();\n vector <int> p;vector <seg> v;\n for (int i = 1;i <= n;++i)\n {\n point A,B;\n A.x = read (),A.y = read ();B.x = read (),B.y = read ();\n if (A.x == B.x)\n {\n if (A.y > B.y) swap (A,B);\n p.push_back (A.x);\n v.push_back ({A,A,1});\n v.push_back ({B,B,3});\n }\n else\n {\n if (A.x > B.x) swap (A,B);\n p.push_back (A.x);p.push_back (B.x);\n v.push_back ({A,B,2});\n }\n }\n sort (p.begin (),p.end ());\n p.erase (unique (p.begin (),p.end ()),p.end ());\n sort (v.begin (),v.end ());\n for (auto [A,B,op] : v)\n {\n int x = lower_bound (p.begin (),p.end (),A.x) - p.begin () + 1;\n int y = lower_bound (p.begin (),p.end (),B.x) - p.begin () + 1;\n if (A.x == B.x) modify (1,1,p.size (),x,op == 1 ? 1 : -1);\n else ans += query (1,1,p.size (),x,y);\n }\n printf (\"%lld\\n\",ans);\n return 0;\n}\ninline int read ()\n{\n int s = 0;int f = 1;\n char ch = getchar ();\n while ((ch < '0' || ch > '9') && ch != EOF)\n {\n if (ch == '-') f = -1;\n ch = getchar ();\n }\n while (ch >= '0' && ch <= '9')\n {\n s = s * 10 + ch - '0';\n ch = getchar ();\n }\n return s * f;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 12188, "score_of_the_acc": -0.0858, "final_rank": 2 }, { "submission_id": "aoj_CGL_6_A_10446161", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntemplate<class S, class T> inline bool chmax(S &a, T b) { return (a < b ? a = b, 1 : 0); }\ntemplate<class S, class T> inline bool chmin(S &a, T b) { return (a > b ? a = b, 1 : 0); }\n\nusing pint = pair<int, int>;\nusing pll = pair<long long, long long>;\nusing tint = array<int, 3>;\nusing tll = array<long long, 3>;\nusing fint = array<int, 4>;\nusing fll = array<long long, 4>;\nusing vll = vector<long long>;\nusing ll = long long;\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nusing int128 = __int128;\nusing u128 = unsigned __int128;\ntemplate <class T>\nusing min_priority_queue = priority_queue<T, vector<T>, greater<T>>;\n\n#define REP(i, a) for (long long i = 0; i < (long long)(a); i++)\n#define REP2(i, a, b) for (long long i = a; i < (long long)(b); i++)\n#define RREP(i, a) for (long long i = (a)-1; i >= (long long)(0); --i)\n#define RREP2(i, a, b) for (long long i = (b)-1; i >= (long long)(a); --i)\n#define EB emplace_back\n#define PB push_back\n#define MP make_pair\n#define MT make_tuple\n#define FI first\n#define SE second\n#define ALL(x) x.begin(), x.end()\n#define COUT(x) cout << #x << \" = \" << (x) << \" (L\" << __LINE__ << \")\" << endl\n\n// debug stream\ntemplate<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P)\n{ return s << '<' << P.first << \", \" << P.second << '>'; }\ntemplate<class T> ostream& operator << (ostream &s, vector<T> P)\n{ for (int i = 0; i < P.size(); ++i) { if (i > 0) { s << \" \"; } s << P[i]; } return s; }\ntemplate<class T> ostream& operator << (ostream &s, deque<T> P)\n{ for (int i = 0; i < P.size(); ++i) { if (i > 0) { s << \" \"; } s << P[i]; } return s; }\ntemplate<class T> ostream& operator << (ostream &s, vector<vector<T> > P)\n{ for (int i = 0; i < P.size(); ++i) { s << endl << P[i]; } return s << endl; }\ntemplate<class T> ostream& operator << (ostream &s, set<T> P)\n{ for (auto it : P) { s << \"<\" << it << \"> \"; } return s; }\ntemplate<class T> ostream& operator << (ostream &s, multiset<T> P)\n{ for (auto it : P) { s << \"<\" << it << \"> \"; } return s; }\ntemplate<class T1, class T2> ostream& operator << (ostream &s, map<T1,T2> P)\n{ for (auto it : P) { s << \"<\" << it.first << \"->\" << it.second << \"> \"; } return s; }\n\n\n//------------------------------//\n// 幾何の基本要素 (点, 線分, 円)\n//------------------------------//\n\n// basic settings\nlong double EPS = 1e-12; // to be set appropriately\nconstexpr long double PI = 3.141592653589793238462643383279502884L;\nlong double torad(long double deg) {return (long double)(deg) * PI / 180;}\nlong double todeg(long double ang) {return ang * 180 / PI;}\n\n// Point or Vector\ntemplate<class DD> struct Point {\n // inner value\n DD x, y;\n \n // constructor\n constexpr Point() : x(0), y(0) {}\n constexpr Point(DD x, DD y) : x(x), y(y) {}\n \n // various functions\n constexpr Point conj() const {return Point(x, -y);}\n constexpr DD dot(const Point &r) const {return x * r.x + y * r.y;}\n constexpr DD cross(const Point &r) const {return x * r.y - y * r.x;}\n constexpr DD norm() const {return dot(*this);}\n constexpr long double abs() const {return sqrt(norm());}\n constexpr long double arg() const {\n if (this->eq(Point(0, 0))) return 0L;\n else if (x < -EPS && this->eq(Point(x, 0))) return PI;\n else return atan2((long double)(y), (long double)(x));\n }\n constexpr bool eq(const Point &r) const {return (*this - r).abs() <= EPS;}\n constexpr Point rot90() const {return Point(-y, x);}\n constexpr Point rot(long double ang) const {\n return Point(cos(ang) * x - sin(ang) * y, sin(ang) * x + cos(ang) * y);\n }\n \n // arithmetic operators\n constexpr Point operator - () const {return Point(-x, -y);}\n constexpr Point operator + (const Point &r) const {return Point(*this) += r;}\n constexpr Point operator - (const Point &r) const {return Point(*this) -= r;}\n constexpr Point operator * (const Point &r) const {return Point(*this) *= r;}\n constexpr Point operator / (const Point &r) const {return Point(*this) /= r;}\n constexpr Point operator * (DD r) const {return Point(*this) *= r;}\n constexpr Point operator / (DD r) const {return Point(*this) /= r;}\n constexpr Point& operator += (const Point &r) {\n x += r.x, y += r.y;\n return *this;\n }\n constexpr Point& operator -= (const Point &r) {\n x -= r.x, y -= r.y;\n return *this;\n }\n constexpr Point& operator *= (const Point &r) {\n DD tx = x, ty = y;\n x = tx * r.x - ty * r.y;\n y = tx * r.y + ty * r.x;\n return *this;\n }\n constexpr Point& operator /= (const Point &r) {\n return *this *= r.conj() / r.norm();\n }\n constexpr Point& operator *= (DD r) {\n x *= r, y *= r;\n return *this;\n }\n constexpr Point& operator /= (DD r) {\n x /= r, y /= r;\n return *this;\n }\n\n // friend functions\n friend ostream& operator << (ostream &s, const Point &p) {\n return s << '(' << p.x << \", \" << p.y << ')';\n }\n friend constexpr Point conj(const Point &p) {return p.conj();}\n friend constexpr DD dot(const Point &p, const Point &q) {return p.dot(q);}\n friend constexpr DD cross(const Point &p, const Point &q) {return p.cross(q);}\n friend constexpr DD norm(const Point &p) {return p.norm();}\n friend constexpr long double abs(const Point &p) {return p.abs();}\n friend constexpr long double arg(const Point &p) {return p.arg();}\n friend constexpr bool eq(const Point &p, const Point &q) {return p.eq(q);}\n friend constexpr Point rot90(const Point &p) {return p.rot90();}\n friend constexpr Point rot(const Point &p, long long ang) {return p.rot(ang);}\n};\n\n// necessary for some functions\ntemplate<class DD> constexpr bool operator < (const Point<DD> &p, const Point<DD> &q) {\n return (abs(p.x - q.x) > EPS ? p.x < q.x : p.y < q.y);\n}\n\n// Line\ntemplate<class DD> struct Line : vector<Point<DD>> {\n Line(Point<DD> a = Point<DD>(0, 0), Point<DD> b = Point<DD>(0, 0)) {\n this->push_back(a);\n this->push_back(b);\n }\n friend ostream& operator << (ostream &s, const Line<DD> &l) {\n return s << '{' << l[0] << \", \" << l[1] << '}';\n }\n};\n\n// Circle\ntemplate<class DD> struct Circle : Point<DD> {\n DD r;\n Circle(Point<DD> p = Point<DD>(0, 0), DD r = 0) : Point<DD>(p), r(r) {}\n friend ostream& operator << (ostream &s, const Circle<DD> &c) {\n return s << '(' << c.x << \", \" << c.y << \", \" << c.r << ')';\n }\n};\n\n\n//------------------------------//\n// 点や線分の位置関係\n//------------------------------//\n\n// arg sort\n// by defining comparison\ntemplate<class DD> void arg_sort(vector<Point<DD>> &v) {\n auto sign = [&](const Point<DD> &p) -> int {\n if (abs(p.x) <= EPS && abs(p.y) <= EPS) return 0;\n else if (p.y < -EPS || (abs(p.y) <= EPS && p.x > EPS)) return -1;\n else return 1;\n };\n auto cmp = [&](const Point<DD> &p, const Point<DD> &q) -> bool {\n if (sign(p) != sign(q)) return sign(p) < sign(q);\n return (abs(cross(p, q)) > EPS ? cross(p, q) > EPS : norm(p) < norm(q));\n };\n sort(v.begin(), v.end(), cmp);\n}\n// by calculating arg directly\ntemplate<class DD> void arg_sort_direct(vector<Point<DD>> &v) {\n auto cmp = [&](const Point<DD> &p, const Point<DD> &q) -> bool {\n return (abs(arg(p) - arg(q)) > EPS ? arg(p) < arg(q) : norm(p) < norm(q));\n };\n sort(v.begin(), v.end(), cmp);\n}\n\n// 粗\n// 1:a-bから見てcは左側(反時計回り)、-1:a-bから見てcは右側(時計回り)、0:一直線上\ntemplate<class DD> int simple_ccw\n (const Point<DD> &a, const Point<DD> &b, const Point<DD> &c) {\n if (cross(b-a, c-a) > EPS) return 1;\n if (cross(b-a, c-a) < -EPS) return -1;\n return 0;\n}\n\n// 精\n// 1:a-bから見てcは左側(反時計回り)、-1:a-bから見てcは右側(時計回り)\n// 2:c-a-bの順に一直線上、-2:a-b-cの順に一直線上、0:a-c-bの順に一直線上\ntemplate<class DD> int ccw\n (const Point<DD> &a, const Point<DD> &b, const Point<DD> &c) {\n if (cross(b-a, c-a) > EPS) return 1;\n if (cross(b-a, c-a) < -EPS) return -1;\n if (dot(b-a, c-a) < -EPS) return 2;\n if (norm(b-a) < norm(c-a) - EPS) return -2;\n return 0;\n}\n\n// 点と三角形の包含関係(辺上については判定していない)\ntemplate<class DD> bool is_contain\n (const Point<DD> &p, const Point<DD> &a, const Point<DD> &b, const Point<DD> &c) {\n int r1 = simple_ccw(p, b, c), r2 = simple_ccw(p, c, a), r3 = simple_ccw(p, a, b);\n if (r1 == 1 && r2 == 1 && r3 == 1) return true;\n if (r1 == -1 && r2 == -1 && r3 == -1) return true;\n return false;\n}\n\n\n//------------------------------//\n// 線分の交差判定や距離計算\n//------------------------------//\n\ntemplate<class DD> int ccw_for_dis\n (const Point<DD> &a, const Point<DD> &b, const Point<DD> &c) {\n if (cross(b-a, c-a) > EPS) return 1;\n if (cross(b-a, c-a) < -EPS) return -1;\n if (dot(b-a, c-a) < -EPS) return 2;\n if (norm(b-a) < norm(c-a) - EPS) return -2;\n return 0;\n}\ntemplate<class DD> Point<DD> proj(const Point<DD> &p, const Line<DD> &l) {\n DD t = dot(p - l[0], l[1] - l[0]) / norm(l[1] - l[0]);\n return l[0] + (l[1] - l[0]) * t;\n}\ntemplate<class DD> Point<DD> refl(const Point<DD> &p, const Line<DD> &l) {\n return p + (proj(p, l) - p) * 2;\n}\ntemplate<class DD> bool is_inter_PL(const Point<DD> &p, const Line<DD> &l) {\n return (abs(p - proj(p, l)) < EPS);\n}\ntemplate<class DD> bool is_inter_PS(const Point<DD> &p, const Line<DD> &s) {\n return (ccw_for_dis(s[0], s[1], p) == 0);\n}\ntemplate<class DD> bool is_inter_LL(const Line<DD> &l, const Line<DD> &m) {\n return (abs(cross(l[1] - l[0], m[1] - m[0])) > EPS ||\n abs(cross(l[1] - l[0], m[0] - l[0])) < EPS);\n}\ntemplate<class DD> bool is_inter_SS(const Line<DD> &s, const Line<DD> &t) {\n if (eq(s[0], s[1])) return is_inter_PS(s[0], t);\n if (eq(t[0], t[1])) return is_inter_PS(t[0], s);\n return (ccw_for_dis(s[0], s[1], t[0]) * ccw_for_dis(s[0], s[1], t[1]) <= 0 &&\n ccw_for_dis(t[0], t[1], s[0]) * ccw_for_dis(t[0], t[1], s[1]) <= 0);\n}\ntemplate<class DD> DD distance_PL(const Point<DD> &p, const Line<DD> &l) {\n return abs(p - proj(p, l));\n}\ntemplate<class DD> DD distance_PS(const Point<DD> &p, const Line<DD> &s) {\n if (dot(p - s[0], s[1] - s[0]) < 0) return abs(p - s[0]);\n else if (dot(p - s[1], s[0] - s[1]) < 0) return abs(p - s[1]);\n else return abs(p - proj(p, s));\n}\ntemplate<class DD> DD distance_LL(const Line<DD> &l, const Line<DD> &m) {\n if (is_inter_LL(l, m)) return 0;\n else return distance_PL(m[0], l);\n}\ntemplate<class DD> DD distance_SS(const Line<DD> &s, const Line<DD> &t) {\n if (is_inter_SS(s, t)) return 0;\n else return min(min(distance_PS(s[0], t), distance_PS(s[1], t)),\n min(distance_PS(t[0], s), distance_PS(t[1], s)));\n}\n\n\n//------------------------------//\n// 円や直線の交点\n//------------------------------//\n\ntemplate<class DD> Point<DD> proj_for_crosspoint(const Point<DD> &p, const Line<DD> &l) {\n DD t = dot(p - l[0], l[1] - l[0]) / norm(l[1] - l[0]);\n return l[0] + (l[1] - l[0]) * t;\n}\ntemplate<class DD> vector<Point<DD>> crosspoint(const Line<DD> &l, const Line<DD> &m) {\n vector<Point<DD>> res;\n DD d = cross(m[1] - m[0], l[1] - l[0]);\n if (abs(d) < EPS) return vector<Point<DD>>();\n res.push_back(l[0] + (l[1] - l[0]) * cross(m[1] - m[0], m[1] - l[0]) / d);\n return res;\n}\ntemplate<class DD> vector<Point<DD>> crosspoint_SS(const Line<DD> &l, const Line<DD> &m) {\n if (is_inter_SS(l, m)) return crosspoint(l, m);\n else return vector<Point<DD>>();\n}\ntemplate<class DD> vector<Point<DD>> crosspoint(const Circle<DD> &e, const Circle<DD> &f) {\n vector<Point<DD>> res;\n DD d = abs(e - f);\n if (d < EPS) return vector<Point<DD>>();\n if (d > e.r + f.r + EPS) return vector<Point<DD>>();\n if (d < abs(e.r - f.r) - EPS) return vector<Point<DD>>();\n DD rcos = (d * d + e.r * e.r - f.r * f.r) / (2.0 * d), rsin;\n if (e.r - abs(rcos) < EPS) rsin = 0;\n else rsin = sqrt(e.r * e.r - rcos * rcos);\n Point<DD> dir = (f - e) / d;\n Point<DD> p1 = e + dir * Point(rcos, rsin);\n Point<DD> p2 = e + dir * Point(rcos, -rsin);\n res.push_back(p1);\n if (!eq(p1, p2)) res.push_back(p2);\n return res;\n}\ntemplate<class DD> vector<Point<DD>> crosspoint(const Circle<DD> &e, const Line<DD> &l) {\n vector<Point<DD>> res;\n Point<DD> p = proj_for_crosspoint(e, l);\n DD rcos = abs(e - p), rsin;\n if (rcos > e.r + EPS) return vector<Point<DD>>();\n else if (e.r - rcos < EPS) rsin = 0;\n else rsin = sqrt(e.r * e.r - rcos * rcos);\n Point<DD> dir = (l[1] - l[0]) / abs(l[1] - l[0]);\n Point<DD> p1 = p + dir * rsin;\n Point<DD> p2 = p - dir * rsin;\n res.push_back(p1);\n if (!eq(p1, p2)) res.push_back(p2);\n return res;\n}\n\ntemplate<class Abel> struct FastMultiSetByBIT {\n int topbit(int x) const { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }\n int lowbit(int x) const { return (x == 0 ? -1 : __builtin_ctz(x)); }\n int lim;\n Abel IDENTITY;\n vector<Abel> dat;\n \n // [0, n)\n FastMultiSetByBIT(int n, Abel identity = 0)\n : lim(n), IDENTITY(identity), dat(n, identity) { }\n void init(int n, Abel identity = 0) {\n lim = n;\n IDENTITY = identity;\n dat.assign(n, IDENTITY);\n }\n \n // p is 0-indexed\n void add(int p, Abel x) {\n if (p < 0) p = 0;\n for (int i = p; i < (int)dat.size(); i |= i + 1)\n dat[i] = dat[i] + x;\n }\n \n // [0, p), p is 0-indexed\n Abel sum(int p) const {\n if (p > lim) p = lim;\n Abel res = IDENTITY;\n for (int i = p - 1; i >= 0; i = (i & (i + 1)) - 1)\n res = res + dat[i];\n return res;\n }\n \n // [l, r), l and r are 0-indexed\n Abel sum(int l, int r) const {\n return sum(r) - sum(l);\n }\n \n // insert, erase, count, min, max\n void insert(int x) { add(x, 1); }\n void erase(int x) { if (count(x)) add(x, -1); }\n Abel count(int x) const { return sum(x, x + 1); }\n Abel count(int l, int r) const { return sum(l, r); }\n Abel size() const { return sum(lim); }\n bool operator [] (int x) const { return count(x); }\n int get_min() const { return next(); }\n int get_max() const { return prev(); }\n\n // get max r s.t. check(sum(l, r)) = True (0-indexed), O(log N)\n // check(IDENTITY) must be True\n int max_right(const function<bool(Abel)> check, int l = 0) const {\n if (l >= lim) return lim;\n assert(check(IDENTITY));\n Abel s = IDENTITY;\n int k = 0;\n while (true) {\n if (l % 2 == 1) s = s - dat[l - 1], --l;\n if (l <= 0) {\n k = topbit(lim) + 1;\n break;\n }\n k = lowbit(l) - 1;\n if (l + (1 << k) > lim) break;\n if (!check(s + dat[l + (1 << k) - 1])) break;\n s = s - dat[l - 1];\n l -= l & -l;\n }\n while (k) {\n --k;\n if (l + (1 << k) - 1 < lim) {\n Abel ns = s + dat[l + (1 << k) - 1];\n if (check(ns)) {\n l += (1 << k);\n s = ns;\n }\n }\n }\n return l;\n }\n \n // get min l s.t. check(sum(l, r)) = True (0-indexed), O(log N)\n // check(IDENTITY) must be True\n int min_left(const function<bool(Abel)> check, int r = -1) const {\n if (r == -1) r = lim;\n if (r <= 0) return 0;\n assert(check(IDENTITY));\n Abel s = IDENTITY;\n int k = 0;\n while (r > 0 && check(s)) {\n s = s + dat[r - 1];\n k = lowbit(r);\n r -= r & -r;\n }\n if (check(s)) return 0;\n while (k) {\n --k;\n Abel ns = s - dat[r + (1 << k) - 1];\n if (!check(ns)) {\n r += (1 << k);\n s = ns;\n }\n }\n return r + 1;\n }\n \n // k-th number that is not less than l (k is 0-indexed)\n int get(Abel k, int l = 0) const {\n return max_right([&](Abel x) { return x <= k; }, l);\n }\n \n // next (including x)\n int next(int l = 0) const {\n if (l < 0) l = 0;\n if (l > lim) l = lim;\n return max_right([&](Abel x) { return x <= 0; }, l);\n }\n \n // prev (including x)\n int prev(int r) const {\n if (r > lim) r = lim;\n return min_left([&](Abel x) { return x <= 0; }, r + 1) - 1;\n }\n int prev() const {\n return prev(lim);\n }\n \n // debug\n friend ostream& operator << (ostream &s, const FastMultiSetByBIT &fs) {\n for (int x = fs.get_min(); x < fs.lim; x = fs.next(x + 1)) {\n s << x << \" \";\n }\n return s;\n }\n};\n\n\nint main() {\n int N;\n cin >> N;\n\n const int IN = 0;\n const int GET = 1;\n const int OUT = 2;\n struct Event {\n int typ, xl, xr, y;\n Event() {}\n Event(int typ, int xl, int xr, int y) : typ(typ), xl(xl), xr(xr), y(y) {}\n constexpr bool operator < (const Event &rhs) const {\n return pint(y, typ) < pint(rhs.y, rhs.typ);\n };\n };\n\n vector<int> comp;\n vector<Event> evs;\n REP(i, N) {\n int x1, y1, x2, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n if (x1 == x2) {\n evs.EB(Event(IN, x1, x2, min(y1, y2)));\n evs.EB(Event(OUT, x1, x2, max(y1, y2)));\n } else {\n evs.EB(Event(GET, min(x1, x2), max(x1, x2), y1));\n }\n comp.EB(x1), comp.EB(x2);\n }\n sort(evs.begin(), evs.end());\n sort(comp.begin(), comp.end());\n comp.erase(unique(comp.begin(), comp.end()), comp.end());\n\n FastMultiSetByBIT<int> sx(comp.size()+10);\n\n ll res = 0;\n for (auto [typ, xl, xr, y] : evs) {\n int l = lower_bound(comp.begin(), comp.end(), xl) - comp.begin() + 1; \n int r = lower_bound(comp.begin(), comp.end(), xr) - comp.begin() + 1;\n if (typ == IN) sx.insert(l);\n else if (typ == OUT) sx.erase(l);\n else {\n ll add = sx.count(l, r+1);\n res += add;\n\n //COUT(comp); COUT(y); COUT(sx); COUT(l); COUT(r); COUT(add);\n }\n }\n cout << res << endl;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 10336, "score_of_the_acc": -0.1488, "final_rank": 9 }, { "submission_id": "aoj_CGL_6_A_10415104", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (i = 0; i < (int)(n); i++)\nusing ll = long long;\n\n#define EPS (1e-10)\n#define equals(a, b) (fabs((a) - (b)) < EPS)\n\nenum\n{\n COUNTER_CLOCKWISE = 1,\n CLOCKWISE = -1,\n ONLINE_BACK = 2,\n ONLINE_FRONT = -2,\n ON_SEGMENT = 0\n};\n\nenum\n{\n IN = 2,\n ON = 1,\n OUT = 0\n};\n\nenum\n{\n BOTTOM = 0,\n LEFT = 1,\n RIGHT = 2,\n TOP = 3\n};\n\nclass Point\n{\npublic:\n double x;\n double y;\n\n Point(double x = 0, double y = 0) : x(x), y(y) {}\n\n Point operator+(const Point p) const\n {\n return Point(x + p.x, y + p.y);\n }\n Point operator-(const Point p) const\n {\n return Point(x - p.x, y - p.y);\n }\n Point operator*(const double k) const\n {\n return Point(x * k, y * k);\n }\n Point operator/(const double k) const\n {\n return Point(x / k, y / k);\n }\n\n double norm()\n {\n return x * x + y * y;\n }\n double abs()\n {\n return sqrt(norm());\n }\n\n bool operator<(const Point &p) const\n {\n if (y != p.y)\n {\n return y < p.y;\n }\n else\n {\n return x < p.x;\n }\n }\n bool operator==(const Point &p) const\n {\n return fabs(x - p.x) < EPS && fabs(y - p.y) < EPS;\n }\n};\n\nclass Circle\n{\npublic:\n Point c;\n double r;\n Circle(Point c = Point(), double r = 0.0) : c(c), r(r) {}\n};\n\nstruct Segment\n{\n Point p1;\n Point p2;\n};\n\ntypedef vector<Point> Polygon;\n\nclass EndPoint\n{\npublic:\n Point p;\n int seg;\n int st;\n EndPoint() {}\n EndPoint(Point p, int seg, int st) : p(p), seg(seg), st(st) {}\n\n bool operator<(const EndPoint &ep) const\n {\n if (p.y == ep.p.y)\n {\n return st < ep.st;\n }\n else\n {\n return p.y < ep.p.y;\n }\n }\n};\n\ndouble arg(Point p)\n{\n return atan2(p.y, p.x);\n}\n\nPoint polar(double a, double r)\n{\n return Point(cos(r) * a, sin(r) * a);\n}\n\ndouble dot(Point a, Point b)\n{\n return a.x * b.x + a.y * b.y;\n}\n\ndouble cross(Point a, Point b)\n{\n return a.x * b.y - a.y * b.x;\n}\n\nbool isOrthogonal(Point a, Point b)\n{\n return equals(dot(a, b), 0.0);\n}\n\nbool isOrthogonal(Point a1, Point a2, Point b1, Point b2)\n{\n return isOrthogonal(a1 - a2, b1 - b2);\n}\n\nbool isOrthogonal(Segment s1, Segment s2)\n{\n return equals(dot(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);\n}\n\nbool isParallel(Point a, Point b)\n{\n return equals(cross(a, b), 0.0);\n}\n\nbool isParallel(Point a1, Point a2, Point b1, Point b2)\n{\n return isParallel(a1 - a2, b1 - b2);\n}\n\nbool isParallel(Segment s1, Segment s2)\n{\n return equals(cross(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);\n}\n\nPoint project(Segment s, Point p)\n{\n Point base = s.p2 - s.p1;\n double r = dot(p - s.p1, base) / base.norm();\n return s.p1 + base * r;\n}\n\nPoint reflect(Segment s, Point p)\n{\n return p + (project(s, p) - p) * 2;\n}\n\nint ccw(Point p0, Point p1, Point p2)\n{\n Point a = p1 - p0;\n Point b = p2 - p0;\n if (cross(a, b) > EPS)\n {\n return COUNTER_CLOCKWISE;\n }\n if (cross(a, b) < -EPS)\n {\n return CLOCKWISE;\n }\n if (dot(a, b) < -EPS)\n {\n return ONLINE_BACK;\n }\n if (a.norm() < b.norm())\n {\n return ONLINE_FRONT;\n }\n return ON_SEGMENT;\n}\n\nbool intersect(Point p1, Point p2, Point p3, Point p4)\n{\n return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 && ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0;\n}\n\nbool intersect(Segment s1, Segment s2)\n{\n return intersect(s1.p1, s1.p2, s2.p1, s2.p2);\n}\n\ndouble getDistance(Point a, Point b)\n{\n return (a - b).abs();\n}\n\ndouble getDistanceLP(Segment s, Point p)\n{\n return abs(cross(s.p2 - s.p1, p - s.p1) / (s.p2 - s.p1).abs());\n}\n\ndouble getDistanceSP(Segment s, Point p)\n{\n if (dot(s.p2 - s.p1, p - s.p1) < 0.0)\n {\n return getDistance(p, s.p1);\n }\n if (dot(s.p1 - s.p2, p - s.p2) < 0.0)\n {\n return getDistance(p, s.p2);\n }\n return getDistanceLP(s, p);\n}\n\ndouble getDistance(Segment s1, Segment s2)\n{\n if (intersect(s1, s2))\n {\n return 0.0;\n }\n return min(min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)), min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2)));\n}\n\nbool intersect(Circle c, Segment s)\n{\n return getDistanceLP(s, c.c) <= c.r;\n}\n\nbool intersect(Circle c1, Circle c2)\n{\n return getDistance(c1.c, c2.c) <= c1.r + c2.r;\n}\n\nPoint getCrossPoint(Segment s1, Segment s2)\n{\n Point base = s2.p2 - s2.p1;\n double d1 = abs(cross(base, s1.p1 - s2.p1));\n double d2 = abs(cross(base, s1.p2 - s2.p1));\n double t = d1 / (d1 + d2);\n return s1.p1 + (s1.p2 - s1.p1) * t;\n}\n\npair<Point, Point> getCrossPoints(Circle c, Segment s)\n{\n Point pr;\n Point e;\n double base;\n\n assert(intersect(c, s));\n pr = project(s, c.c);\n e = (s.p2 - s.p1) / (s.p2 - s.p1).abs();\n base = sqrt(c.r * c.r - (pr - c.c).norm());\n return {pr - e * base, pr + e * base};\n}\n\npair<Point, Point> getCrossPoints(Circle c1, Circle c2)\n{\n double d;\n double a;\n double t;\n\n assert(intersect(c1, c2));\n d = (c1.c - c2.c).abs();\n a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));\n t = arg(c2.c - c1.c);\n return {c1.c + polar(c1.r, t + a), c1.c + polar(c1.r, t - a)};\n}\n\nint contains(Polygon g, Point p)\n{\n bool ans;\n Point a;\n Point b;\n int i;\n\n ans = false;\n rep(i, g.size())\n {\n a = g.at(i) - p;\n b = g.at((i + 1) % g.size()) - p;\n if (abs(cross(a, b)) < EPS && dot(a, b) < EPS)\n {\n return ON;\n }\n if (a.y > b.y)\n {\n swap(a, b);\n }\n if (a.y < EPS && EPS < b.y && cross(a, b) > EPS)\n {\n ans = !ans;\n }\n }\n if (ans)\n {\n return IN;\n }\n else\n {\n return OUT;\n }\n}\n\nPolygon andrewScan(Polygon s)\n{\n Polygon u;\n Polygon l;\n int i;\n int n;\n\n if (s.size() < 3)\n {\n return s;\n }\n sort(s.begin(), s.end());\n u.push_back(s.at(0));\n u.push_back(s.at(1));\n l.push_back(s.at(s.size() - 1));\n l.push_back(s.at(s.size() - 2));\n\n for (i = 2; i < (int)s.size(); i++)\n {\n for (n = u.size(); n >= 2 && ccw(u.at(n - 2), u.at(n - 1), s.at(i)) != CLOCKWISE && ccw(u.at(n - 2), u.at(n - 1), s.at(i)) != ONLINE_FRONT; n--)\n {\n u.pop_back();\n }\n u.push_back(s.at(i));\n }\n\n for (i = s.size() - 3; i >= 0; i--)\n {\n for (n = l.size(); n >= 2 && ccw(l.at(n - 2), l.at(n - 1), s.at(i)) != CLOCKWISE && ccw(l.at(n - 2), l.at(n - 1), s.at(i)) != ONLINE_FRONT; n--)\n {\n l.pop_back();\n }\n l.push_back(s.at(i));\n }\n\n reverse(l.begin(), l.end());\n for (i = u.size() - 2; i >= 1; i--)\n {\n l.push_back(u.at(i));\n }\n return l;\n}\n\nint manhattanIntersection(vector<Segment> S)\n{\n int i;\n vector<EndPoint> EP;\n set<int> BT;\n BT.insert(INT_MAX);\n int cnt;\n\n rep(i, S.size())\n {\n if (S.at(i).p1.y == S.at(i).p2.y)\n {\n if (S.at(i).p1.x > S.at(i).p2.x)\n {\n swap(S.at(i).p1, S.at(i).p2);\n }\n }\n else\n {\n if (S.at(i).p1.y > S.at(i).p2.y)\n {\n swap(S.at(i).p1, S.at(i).p2);\n }\n }\n\n if (S.at(i).p1.y == S.at(i).p2.y)\n {\n EP.push_back(EndPoint(S.at(i).p1, i, LEFT));\n EP.push_back(EndPoint(S.at(i).p2, i, RIGHT));\n }\n else\n {\n EP.push_back(EndPoint(S.at(i).p1, i, BOTTOM));\n EP.push_back(EndPoint(S.at(i).p2, i, TOP));\n }\n }\n sort(EP.begin(), EP.end());\n\n cnt = 0;\n rep(i, EP.size())\n {\n if (EP.at(i).st == TOP)\n {\n BT.erase(EP.at(i).p.x);\n }\n else if (EP.at(i).st == BOTTOM)\n {\n BT.insert(EP.at(i).p.x);\n }\n else if (EP.at(i).st == LEFT)\n {\n auto b = BT.lower_bound(S.at(EP.at(i).seg).p1.x);\n auto e = BT.upper_bound(S.at(EP.at(i).seg).p2.x);\n cnt += distance(b, e);\n }\n }\n return cnt;\n}\n\nint main()\n{\n int n;\n int i;\n\n cin >> n;\n vector<Segment> S(n);\n rep(i, n)\n {\n cin >> S.at(i).p1.x >> S.at(i).p1.y >> S.at(i).p2.x >> S.at(i).p2.y;\n }\n cout << manhattanIntersection(S) << endl;\n\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 17872, "score_of_the_acc": -0.2941, "final_rank": 16 }, { "submission_id": "aoj_CGL_6_A_10396731", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int BOTTOM = 0, LEFT = 1, RIGHT = 2, TOP = 3;\n\nstruct Point {\n\tint x, y;\n\tPoint(int x = 0, int y = 0) : x(x), y(y) {}\n\t\n};\n\nstruct Segment {\n\tPoint p1, p2;\n};\n\nstruct EndPoint {\n\tPoint p;\n\tint seg, type;\n\tEndPoint() {}\n\tEndPoint(Point p, int seg, int type) : p(p), seg(seg), type(type) {}\n\t\n\tbool operator < (const EndPoint &ep) const {\n\t\treturn p.y == ep.p.y ? type < ep.type : p.y < ep.p.y;\n\t}\n};\n\nEndPoint EP[2 * 100000];\n\nint manhattanIntersection(vector<Segment> S) {\n\tint n = S.size();\n\t\n\tfor (int i = 0, k = 0; i < n; ++i) {\n\t\tif (S[i].p1.y == S[i].p2.y) {\n\t\t\tif (S[i].p1.x > S[i].p2.x) swap(S[i].p1, S[i].p2);\n\t\t} else if (S[i].p1.y > S[i].p2.y) swap(S[i].p1, S[i].p2);\n\t\t\n\t\tif (S[i].p1.y == S[i].p2.y) {\n\t\t\tEP[k++] = EndPoint(S[i].p1, i, LEFT);\n\t\t\tEP[k++] = EndPoint(S[i].p2, i, RIGHT);\n\t\t} else {\n\t\t\tEP[k++] = EndPoint(S[i].p1, i, BOTTOM);\n\t\t\tEP[k++] = EndPoint(S[i].p2, i, TOP);\n\t\t}\n\t}\n\t\n\tsort(EP, EP + (2 * n));\n\t\n\tset<int> BT;\n\tint cnt = 0;\n\t\n\tfor (int i = 0; i < 2 * n; ++i) {\n\t\tif (EP[i].type == BOTTOM) {\n\t\t\tBT.insert(EP[i].p.x);\n\t\t} else if (EP[i].type == LEFT) {\n\t\t\tauto b = BT.lower_bound(S[EP[i].seg].p1.x);\n\t\t\tauto e = BT.upper_bound(S[EP[i].seg].p2.x);\n\t\t\tcnt += distance(b, e);\n\t\t} else if (EP[i].type == TOP) {\n\t\t\tBT.erase(EP[i].p.x);\n\t\t}\n\t}\n\t\n\treturn cnt;\n}\n\nint main() {\n\tint n; cin >> n;\n\tvector<Segment> S(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> S[i].p1.x >> S[i].p1.y >> S[i].p2.x >> S[i].p2.y;\n\t}\n\t\n\tcout << manhattanIntersection(S) << endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 12088, "score_of_the_acc": -0.1772, "final_rank": 10 } ]
aoj_NTL_2_B_cpp
Difference of Big Integers Given two integers $A$ and $B$, compute the difference, $A - B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the difference in a line. Constraints $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample Output 1 -3 Sample Input 2 100 25 Sample Output 2 75 Sample Input 3 -1 -1 Sample Output 3 0 Sample Input 4 12 -3 Sample Output 4 15
[ { "submission_id": "aoj_NTL_2_B_10774191", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print_arr( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() ; i++ )\n cout << v[i];\n cout << endl;\n}\n\nstruct BigInteger{\n\n bool minus;\n int digit;\n vector<ll> arr;\n\n BigInteger( string val = \"\", bool m = false ){\n\n minus = m;\n while( val.length() > 4 ){\n arr.push_back( stoll( val.substr( val.length() - 4 ) ) );\n val = val.substr( 0, val.length() - 4 );\n }\n if( val.length() != 0 )\n arr.push_back( stoll( val ) );\n set_digit();\n\n }\n\n void shift_l(){\n\n ll up = 0;\n for( int i = 0 ; i < digit ; i++ ){\n ll next_up = arr[i] / 1000;\n arr[i] = ( arr[i] % 1000 ) * 10 + up; \n up = next_up;\n }\n arr.push_back( up );\n set_digit();\n\n }\n\n void shift_r(){\n\n ll down = 0;\n for( int i = digit - 1 ; i >= 0 ; i-- ){\n ll next_down = arr[i] % 10;\n arr[i] = 1000 * down + arr[i] / 10;\n down = next_down;\n }\n set_digit();\n\n }\n\n bool zero(){\n\n return digit == 1 && arr[0] == 0;\n\n }\n\n void set_digit(){\n\n while( arr.size() > 1 && arr[arr.size()-1] == 0 )\n arr.pop_back();\n digit = arr.size();\n\n }\n\n void print(){\n\n if( zero() ){\n cout << 0 << endl;\n return;\n }\n if( minus )\n cout << \"-\";\n cout << arr[digit - 1];\n for( int i = digit - 2 ; i >= 0 ; i-- )\n cout << setfill( '0' ) << std::setw( 4 ) << arr[i];\n cout << endl;\n\n }\n\n};\n\nBigInteger add( BigInteger bi1, BigInteger bi2 );\nBigInteger sub( BigInteger bi1, BigInteger bi2 );\nBigInteger mul( BigInteger bi1, BigInteger bi2 );\nBigInteger div( BigInteger bi1, BigInteger bi2 );\nbool operator<( const BigInteger bi1, const BigInteger bi2 );\nbool operator>( const BigInteger bi1, const BigInteger bi2 );\nbool operator<=( const BigInteger bi1, const BigInteger bi2 );\nbool operator>=( const BigInteger bi1, const BigInteger bi2 );\nbool operator==( const BigInteger bi1, const BigInteger bi2 );\nbool operator!=( const BigInteger bi1, const BigInteger bi2 );\n\nBigInteger add( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return sub( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n return sub( bi2, bi1 );\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n\n BigInteger res;\n ll up = 0;\n for( int i = 0 ; i < max( bi1.digit, bi2.digit ) ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i];\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n res.arr.push_back( ( val1 + val2 + up ) % 10000 ); \n up = ( val1 + val2 + up ) / 10000;\n }\n res.arr.push_back( up );\n res.set_digit();\n return res;\n\n}\n\nBigInteger sub( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return add( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = sub( bi2, bi1 );\n return res;\n }\n\n if( bi1.digit < bi2.digit ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n else if( bi1.digit == bi2.digit ){\n for( int i = bi1.digit-1 ; i >= 0 ; i-- ){\n if( bi1.arr[i] > bi2.arr[i] )\n break;\n else if( bi1.arr[i] < bi2.arr[i] ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n }\n }\n \n BigInteger res;\n ll down = 0;\n for( int i = 0 ; i < bi1.digit ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i] - down;\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n if( val1 < val2 ){\n down = 1;\n val1 += 10000;\n }\n else \n down = 0;\n res.arr.push_back( val1 - val2 );\n }\n res.set_digit();\n return res;\n\n}\n\nBigInteger mul( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n res.minus = ( bi1.minus != bi2.minus );\n for( int i = 0 ; i < bi1.digit + bi2.digit ; i++ )\n res.arr.push_back( 0 );\n for( int i = 0 ; i < bi1.digit ; i++ ){\n for( int j = 0 ; j < bi2.digit ; j++ )\n res.arr[i+j] += bi1.arr[i] * bi2.arr[j];\n }\n ll up = 0;\n for( int i = 0 ; i < bi1.digit + bi2.digit ; i++ ){\n ll next_up = ( res.arr[i] + up ) / 10000;\n res.arr[i] = ( res.arr[i] + up ) % 10000;\n up = next_up;\n }\n res.set_digit();\n return res;\n\n}\n\nBigInteger div( BigInteger bi1, BigInteger bi2 ){\n\n string num = \"\";\n bool m = ( bi1.minus != bi2.minus );\n bi1.minus = bi2.minus = false;\n BigInteger org = bi2;\n if( bi1 < bi2 ){\n BigInteger zero( \"0\", false );\n return zero;\n }\n while( bi1.digit > bi2.digit ){\n bi2.arr.insert( bi2.arr.begin(), 0 );\n bi2.digit++;\n }\n while( to_string( bi1.arr[bi1.digit-1] ).length() > to_string( bi2.arr[bi2.digit-1] ).length() )\n bi2.shift_l();\n while( to_string( bi1.arr[bi1.digit-1] ).length() < to_string( bi2.arr[bi2.digit-1] ).length() )\n bi2.shift_r();\n while( bi2 >= org ){ \n int i;\n for( i = 0 ; i <= 9 ; i++ ){\n BigInteger tmp = sub( bi1, bi2 );\n tmp.print();\n if( !tmp.zero() && tmp.minus )\n break;\n bi1 = tmp;\n } \n num += to_string( i );\n bi2.shift_r();\n }\n BigInteger res( num, m );\n return res;\n\n}\n\nbool operator<( const BigInteger bi1, const BigInteger bi2 ){\n\n BigInteger tmp = sub( bi1, bi2 );\n return tmp.minus && !tmp.zero();\n\n}\n\nbool operator>( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.minus && !tmp.zero();\n\n}\n\nbool operator<=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return tmp.minus || tmp.zero();\n\n}\n\nbool operator>=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.minus || tmp.zero();\n\n}\n\nbool operator==( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return tmp.zero();\n\n}\n\nbool operator!=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.zero();\n\n}\n\nint main(){\n\n string val1, val2;\n bool minus;\n \n cin >> val1;\n if( val1[0] == '-' ){\n minus = true;\n val1 = val1.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi1( val1, minus );\n\n cin >> val2;\n if( val2[0] == '-' ){\n minus = true;\n val2 = val2.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi2( val2, minus );\n \n BigInteger res = sub( bi1, bi2 );\n res.print();\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5108, "score_of_the_acc": -0.0758, "final_rank": 2 }, { "submission_id": "aoj_NTL_2_B_10710923", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print_arr( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() ; i++ )\n cout << v[i];\n cout << endl;\n}\n\nstruct BigInteger{\n\n bool minus;\n int digit;\n vector<ll> arr;\n\n BigInteger( string val = \"\", bool m = false ){\n\n minus = m;\n while( val.length() > 4 ){\n arr.push_back( stoll( val.substr( val.length() - 4 ) ) );\n val = val.substr( 0, val.length() - 4 );\n }\n if( val.length() != 0 )\n arr.push_back( stoll( val ) );\n set_digit();\n\n }\n\n bool zero(){\n\n return arr.size() == 1 && arr[0] == 0;\n\n }\n\n void set_digit(){\n\n while( arr.size() > 1 && arr[arr.size()-1] == 0 ){\n arr.pop_back();\n }\n digit = arr.size();\n\n }\n\n void print(){\n\n if( zero() ){\n cout << 0 << endl;\n return;\n }\n if( minus )\n cout << \"-\";\n cout << arr[digit - 1];\n for( int i = digit - 2 ; i >= 0 ; i-- )\n cout << setfill( '0' ) << std::setw( 4 ) << arr[i];\n cout << endl;\n\n }\n\n};\n\nBigInteger add( BigInteger bi1, BigInteger bi2 );\nBigInteger sub( BigInteger bi1, BigInteger bi2 );\n\nBigInteger add( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return sub( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n return sub( bi2, bi1 );\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n\n BigInteger res;\n ll up = 0;\n for( int i = 0 ; i < max( bi1.digit, bi2.digit ) ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i];\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n res.arr.push_back( ( val1 + val2 + up ) % 10000 ); \n up = ( val1 + val2 + up ) / 10000;\n }\n res.arr.push_back( up );\n res.set_digit();\n return res;\n\n}\n\nBigInteger sub( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return add( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = sub( bi2, bi1 );\n return res;\n }\n\n if( bi1.digit < bi2.digit ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n else if( bi1.digit == bi2.digit ){\n if( bi1.arr[bi1.digit-1] < bi2.arr[bi2.digit-1] ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n }\n \n BigInteger res;\n ll down = 0;\n for( int i = 0 ; i < bi1.digit ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i] - down;\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n if( val1 < val2 ){\n down = 1;\n val1 += 10000;\n }\n else \n down = 0;\n res.arr.push_back( val1 - val2 );\n }\n res.set_digit();\n return res;\n\n}\n\nint main(){\n\n string val1, val2;\n bool minus;\n \n cin >> val1;\n if( val1[0] == '-' ){\n minus = true;\n val1 = val1.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi1( val1, minus );\n\n cin >> val2;\n if( val2[0] == '-' ){\n minus = true;\n val2 = val2.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi2( val2, minus );\n \n BigInteger res = sub( bi1, bi2 );\n res.print();\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5040, "score_of_the_acc": -0.0751, "final_rank": 1 }, { "submission_id": "aoj_NTL_2_B_10025747", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n string rawA, rawB;\n cin >> rawA >> rawB;\n int fa = 1, fb = 1;\n string A = rawA, B = rawB;\n if (B[0] == '-') {\n B.erase(0, 1);\n } else {\n B = \"-\" + B;\n }\n if (A[0] == '-') {\n fa = -1;\n A.erase(0, 1);\n }\n if (B[0] == '-') {\n fb = -1;\n B.erase(0, 1);\n }\n bool is_swap = A.size() < B.size();\n if (A.size() == B.size()) {\n for (int i = 0; i < A.size(); i++) {\n if (A[i] == B[i]) {\n continue;\n }\n is_swap = A[i] < B[i];\n break;\n }\n }\n if (is_swap) {\n std::swap(A, B);\n std::swap(fa, fb);\n std::swap(rawA, rawB);\n }\n int diff = (A.size() - B.size());\n for (int i = 0; i < diff; i++) {\n B = '0' + B;\n }\n int f = fa * fb;\n int next = 0;\n string s = \"\";\n for (int i = 1; i <= A.size(); i++) {\n int val = A[A.size() - i] - '0' + f * (B[B.size() - i] - '0') + next;\n if (val > 9) {\n next = 1;\n val -= 10;\n } else if (val < 0) {\n next = -1;\n val += 10;\n } else {\n next = 0;\n }\n s = to_string(val) + s;\n }\n if (next != 0) {\n s = \"1\" + s;\n }\n while (s.size() > 1 && s[0] == '0') {\n s.erase(0, 1);\n }\n if (s != \"0\" && fa < 0) {\n s = \"-\" + s;\n }\n cout << s << endl;\n}", "accuracy": 1, "time_ms": 260, "memory_kb": 4100, "score_of_the_acc": -0.3695, "final_rank": 7 }, { "submission_id": "aoj_NTL_2_B_9795744", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n\ntemplate <int BASE>\nclass BigDecimal {\n public:\n static constexpr std::string_view NUMERAL{\n \"0123456789ABCDEF\"}; // 16進数まで対応\n\n private: // 静的関数\n static int CompareIgnoreSign(const BigDecimal& a, const BigDecimal& b) {\n // a-bの符号で覚えてもよいかも。\n // a<b: -1\n // a>b: +1\n // a==b: 0\n if (a._digit.size() != b._digit.size())\n return a._digit.size() < b._digit.size() ? -1 : 1;\n for (int i = a._digit.size() - 1; i >= 0; --i) {\n if (a._digit[i] == b._digit[i]) continue;\n return a._digit[i] < b._digit[i] ? -1 : 1;\n }\n return 0;\n }\n\n static BigDecimal Karatsuba(const BigDecimal& a, const BigDecimal& b) {\n // |a| >= |b|にする\n if (a._digit.size() < b._digit.size()) return Karatsuba(b, a);\n // 1桁に絞ったら直に計算して返す\n if (b._digit.size() == 1) {\n BigDecimal ret(a);\n for (int i = 0; i < a._digit.size(); ++i) {\n ret._digit[i] *= b._digit[0];\n }\n ret.carry_and_fix();\n if (b._positive)\n return ret;\n else\n return -ret;\n }\n int N = a._digit.size() / 2; // 下半分の桁数\n bool sign = !(a._positive xor b._positive); // 符号を計算しておく\n BigDecimal a0(a), a1(a), b0(b), b1(b); // x = concat(x0, x1)\n // aの処理\n // x1の下N桁を残す形で上の桁を取り除く\n while (a1._digit.size() > N) a1._digit.pop_back();\n // x0のデータを消去\n a0._digit.clear();\n // x0に下N桁より上の桁を保存しなおす\n for (int i = 0; N + i < a._digit.size(); ++i)\n a0._digit.emplace_back(a._digit[N + i]);\n if (a0._digit.size() == 0) a0._digit.emplace_back(0);\n // x0, x1の符号を取り除く\n a0._positive = a1._positive = true;\n if (b._digit.size() < N) { // 一方が他方の半分もない\n BigDecimal p0, c1;\n p0 = Karatsuba(a0, b);\n c1 = Karatsuba(a1, b);\n BigDecimal c0;\n for (int i = 0; i < N - 1; ++i) c0._digit.emplace_back(0);\n for (const auto& d : p0._digit) c0._digit.emplace_back(d);\n BigDecimal ret = c0 + c1;\n ret._positive = sign;\n return ret;\n }\n // bの処理\n // x1の下N桁を残す形で上の桁を取り除く\n while (b1._digit.size() > N) b1._digit.pop_back();\n // x0のデータを消去\n b0._digit.clear();\n // x0に下N桁より上の桁を保存しなおす\n for (int i = 0; N + i < b._digit.size(); ++i)\n b0._digit.emplace_back(b._digit[N + i]);\n if (b0._digit.size() == 0) b0._digit.emplace_back(0);\n // x0, x1の符号を取り除く\n b0._positive = b1._positive = true;\n // 3種類の積\n BigDecimal p0, p1, p2;\n p0 = Karatsuba(a0, b0);\n p2 = Karatsuba(a1, b1);\n p1 = Karatsuba(a0 + a1, b0 + b1) - p0 - p2;\n // 積に対応する数\n BigDecimal c0, c1, c2;\n c0._digit.clear();\n c1._digit.clear();\n c2._digit.clear();\n for (int i = 0; i < N; ++i) {\n c0._digit.emplace_back(0);\n c0._digit.emplace_back(0);\n c1._digit.emplace_back(0);\n }\n for (const auto& d : p0._digit) c0._digit.emplace_back(d);\n for (const auto& d : p1._digit) c1._digit.emplace_back(d);\n for (const auto& d : p2._digit) c2._digit.emplace_back(d);\n BigDecimal ret = c0 + c1 + c2;\n ret._positive = sign;\n return ret;\n }\n\n private:\n std::vector<int> _digit;\n bool _positive;\n\n void carry_and_fix() {\n // 新規の桁が発生しない範疇(最後の桁以外)を処理\n for (int i = 0; i < _digit.size() - 1; ++i) {\n if (_digit[i] >= BASE) {\n // 桁の数が基数以上: 繰り上げる必要あり\n int k = _digit[i] / BASE; // 繰り上がり発生回数\n _digit[i] -= k * BASE;\n _digit[i + 1] += k;\n } else if (_digit[i] < 0) {\n // 桁の数が負: 繰り下げが必要\n int k = (-_digit[i] - 1) / BASE + 1;\n _digit[i] += k * BASE;\n _digit[i + 1] -= k;\n }\n }\n // 最後の桁を処理する場合\n while (_digit.back() >= BASE) {\n int k = _digit.back() / BASE; // 繰り上がり発生回数\n _digit.back() -= k * BASE;\n _digit.emplace_back(k);\n }\n // 計算結果がマイナスなら全体に-1をかけて符号反転\n if (_digit.back() < 0) {\n this->_positive = !this->_positive;\n for (int i = 0; i < _digit.size(); ++i) {\n _digit[i] *= -1;\n }\n this->carry_and_fix();\n }\n // 0の桁を上から消す\n while (_digit.size() >= 2 && _digit.back() == 0) _digit.pop_back();\n // 0になったら正の数にしておく(-0表記は困るため)\n if(_digit.size() == 1 && _digit[0] == 0) _positive = true;\n }\n\n public:\n // コンストラクタ\n BigDecimal(int num = 0) : _digit(0), _positive(num >= 0) {\n if (!_positive) num *= -1;\n while (num > 0) {\n _digit.emplace_back(num % BASE);\n num /= BASE;\n }\n if (_digit.size() == 0) _digit.emplace_back(0);\n }\n BigDecimal(std::string s) {\n if (s[0] == '-') {\n s = s.substr(1);\n _positive = false;\n } else {\n _positive = true;\n }\n while (s.size() > 0) {\n int i = NUMERAL.find(s.back());\n _digit.emplace_back(i);\n s.pop_back();\n }\n }\n // コピーコンストラクタ\n BigDecimal(const BigDecimal& x)\n : _digit(x._digit.size()), _positive(x._positive) {\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] = x._digit[i];\n }\n }\n\n // 比較演算子\n bool operator==(const BigDecimal& x) const {\n if (this->_positive != x._positive) return false;\n if (this->_digit.size() != x._digit.size()) return false;\n for (int i = 0; i < this->_digit.size(); ++i) {\n if (this->_digit[i] != x._digit[i]) return false;\n }\n return true;\n }\n bool operator!=(const BigDecimal& x) const { return !(*this == x); }\n bool operator<(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return false; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) < 0;\n } else {\n if (x._positive) return true; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) > 0;\n }\n }\n bool operator>(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return true; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) > 0;\n } else {\n if (x._positive) return false; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) < 0;\n }\n }\n bool operator<=(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return false; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) <= 0;\n } else {\n if (x._positive) return true; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) >= 0;\n }\n }\n bool operator>=(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return true; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) >= 0;\n } else {\n if (x._positive) return false; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) <= 0;\n }\n }\n\n // 単項演算子\n BigDecimal operator+() const { return *this; }\n BigDecimal operator-() const {\n BigDecimal ret = *this;\n ret._positive = !ret._positive;\n return ret;\n }\n // 複号代入演算子\n BigDecimal& operator+=(const BigDecimal& x) {\n // 符号が異なる場合は符号をそろえて引き算に\n if (this->_positive != x._positive) {\n return *this -= (-x);\n }\n // 符号が同じ物にのみ足し算を行う\n while (this->_digit.size() < x._digit.size()) {\n this->_digit.emplace_back(0);\n }\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] += x._digit[i];\n }\n this->carry_and_fix();\n return *this;\n }\n BigDecimal& operator-=(const BigDecimal& x) {\n // 符号が異なる場合は符号をそろえて足し算に\n if (this->_positive != x._positive) {\n return *this += (-x);\n }\n // 符号が同じ物にのみ引き算を行う\n while (this->_digit.size() < x._digit.size()) {\n this->_digit.emplace_back(0);\n }\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] -= x._digit[i];\n }\n this->carry_and_fix();\n return *this;\n }\n BigDecimal& operator*=(const BigDecimal& x) { return *this; }\n BigDecimal& operator/=(const BigDecimal& x) { return *this; }\n BigDecimal& operator%=(const BigDecimal& x) { return *this; }\n\n // 二項演算子\n BigDecimal operator+(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret += x);\n }\n BigDecimal operator-(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret -= x);\n }\n BigDecimal operator*(const BigDecimal& x) const {\n return Karatsuba(*this, x);\n }\n BigDecimal operator/(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret /= x);\n }\n BigDecimal operator%(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret %= x);\n }\n\n // キャスト\n operator std::string() const {\n std::string ret = \"\";\n for (const auto& c : _digit) {\n ret = NUMERAL.at(c) + ret;\n }\n if (!_positive) ret = \"-\" + ret;\n return ret;\n }\n};\n\nint main() {\n std::string A, B;\n std::cin >> A >> B;\n BigDecimal<10> a(A), b(B);\n std::cout << std::string(a-b) << std::endl;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 5128, "score_of_the_acc": -0.1484, "final_rank": 5 }, { "submission_id": "aoj_NTL_2_B_9478646", "code_snippet": "#include <iostream>\n#include <list>\n#include <string>\n#define Nm 0\n#define nM 1\n#define NM 2\nusing namespace std;\n\n// グローバル変数\nlist<int> n, m, result;\nint x = 0;\nint nminus = 0, mminus = 1;\n\n// 1つ目の数値を入力する関数\nvoid inputN() {\n string N;\n cin >> N;\n if (N[0] == '-') nminus = 1; // 負数の場合\n for (int i = nminus; i < N.length(); i++) {\n n.push_front(N[i] - '0'); // 数値をリストに追加\n }\n}\n\n// 2つ目の数値を入力する関数\nvoid inputM() {\n string M;\n cin >> M;\n if (M[0] == '-') mminus = 0; // 負数の場合\n for (int i = 1 - mminus; i < M.length(); i++) {\n m.push_front(M[i] - '0'); // 数値をリストに追加\n }\n}\n\n// 足し算を行う関数\nvoid computeplus(list<int> *n, list<int> *m) {\n if ((*n).empty() && (*m).empty()) {\n if (x == 0) return;\n else {\n result.push_front(1);\n return;\n }\n }\n if ((*n).empty()) {\n result.push_front((*((*m).begin()) + x) % 10);\n x = (*((*m).begin()) + x) / 10;\n (*m).pop_front();\n computeplus(n, m);\n return;\n }\n if ((*m).empty()) {\n result.push_front((*((*n).begin()) + x) % 10);\n x = (*((*n).begin()) + x) / 10;\n (*n).pop_front();\n computeplus(n, m);\n return;\n }\n result.push_front((*((*n).begin()) + *((*m).begin()) + x) % 10);\n x = ((*((*n).begin()) + *((*m).begin()) + x) / 10);\n (*n).pop_front();\n (*m).pop_front();\n computeplus(n, m);\n return;\n}\n\n// 数値の大小を比較する関数\nint compare(list<int> n, list<int> m) {\n if (n.size() > m.size()) return Nm;\n if (n.size() < m.size()) return nM;\n auto itn = n.end();\n auto itm = m.end();\n for (; itn != n.begin();) {\n itn--;\n itm--;\n if (*itn == *itm) continue;\n if (*itn > *itm) return Nm;\n if (*itn < *itm) return nM;\n }\n return NM;\n}\n\n// 引き算を行う関数\nvoid computeminus(list<int> *n, list<int> *m) {\n if ((*n).empty() && (*m).empty()) return;\n if ((*m).empty()) {\n if ((*((*n).begin()) - x) >= 0) {\n result.push_front((*((*n).begin()) - x));\n x = 0;\n (*n).pop_front();\n computeminus(n, m);\n return;\n } else {\n result.push_front((*((*n).begin()) - x) + 10);\n x = 1;\n (*n).pop_front();\n computeminus(n, m);\n return;\n }\n }\n if ((*((*n).begin()) - *((*m).begin()) - x) >= 0) {\n result.push_front((*((*n).begin()) - *((*m).begin()) - x));\n x = 0;\n (*n).pop_front();\n (*m).pop_front();\n computeminus(n, m);\n return;\n } else {\n result.push_front((*((*n).begin()) - *((*m).begin()) - x) + 10);\n x = 1;\n (*n).pop_front();\n (*m).pop_front();\n computeminus(n, m);\n return;\n }\n}\n\n// 先頭の0を削除する関数\nvoid eliminateO() {\n while (*(result.begin()) == 0 && result.size() > 1) {\n result.pop_front();\n }\n return;\n}\n\nint main(void) {\n inputN();\n inputM();\n if (nminus == 0 && mminus == 0) computeplus(&n, &m);\n if (nminus == 1 && mminus == 1) {\n computeplus(&n, &m);\n cout << \"-\";\n }\n if (nminus == 0 && mminus == 1) {\n if (compare(n, m) == NM) {\n cout << 0 << endl;\n return 0;\n } else if (compare(n, m) == Nm) {\n computeminus(&n, &m);\n eliminateO();\n } else if (compare(n, m) == nM) {\n computeminus(&m, &n);\n eliminateO();\n cout << \"-\";\n }\n }\n if (nminus == 1 && mminus == 0) {\n if (compare(n, m) == NM) {\n cout << 0 << endl;\n return 0;\n } else if (compare(n, m) == Nm) {\n computeminus(&n, &m);\n eliminateO();\n cout << \"-\";\n } else if (compare(n, m) == nM) {\n computeminus(&m, &n);\n eliminateO();\n }\n }\n while (!(result.empty())) {\n cout << *(result.begin());\n result.pop_front();\n }\n cout << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 15940, "score_of_the_acc": -0.1462, "final_rank": 4 }, { "submission_id": "aoj_NTL_2_B_9288522", "code_snippet": "#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\n\nint main() {\n boost::multiprecision::cpp_int a, b;\n cin >> a >> b;\n cout << a - b << '\\n' \n ;return 0;\n \n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3416, "score_of_the_acc": -1, "final_rank": 13 }, { "submission_id": "aoj_NTL_2_B_8219549", "code_snippet": "#include <bits/stdc++.h>\n\n\nint main() {\n std::string rawA, rawB;\n std::cin >> rawA >> rawB;\n\n int fa = 1, fb = 1;\n std::string A = rawA, B = rawB;\n\n if (B[0] == '-') {\n B.erase(0, 1);\n } else {\n B = \"-\" + B;\n }\n\n if (A[0] == '-') {\n fa = -1;\n A.erase(0, 1);\n }\n if (B[0] == '-') {\n fb = -1;\n B.erase(0, 1);\n }\n // std::cout << A << \" , \" << B << std::endl;\n\n bool is_swap = A.size() < B.size();\n if (A.size() == B.size()) {\n for (int i = 0; i < A.size(); i++) {\n if (A[i] == B[i]) {\n continue;\n }\n is_swap = A[i] < B[i];\n break;\n }\n }\n\n if (is_swap) {\n std::swap(A, B);\n std::swap(fa, fb);\n std::swap(rawA, rawB);\n }\n\n int diff = (A.size() - B.size());\n for (int i = 0; i < diff; i++) {\n B = '0' + B;\n }\n\n int f = fa * fb;\n int next = 0;\n std::string s = \"\";\n // std::cout << A << std::endl;\n // std::cout << B << std::endl;\n for (int i = 1; i <= A.size(); i++) {\n int val = A[A.size() - i] - '0' + f * (B[B.size() - i] - '0') + next;\n if (val > 9) {\n next = 1;\n val -= 10;\n } else if (val < 0) {\n next = -1;\n val += 10;\n } else {\n next = 0;\n }\n s = std::to_string(val) + s;\n }\n if (next != 0) {\n s = \"1\" + s;\n }\n\n while (s.size() > 1 && s[0] == '0') {\n s.erase(0, 1);\n }\n\n if (s != \"0\" && fa < 0) {\n s = \"-\" + s;\n }\n\n std::cout << s << std::endl;\n}", "accuracy": 1, "time_ms": 270, "memory_kb": 4164, "score_of_the_acc": -0.3847, "final_rank": 8 }, { "submission_id": "aoj_NTL_2_B_7680380", "code_snippet": "#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long u64;\ntypedef __uint128_t u128;\n\nstruct bignum {\n u64 a[30005];\n int n;\n\n int ctz() const {\n for (int i = 0;; i++) {\n if (a[i]) {\n return i << 6 | __builtin_ctzll(a[i]);\n }\n }\n }\n\n int lg() const {\n return n << 6 | __lg(a[n]);\n }\n\n bool operator<(const bignum &b) const {\n if (n != b.n) {\n return n < b.n;\n }\n for (int i = n; i != -1; i--) {\n if (a[i] < b.a[i]) {\n return 1;\n }\n if (a[i] > b.a[i]) {\n return 0;\n }\n }\n return 0;\n }\n\n bool operator>(const bignum &b) const {\n return b < *this;\n }\n\n bool operator<=(const bignum &b) const {\n return !(b < *this);\n }\n\n bool operator>=(const bignum &b) const {\n return !(*this < b);\n }\n\n bool operator==(const bignum &b) const {\n if (n != b.n) {\n return 0;\n }\n for (int i = 0; i <= n; i++) {\n if (a[i] != b.a[i]) {\n return 0;\n }\n }\n return 1;\n }\n\n bool operator!=(const bignum &b) const {\n return !(*this == b);\n }\n\n bignum operator+(u64 x) const {\n bignum c = *this;\n int l = c.n;\n\n c.a[0] += x;\n\n bool o = c.a[0] < a[0];\n if (o) {\n for (int i = 1; i <= l; i++) {\n if (a[i] == (u64)-1) {\n c.a[i] = 0;\n } else {\n c.a[i]++;\n o = 0;\n break;\n }\n }\n\n if (o) {\n c.a[++l] = 1;\n }\n }\n c.n = l;\n return c;\n }\n\n bignum operator-(u64 x) const {\n bignum c = *this;\n int l = c.n;\n\n c.a[0] -= x;\n\n bool o = c.a[0] > a[0];\n if (o) {\n for (int i = 1; i <= l; i++) {\n if (!a[i]) {\n c.a[i] = -1;\n } else {\n c.a[i]--;\n break;\n }\n }\n while (l && !c.a[l]) {\n l--;\n c.n--;\n }\n }\n return c;\n }\n\n bignum operator*(u64 x) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int l = n;\n u128 ad = 0;\n\n for (int i = 0; i <= l; i++) {\n ad += (u128)a[i] * x;\n c.a[i] = ad, ad >>= 64;\n }\n\n if (ad) {\n c.a[++l] = ad;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator/(int m) const {\n if (m == 1) {\n return *this;\n }\n\n bignum c;\n memset(&c, 0, sizeof c);\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n\n int l = n;\n int r = 0;\n\n for (int i = l; i != -1; i--) {\n u128 v = (u128)r * rr + a[i];\n u64 q = (v * b) >> 64;\n int gu = v - (u128)q * m;\n if (gu >= m) {\n gu -= m, q++;\n }\n\n c.a[i] = r * b + q, r = gu;\n }\n\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n int operator%(int m) const {\n if (m == 1) {\n return 0;\n }\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n int r = 0;\n\n for (int i = n; i != -1; i--) {\n u128 v = (u128)r * rr + a[i];\n u64 q = (v * b) >> 64;\n r = v - q * m;\n if (r >= m) {\n r -= m;\n }\n }\n\n return r;\n }\n\n bignum operator+(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n bool o = 0;\n int l = max(n, b.n);\n for (int i = 0; i <= l; i++) {\n c.a[i] = a[i] + b.a[i] + o;\n o = (c.a[i] < a[i]) || (b.a[i] == (u64)-1 && o);\n }\n if (o) {\n c.a[++l] = 1;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator-(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n bool o = 0;\n int l = n;\n for (int i = 0; i <= l; i++) {\n c.a[i] = a[i] - b.a[i] - o;\n o = (c.a[i] > a[i]) || (b.a[i] == (u64)-1 && o);\n }\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator*(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n u128 r = 0;\n int l = n + b.n;\n for (int i = 0; i <= n + b.n; i++) {\n u128 h = 0;\n\n for (int j = max(0, i - b.n); j <= min(i, n); j++) {\n u128 tp = (u128)a[j] * b.a[i - j];\n r += tp & ((u64)-1), h += tp >> 64;\n }\n\n c.a[i] = r;\n r = h + (r >> 64);\n }\n if (r) {\n c.a[++l] = r;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator/(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int n = lg(), m = b.lg();\n if (n < m) {\n return c;\n }\n\n bignum tp = *this, qwq = b << (n - m);\n int l = 0;\n for (int i = n - m; i != -1; i--, qwq >>= 1) {\n if (tp >= qwq) {\n tp -= qwq;\n c.a[i >> 6] |= 1ull << (i & 63);\n if (!l) {\n l = i;\n }\n }\n }\n\n c.n = l >> 6;\n return c;\n }\n\n bignum operator%(const bignum &b) const {\n bignum c = *this;\n\n int n = lg(), m = b.lg();\n if (n < m) {\n return c;\n }\n\n bignum tp = b << (n - m);\n for (int i = n; i >= m; i--, tp >>= 1) {\n if (c >= tp) {\n c -= tp;\n }\n }\n\n return c;\n }\n\n bignum operator+=(u64 x) {\n u64 tp = a[0];\n a[0] += x;\n bool o = a[0] < tp;\n\n if (o) {\n for (int i = 1; i <= n; i++) {\n if (a[i] == (u64)-1) {\n a[i] = 0;\n } else {\n a[i]++;\n o = 0;\n break;\n }\n }\n\n if (o) {\n a[++n] = 1;\n }\n }\n return *this;\n }\n\n bignum operator-=(u64 x) {\n u64 tp = a[0];\n a[0] -= x;\n bool o = a[0] > tp;\n\n if (o) {\n for (int i = 1; i <= n; i++) {\n if (!a[i]) {\n a[i] = -1;\n } else {\n a[i]--;\n break;\n }\n }\n while (n && !a[n]) {\n n--;\n }\n }\n return *this;\n }\n\n bignum operator*=(u64 x) {\n u128 ad = 0;\n\n for (int i = 0; i <= n; i++) {\n ad += (u128)a[i] * x;\n a[i] = ad, ad >>= 64;\n }\n\n if (ad) {\n a[++n] = ad;\n }\n\n return *this;\n }\n\n bignum operator/=(int m) {\n if (m == 1) {\n return *this;\n }\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n\n int r = 0;\n\n for (int i = n; i != -1; i--) {\n u128 v = (u128)r * rr + a[i];\n u64 q = (v * b) >> 64;\n int gu = v - (u128)q * m;\n if (gu >= m) {\n gu -= m, q++;\n }\n\n a[i] = r * b + q, r = gu;\n }\n\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n\n bignum operator+=(const bignum &b) {\n bool o = 0;\n int l = max(n, b.n);\n for (int i = 0; i <= l; i++) {\n u64 tp = a[i];\n a[i] += b.a[i] + o;\n o = (a[i] < tp) || (b.a[i] == (u64)-1 && o);\n }\n if (o) {\n a[++l] = 1;\n }\n n = l;\n\n return *this;\n }\n\n bignum operator-=(const bignum &b) {\n bool o = 0;\n int l = n;\n for (int i = 0; i <= l; i++) {\n u64 tp = a[i];\n a[i] -= b.a[i] + o;\n o = (a[i] > tp) || (b.a[i] == (u64)-1 && o);\n }\n while (l && !a[l]) {\n l--;\n }\n n = l;\n\n return *this;\n }\n\n bignum operator*=(const bignum &b) {\n return *this = *this * b;\n }\n\n bignum operator/=(const bignum &b) {\n return *this = *this / b;\n }\n\n bignum operator%=(const bignum &b) {\n return *this = *this % b;\n }\n\n bignum operator<<(int k) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int t = k >> 6;\n memcpy(c.a + t, a, (n + 1) << 3);\n int l = n + t;\n\n t = k & 63;\n if (t) {\n for (int i = l + 1; i; i--) {\n c.a[i] = (c.a[i] << t) | (c.a[i - 1] >> (64 - t));\n }\n c.a[0] <<= t;\n\n if (c.a[l + 1]) {\n l++;\n }\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator>>(int k) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int t = k >> 6;\n if (t > n) {\n return c;\n }\n\n memcpy(c.a, a + t, (n - t + 1) << 3);\n\n int l = n - t;\n t = k & 63;\n\n if (t) {\n for (int i = 0; i <= l; i++) {\n c.a[i] = (c.a[i] >> t) | (c.a[i + 1] << (64 - t));\n }\n }\n\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator&(const bignum &b) const {\n bignum c = *this;\n\n for (int i = 0; i <= b.n; i++) {\n c.a[i] &= b.a[i];\n }\n for (int i = b.n + 1; i <= c.n; i++) {\n c.a[i] = 0;\n }\n\n int l = c.n;\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator|(const bignum &b) const {\n bignum c = *this;\n\n for (int i = 0; i <= b.n; i++) {\n c.a[i] |= b.a[i];\n }\n c.n = max(c.n, b.n);\n\n return c;\n }\n\n bignum operator^(const bignum &b) const {\n bignum c = *this;\n\n for (int i = 0; i <= b.n; i++) {\n c.a[i] ^= b.a[i];\n }\n\n int l = max(c.n, b.n);\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator<<=(int k) {\n int t = k >> 6;\n\n if (t) {\n for (int i = n; i != -1; i--) {\n a[i + t] = a[i];\n }\n memset(a, 0, t << 3);\n }\n n += t;\n\n t = k & 63;\n\n if (t) {\n for (int i = n + 1; i; i--) {\n a[i] = (a[i] << t) | (a[i - 1] >> (64 - t));\n }\n a[0] <<= t;\n }\n\n if (a[n + 1]) {\n n++;\n }\n\n return *this;\n }\n\n bignum operator>>=(int k) {\n int t = k >> 6;\n\n if (t > n) {\n memset(a, 0, (n + 1) << 3);\n n = 0;\n return *this;\n }\n\n for (int i = t; i <= n; i++) {\n a[i - t] = a[i];\n }\n memset(a + n - t + 1, 0, t << 3);\n n -= t;\n\n t = k & 63;\n\n if (t) {\n for (int i = 0; i <= n; i++) {\n a[i] = (a[i] >> t) | (a[i + 1] << (64 - t));\n }\n }\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n\n bignum operator&=(const bignum &b) {\n for (int i = 0; i <= b.n; i++) {\n a[i] &= b.a[i];\n }\n for (int i = b.n + 1; i <= n; i++) {\n a[i] = 0;\n }\n\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n\n bignum operator|=(const bignum &b) {\n for (int i = 0; i <= b.n; i++) {\n a[i] |= b.a[i];\n }\n n = max(n, b.n);\n\n return *this;\n }\n\n bignum operator^=(const bignum &b) {\n n = max(n, b.n);\n for (int i = 0; i <= b.n; i++) {\n a[i] ^= b.a[i];\n }\n\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n};\n\nbool oa, ob;\n\nbignum read_bignum(bool &o) {\n static char str[100005];\n static u64 a[10005];\n static u64 bs = 1000000000000000000ll;\n\n cin >> str;\n int n = strlen(str);\n if (str[0] == '-') {\n o = 1;\n n--;\n for (int i = 0; i != n; i++) {\n str[i] = str[i + 1];\n }\n }\n reverse(str, str + n);\n\n for (int i = 0; i <= (n - 1) / 18; i++) {\n u64 v = 0;\n for (int j = min(n, (i + 1) * 18) - 1; j >= i * 18; j--) {\n v = v * 10 + str[j] - '0';\n }\n a[i] = v;\n }\n n = (n - 1) / 18;\n\n bignum c;\n memset(&c, 0, sizeof c);\n int m = 0;\n\n for (int i = n; i != -1; i--) {\n u128 ad = 0;\n for (int j = 0; j <= m; j++) {\n ad += (u128)c.a[j] * bs;\n c.a[j] = ad, ad >>= 64;\n }\n\n while (ad) {\n c.a[++m] = ad, ad >>= 64;\n }\n c.n = m;\n\n c += a[i], m = c.n;\n }\n\n return c;\n}\n\nvoid output(bignum a) {\n static u64 v[30005];\n const u64 bs = 1000000000000000000ll;\n\n int n = a.n, m = 0;\n\n for (int i = n; i != -1; i--) {\n u128 ad = 0;\n for (int j = 0; j <= m; j++) {\n ad += (u128)v[j] << 64;\n u128 gu = ad / bs;\n v[j] = ad - gu * bs, ad = gu;\n }\n\n while (ad) {\n u128 gu = ad / bs;\n v[++m] = ad - gu * bs, ad = gu;\n }\n\n ad = a.a[i];\n for (int j = 0; j <= m && ad; j++) {\n ad += v[j];\n u128 gu = ad / bs;\n v[j] = ad - gu * bs, ad = gu;\n }\n while (ad) {\n u128 gu = ad / bs;\n v[++m] = ad - gu * bs, ad = gu;\n }\n }\n\n cout << v[m];\n for (int i = m - 1; i != -1; i--) {\n cout << setw(18) << setfill('0') << v[i];\n }\n memset(v, 0, sizeof v);\n}\n\nbignum updiv(bignum &a, int m) {\n static bignum c;\n memset(&c, 0, sizeof c);\n\n if (m == 1) {\n return a;\n }\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n\n int l = a.n;\n int r = 0;\n\n for (int i = l; i != -1; i--) {\n u128 v = (u128)r * rr + a.a[i];\n u64 q = (v * b) >> 64;\n int gu = v - (u128)q * m;\n if (gu >= m) {\n gu -= m, q++;\n }\n\n c.a[i] = r * b + q, r = gu;\n }\n\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n if (r) {\n bool o = 1;\n for (int i = 0; i <= l; i++) {\n if (c.a[i] == (u64)-1) {\n c.a[i] = 0;\n } else {\n c.a[i]++;\n o = 0;\n break;\n }\n }\n\n if (o) {\n c.a[++l] = 1;\n }\n }\n\n c.n = l;\n\n return c;\n}\n\nbignum gcd(bignum a, bignum b) {\n if (a > b) {\n swap(a, b);\n }\n\n if (a.n == 0 && !a.a[0]) {\n return b;\n }\n\n int l = min(a.ctz(), b.ctz());\n a >>= a.ctz(), b >>= b.ctz();\n\n while (1) {\n if (a.n == 0 && !a.a[0]) {\n return b << l;\n }\n\n if (!(a.a[0] & 1)) {\n a >>= 1;\n } else if (!(b.a[0] & 1)) {\n b >>= 1;\n } else {\n if (a < b) {\n swap(a, b);\n }\n a -= b;\n }\n }\n}\n\nint main() {\n ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n\n bignum a = read_bignum(oa), b = read_bignum(ob);\n ob ^= 1;\n if (oa && ob) {\n cout << '-';\n oa = ob = 0;\n }\n\n if (oa == 0 && ob == 0) {\n output(a + b);\n cout << endl;\n return 0;\n }\n\n if (oa) {\n swap(a, b);\n }\n\n if (a >= b) {\n output(a - b);\n cout << endl;\n } else {\n cout << '-';\n output(b - a);\n cout << endl;\n }\n}", "accuracy": 1, "time_ms": 310, "memory_kb": 5028, "score_of_the_acc": -0.4517, "final_rank": 9 }, { "submission_id": "aoj_NTL_2_B_7593487", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nsigned main() {\n boost::multiprecision::cpp_int A, B;\n cin >> A >> B;\n cout << A - B << endl;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3468, "score_of_the_acc": -1.0005, "final_rank": 16 }, { "submission_id": "aoj_NTL_2_B_7525128", "code_snippet": "#include <bits/stdc++.h>\n#define forr(i,a,b) for(int i = (a); i <= (b); i++)\n#define forw(i,a,b) for(int i = (a); i >= (b); i--)\n#define pb push_back\n#define f first\n#define s second\n\nusing namespace std;\ntypedef pair <int,int> pii;\n\nconst int maxn = 1e5 + 5;\n\nstring t(string a,string b)\n{\n string c = \"\";\n int n1 = a.size();\n int n2 = b.size();\n if(n1 > n2) forr(i,1,n1 - n2) b = \"0\" + b;\n if(n1 < n2)\n {\n forr(i,1,n2 - n1) a = \"0\" + a;\n n1 = n2;\n }\n int nho = 0;\n forw(i,n1 - 1,0)\n {\n int res = a[i] - '0' + b[i] - '0' + nho;\n if(res > 9) nho = 1;\n else nho = 0;\n c = char(res%10 + 48) + c;\n }\n if(nho == 1) c = \"1\" + c;\n return c;\n}\n\nstring h(string a,string b)\n{\n string c = \"\";\n int n1 = a.size();\n int n2 = b.size();\n if(n2 < n1) forr(i,1,n1 - n2) b = \"0\" + b;\n int nho = 0;\n forw(i,n1 - 1,0)\n {\n int res = a[i] - '0' - (b[i] - '0') - nho;\n if(res < 0) nho = 1;\n else nho = 0;\n if(res < 0) c = char(res + 10 + 48) + c;\n else c = char(res + 48) + c;\n }\n while(c.size() > 1 && c[0] == '0') c.erase(0,1);\n return c;\n}\n\nstring a,b;\n\nint main()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n cin >> a >> b;\n if(a[0] != '-')\n {\n if(b[0] != '-')\n {\n if(a.size() > b.size() || (a.size() == b.size() && a >= b))\n {\n cout << h(a,b) << \"\\n\";\n return 0;\n }\n else\n {\n cout << \"-\" << h(b,a) << \"\\n\";\n return 0;\n }\n }\n else /// -> a + b;\n {\n b.erase(0,1);\n cout << t(a,b) << \"\\n\";\n return 0;\n }\n }\n else\n {\n if(b[0] != '-') /// - a - b = - (a + b);\n {\n a.erase(0,1);\n cout << \"-\" << t(a,b) << \"\\n\";\n return 0;\n }\n else /// - a + b -> b - a\n {\n a.erase(0,1);\n b.erase(0,1);\n if(a.size() < b.size() || (a.size() == b.size() && a <= b))\n {\n cout << h(b,a) << \"\\n\";\n return 0;\n }\n else\n {\n cout << \"-\" << h(a,b) << \"\\n\";\n return 0;\n }\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 3992, "score_of_the_acc": -0.3539, "final_rank": 6 }, { "submission_id": "aoj_NTL_2_B_7338656", "code_snippet": "#line 2 \"nachia\\\\math-modulo\\\\modulo-primitive-root.hpp\"\n#include <vector>\n#include <utility>\n\nnamespace nachia{\n\ntemplate<unsigned int MOD>\nstruct PrimitiveRoot{\n using u64 = unsigned long long;\n static constexpr u64 powm(u64 a, u64 i) {\n u64 res = 1, aa = a;\n while(i){\n if(i & 1) res = res * aa % MOD;\n aa = aa * aa % MOD;\n i /= 2;\n }\n return res;\n }\n static constexpr bool ExamineVal(unsigned int g){\n unsigned int t = MOD - 1;\n for(u64 d=2; d*d<=t; d++) if(t % d == 0){\n if(powm(g, (MOD - 1) / d) == 1) return false;\n while(t % d == 0) t /= d;\n }\n if(t != 1) if(powm(g, (MOD - 1) / t) == 1) return false;\n return true;\n }\n static constexpr unsigned int GetVal(){\n for(unsigned int x=2; x<MOD; x++) if(ExamineVal(x)) return x;\n return 0;\n }\n static const unsigned int val = GetVal();\n};\n\n} // namespace nachia\n#line 1 \"nachia\\\\fps\\\\ntt-interface.hpp\"\n#include <algorithm>\n\nnamespace nachia {\n\ntemplate<class mint>\nstruct NttInterface{\n\ntemplate<class Iter>\nvoid Butterfly(Iter, int) const {}\n\ntemplate<class Iter>\nvoid IButterfly(Iter, int) const {}\n\ntemplate<class Iter>\nvoid BitReversal(Iter a, int N) const {\n for(int i=0, j=0; j<N; j++){\n if(i < j) std::swap(a[i], a[j]);\n for(int k = N>>1; k > (i^=k); k>>=1);\n }\n}\n\n};\n\n} // namespace nachia\n#line 4 \"nachia\\\\misc\\\\bit-operations.hpp\"\n\nnamespace nachia{\n\nint Popcount(unsigned long long c) noexcept {\n#ifdef __GNUC__\n return __builtin_popcountll(c);\n#else\n c = (c & (~0ull/3)) + ((c >> 1) & (~0ull/3));\n c = (c & (~0ull/5)) + ((c >> 2) & (~0ull/5));\n c = (c & (~0ull/17)) + ((c >> 4) & (~0ull/17));\n c = (c * (~0ull/257)) >> 56;\n return c;\n#endif\n}\n\n// please ensure x != 0\nint MsbIndex(unsigned long long x) noexcept {\n#ifdef __GNUC__\n return 63 - __builtin_clzll(x);\n#else\n int res = 0;\n for(int d=32; d>0; d>>=1) if(x >> d){ res |= d; x >>= d; }\n return res;\n#endif\n}\n\n// please ensure x != 0\nint LsbIndex(unsigned long long x) noexcept {\n#ifdef __GNUC__\n return __builtin_ctzll(x);\n#else\n return MsbIndex(x & -x);\n#endif\n}\n\n}\n\n#line 5 \"nachia\\\\bigint\\\\ntt.hpp\"\n#include <iterator>\n#include <cassert>\n#line 8 \"nachia\\\\bigint\\\\ntt.hpp\"\n#include <array>\n\nnamespace nachia{\nnamespace bigint{\n\nconstexpr int bsf_constexpr(unsigned int n) {\n\tint x = 0;\n\twhile (!(n & (1 << x))) x++;\n\treturn x;\n}\n\ntemplate <class mint>\nstruct NttFromAcl : NttInterface<mint> {\n\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\n \nstatic int ceil_pow2(int n) {\n\tint x = 0;\n\twhile ((1U << x) < (u32)(n)) x++;\n\treturn x;\n}\n\nstruct fft_info {\n\tstatic constexpr u32 g = nachia::PrimitiveRoot<mint::GetMod()>::val;\n\tstatic constexpr int rank2 = bsf_constexpr(mint::GetMod()-1);\n\tstd::array<mint, rank2+1> root;\n\tstd::array<mint, rank2+1> iroot;\n\n\tstd::array<mint, std::max(0, rank2-1)> rate2;\n\tstd::array<mint, std::max(0, rank2-1)> irate2;\n\n\tstd::array<mint, std::max(0, rank2-2)> rate3;\n\tstd::array<mint, std::max(0, rank2-2)> irate3;\n\n\tfft_info(){\n\t\troot[rank2] = mint(g).pow((mint::GetMod() - 1) >> rank2);\n\t\tiroot[rank2] = root[rank2].inv();\n\t\tfor(int i=rank2-1; i>=0; i--){\n\t\t\troot[i] = root[i+1] * root[i+1];\n\t\t\tiroot[i] = iroot[i+1] * iroot[i+1];\n\t\t}\n\t\tmint prod = 1u, iprod = 1u;\n\t\tfor(int i=0; i<=rank2-2; i++){\n\t\t\trate2[i] = root[i+2] * prod;\n\t\t\tirate2[i] = iroot[i+2] * iprod;\n\t\t\tprod *= iroot[i+2];\n\t\t\tiprod *= root[i+2];\n\t\t}\n\t\tprod = 1u; iprod = 1u;\n\t\tfor(int i=0; i<=rank2-3; i++){\n\t\t\trate3[i] = root[i+3] * prod;\n\t\t\tirate3[i] = iroot[i+3] * iprod;\n\t\t\tprod *= iroot[i+3];\n\t\t\tiprod *= root[i+3];\n\t\t}\n\t}\n};\n\ntemplate<class RandomAccessIterator>\nvoid Butterfly(RandomAccessIterator a, int n) const {\n\tint h = ceil_pow2(n);\n\n\tstatic const fft_info info;\n\n\tint len = 0;\n\twhile(len < h){\n\t\tif(h-len == 1){\n\t\t\tint p = 1 << (h-len-1);\n\t\t\tmint rot = 1u;\n\t\t\tfor(int s=0; s<(1<<len); s++){\n\t\t\t\tint offset = s << (h-len);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto l = a[i+offset];\n\t\t\t\t\tauto r = a[i+offset+p] * rot;\n\t\t\t\t\ta[i+offset] = l+r;\n\t\t\t\t\ta[i+offset+p] = l-r;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<len)) rot *= info.rate2[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen++;\n\t\t} else {\n\t\t\tint p = 1 << (h-len-2);\n\t\t\tmint rot = 1u, imag = info.root[2];\n\t\t\tfor(int s=0; s<(1<<len); s++){\n\t\t\t\tmint rot2 = rot * rot;\n\t\t\t\tmint rot3 = rot2 * rot;\n\t\t\t\tint offset = s << (h-len);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto a0 = a[i+offset];\n\t\t\t\t\tauto a1 = a[i+offset+p] * rot;\n\t\t\t\t\tauto a2 = a[i+offset+2*p] * rot2;\n\t\t\t\t\tauto a3 = a[i+offset+3*p] * rot3;\n\t\t\t\t\tauto a0a2 = a0 + a2;\n\t\t\t\t\tauto a0b2 = a0 - a2;\n\t\t\t\t\tauto a1a3 = a1 + a3;\n\t\t\t\t\tauto a1na3imag = (a1 - a3) * imag;\n\t\t\t\t\ta[i+offset] = a0a2 + a1a3;\n\t\t\t\t\ta[i+offset+1*p] = a0a2 - a1a3;\n\t\t\t\t\ta[i+offset+2*p] = a0b2 + a1na3imag;\n\t\t\t\t\ta[i+offset+3*p] = a0b2 - a1na3imag;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<len)) rot *= info.rate3[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen += 2;\n\t\t}\n\t}\n}\n\ntemplate<class RandomAccessIterator>\nvoid IButterfly(RandomAccessIterator a, int n) const {\n\tint h = ceil_pow2(n);\n\n\tstatic const fft_info info;\n\n\tint len = h;\n\twhile(len){\n\t\tif(len == 1){\n\t\t\tint p = 1 << (h-len);\n\t\t\tmint irot = 1u;\n\t\t\tfor(int s=0; s<(1<<(len-1)); s++){\n\t\t\t\tint offset = s << (h-len+1);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto l = a[i+offset];\n\t\t\t\t\tauto r = a[i+offset+p];\n\t\t\t\t\ta[i+offset] = l+r;\n\t\t\t\t\ta[i+offset+p] = (l-r)*irot;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<(len-1))) irot *= info.irate2[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen--;\n\t\t} else {\n\t\t\tint p = 1 << (h-len);\n\t\t\tmint irot = 1u, iimag = info.iroot[2];\n\t\t\tfor(int s=0; s<(1<<(len-2)); s++){\n\t\t\t\tmint irot2 = irot * irot;\n\t\t\t\tmint irot3 = irot2 * irot;\n\t\t\t\tint offset = s << (h-len+2);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto a0 = a[i+offset+0*p];\n\t\t\t\t\tauto a1 = a[i+offset+1*p];\n\t\t\t\t\tauto a2 = a[i+offset+2*p];\n\t\t\t\t\tauto a3 = a[i+offset+3*p];\n\t\t\t\t\tauto a0a1 = a0 + a1;\n\t\t\t\t\tauto a0b1 = a0 - a1;\n\t\t\t\t\tauto a2a3 = a2 + a3;\n\t\t\t\t\tauto a2na3iimag = (a2 - a3) * iimag;\n\n\t\t\t\t\ta[i+offset] = a0a1 + a2a3;\n\t\t\t\t\ta[i+offset+1*p] = (a0b1 + a2na3iimag) * irot;\n\t\t\t\t\ta[i+offset+2*p] = (a0a1 - a2a3) * irot2;\n\t\t\t\t\ta[i+offset+3*p] = (a0b1 - a2na3iimag) * irot3;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<(len-2))) irot *= info.irate3[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen -= 2;\n\t\t}\n\t}\n}\n\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 3 \"nachia\\\\bigint\\\\static-p-modint.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\ntemplate<unsigned int MxVal>\nclass Montgomery32Info{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static constexpr u32 u32inverse(u32 x){\n u32 v = 1;\n for(int i=0; i<5; i++) v = v * ((u32)2 - v * x);\n return v;\n }\n static constexpr u32 getMy(u32 mx){ return (-mx) % mx; }\n static constexpr u32 powMod(u32 a, u32 i, u32 m){\n if(i == 0) return 1 % m;\n if(i % 2 == 0) return powMod((u64)a*a%m, i/2, m);\n return (u64)a*powMod((u64)a*a%m, i/2, m)%m;\n }\n static constexpr u32 Mx = MxVal;\n static constexpr u32 iMx = u32inverse(Mx);\n static constexpr u32 My1 = getMy(Mx);\n static constexpr u32 My2 = powMod(getMy(Mx), 2, Mx);\n static constexpr u32 My3 = powMod(getMy(Mx), 3, Mx);\n // return z\n // + z % Mx == x % Mx\n // + x <= max(x>>32, Mx-1)\n static constexpr u32 red(u64 x){\n u32 z1 = x >> 32;\n u32 z2 = ((u64)Mx * ((u32)x*iMx)) >> 32;\n return z1 - z2 + (z1 < z2 ? Mx : 0);\n }\n};\n\ntemplate<unsigned int MOD>\nclass StaticPModint{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\nprivate:\n static constexpr u32 mod = MOD;\n using Tool = Montgomery32Info<MOD>;\n using MyType = StaticPModint;\n u32 _v;\n static MyType RAW(u32 v) { auto res = StaticPModint(); res._v = v; return res; }\npublic:\n StaticPModint() : _v(0) {}\n StaticPModint(u32 v) : _v(Tool::red((u64)v * Tool::My2)) {}\n StaticPModint(u64 v) : _v(Tool::red((u64)Tool::My3 * Tool::red(v))) {}\n u32 val() const { return Tool::red(_v); }\n u32 mrVal() const { return _v; }\n MyType& operator-=(MyType r) { _v = _v - r._v + (_v < r._v ? mod : 0); return *this; }\n MyType& operator+=(MyType r) { u32 t = mod - r._v; _v = _v - t + (_v < t ? mod : 0); return *this; }\n MyType& operator*=(MyType r) { _v = Tool::red((u64)_v * r._v); return *this; }\n MyType operator+(MyType r) const { auto v = *this; v += r; return v; }\n MyType operator-(MyType r) const { auto v = *this; v -= r; return v; }\n MyType operator*(MyType r) const { auto v = *this; v *= r; return v; }\n MyType operator-() const { return RAW(_v ? mod - _v : (u32)0); }\n MyType pow(unsigned long long i) const {\n MyType x = *this, r = RAW(Tool::My1);\n while(i){ if(i&1){ r *= x; } x*=x; i>>=1; }\n return r;\n }\n MyType inv() const { return pow(mod-2); }\n static constexpr u32 GetMod() { return mod; }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 2 \"nachia\\\\bigint\\\\dynamic-p-modint.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nclass DynMontgomery32Info{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static u32 u32inverse(u32 x) {\n u32 v = 1;\n for(int i=0; i<5; i++) v = v * ((u32)2 - v * x);\n return v;\n }\n static u32 getMy(u32 mx) { return (-mx) % mx; }\n static u32 powMod(u32 a, u32 i, u32 m) {\n if(i == 0) return 1 % m;\n if(i % 2 == 0) return powMod((u64)a*a%m, i/2, m);\n return (u64)a*powMod((u64)a*a%m, i/2, m)%m;\n }\n const u32 Mx;\n const u32 iMx;\n const u32 My1;\n const u32 My2;\n const u32 My3;\n DynMontgomery32Info(u32 newMod)\n : Mx(newMod)\n , iMx(u32inverse(Mx))\n , My1(getMy(Mx))\n , My2((u64)My1 * My1 % Mx)\n , My3((u64)My2 * My1 % Mx) {}\n\n // return z\n // + z % Mx == x % Mx\n // + x <= max(x>>32, Mx-1)\n u32 red(u64 x) const {\n u32 z1 = x >> 32;\n u32 z2 = ((u64)Mx * ((u32)x*iMx)) >> 32;\n return z1 - z2 + (z1 < z2 ? Mx : 0);\n }\n u32 add(u32 a, u32 b) const { b = Mx-b; return a - b + ((a < b) ? Mx : 0u); }\n u32 sub(u32 a, u32 b) const { return a - b + ((a < b) ? Mx : 0u); }\n u32 mul(u32 a, u32 b) const { return red((u64)a * b); }\n u32 pow(u32 a, u32 i) const {\n u32 x = a, r = My1;\n while(i){ if(i&1){ r=mul(r,x); } x=mul(x,x); i>>=1; }\n return r;\n }\n u32 inv(u32 a) const { return pow(a, Mx-2); }\n u32 input64(u64 a) const { return mul(red(a), My3); }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\garner.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nstruct GarnerU96{\n using u32 = unsigned int;\n using u64 = unsigned long long;\n std::vector<u32> mods;\n std::vector<DynMontgomery32Info> dynmods;\n std::vector<std::vector<u32>> table_coeff;\n std::vector<u32> table_coeffinv;\n\n void precalc(std::vector<u32> new_mods){\n mods = std::move(new_mods);\n for(std::size_t i=0; i<mods.size(); i++) dynmods.emplace_back(mods[i]);\n int nmods = mods.size();\n table_coeff.assign(nmods+1, std::vector<u32>(nmods, 0));\n for(int k=0; k<nmods; k++) table_coeff[0][k] = dynmods[k].My2;\n for(int j=0; j<nmods; j++){\n for(int k=0; k<nmods; k++) table_coeff[j+1][k] = table_coeff[j][k];\n for(int k=j+1; k<nmods; k++) table_coeff[j+1][k] = dynmods[k].mul(table_coeff[j+1][k], dynmods[k].input64(mods[j]));\n }\n table_coeffinv.resize(nmods);\n for(int i=0; i<nmods; i++) table_coeffinv[i] = dynmods[i].inv(table_coeff[i][i]);\n }\n\n u64 calc(const std::vector<u32>& x){\n int nmods = mods.size();\n std::vector<u32> table_const(nmods);\n u64 res = 0;\n u64 res_coeff = 1;\n for(int j=0; j<nmods; j++){\n u32 t = dynmods[j].mul(dynmods[j].sub(x[j], table_const[j]), table_coeffinv[j]);\n for(int k=j+1; k<nmods; k++){\n table_const[k] = dynmods[k].add(dynmods[k].mul(t, table_coeff[j][k]), table_const[k]);\n }\n res += res_coeff * u64(t);\n res_coeff *= mods[j];\n }\n return res;\n }\n\n std::pair<std::vector<u32>, std::vector<u64>> calc(std::vector<std::vector<u32>> x){\n int n = x[0].size(), m = x.size();\n std::vector<u64> resl(n);\n std::vector<u32> resh(n);\n std::vector<u32> buf(m);\n u32 inv64 = dynmods[0].inv(dynmods[0].mul(dynmods[0].My3, dynmods[0].My2));\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++) buf[j] = x[j][i];\n resl[i] = calc(buf);\n resh[i] = dynmods[0].mul(dynmods[0].sub(buf[0], dynmods[0].input64(resl[i])), inv64);\n }\n return std::make_pair(std::move(resh), std::move(resl));\n }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\convolution.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nstruct MultiplySupply {\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static constexpr u32 MODCNT = 3;\n static constexpr u32 MOD[3] = { 3892314113, 3489660929, 3221225473 };\n \n GarnerU96 garner;\n\n MultiplySupply(){\n garner.precalc(std::vector<u32>(MOD, MOD + MODCNT));\n }\n \n template<unsigned int P>\n static std::vector<u32> SubConvolution(\n const std::vector<u32>& a,\n const std::vector<u32>& b\n ) {\n using Elem = StaticPModint<P>;\n static NttFromAcl<Elem> ntt;\n int z = a.size() + b.size() - 1;\n int N = 1; while(N < z) N *= 2;\n std::vector<Elem> A(N), B(N);\n for(std::size_t i=0; i<a.size(); i++) A[i] = a[i];\n for(std::size_t i=0; i<b.size(); i++) B[i] = b[i];\n Elem iN = Elem((u32)N).inv();\n ntt.Butterfly(A.begin(), N);\n ntt.Butterfly(B.begin(), N);\n for(int i=0; i<N; i++) A[i] = A[i] * B[i] * iN;\n ntt.IButterfly(A.begin(), N);\n std::vector<u32> res(z);\n for(int i=0; i<z; i++) res[i] = A[i].mrVal();\n return res;\n }\n \n std::vector<u32> multiplyBin(\n const std::vector<u32>& a,\n const std::vector<u32>& b\n ){\n if(a.empty() || b.empty()) return {};\n std::vector<std::vector<u32>> cx(MODCNT);\n cx[0] = SubConvolution<MOD[0]>(a, b);\n cx[1] = SubConvolution<MOD[1]>(a, b);\n cx[2] = SubConvolution<MOD[2]>(a, b);\n auto q = garner.calc(std::move(cx));\n int n = q.first.size();\n std::vector<u32> res(n + 2);\n for(int i=0; i<n; i++) res[i] = q.second[i];\n u64 c = 0;\n for(int i=0; i<n; i++){ res[i+1] = c += (u64)res[i+1] + (q.second[i] >> 32); c >>= 32; }\n res[n+1] = c; c = 0;\n for(int i=0; i<n; i++){ res[i+2] = c += (u64)res[i+2] + q.first[i]; c >>= 32; }\n while(res.size() && res.back() == 0) res.pop_back();\n return res;\n }\n \n std::vector<u32> multiplyDec(\n std::vector<u32> a,\n std::vector<u32> b\n ){\n static constexpr u32 d = 1000000000;\n if(a.empty() || b.empty()) return {};\n std::vector<std::vector<u32>> cx(MODCNT);\n cx[0] = SubConvolution<MOD[0]>(a, b);\n cx[1] = SubConvolution<MOD[1]>(a, b);\n cx[2] = SubConvolution<MOD[2]>(a, b);\n auto q0 = garner.calc(std::move(cx));\n int n = q0.first.size();\n std::vector<u64> buf(n + 2);\n static constexpr u32 j11 = (1ull << 32) / d;\n static constexpr u32 j10 = (-d) % d;\n static constexpr u32 j22 = 1 + (0ull- 1ull * d * d) / d / d;\n static constexpr u32 j21 = (-1ull * j22 * d * d) / d;\n static constexpr u32 j20 = (0ull-d) % d;\n for(int i=0; i<n; i++) buf[i] = q0.second[i] & ((1ull << 32) - 1);\n for(int i=0; i<n; i++) buf[i] += 1ull * (q0.second[i] >> 32) * j10;\n for(int i=0; i<n; i++) buf[i+1] += 1ull * (q0.second[i] >> 32) * j11;\n for(int i=0; i<n; i++) buf[i] += 1ull * q0.first[i] * j20; // q0.first[i] is small enough\n for(int i=0; i<n; i++) buf[i+1] += 1ull * q0.first[i] * j21;\n for(int i=0; i<n; i++) buf[i+2] += 1ull * q0.first[i] * j22;\n std::vector<u32> res(n + 2);\n u64 c = 0;\n for(int i=0; i<n+2; i++){ c += buf[i]; res[i] = c % d; c /= d; }\n while(res.size() && res.back() == 0) res.pop_back();\n return res;\n }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\base-operators.hpp\"\n#include <iostream>\n\nnamespace nachia {\nnamespace bigint {\n\nclass UIntDec {\npublic:\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nstd::vector<u32> x;\nstatic constexpr u32 BASE = 1'000'000'000;\n\nvoid Regularize(){ while(!x.empty() & !x.back()) x.pop_back(); }\n\nUIntDec() = default;\nUIntDec(std::vector<u32> _x) : x(std::move(_x)) {}\nUIntDec& operator+=(const UIntDec& b){\n x.resize(std::max(x.size(), b.x.size()) + 1);\n u64 c = 0;\n for(std::size_t i=0; i<b.x.size(); i++){\n c += b.x[i]; c += x[i];\n if(c >= BASE){ x[i] = c - BASE; c = 1; }\n else{ x[i] = c; c = 0; }\n }\n for(int i=b.x.size(); c; i++){\n c += x[i];\n if(c >= BASE){\n x[i] = c - BASE;\n c = 1;\n } else {\n x[i] = c;\n c = 0;\n break;\n }\n }\n Regularize();\n return *this;\n}\nUIntDec operator*(const UIntDec& b) const { return MultiplySupply().multiplyDec(x, b.x); }\n\nUIntDec Pow(u32 c) const {\n if(c == 0) return std::vector<u32>{1};\n if(c == 1) return *this;\n auto aa = Pow(c/2);\n aa = aa * aa;\n return (c&1) ? aa * (*this) : aa;\n}\nvoid mulU32(unsigned int cx) {\n u64 c = cx;\n for(std::size_t i=0; i<x.size(); i++){ c += (u64)x[i] << 32; x[i] = c % BASE; c /= BASE; }\n while(c){ x.push_back(c % BASE); c /= BASE; }\n}\n\n};\n\nclass UIntBin {\npublic:\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nstd::vector<u32> x;\n\nvoid Regularize(){ while(!x.empty() & !x.back()) x.pop_back(); }\n\nUIntBin() = default;\nUIntBin(std::vector<u32> _x) : x(std::move(_x)) {}\nUIntBin& operator+=(const UIntBin& b){\n x.resize(std::max(x.size(), b.x.size()) + 1);\n u64 c = 0;\n for(std::size_t i=0; i<b.x.size(); i++){\n c += b.x[i]; c += x[i];\n x[i] = c; c >>= 32;\n }\n for(int i=b.x.size(); c; i++){ x[i] = c += x[i]; c >>= 32; }\n Regularize();\n return *this;\n}\nUIntBin operator*(const UIntBin& b) const { return MultiplySupply().multiplyBin(x, b.x); }\n\nUIntBin Pow(u32 c) const {\n if(c == 0) return std::vector<u32>{1};\n if(c == 1) return *this;\n auto aa = Pow(c/2);\n aa = aa * aa;\n return (c&1) ? aa * (*this) : aa;\n}\nvoid mulD(unsigned int d, unsigned int cx) {\n u64 c = cx;\n for(std::size_t i=0; i<x.size(); i++){ x[i] = (c += (u64)x[i] * d); c >>= 32; }\n if(c) x.push_back(c);\n}\n\n};\n\nstd::vector<unsigned int> DecToBin(std::string decstr){\n std::vector<UIntBin> pdec;\n auto dfs = [&](auto& dfs, int l, int r) -> UIntBin {\n if(r - l <= 308){\n UIntBin p;\n for(int j=l; j<l+(r-l)%9; j++) p.mulD(10, decstr[j] - '0');\n for(int j=l+(r-l)%9; j<r; j+=9) p.mulD(1000000000, std::stoi(decstr.substr(j, 9)));\n return p;\n }\n if(pdec.empty()) pdec.push_back(UIntBin({10}).Pow(308));\n int h = 0; while(((308*2)<<h) < r-l) h++;\n while((int)pdec.size() < h+1) pdec.push_back(pdec.back() * pdec.back());\n auto res = dfs(dfs, l, r-(308<<h)) * pdec[h];\n res += dfs(dfs, r-(308<<h), r);\n return res;\n };\n return std::move(dfs(dfs, 0, decstr.size()).x);\n}\n\nstd::string BinToDec(std::vector<unsigned int> b){\n while(!b.empty() && !b.back()) b.pop_back();\n std::reverse(b.begin(), b.end());\n if(b.empty()) return \"0\";\n std::vector<UIntDec> pbin;\n auto dfs = [&](auto& dfs, int l, int r) -> UIntDec {\n if(r - l <= 29){\n UIntDec p;\n for(int j=l; j<r; j++) p.mulU32(b[j]);\n return p;\n }\n if(pbin.empty()) pbin.push_back(UIntDec({2}).Pow(32*29));\n int h = 0; while(((29*2)<<h) < r-l) h++;\n while((int)pbin.size() < h+1) pbin.push_back(pbin.back() * pbin.back());\n auto res = dfs(dfs, l, r-(29<<h)) * pbin[h];\n res += dfs(dfs, r-(29<<h), r);\n return res;\n };\n auto x = std::move(dfs(dfs, 0, b.size()).x);\n while(!x.empty() && !x.back()) x.pop_back();\n std::string res = std::to_string(x.back());\n res.resize(res.size() + 9 * (int)(x.size()-1), '0');\n for(int i=(int)x.size()-2; i>=0; i--){\n int o = res.size() - i*9 - 9;\n for(int j=o+8; j>=o; j--){ res[j] += x[i] % 10; x[i] /= 10; }\n }\n return res;\n}\n\n} // namespace bigint\n} // namespace nachia\n#line 4 \"nachia\\\\bigint\\\\integer.hpp\"\n\nnamespace nachia{\n\nclass UnsignedIntegerBin{\npublic:\n using MyType = UnsignedIntegerBin;\n friend class SignedIntegerBin;\nprivate:\n using u32 = uint32_t;\n using u64 = uint64_t;\n std::vector<u32> x;\n static inline bool Cflag;\n static MyType FromVec(std::vector<u32> _x){ MyType res; res.x = std::move(_x); return res; }\npublic:\n UnsignedIntegerBin(){}\n MyType operator>>(int sh) const {\n int h = sh / 32, l = sh % 32;\n MyType res; res.memreserve(size() - h);\n for(int i=h; i<size(); i++) res[i-h] = x[i] >> l;\n if(l) for(int i=h+1; i<size(); i++) res[i-h-1] |= x[i] << (32-l);\n res.regularize();\n return res;\n }\n MyType operator<<(int sh) const {\n int h = sh / 32, l = sh % 32;\n MyType res; res.memreserve(size() + h + 1);\n for(int i=0; i<size(); i++) res[i+h] = x[i] << l;\n if(l) for(int i=0; i<size(); i++) res[i+h+1] |= x[i] >> (32-l);\n res.regularize();\n return res;\n }\n MyType& operator>>=(int sh) { return (*this) = operator>>(sh); }\n MyType& operator<<=(int sh) { return (*this) = operator<<(sh); }\n MyType& operator%=(const MyType& d) { divInternal(d); return *this; }\n MyType operator%(const MyType& d) const { auto p = *this; return p.divInternal(d); }\n MyType operator/(const MyType& d) const { auto p = *this; return p.divInternal(d); }\n MyType& operator/=(const MyType& d) { return (*this) = divInternal(d); }\n MyType& operator+=(const MyType& v){\n memreserve(std::max(size(), v.size()) + 1);\n u64 c = 0;\n for(int i=0; i<v.size(); i++){ x[i] = (c += (u64)x[i] + v[i]); c >>= 32; }\n for(int i=v.size(); c; i++){ x[i] = c += x[i]; c >>= 32; }\n regularize();\n return *this;\n }\n MyType& operator-=(const MyType& v){\n memreserve(std::max(size(), v.size()));\n u64 c = 0;\n for(int i=0; i<v.size(); i++){\n c += v[i];\n x[i] -= c;\n c = (c + x[i]) >> 32;\n }\n for(int i=v.size(); i<size() && c; i++){\n x[i] -= c;\n c = (c + x[i]) >> 32;\n }\n Cflag = c;\n if(c){ complement(); increment(); }\n regularize();\n return *this;\n }\n MyType operator*(const MyType& v) const {\n MyType res;\n res.x = bigint::MultiplySupply().multiplyBin(x, v.x);\n res.regularize();\n return res;\n }\n MyType& operator*=(const MyType& r) { return (*this) = operator*(r); }\n MyType operator+(const MyType& r) { auto p = *this; p += r; return p; }\n MyType operator-(const MyType& r) { auto p = *this; p -= r; return p; }\n bool operator<(const MyType& r) const {\n return (size() != r.size())\n ? (size() < r.size())\n : std::lexicographical_compare(x.rbegin(), x.rend(), r.x.rbegin(), r.x.rend());\n }\n bool operator>(const MyType& r) const { return r < (*this); }\n bool operator<=(const MyType& r) const { return !(r < (*this)); }\n bool operator>=(const MyType& r) const { return !operator<(r); }\n bool operator==(const MyType& r) const { return x == r.x; }\n bool operator!=(const MyType& r) const { return x != r.x; }\n bool operator!() const { return size(); }\n bool isZero() const { return size() == 0; }\n std::string toStringBin() const {\n std::string res;\n for(int i=size()-1; i>=0; i--) for(int j=31; j>=0; j--) res.push_back('0' + (x[i]>>j) % 2);\n return res;\n }\n std::string toStringDec() const {\n if(isZero()) return \"0\";\n \n //auto p = *this;\n //std::string s;\n //while(!p.isZero()) s.push_back('0' + p.div10());\n //std::reverse(s.begin(), s.end());\n //return s;\n \n return bigint::BinToDec(x);\n }\n static MyType FromStringDec(const std::string& s) {\n return FromVec(bigint::DecToBin(s));\n }\n int lsb() const { for(int i=0; i<size(); i++){ if(x[i]) return nachia::LsbIndex(x[i]) + i * 32; } return -1; }\n int msb() const { for(int i=size()-1; i>=0; i--){ if(x[i]) return nachia::MsbIndex(x[i]) + i * 32; } return -1; }\nprivate:\n int size() const { return x.size(); }\n u32& operator[](int at) { return x[at]; }\n u32 operator[](int at) const { return x[at]; }\n void memreserve(int sz) { if((int)x.size() < sz) x.resize(sz); }\n void setBit(int at, bool val){ memreserve(at/32+1); x[at/32] |= (u32)(val?1:0) << (at%32); regularize(); }\n MyType divInternal(const MyType& d) {\n if(d.isZero()) throw 1;\n MyType res;\n for(int s=(size()-d.size())*32+31; s>=0; s--){\n MyType x = d << s;\n if(operator>=(x)){\n res.setBit(s, true); operator-=(x);\n }\n }\n res.regularize();\n return res;\n }\n void complement() { for(u32& y:x){ y = ~y; } }\n void increment() { if(isZero()){ x = {1}; return; } int i=0; while(i < size() && !~x[i]){ x[i++]++; } if(i>=size()){ x.push_back(1); } else x[i]++; }\n void decrement() { if(isZero()){ x = {1}; return; } int i=0; while(x[i]){ x[i++]--; } x[i]--; regularize(); }\n void regularize() { while(!x.empty() && 0 == x.back()) x.pop_back(); }\n int div10() {\n u64 c = 0;\n for(int i=size()-1; i>=0; i--){\n c = (c << 32) | x[i];\n x[i] = c / 10;\n c %= 10;\n }\n regularize();\n return c;\n }\n void mul10(int d) {\n u64 c = d;\n for(int i=0; i<size(); i++){ x[i] = (c += (u64)x[i] * 10); c >>= 32; }\n if(c) x.push_back(c);\n }\n};\n\nclass SignedIntegerBin{\n using MyType = SignedIntegerBin;\n using UInt = UnsignedIntegerBin;\nprivate:\n UInt u;\n int sign = 1;\n void regularize(){ u.regularize(); if(u.isZero()) sign = 1; }\n static MyType Raw(UInt u, int s){ MyType res; res.u = std::move(u); res.sign = s; res.regularize(); return res; }\npublic:\n bool isZero() const { return u.isZero(); }\n MyType& operator+=(const MyType& r) {\n if(sign == r.sign) u += r.u;\n else{ u -= r.u; if(u.Cflag){ sign = -sign; } }\n regularize();\n return *this;\n }\n MyType& operator-=(const MyType& r) {\n if(sign != r.sign) u += r.u;\n else{ u -= r.u; if(u.Cflag){ sign = -sign; } }\n regularize();\n return *this;\n }\n MyType operator*(const MyType& r) const { return Raw(u*r.u, sign*r.sign); }\n MyType& operator*=(const MyType& r) { return (*this) = operator*(r); }\n MyType operator+(const MyType& r) const { auto p = *this; p += r; return p; }\n MyType operator-(const MyType& r) const { auto p = *this; p -= r; return p; }\n MyType operator-() const { return Raw(u, -sign); }\n MyType& operator<<=(int sh) { u <<= sh; return *this; }\n MyType& operator>>=(int sh) { u >>= sh; return *this; }\n MyType operator<<(int sh) const { return Raw(u<<sh, sign); }\n MyType operator>>(int sh) const { return Raw(u<<sh, sign); }\n MyType operator/(const MyType& r) const { return Raw(u/r.u, sign*r.sign); }\n MyType& operator/=(const MyType& r) { return (*this) = operator/(r); }\n MyType operator%(const MyType& r) const { return Raw(u%r.u, sign*r.sign); }\n MyType& operator%=(const MyType& r) { return (*this) = operator%(r); }\n std::string toStringDec() const {\n if(isZero()) return \"0\";\n return (sign>0 ? \"\" : \"-\") + u.toStringDec();\n }\n static MyType FromStringDec(const std::string& s) {\n if(s.empty()) return MyType();\n if(s[0] == '+') return Raw(UInt::FromStringDec(s.substr(1)), 1);\n if(s[0] == '-') return Raw(UInt::FromStringDec(s.substr(1)), -1);\n return Raw(UInt::FromStringDec(s), 1);\n }\n};\n\n} // namespace nachia\n#line 2 \"Main.cpp\"\n#include <cstdint>\n#line 5 \"Main.cpp\"\n#include <string>\n#line 7 \"Main.cpp\"\n\n\nint main() {\n using Int = nachia::SignedIntegerBin;\n std::string s;\n std::cin >> s;\n Int a = Int::FromStringDec(s);\n std::cin >> s;\n Int b = Int::FromStringDec(s);\n Int c = a - b;\n std::cout << c.toStringDec() << '\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4260, "score_of_the_acc": -0.0813, "final_rank": 3 }, { "submission_id": "aoj_NTL_2_B_6975959", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<int> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = str[id++] - '0';\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<int> v( 8, 0 );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n int top = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n // sizeの再計算\n void resize(){\n\n size = 0;\n for( int i = dat.size()-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- ){\n if( dat[i][j] != 0 ){\n size = i;\n return;\n }\n }\n }\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n int up = 0; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.minus = l.minus;\n }\n res.resize();\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l.minus & r.minus ){\n if( l < r ){\n l.minus = false;\n r.minus = false;\n res = l - r;\n res.minus = true;\n }\n else{\n l.minus = false;\n r.minus = false;\n res = r - l;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n int maxSize = max( l.size, r.size );\n int down = 0; // 繰り下がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n }\n }\n }\n res.resize();\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt diff = a - b;\n diff.print();\n\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 74116, "score_of_the_acc": -0.8161, "final_rank": 11 }, { "submission_id": "aoj_NTL_2_B_6975947", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<int> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = str[id++] - '0';\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<int> v( 8, 0 );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n int top = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n // sizeの再計算\n void resize(){\n\n size = 0;\n for( int i = dat.size()-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- ){\n if( dat[i][j] != 0 ){\n size = i;\n return;\n }\n }\n }\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n int up = 0; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.minus = l.minus;\n }\n res.resize();\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n int maxSize = max( l.size, r.size );\n int down = 0; // 繰り下がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n }\n }\n res.resize();\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt diff = a - b;\n diff.print();\n\n}", "accuracy": 0.44, "time_ms": 60, "memory_kb": 74040, "score_of_the_acc": -0.8153, "final_rank": 19 }, { "submission_id": "aoj_NTL_2_B_6975935", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<int> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = str[id++] - '0';\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<int> v( 8, 0 );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n int top = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n int up = 0; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.size = ( up != 0 ? maxSize+1 : maxSize );\n res.minus = l.minus;\n }\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n res.size = max( l.size, r.size );\n int down = 0; // 繰り下がり\n for( int i = 0 ; i <= res.size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n if( res.dat[res.size][0] == 0 && res.dat[res.size][1] == 0 && res.dat[res.size][2] == 0 && res.dat[res.size][3] == 0 )\n res.size = max( res.size-1, 0 );\n }\n }\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt diff = a - b;\n diff.print();\n\n}", "accuracy": 0.44, "time_ms": 60, "memory_kb": 74336, "score_of_the_acc": -0.8184, "final_rank": 20 }, { "submission_id": "aoj_NTL_2_B_6917609", "code_snippet": "// multiprecision\n#include <vector>\n#include <string>\n#include <iostream>\n// fft\n#include <complex>\n#include <cmath>\nnamespace fourier {\n using complex = std::complex<double>;\n constexpr double pi = 3.14159265358979323L;\n\n std::vector<complex> fft(const std::vector<complex>& c, bool inverse = false) {\n std::size_t N = c.size(); // N = 2^m\n double N_inv = 1.0 / static_cast<double>(N); // Inverse of N\n std::vector<complex> f(N); // FFT result\n int inv = inverse ? -1 : 1; // Inverse flag\n if(N <= 1) return c;\n\n // Decompose by even-odd\n std::vector<complex> even(N / 2), odd(N / 2);\n for(int i = 0; i < N / 2; ++i) {\n even.at(i) = c.at(2 * i);\n odd.at(i) = c.at((2 * i) + 1);\n }\n even = fft(even, inverse);\n odd = fft(odd, inverse);\n\n // Calculate C_k(e) + C_k(o) * xi^j\n double theta = (2.0 * pi * N_inv * inv);\n const auto xi = [&](int j) {\n return complex(std::cos(theta * j), std::sin(theta * j));\n };\n for(int j = 0; j < N; ++j) {\n int k = j % (N / 2);\n f.at(j) = even.at(k) + (odd.at(k) * xi(j));\n }\n return f;\n }\n std::vector<complex> convolution(const std::vector<complex>& f, const std::vector<complex>& g) {\n std::size_t N = 1;\n while(N < (f.size() + g.size() - 1)) N *= 2;\n\n std::vector<complex> F(N), G(N);\n for(int i = 0; i < f.size(); ++i) {\n F.at(i) = f.at(i);\n G.at(i) = g.at(i);\n }\n F = fft(F);\n G = fft(G);\n\n std::vector<complex> conv(N);\n for(int i = 0; i < N; ++i)\n conv.at(i) = F.at(i) * G.at(i);\n \n conv = fft(conv, -1);\n for(int i = 0; i < N; ++i)\n conv.at(i) *= complex(1.0 / static_cast<double>(conv.size()));\n return conv;\n }\n}\nnamespace multiprecision {\n using i32 = std::int32_t;\n using i64 = std::int64_t;\n using Bigint = std::vector<i32>;\n class Int {\n private:\n Bigint integer; // 120 -> 0, 2, 1\n bool is_negative; // -1 -> true\n\n public:\n Int() : integer({0}), is_negative(false){} // default\n Int(const Int& i) : integer(i.integer), is_negative(i.is_negative){} // copy\n Int(const std::string& s){ (*this) = string_to_integer(s); } // string to bigint\n Int(const char*& s){ (*this) = string_to_integer(s); } // char* to bigint\n Int(const i64& i){ (*this) = string_to_integer(std::to_string(i)); } // int to bigint\n \n private:\n // string から integer 配列を生成する.\n Int string_to_integer(const std::string& s) {\n Bigint t;\n Int temp;\n if(s.front() == '-') temp.is_negative = true;\n\n for(int i = s.size() - 1; temp.is_negative ? (i > 0) : (i >= 0); --i) {\n t.push_back(static_cast<i32>(s.at(i) - '0'));\n }\n temp.integer = t;\n return temp;\n };\n // 繰り上がり, 繰り下がり処理を行う.\n Int carry() {\n // [19, 2, -2, 15] -> [9, 3, 8, 14]\n for(int i = 0; i < this->integer.size() - 1; ++i) {\n if(this->integer.at(i) >= 10) {\n int k = this->integer.at(i) / 10;\n this->integer.at(i) -= k * 10;\n this->integer.at(i + 1) += k;\n }\n if(this->integer.at(i) < 0) {\n int k = (-this->integer.at(i) - 1) / 10 + 1;\n this->integer.at(i) += k * 10;\n this->integer.at(i + 1) -= k;\n }\n }\n // [9, 3, 8, 14] -> [9, 3, 8, 4, 1]\n while(this->integer.back() >= 10) {\n int k = this->integer.back() / 10;\n this->integer.back() -= k * 10;\n this->integer.push_back(k);\n }\n // [1, 2, 3, 0, 0, 0, 0] -> [1, 2, 3]\n while(this->integer.size() > 1 && this->integer.back() == 0) {\n this->integer.pop_back();\n }\n // [-0] -> [0]\n if(this->integer.size() == 1 && this->integer.front() == 0) {\n this->is_negative = false;\n }\n return (*this);\n }\n // true なら -1, false なら +1 を返す\n i32 sign(const bool& is_negative) { return is_negative ? -1 : +1; }\n public:\n bool positive() const { return !this->is_negative; }\n bool negative() const { return this->is_negative; }\n std::size_t size() const { return this->integer.size(); }\n i32 at(const std::size_t& i) const { return this->integer.at(i); }\n\n Int abs() const { Int tmp = (*this); tmp.is_negative = false; return tmp; }\n Int operator= (const Int& r) { this->integer = r.integer; this->is_negative = r.is_negative; return (*this); }\n Int operator+=(const Int& r) {\n bool operator< (const Int&, const Int&);\n Bigint result(std::max(this->integer.size(), r.integer.size()));\n // 異符号\n if(this->is_negative != r.is_negative){\n // 右辺が大きいなら 右辺 - 左辺\n if((*this).abs() < r.abs()) {\n this->is_negative = !this->is_negative;\n for(int i = 0; i < result.size(); ++i) {\n result.at(i)\n = (i < r.integer.size() ? r.integer.at(i) : 0) - (i < this->integer.size() ? this->integer.at(i) : 0);\n }\n }\n // 左辺が大きいなら 左辺 - 右辺\n else {\n for(int i = 0; i < result.size(); ++i) {\n result.at(i)\n = (i < this->integer.size() ? this->integer.at(i) : 0) - (i < r.integer.size() ? r.integer.at(i) : 0);\n }\n }\n }\n // 同符号 -> そのまま加算\n else {\n for(int i = 0; i < result.size(); ++i) {\n result.at(i)\n = (i < this->integer.size() ? this->integer.at(i) : 0) + (i < r.integer.size() ? r.integer.at(i) : 0);\n }\n }\n this->integer = result;\n return (*this).carry();\n }\n Int operator-=(const Int& r) {\n Int operator-(const Int&);\n (*this) += -r;\n // 繰り上がり処理済み\n return (*this);\n }\n Int operator*=(const Int& r) {\n std::vector<std::complex<double>> lhs(this->integer.size()), rhs(r.integer.size()), conv;\n for(int i = 0; i < std::max(lhs.size(), rhs.size()); ++i) {\n if(i < lhs.size()) lhs.at(i) = this->integer.at(i);\n if(i < rhs.size()) rhs.at(i) = r.integer.at(i);\n }\n while(lhs.size() < rhs.size()) lhs.push_back(0);\n while(lhs.size() > rhs.size()) rhs.push_back(0);\n conv = fourier::convolution(lhs, rhs);\n Bigint result(conv.size());\n for(int i = 0; i < result.size(); ++i)\n result.at(i) = std::round(conv.at(i).real());\n this->integer = result, this->is_negative ^= r.is_negative;\n return (*this).carry();\n }\n \n private:\n friend std::ostream& operator<<(std::ostream&, const Int&);\n friend std::istream& operator>>(std::istream&, Int&);\n };\n Int operator+(const Int& r) { return r; }\n Int operator-(const Int& r) { Int l(-1); l *= r; return l; }\n Int operator+(const Int& lhs, const Int& rhs) { Int tmp = lhs; return tmp += rhs; }\n Int operator-(const Int& lhs, const Int& rhs) { Int tmp = lhs; return tmp -= rhs; }\n Int operator*(const Int& lhs, const Int& rhs) { Int tmp = lhs; return tmp *= rhs; }\n \n bool operator==(const Int& lhs, const Int& rhs) {\n if(lhs.size() != rhs.size()) return false;\n for(int i = 0; i < lhs.size(); ++i) {\n if(lhs.at(i) != rhs.at(i)) return false;\n }\n return true;\n }\n bool operator!=(const Int& lhs, const Int& rhs) { return !(lhs == rhs); }\n bool operator> (const Int& lhs, const Int& rhs) {\n if(lhs.positive() != rhs.positive())\n return lhs.positive();\n if(lhs.size() != rhs.size())\n return lhs.positive() ? (lhs.size() > rhs.size()) : (lhs.size() < rhs.size());\n for(int i = lhs.size() - 1; i >= 0; --i) {\n if(lhs.at(i) != rhs.at(i))\n return lhs.positive() ? (lhs.at(i) > rhs.at(i)) : (lhs.at(i) < rhs.at(i));\n }\n return false;\n }\n bool operator>=(const Int& lhs, const Int& rhs) {\n return (lhs > rhs) || (lhs == rhs);\n }\n bool operator< (const Int& lhs, const Int& rhs) {\n return !(lhs >= rhs);\n }\n bool operator<=(const Int& lhs, const Int& rhs) {\n return !(lhs > rhs);\n }\n std::ostream& operator<<(std::ostream& out, const Int& v) {\n if(v.is_negative) out << \"-\";\n for(int i = v.integer.size() - 1; i >= 0; --i)\n out << v.integer.at(i);\n return out;\n }\n std::istream& operator>>(std::istream& cin, Int& v) {\n std::string s; cin >> s;\n v = Int(s);\n return cin;\n }\n}\n\nint main() {\n multiprecision::Int a, b;\n std::cin >> a >> b;\n std::cout << a - b << std::endl;\n return 0;\n}", "accuracy": 1, "time_ms": 390, "memory_kb": 36412, "score_of_the_acc": -0.8978, "final_rank": 12 }, { "submission_id": "aoj_NTL_2_B_6691787", "code_snippet": "#include<bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(n);i++)\ntypedef long long ll;\nusing namespace boost::multiprecision;\n\nint main() {\n cpp_int a,b;cin>>a>>b;\n cpp_int ans=a-b;\n cout<<ans<<endl;\n return 0;\n\n\n\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3456, "score_of_the_acc": -1.0004, "final_rank": 14 }, { "submission_id": "aoj_NTL_2_B_6677814", "code_snippet": "#include<bits/stdc++.h>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\nconst int mod=1e9+7;\n\nint32_t main()\n{\n boost::multiprecision::cpp_int a, b;\n cin >> a >> b;\n \n cout << a-b << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3456, "score_of_the_acc": -1.0004, "final_rank": 14 }, { "submission_id": "aoj_NTL_2_B_6499536", "code_snippet": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool f(const string& a) {return a == \"\" || a == \"-\";}\n\nstring add(string& a, string& b, int c)\n{\n\tif (!f(a)) {\n\t\tc += a.back() - '0';\n\t\ta.pop_back();\n\t}\n\tif (!f(b)) {\n\t\tc += b.back() - '0';\n\t\tb.pop_back();\n\t}\n\tif (f(a) && f(b)) {\n\t\tif (c < 0 || a == b) return \"x\";\n\t\tif (c < 10) {\n\t\t\tif (c > 0) a.push_back(c % 10 + '0');\n\t\t\treturn a;\n\t\t}\n\t}\n\tauto t = add(a, b, c / 10);\n\tt.push_back(c % 10 + '0');\n\treturn t;\n}\n\nstring sub(string& a, string& b, int c, bool rev)\n{\n\tif (!f(a)) {\n\t\tc += a.back() - '0';\n\t\ta.pop_back();\n\t}\n\tif (!f(b)) {\n\t\tc -= b.back() - '0';\n\t\tb.pop_back();\n\t}\n\tif (f(a) && f(b)) {\n\t\tif (c < 0 || a != b) return \"x\";\n\t\tif (rev) {if (a == \"\") a = \"-\"; else a = \"\";}\n\t\tif (c < 10) {\n\t\t\tif (c > 0) a.push_back(c % 10 + '0');\n\t\t\treturn a;\n\t\t}\n\t}\n\tauto t = sub(a, b, (c - (c + 100) % 10) / 10, rev);\n\tt.push_back((c + 100) % 10 + '0');\n\treturn t;\n}\n\nstring add(string a, string b) {return add(a, b, 0);}\nstring sub(string a, string b, bool rev) {return sub(a, b, 0, rev);}\n\nint main()\n{\n\tstring a, b, c; cin >> a >> b;\n\tc = add(a, b);\n\tif (c[0] == 'x') c = sub(a, b, false);\n\tif (c[0] == 'x') c = sub(b, a, true);\n\tif (f(c) || c == \"-0\") c = \"0\";\n\tcout << c << endl;\n\treturn 0;\n}", "accuracy": 0.9, "time_ms": 10, "memory_kb": 13172, "score_of_the_acc": -0.1026, "final_rank": 18 }, { "submission_id": "aoj_NTL_2_B_6386415", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for (int i = 0; i < (int)(n); i++)\n#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)\n#define all(v) v.begin(), v.end()\n#define sz(v) int(v.size())\n#define INF 1e18+999999\n#define EPSILON 1e-14\ntemplate <typename T>\nbool chmax(T &a, const T& b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool chmin(T &a, const T& b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n\nstring BigSum(string A, string B){\n vector<int> a(sz(A));\n vector<int> b(sz(B));\n rep(i, sz(A)){\n a.at(i) = A.at(sz(A)-1-i) - '0';\n }\n rep(i, sz(B)){\n b.at(i) = B.at(sz(B)-1-i) - '0';\n }\n vector<int> ans(sz(A)+sz(B)+1, 0);\n rep(i, max(sz(A), sz(B))){\n ans.at(i) = (i < sz(A) ? a.at(i) : 0) + (i < sz(B) ? b.at(i) : 0);\n }\n rep(i, sz(ans)-1){\n ans.at(i+1) += ans.at(i) / 10;\n ans.at(i) %= 10;\n }\n string Ans;\n rep(i, sz(ans)){\n Ans += ans.at(i) + '0';\n }\n reverse(all(Ans));\n while(sz(Ans) > 1){\n if(Ans.at(0) == '0'){\n Ans.erase(0, 1);\n }\n else{\n break;\n }\n }\n return Ans;\n}\n\nstring BigSub(string A, string B){\n if(sz(A) < sz(B)){\n return '-' + BigSub(B, A);\n }\n vector<int> a(sz(A));\n vector<int> b(sz(B));\n rep(i, sz(A)){\n a.at(i) = A.at(sz(A)-1-i) - '0';\n }\n rep(i, sz(B)){\n b.at(i) = B.at(sz(B)-1-i) - '0';\n }\n if(sz(A) == sz(B)){\n rep(i, sz(A)){\n if(a.at(sz(a)-1-i) > b.at(sz(a)-1-i)){\n break;\n }\n if(a.at(sz(a)-1-i) < b.at(sz(a)-1-i)){\n return '-' + BigSub(B, A);\n }\n }\n }\n vector<int> ans(sz(A)+sz(B)+1, 0);\n rep(i, max(sz(A), sz(B))){\n ans.at(i) = (i < sz(A) ? a.at(i) : 0) - (i < sz(B) ? b.at(i) : 0);\n }\n rep(i, sz(ans)-1){\n if(ans.at(i) < 0){\n int c = (-ans.at(i) + 9) / 10;\n ans.at(i+1) -= c;\n ans.at(i) += 10 * c;\n }\n }\n string Ans;\n rep(i, sz(ans)){\n Ans += ans.at(i) + '0';\n }\n reverse(all(Ans));\n while(sz(Ans) > 1){\n if(Ans.at(0) == '0'){\n Ans.erase(0, 1);\n }\n else{\n break;\n }\n }\n return Ans;\n}\n\nint main()\n{\n string A, B;\n cin >> A >> B;\n if(A.at(0) == '-'){\n A.erase(0, 1);\n if(B.at(0) == '-'){\n B.erase(0, 1);\n cout << BigSub(B, A) << '\\n';\n }\n else{\n cout << '-' << BigSum(A, B) << '\\n';\n }\n }\n else{\n if(B.at(0) == '-'){\n B.erase(0, 1);\n cout << BigSum(A, B) << '\\n';\n }\n else{\n cout << BigSub(A, B) << '\\n';\n }\n }\n}", "accuracy": 1, "time_ms": 510, "memory_kb": 6144, "score_of_the_acc": -0.7533, "final_rank": 10 }, { "submission_id": "aoj_NTL_2_B_6347785", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nstruct BigIntTiny {\n int sign;\n std::vector<int> v;\n\n BigIntTiny() : sign(1) {}\n BigIntTiny(const std::string& s) { *this = s; }\n BigIntTiny(int v) {\n char buf[21];\n sprintf(buf, \"%d\", v);\n *this = buf;\n }\n void zip(int unzip) {\n if (unzip == 0) {\n for (int i = 0; i < (int)v.size(); i++)\n v[i] = get_pos(i * 4) + get_pos(i * 4 + 1) * 10 + get_pos(i * 4 + 2) * 100 + get_pos(i * 4 + 3) * 1000;\n }\n else\n for (int i = (v.resize(v.size() * 4), (int)v.size() - 1), a; i >= 0; i--)\n a = (i % 4 >= 2) ? v[i / 4] / 100 : v[i / 4] % 100, v[i] = (i & 1) ? a / 10 : a % 10;\n setsign(1, 1);\n }\n int get_pos(unsigned pos) const { return pos >= v.size() ? 0 : v[pos]; }\n BigIntTiny& setsign(int newsign, int rev) {\n for (int i = (int)v.size() - 1; i > 0 && v[i] == 0; i--)\n v.erase(v.begin() + i);\n sign = (v.size() == 0 || (v.size() == 1 && v[0] == 0)) ? 1 : (rev ? newsign * sign : newsign);\n return *this;\n }\n std::string to_str() const {\n BigIntTiny b = *this;\n std::string s;\n for (int i = (b.zip(1), 0); i < (int)b.v.size(); ++i)\n s += char(*(b.v.rbegin() + i) + '0');\n return (sign < 0 ? \"-\" : \"\") + (s.empty() ? std::string(\"0\") : s);\n }\n bool absless(const BigIntTiny& b) const {\n if (v.size() != b.v.size()) return v.size() < b.v.size();\n for (int i = (int)v.size() - 1; i >= 0; i--)\n if (v[i] != b.v[i]) return v[i] < b.v[i];\n return false;\n }\n BigIntTiny operator-() const {\n BigIntTiny c = *this;\n c.sign = (v.size() > 1 || v[0]) ? -c.sign : 1;\n return c;\n }\n BigIntTiny& operator=(const std::string& s) {\n if (s[0] == '-')\n *this = s.substr(1);\n else {\n for (int i = (v.clear(), 0); i < (int)s.size(); ++i)\n v.push_back(*(s.rbegin() + i) - '0');\n zip(0);\n }\n return setsign(s[0] == '-' ? -1 : 1, sign = 1);\n }\n bool operator<(const BigIntTiny& b) const {\n return sign != b.sign ? sign < b.sign : (sign == 1 ? absless(b) : b.absless(*this));\n }\n bool operator==(const BigIntTiny& b) const { return v == b.v && sign == b.sign; }\n BigIntTiny& operator+=(const BigIntTiny& b) {\n if (sign != b.sign) return *this = (*this) - -b;\n v.resize(std::max(v.size(), b.v.size()) + 1);\n for (int i = 0, carry = 0; i < (int)b.v.size() || carry; i++) {\n carry += v[i] + b.get_pos(i);\n v[i] = carry % 10000, carry /= 10000;\n }\n return setsign(sign, 0);\n }\n BigIntTiny operator+(const BigIntTiny& b) const {\n BigIntTiny c = *this;\n return c += b;\n }\n void add_mul(const BigIntTiny& b, int mul) {\n v.resize(std::max(v.size(), b.v.size()) + 2);\n for (int i = 0, carry = 0; i < (int)b.v.size() || carry; i++) {\n carry += v[i] + b.get_pos(i) * mul;\n v[i] = carry % 10000, carry /= 10000;\n }\n }\n BigIntTiny operator-(const BigIntTiny& b) const {\n if (sign != b.sign) return (*this) + -b;\n if (absless(b)) return -(b - *this);\n BigIntTiny c;\n for (int i = 0, borrow = 0; i < (int)v.size(); i++) {\n borrow += v[i] - b.get_pos(i);\n c.v.push_back(borrow);\n c.v.back() -= 10000 * (borrow >>= 31);\n }\n return c.setsign(sign, 0);\n }\n BigIntTiny operator*(const BigIntTiny& b) const {\n if (b < *this) return b * *this;\n BigIntTiny c, d = b;\n for (int i = 0; i < (int)v.size(); i++, d.v.insert(d.v.begin(), 0))\n c.add_mul(d, v[i]);\n return c.setsign(sign * b.sign, 0);\n }\n BigIntTiny operator/(const BigIntTiny& b) const {\n BigIntTiny c, d;\n d.v.resize(v.size());\n double db = 1.0 / (b.v.back() + (b.get_pos((unsigned)b.v.size() - 2) / 1e4) +\n (b.get_pos((unsigned)b.v.size() - 3) + 1) / 1e8);\n for (int i = (int)v.size() - 1; i >= 0; i--) {\n c.v.insert(c.v.begin(), v[i]);\n int m = (int)((c.get_pos((int)b.v.size()) * 10000 + c.get_pos((int)b.v.size() - 1)) * db);\n c = c - b * m, d.v[i] += m;\n while (!(c < b))\n c = c - b, d.v[i] += 1;\n }\n return d.setsign(sign * b.sign, 0);\n }\n BigIntTiny operator%(const BigIntTiny& b) const { return *this - *this / b * b; }\n bool operator>(const BigIntTiny& b) const { return b < *this; }\n bool operator<=(const BigIntTiny& b) const { return !(b < *this); }\n bool operator>=(const BigIntTiny& b) const { return !(*this < b); }\n bool operator!=(const BigIntTiny& b) const { return !(*this == b); }\n};\n//FFT部分 \nconst double PI = acos(-1);\ntypedef complex<double> Complex;\nconst int maxn = 3e6 + 10;\n\nComplex a[maxn], b[maxn];\nint m, n;\nint bit = 2, rev[maxn];\nint ans[maxn];\n\nvoid get_rev() {\n memset(rev, 0, sizeof(rev));\n while (bit <= n + m) bit <<= 1;\n for (int i = 0; i < bit; ++i) {\n rev[i] = (rev[i >> 1] >> 1) | (bit >> 1) * (i & 1);\n }\n}\n\nvoid FFT(Complex* a, int op) {\n for (int i = 0; i < bit; ++i) {\n if (i < rev[i]) swap(a[i], a[rev[i]]);\n }\n for (int mid = 1; mid < bit; mid <<= 1) {\n Complex wn = Complex(cos(PI / mid), op * sin(PI / mid));\n for (int j = 0; j < bit; j += mid << 1) {\n Complex w(1, 0);\n for (int k = 0; k < mid; ++k, w = w * wn) {\n Complex x = a[j + k], y = w * a[j + k + mid];\n a[j + k] = x + y, a[j + k + mid] = x - y;\n }\n }\n }\n}\n\nstring fftmul(string s1, string s2) {\n //cout<<s1<<endl<<s2<<endl;\n n = s1.size(), m = s2.size();\n memset(a, 0, sizeof(a));\n memset(b, 0, sizeof(b));\n for (int i = 0; i < n; ++i) {\n a[i] = s1[n - i - 1] - '0';\n }\n for (int i = 0; i < m; ++i) {\n b[i] = s2[m - i - 1] - '0';\n }\n get_rev();\n FFT(a, 1);\n FFT(b, 1);\n for (int i = 0; i <= bit; ++i) {\n a[i] *= b[i];\n }\n FFT(a, -1);\n for (int i = 0; i < n + m; ++i) {\n ans[i] = (int)(a[i].real() / bit + 0.5);\n }\n for (int i = 1; i < n + m; ++i) {\n ans[i] = ans[i] + ans[i - 1] / 10;\n ans[i - 1] = ans[i - 1] % 10;\n }\n int s = n + m - 1;\n for (; s >= 0; --s) {\n if (ans[s]) break;\n }\n string ret;\n if (s < 0) ret.push_back('0');//printf(\"0\\n\");\n else {\n for (int i = s; i >= 0; --i) {\n ret.push_back(ans[i] + '0');//printf(\"%d\", ans[i]);\n }\n //printf(\"\\n\");\n }\n return ret;\n}\n\nBigIntTiny fastmul(BigIntTiny b1, BigIntTiny b2) {\n //cout<<b1.to_str()<<'\\n'<<b2.to_str()<<endl;\n //cout<<fftmul(b1.to_str(),b2.to_str())<<endl;\n bool flag = 0;//要不要变负,1负\n if (b1 < 0)b1 = -b1, flag ^= 1;\n if (b2 < 0)b2 = -b2, flag ^= 1;\n BigIntTiny ans = fftmul(b1.to_str(), b2.to_str());\n return flag ? -ans : ans;\n}\nconst int p = 998244353;\nBigIntTiny qpow(BigIntTiny a, BigIntTiny n, BigIntTiny p) {\n BigIntTiny res = 1;\n while (n>0) {\n if (n % 2 == 1) res = res * a % p;\n a = a * a % p;\n n = n / 2;\n }\n return res;\n}\nBigIntTiny qpow1(BigIntTiny a, BigIntTiny n) {\n BigIntTiny res = 1;\n while (n > 0) {\n if (n % 2 == 1) res = res * a;\n a = a * a;\n n = n / 2;\n }\n return res;\n}\nBigIntTiny v[51], sum[51];\nint main(){\n string a, b;\n cin>>a>>b;\n cout<<(BigIntTiny(a)-BigIntTiny(b)).to_str()<<'\\n';\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 98488, "score_of_the_acc": -1.0145, "final_rank": 17 } ]
aoj_NTL_2_A_cpp
Addition of Big Integers Given two integers $A$ and $B$, compute the sum, $A + B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the sum in a line. Constraints $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample Output 1 13 Sample Input 2 100 25 Sample Output 2 125 Sample Input 3 -1 1 Sample Output 3 0 Sample Input 4 12 -3 Sample Output 4 9
[ { "submission_id": "aoj_NTL_2_A_10774189", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print_arr( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() ; i++ )\n cout << v[i];\n cout << endl;\n}\n\nstruct BigInteger{\n\n bool minus;\n int digit;\n vector<ll> arr;\n\n BigInteger( string val = \"\", bool m = false ){\n\n minus = m;\n while( val.length() > 4 ){\n arr.push_back( stoll( val.substr( val.length() - 4 ) ) );\n val = val.substr( 0, val.length() - 4 );\n }\n if( val.length() != 0 )\n arr.push_back( stoll( val ) );\n set_digit();\n\n }\n\n void shift_l(){\n\n ll up = 0;\n for( int i = 0 ; i < digit ; i++ ){\n ll next_up = arr[i] / 1000;\n arr[i] = ( arr[i] % 1000 ) * 10 + up; \n up = next_up;\n }\n arr.push_back( up );\n set_digit();\n\n }\n\n void shift_r(){\n\n ll down = 0;\n for( int i = digit - 1 ; i >= 0 ; i-- ){\n ll next_down = arr[i] % 10;\n arr[i] = 1000 * down + arr[i] / 10;\n down = next_down;\n }\n set_digit();\n\n }\n\n bool zero(){\n\n return digit == 1 && arr[0] == 0;\n\n }\n\n void set_digit(){\n\n while( arr.size() > 1 && arr[arr.size()-1] == 0 )\n arr.pop_back();\n digit = arr.size();\n\n }\n\n void print(){\n\n if( zero() ){\n cout << 0 << endl;\n return;\n }\n if( minus )\n cout << \"-\";\n cout << arr[digit - 1];\n for( int i = digit - 2 ; i >= 0 ; i-- )\n cout << setfill( '0' ) << std::setw( 4 ) << arr[i];\n cout << endl;\n\n }\n\n};\n\nBigInteger add( BigInteger bi1, BigInteger bi2 );\nBigInteger sub( BigInteger bi1, BigInteger bi2 );\nBigInteger mul( BigInteger bi1, BigInteger bi2 );\nBigInteger div( BigInteger bi1, BigInteger bi2 );\nbool operator<( const BigInteger bi1, const BigInteger bi2 );\nbool operator>( const BigInteger bi1, const BigInteger bi2 );\nbool operator<=( const BigInteger bi1, const BigInteger bi2 );\nbool operator>=( const BigInteger bi1, const BigInteger bi2 );\nbool operator==( const BigInteger bi1, const BigInteger bi2 );\nbool operator!=( const BigInteger bi1, const BigInteger bi2 );\n\nBigInteger add( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return sub( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n return sub( bi2, bi1 );\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n\n BigInteger res;\n ll up = 0;\n for( int i = 0 ; i < max( bi1.digit, bi2.digit ) ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i];\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n res.arr.push_back( ( val1 + val2 + up ) % 10000 ); \n up = ( val1 + val2 + up ) / 10000;\n }\n res.arr.push_back( up );\n res.set_digit();\n return res;\n\n}\n\nBigInteger sub( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return add( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = sub( bi2, bi1 );\n return res;\n }\n\n if( bi1.digit < bi2.digit ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n else if( bi1.digit == bi2.digit ){\n for( int i = bi1.digit-1 ; i >= 0 ; i-- ){\n if( bi1.arr[i] > bi2.arr[i] )\n break;\n else if( bi1.arr[i] < bi2.arr[i] ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n }\n }\n \n BigInteger res;\n ll down = 0;\n for( int i = 0 ; i < bi1.digit ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i] - down;\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n if( val1 < val2 ){\n down = 1;\n val1 += 10000;\n }\n else \n down = 0;\n res.arr.push_back( val1 - val2 );\n }\n res.set_digit();\n return res;\n\n}\n\nBigInteger mul( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n res.minus = ( bi1.minus != bi2.minus );\n for( int i = 0 ; i < bi1.digit + bi2.digit ; i++ )\n res.arr.push_back( 0 );\n for( int i = 0 ; i < bi1.digit ; i++ ){\n for( int j = 0 ; j < bi2.digit ; j++ )\n res.arr[i+j] += bi1.arr[i] * bi2.arr[j];\n }\n ll up = 0;\n for( int i = 0 ; i < bi1.digit + bi2.digit ; i++ ){\n ll next_up = ( res.arr[i] + up ) / 10000;\n res.arr[i] = ( res.arr[i] + up ) % 10000;\n up = next_up;\n }\n res.set_digit();\n return res;\n\n}\n\nBigInteger div( BigInteger bi1, BigInteger bi2 ){\n\n string num = \"\";\n bool m = ( bi1.minus != bi2.minus );\n bi1.minus = bi2.minus = false;\n BigInteger org = bi2;\n if( bi1 < bi2 ){\n BigInteger zero( \"0\", false );\n return zero;\n }\n while( bi1.digit > bi2.digit ){\n bi2.arr.insert( bi2.arr.begin(), 0 );\n bi2.digit++;\n }\n while( to_string( bi1.arr[bi1.digit-1] ).length() > to_string( bi2.arr[bi2.digit-1] ).length() )\n bi2.shift_l();\n while( to_string( bi1.arr[bi1.digit-1] ).length() < to_string( bi2.arr[bi2.digit-1] ).length() )\n bi2.shift_r();\n while( bi2 >= org ){ \n int i;\n for( i = 0 ; i <= 9 ; i++ ){\n BigInteger tmp = sub( bi1, bi2 );\n tmp.print();\n if( !tmp.zero() && tmp.minus )\n break;\n bi1 = tmp;\n } \n num += to_string( i );\n bi2.shift_r();\n }\n BigInteger res( num, m );\n return res;\n\n}\n\nbool operator<( const BigInteger bi1, const BigInteger bi2 ){\n\n BigInteger tmp = sub( bi1, bi2 );\n return tmp.minus && !tmp.zero();\n\n}\n\nbool operator>( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.minus && !tmp.zero();\n\n}\n\nbool operator<=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return tmp.minus || tmp.zero();\n\n}\n\nbool operator>=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.minus || tmp.zero();\n\n}\n\nbool operator==( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return tmp.zero();\n\n}\n\nbool operator!=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.zero();\n\n}\n\nint main(){\n\n string val1, val2;\n bool minus;\n \n cin >> val1;\n if( val1[0] == '-' ){\n minus = true;\n val1 = val1.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi1( val1, minus );\n\n cin >> val2;\n if( val2[0] == '-' ){\n minus = true;\n val2 = val2.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi2( val2, minus );\n \n BigInteger res = add( bi1, bi2 );\n res.print();\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5368, "score_of_the_acc": -0.0795, "final_rank": 2 }, { "submission_id": "aoj_NTL_2_A_10774163", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print_arr( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() ; i++ )\n cout << v[i];\n cout << endl;\n}\n\nstruct BigInteger{\n\n bool minus;\n int digit;\n vector<ll> arr;\n\n BigInteger( string val = \"\", bool m = false ){\n\n minus = m;\n while( val.length() > 4 ){\n arr.push_back( stoll( val.substr( val.length() - 4 ) ) );\n val = val.substr( 0, val.length() - 4 );\n }\n if( val.length() != 0 )\n arr.push_back( stoll( val ) );\n set_digit();\n\n }\n\n void shift_l(){\n\n ll up = 0;\n for( int i = 0 ; i < digit ; i++ ){\n ll next_up = arr[i] / 1000;\n arr[i] = ( arr[i] % 1000 ) * 10 + up; \n up = next_up;\n }\n arr.push_back( up );\n set_digit();\n\n }\n\n void shift_r(){\n\n ll down = 0;\n for( int i = digit - 1 ; i >= 0 ; i-- ){\n ll next_down = arr[i] % 10;\n arr[i] = 1000 * down + arr[i] / 10;\n down = next_down;\n }\n set_digit();\n\n }\n\n bool zero(){\n\n return digit == 1 && arr[0] == 0;\n\n }\n\n void set_digit(){\n\n while( arr.size() > 1 && arr[arr.size()-1] == 0 )\n arr.pop_back();\n digit = arr.size();\n\n }\n\n void print(){\n\n if( zero() ){\n cout << 0 << endl;\n return;\n }\n if( minus )\n cout << \"-\";\n cout << arr[digit - 1];\n for( int i = digit - 2 ; i >= 0 ; i-- )\n cout << setfill( '0' ) << std::setw( 4 ) << arr[i];\n cout << endl;\n\n }\n\n};\n\nBigInteger add( BigInteger bi1, BigInteger bi2 );\nBigInteger sub( BigInteger bi1, BigInteger bi2 );\nBigInteger mul( BigInteger bi1, BigInteger bi2 );\nBigInteger div( BigInteger bi1, BigInteger bi2 );\nbool operator<( const BigInteger bi1, const BigInteger bi2 );\nbool operator>( const BigInteger bi1, const BigInteger bi2 );\nbool operator<=( const BigInteger bi1, const BigInteger bi2 );\nbool operator>=( const BigInteger bi1, const BigInteger bi2 );\nbool operator==( const BigInteger bi1, const BigInteger bi2 );\nbool operator!=( const BigInteger bi1, const BigInteger bi2 );\n\nBigInteger add( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return sub( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n return sub( bi2, bi1 );\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n\n BigInteger res;\n ll up = 0;\n for( int i = 0 ; i < max( bi1.digit, bi2.digit ) ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i];\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n res.arr.push_back( ( val1 + val2 + up ) % 10000 ); \n up = ( val1 + val2 + up ) / 10000;\n }\n res.arr.push_back( up );\n res.set_digit();\n return res;\n\n}\n\nBigInteger sub( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return add( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = sub( bi2, bi1 );\n return res;\n }\n\n if( bi1.digit < bi2.digit ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n else if( bi1.digit == bi2.digit ){\n for( int i = bi1.digit-1 ; i >= 0 ; i++ ){\n if( bi1.arr[i] > bi2.arr[i] )\n break;\n else if( bi1.arr[i] < bi2.arr[i] ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n }\n }\n \n BigInteger res;\n ll down = 0;\n for( int i = 0 ; i < bi1.digit ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i] - down;\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n if( val1 < val2 ){\n down = 1;\n val1 += 10000;\n }\n else \n down = 0;\n res.arr.push_back( val1 - val2 );\n }\n res.set_digit();\n return res;\n\n}\n\nBigInteger mul( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n res.minus = ( bi1.minus != bi2.minus );\n for( int i = 0 ; i < bi1.digit + bi2.digit ; i++ )\n res.arr.push_back( 0 );\n for( int i = 0 ; i < bi1.digit ; i++ ){\n for( int j = 0 ; j < bi2.digit ; j++ )\n res.arr[i+j] += bi1.arr[i] * bi2.arr[j];\n }\n ll up = 0;\n for( int i = 0 ; i < bi1.digit + bi2.digit ; i++ ){\n ll next_up = ( res.arr[i] + up ) / 10000;\n res.arr[i] = ( res.arr[i] + up ) % 10000;\n up = next_up;\n }\n res.set_digit();\n return res;\n\n}\n\nBigInteger div( BigInteger bi1, BigInteger bi2 ){\n\n string num = \"\";\n bool m = ( bi1.minus != bi2.minus );\n bi1.minus = bi2.minus = false;\n BigInteger org = bi2;\n if( bi1 < bi2 ){\n BigInteger zero( \"0\", false );\n return zero;\n }\n while( bi1.digit > bi2.digit ){\n bi2.arr.insert( bi2.arr.begin(), 0 );\n bi2.digit++;\n }\n while( to_string( bi1.arr[bi1.digit-1] ).length() > to_string( bi2.arr[bi2.digit-1] ).length() )\n bi2.shift_l();\n while( to_string( bi1.arr[bi1.digit-1] ).length() < to_string( bi2.arr[bi2.digit-1] ).length() )\n bi2.shift_r();\n while( bi2 >= org ){ \n int i;\n for( i = 0 ; i <= 9 ; i++ ){\n BigInteger tmp = sub( bi1, bi2 );\n tmp.print();\n if( !tmp.zero() && tmp.minus )\n break;\n bi1 = tmp;\n } \n num += to_string( i );\n bi2.shift_r();\n }\n BigInteger res( num, m );\n return res;\n\n}\n\nbool operator<( const BigInteger bi1, const BigInteger bi2 ){\n\n BigInteger tmp = sub( bi1, bi2 );\n return tmp.minus && !tmp.zero();\n\n}\n\nbool operator>( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.minus && !tmp.zero();\n\n}\n\nbool operator<=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return tmp.minus || tmp.zero();\n\n}\n\nbool operator>=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.minus || tmp.zero();\n\n}\n\nbool operator==( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return tmp.zero();\n\n}\n\nbool operator!=( const BigInteger bi1, const BigInteger bi2 ){\n \n BigInteger tmp = sub( bi1, bi2 );\n return !tmp.zero();\n\n}\n\nint main(){\n\n string val1, val2;\n bool minus;\n \n cin >> val1;\n if( val1[0] == '-' ){\n minus = true;\n val1 = val1.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi1( val1, minus );\n\n cin >> val2;\n if( val2[0] == '-' ){\n minus = true;\n val2 = val2.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi2( val2, minus );\n \n BigInteger res = add( bi1, bi2 );\n res.print();\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5420, "score_of_the_acc": -0.0801, "final_rank": 3 }, { "submission_id": "aoj_NTL_2_A_10710894", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst ld PI = acos( -1.0 );\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\ntemplate <typename T>\nvoid print_arr( vector<T> v ){\n if( v.size() == 0 ) return;\n for( int i = 0 ; i < v.size() ; i++ )\n cout << v[i];\n cout << endl;\n}\n\nstruct BigInteger{\n\n bool minus;\n int digit;\n vector<ll> arr;\n\n BigInteger( string val = \"\", bool m = false ){\n\n minus = m;\n while( val.length() > 4 ){\n arr.push_back( stoll( val.substr( val.length() - 4 ) ) );\n val = val.substr( 0, val.length() - 4 );\n }\n if( val.length() != 0 )\n arr.push_back( stoll( val ) );\n set_digit();\n\n }\n\n bool zero(){\n\n return arr.size() == 1 && arr[0] == 0;\n\n }\n\n void set_digit(){\n\n while( arr.size() > 1 && arr[arr.size()-1] == 0 ){\n arr.pop_back();\n }\n digit = arr.size();\n\n }\n\n void print(){\n\n if( zero() ){\n cout << 0 << endl;\n return;\n }\n if( minus )\n cout << \"-\";\n cout << arr[digit - 1];\n for( int i = digit - 2 ; i >= 0 ; i-- )\n cout << setfill( '0' ) << std::setw( 4 ) << arr[i];\n cout << endl;\n\n }\n\n};\n\nBigInteger add( BigInteger bi1, BigInteger bi2 );\nBigInteger sub( BigInteger bi1, BigInteger bi2 );\n\nBigInteger add( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return sub( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n return sub( bi2, bi1 );\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n\n BigInteger res;\n ll up = 0;\n for( int i = 0 ; i < max( bi1.digit, bi2.digit ) ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i];\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n res.arr.push_back( ( val1 + val2 + up ) % 10000 ); \n up = ( val1 + val2 + up ) / 10000;\n }\n res.arr.push_back( up );\n res.set_digit();\n return res;\n\n}\n\nBigInteger sub( BigInteger bi1, BigInteger bi2 ){\n\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n return add( bi1, bi2 );\n }\n else if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n BigInteger res = add( bi1, bi2 );\n res.minus = true;\n return res;\n }\n else if( bi1.minus && bi2.minus ){\n bi1.minus = false;\n bi2.minus = false;\n BigInteger res = sub( bi2, bi1 );\n return res;\n }\n\n if( bi1.digit < bi2.digit ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n else if( bi1.digit == bi2.digit ){\n if( bi1.arr[bi1.digit-1] < bi2.arr[bi2.digit-1] ){\n BigInteger res = sub( bi2, bi1 );\n res.minus = true;\n return res;\n }\n }\n \n BigInteger res;\n ll down = 0;\n for( int i = 0 ; i < bi1.digit ; i++ ){\n ll val1 = 0, val2 = 0;\n if( i < bi1.digit )\n val1 = bi1.arr[i] - down;\n if( i < bi2.digit )\n val2 = bi2.arr[i];\n if( val1 < val2 ){\n down = 1;\n val1 += 10000;\n }\n else \n down = 0;\n res.arr.push_back( val1 - val2 );\n }\n res.set_digit();\n return res;\n\n}\n\nint main(){\n\n string val1, val2;\n bool minus;\n \n cin >> val1;\n if( val1[0] == '-' ){\n minus = true;\n val1 = val1.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi1( val1, minus );\n\n cin >> val2;\n if( val2[0] == '-' ){\n minus = true;\n val2 = val2.substr( 1 );\n }\n else\n minus = false;\n BigInteger bi2( val2, minus );\n \n BigInteger res = add( bi1, bi2 );\n res.print();\n\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 5448, "score_of_the_acc": -0.0804, "final_rank": 4 }, { "submission_id": "aoj_NTL_2_A_9795740", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n\ntemplate <int BASE>\nclass BigDecimal {\n public:\n static constexpr std::string_view NUMERAL{\n \"0123456789ABCDEF\"}; // 16進数まで対応\n\n private: // 静的関数\n static int CompareIgnoreSign(const BigDecimal& a, const BigDecimal& b) {\n // a-bの符号で覚えてもよいかも。\n // a<b: -1\n // a>b: +1\n // a==b: 0\n if (a._digit.size() != b._digit.size())\n return a._digit.size() < b._digit.size() ? -1 : 1;\n for (int i = a._digit.size() - 1; i >= 0; --i) {\n if (a._digit[i] == b._digit[i]) continue;\n return a._digit[i] < b._digit[i] ? -1 : 1;\n }\n return 0;\n }\n\n static BigDecimal Karatsuba(const BigDecimal& a, const BigDecimal& b) {\n // |a| >= |b|にする\n if (a._digit.size() < b._digit.size()) return Karatsuba(b, a);\n // 1桁に絞ったら直に計算して返す\n if (b._digit.size() == 1) {\n BigDecimal ret(a);\n for (int i = 0; i < a._digit.size(); ++i) {\n ret._digit[i] *= b._digit[0];\n }\n ret.carry_and_fix();\n if (b._positive)\n return ret;\n else\n return -ret;\n }\n int N = a._digit.size() / 2; // 下半分の桁数\n bool sign = !(a._positive xor b._positive); // 符号を計算しておく\n BigDecimal a0(a), a1(a), b0(b), b1(b); // x = concat(x0, x1)\n // aの処理\n // x1の下N桁を残す形で上の桁を取り除く\n while (a1._digit.size() > N) a1._digit.pop_back();\n // x0のデータを消去\n a0._digit.clear();\n // x0に下N桁より上の桁を保存しなおす\n for (int i = 0; N + i < a._digit.size(); ++i)\n a0._digit.emplace_back(a._digit[N + i]);\n if (a0._digit.size() == 0) a0._digit.emplace_back(0);\n // x0, x1の符号を取り除く\n a0._positive = a1._positive = true;\n if (b._digit.size() < N) { // 一方が他方の半分もない\n BigDecimal p0, c1;\n p0 = Karatsuba(a0, b);\n c1 = Karatsuba(a1, b);\n BigDecimal c0;\n for (int i = 0; i < N - 1; ++i) c0._digit.emplace_back(0);\n for (const auto& d : p0._digit) c0._digit.emplace_back(d);\n BigDecimal ret = c0 + c1;\n ret._positive = sign;\n return ret;\n }\n // bの処理\n // x1の下N桁を残す形で上の桁を取り除く\n while (b1._digit.size() > N) b1._digit.pop_back();\n // x0のデータを消去\n b0._digit.clear();\n // x0に下N桁より上の桁を保存しなおす\n for (int i = 0; N + i < b._digit.size(); ++i)\n b0._digit.emplace_back(b._digit[N + i]);\n if (b0._digit.size() == 0) b0._digit.emplace_back(0);\n // x0, x1の符号を取り除く\n b0._positive = b1._positive = true;\n // 3種類の積\n BigDecimal p0, p1, p2;\n p0 = Karatsuba(a0, b0);\n p2 = Karatsuba(a1, b1);\n p1 = Karatsuba(a0 + a1, b0 + b1) - p0 - p2;\n // 積に対応する数\n BigDecimal c0, c1, c2;\n c0._digit.clear();\n c1._digit.clear();\n c2._digit.clear();\n for (int i = 0; i < N; ++i) {\n c0._digit.emplace_back(0);\n c0._digit.emplace_back(0);\n c1._digit.emplace_back(0);\n }\n for (const auto& d : p0._digit) c0._digit.emplace_back(d);\n for (const auto& d : p1._digit) c1._digit.emplace_back(d);\n for (const auto& d : p2._digit) c2._digit.emplace_back(d);\n BigDecimal ret = c0 + c1 + c2;\n ret._positive = sign;\n return ret;\n }\n\n private:\n std::vector<int> _digit;\n bool _positive;\n\n void carry_and_fix() {\n // 新規の桁が発生しない範疇(最後の桁以外)を処理\n for (int i = 0; i < _digit.size() - 1; ++i) {\n if (_digit[i] >= BASE) {\n // 桁の数が基数以上: 繰り上げる必要あり\n int k = _digit[i] / BASE; // 繰り上がり発生回数\n _digit[i] -= k * BASE;\n _digit[i + 1] += k;\n } else if (_digit[i] < 0) {\n // 桁の数が負: 繰り下げが必要\n int k = (-_digit[i] - 1) / BASE + 1;\n _digit[i] += k * BASE;\n _digit[i + 1] -= k;\n }\n }\n // 最後の桁を処理する場合\n while (_digit.back() >= BASE) {\n int k = _digit.back() / BASE; // 繰り上がり発生回数\n _digit.back() -= k * BASE;\n _digit.emplace_back(k);\n }\n // 計算結果がマイナスなら全体に-1をかけて符号反転\n if (_digit.back() < 0) {\n this->_positive = !this->_positive;\n for (int i = 0; i < _digit.size(); ++i) {\n _digit[i] *= -1;\n }\n this->carry_and_fix();\n }\n // 0の桁を上から消す\n while (_digit.size() >= 2 && _digit.back() == 0) _digit.pop_back();\n // 0になったら正の数にしておく(-0表記は困るため)\n if(_digit.size() == 1 && _digit[0] == 0) _positive = true;\n }\n\n public:\n // コンストラクタ\n BigDecimal(int num = 0) : _digit(0), _positive(num >= 0) {\n if (!_positive) num *= -1;\n while (num > 0) {\n _digit.emplace_back(num % BASE);\n num /= BASE;\n }\n if (_digit.size() == 0) _digit.emplace_back(0);\n }\n BigDecimal(std::string s) {\n if (s[0] == '-') {\n s = s.substr(1);\n _positive = false;\n } else {\n _positive = true;\n }\n while (s.size() > 0) {\n int i = NUMERAL.find(s.back());\n _digit.emplace_back(i);\n s.pop_back();\n }\n }\n // コピーコンストラクタ\n BigDecimal(const BigDecimal& x)\n : _digit(x._digit.size()), _positive(x._positive) {\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] = x._digit[i];\n }\n }\n\n // 比較演算子\n bool operator==(const BigDecimal& x) const {\n if (this->_positive != x._positive) return false;\n if (this->_digit.size() != x._digit.size()) return false;\n for (int i = 0; i < this->_digit.size(); ++i) {\n if (this->_digit[i] != x._digit[i]) return false;\n }\n return true;\n }\n bool operator!=(const BigDecimal& x) const { return !(*this == x); }\n bool operator<(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return false; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) < 0;\n } else {\n if (x._positive) return true; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) > 0;\n }\n }\n bool operator>(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return true; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) > 0;\n } else {\n if (x._positive) return false; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) < 0;\n }\n }\n bool operator<=(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return false; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) <= 0;\n } else {\n if (x._positive) return true; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) >= 0;\n }\n }\n bool operator>=(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return true; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) >= 0;\n } else {\n if (x._positive) return false; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) <= 0;\n }\n }\n\n // 単項演算子\n BigDecimal operator+() const { return *this; }\n BigDecimal operator-() const {\n BigDecimal ret = *this;\n ret._positive = !ret._positive;\n return ret;\n }\n // 複号代入演算子\n BigDecimal& operator+=(const BigDecimal& x) {\n // 符号が異なる場合は符号をそろえて引き算に\n if (this->_positive != x._positive) {\n return *this -= (-x);\n }\n // 符号が同じ物にのみ足し算を行う\n while (this->_digit.size() < x._digit.size()) {\n this->_digit.emplace_back(0);\n }\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] += x._digit[i];\n }\n this->carry_and_fix();\n return *this;\n }\n BigDecimal& operator-=(const BigDecimal& x) {\n // 符号が異なる場合は符号をそろえて足し算に\n if (this->_positive != x._positive) {\n return *this += (-x);\n }\n // 符号が同じ物にのみ引き算を行う\n while (this->_digit.size() < x._digit.size()) {\n this->_digit.emplace_back(0);\n }\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] -= x._digit[i];\n }\n this->carry_and_fix();\n return *this;\n }\n BigDecimal& operator*=(const BigDecimal& x) { return *this; }\n BigDecimal& operator/=(const BigDecimal& x) { return *this; }\n BigDecimal& operator%=(const BigDecimal& x) { return *this; }\n\n // 二項演算子\n BigDecimal operator+(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret += x);\n }\n BigDecimal operator-(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret -= x);\n }\n BigDecimal operator*(const BigDecimal& x) const {\n return Karatsuba(*this, x);\n }\n BigDecimal operator/(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret /= x);\n }\n BigDecimal operator%(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret %= x);\n }\n\n // キャスト\n operator std::string() const {\n std::string ret = \"\";\n for (const auto& c : _digit) {\n ret = NUMERAL.at(c) + ret;\n }\n if (!_positive) ret = \"-\" + ret;\n return ret;\n }\n};\n\nint main() {\n std::string A, B;\n std::cin >> A >> B;\n BigDecimal<10> a(A), b(B);\n std::cout << std::string(a+b) << std::endl;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 5252, "score_of_the_acc": -0.1652, "final_rank": 6 }, { "submission_id": "aoj_NTL_2_A_9288512", "code_snippet": "#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\n\nint main() {\n boost::multiprecision::cpp_int a, b;\n cin >> a >> b;\n cout << a+b << '\\n';\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3432, "score_of_the_acc": -1.0005, "final_rank": 14 }, { "submission_id": "aoj_NTL_2_A_9072897", "code_snippet": "#include <iostream>\n\n#include \"boost/multiprecision/cpp_int.hpp\"\n\nint main() {\n boost::multiprecision::cpp_int a, b;\n std::cin >> a >> b;\n std::cout << a + b << std::endl;\n return 0;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3424, "score_of_the_acc": -1.0004, "final_rank": 12 }, { "submission_id": "aoj_NTL_2_A_8219544", "code_snippet": "#include <bits/stdc++.h>\n\n\nint main() {\n std::string rawA, rawB;\n std::cin >> rawA >> rawB;\n\n int fa = 1, fb = 1;\n std::string A = rawA, B = rawB;\n if (A[0] == '-') {\n fa = -1;\n A.erase(0, 1);\n }\n if (B[0] == '-') {\n fb = -1;\n B.erase(0, 1);\n }\n // std::cout << A << \" , \" << B << std::endl;\n\n bool is_swap = A.size() < B.size();\n if (A.size() == B.size()) {\n for (int i = 0; i < A.size(); i++) {\n if (A[i] == B[i]) {\n continue;\n }\n is_swap = A[i] < B[i];\n break;\n }\n }\n\n if (is_swap) {\n std::swap(A, B);\n std::swap(fa, fb);\n std::swap(rawA, rawB);\n }\n\n int diff = (A.size() - B.size());\n for (int i = 0; i < diff; i++) {\n B = '0' + B;\n }\n\n int f = fa * fb;\n int next = 0;\n std::string s = \"\";\n // std::cout << A << std::endl;\n // std::cout << B << std::endl;\n for (int i = 1; i <= A.size(); i++) {\n int val = A[A.size() - i] - '0' + f * (B[B.size() - i] - '0') + next;\n if (val > 9) {\n next = 1;\n val -= 10;\n } else if (val < 0) {\n next = -1;\n val += 10;\n } else {\n next = 0;\n }\n s = std::to_string(val) + s;\n }\n if (next != 0) {\n s = \"1\" + s;\n }\n\n while (s.size() > 1 && s[0] == '0') {\n s.erase(0, 1);\n }\n\n if (s != \"0\" && fa < 0) {\n s = \"-\" + s;\n }\n\n std::cout << s << std::endl;\n}", "accuracy": 1, "time_ms": 260, "memory_kb": 4196, "score_of_the_acc": -0.3711, "final_rank": 8 }, { "submission_id": "aoj_NTL_2_A_7680352", "code_snippet": "#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long u64;\ntypedef __uint128_t u128;\n\nstruct bignum {\n u64 a[30005];\n int n;\n\n int ctz() const {\n for (int i = 0;; i++) {\n if (a[i]) {\n return i << 6 | __builtin_ctzll(a[i]);\n }\n }\n }\n\n int lg() const {\n return n << 6 | __lg(a[n]);\n }\n\n bool operator<(const bignum &b) const {\n if (n != b.n) {\n return n < b.n;\n }\n for (int i = n; i != -1; i--) {\n if (a[i] < b.a[i]) {\n return 1;\n }\n if (a[i] > b.a[i]) {\n return 0;\n }\n }\n return 0;\n }\n\n bool operator>(const bignum &b) const {\n return b < *this;\n }\n\n bool operator<=(const bignum &b) const {\n return !(b < *this);\n }\n\n bool operator>=(const bignum &b) const {\n return !(*this < b);\n }\n\n bool operator==(const bignum &b) const {\n if (n != b.n) {\n return 0;\n }\n for (int i = 0; i <= n; i++) {\n if (a[i] != b.a[i]) {\n return 0;\n }\n }\n return 1;\n }\n\n bool operator!=(const bignum &b) const {\n return !(*this == b);\n }\n\n bignum operator+(u64 x) const {\n bignum c = *this;\n int l = c.n;\n\n c.a[0] += x;\n\n bool o = c.a[0] < a[0];\n if (o) {\n for (int i = 1; i <= l; i++) {\n if (a[i] == (u64)-1) {\n c.a[i] = 0;\n } else {\n c.a[i]++;\n o = 0;\n break;\n }\n }\n\n if (o) {\n c.a[++l] = 1;\n }\n }\n c.n = l;\n return c;\n }\n\n bignum operator-(u64 x) const {\n bignum c = *this;\n int l = c.n;\n\n c.a[0] -= x;\n\n bool o = c.a[0] > a[0];\n if (o) {\n for (int i = 1; i <= l; i++) {\n if (!a[i]) {\n c.a[i] = -1;\n } else {\n c.a[i]--;\n break;\n }\n }\n while (l && !c.a[l]) {\n l--;\n c.n--;\n }\n }\n return c;\n }\n\n bignum operator*(u64 x) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int l = n;\n u128 ad = 0;\n\n for (int i = 0; i <= l; i++) {\n ad += (u128)a[i] * x;\n c.a[i] = ad, ad >>= 64;\n }\n\n if (ad) {\n c.a[++l] = ad;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator/(int m) const {\n if (m == 1) {\n return *this;\n }\n\n bignum c;\n memset(&c, 0, sizeof c);\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n\n int l = n;\n int r = 0;\n\n for (int i = l; i != -1; i--) {\n u128 v = (u128)r * rr + a[i];\n u64 q = (v * b) >> 64;\n int gu = v - (u128)q * m;\n if (gu >= m) {\n gu -= m, q++;\n }\n\n c.a[i] = r * b + q, r = gu;\n }\n\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n int operator%(int m) const {\n if (m == 1) {\n return 0;\n }\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n int r = 0;\n\n for (int i = n; i != -1; i--) {\n u128 v = (u128)r * rr + a[i];\n u64 q = (v * b) >> 64;\n r = v - q * m;\n if (r >= m) {\n r -= m;\n }\n }\n\n return r;\n }\n\n bignum operator+(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n bool o = 0;\n int l = max(n, b.n);\n for (int i = 0; i <= l; i++) {\n c.a[i] = a[i] + b.a[i] + o;\n o = (c.a[i] < a[i]) || (b.a[i] == (u64)-1 && o);\n }\n if (o) {\n c.a[++l] = 1;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator-(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n bool o = 0;\n int l = n;\n for (int i = 0; i <= l; i++) {\n c.a[i] = a[i] - b.a[i] - o;\n o = (c.a[i] > a[i]) || (b.a[i] == (u64)-1 && o);\n }\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator*(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n u128 r = 0;\n int l = n + b.n;\n for (int i = 0; i <= n + b.n; i++) {\n u128 h = 0;\n\n for (int j = max(0, i - b.n); j <= min(i, n); j++) {\n u128 tp = (u128)a[j] * b.a[i - j];\n r += tp & ((u64)-1), h += tp >> 64;\n }\n\n c.a[i] = r;\n r = h + (r >> 64);\n }\n if (r) {\n c.a[++l] = r;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator/(const bignum &b) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int n = lg(), m = b.lg();\n if (n < m) {\n return c;\n }\n\n bignum tp = *this, qwq = b << (n - m);\n int l = 0;\n for (int i = n - m; i != -1; i--, qwq >>= 1) {\n if (tp >= qwq) {\n tp -= qwq;\n c.a[i >> 6] |= 1ull << (i & 63);\n if (!l) {\n l = i;\n }\n }\n }\n\n c.n = l >> 6;\n return c;\n }\n\n bignum operator%(const bignum &b) const {\n bignum c = *this;\n\n int n = lg(), m = b.lg();\n if (n < m) {\n return c;\n }\n\n bignum tp = b << (n - m);\n for (int i = n; i >= m; i--, tp >>= 1) {\n if (c >= tp) {\n c -= tp;\n }\n }\n\n return c;\n }\n\n bignum operator+=(u64 x) {\n u64 tp = a[0];\n a[0] += x;\n bool o = a[0] < tp;\n\n if (o) {\n for (int i = 1; i <= n; i++) {\n if (a[i] == (u64)-1) {\n a[i] = 0;\n } else {\n a[i]++;\n o = 0;\n break;\n }\n }\n\n if (o) {\n a[++n] = 1;\n }\n }\n return *this;\n }\n\n bignum operator-=(u64 x) {\n u64 tp = a[0];\n a[0] -= x;\n bool o = a[0] > tp;\n\n if (o) {\n for (int i = 1; i <= n; i++) {\n if (!a[i]) {\n a[i] = -1;\n } else {\n a[i]--;\n break;\n }\n }\n while (n && !a[n]) {\n n--;\n }\n }\n return *this;\n }\n\n bignum operator*=(u64 x) {\n u128 ad = 0;\n\n for (int i = 0; i <= n; i++) {\n ad += (u128)a[i] * x;\n a[i] = ad, ad >>= 64;\n }\n\n if (ad) {\n a[++n] = ad;\n }\n\n return *this;\n }\n\n bignum operator/=(int m) {\n if (m == 1) {\n return *this;\n }\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n\n int r = 0;\n\n for (int i = n; i != -1; i--) {\n u128 v = (u128)r * rr + a[i];\n u64 q = (v * b) >> 64;\n int gu = v - (u128)q * m;\n if (gu >= m) {\n gu -= m, q++;\n }\n\n a[i] = r * b + q, r = gu;\n }\n\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n\n bignum operator+=(const bignum &b) {\n bool o = 0;\n int l = max(n, b.n);\n for (int i = 0; i <= l; i++) {\n u64 tp = a[i];\n a[i] += b.a[i] + o;\n o = (a[i] < tp) || (b.a[i] == (u64)-1 && o);\n }\n if (o) {\n a[++l] = 1;\n }\n n = l;\n\n return *this;\n }\n\n bignum operator-=(const bignum &b) {\n bool o = 0;\n int l = n;\n for (int i = 0; i <= l; i++) {\n u64 tp = a[i];\n a[i] -= b.a[i] + o;\n o = (a[i] > tp) || (b.a[i] == (u64)-1 && o);\n }\n while (l && !a[l]) {\n l--;\n }\n n = l;\n\n return *this;\n }\n\n bignum operator*=(const bignum &b) {\n return *this = *this * b;\n }\n\n bignum operator/=(const bignum &b) {\n return *this = *this / b;\n }\n\n bignum operator%=(const bignum &b) {\n return *this = *this % b;\n }\n\n bignum operator<<(int k) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int t = k >> 6;\n memcpy(c.a + t, a, (n + 1) << 3);\n int l = n + t;\n\n t = k & 63;\n if (t) {\n for (int i = l + 1; i; i--) {\n c.a[i] = (c.a[i] << t) | (c.a[i - 1] >> (64 - t));\n }\n c.a[0] <<= t;\n\n if (c.a[l + 1]) {\n l++;\n }\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator>>(int k) const {\n bignum c;\n memset(&c, 0, sizeof c);\n\n int t = k >> 6;\n if (t > n) {\n return c;\n }\n\n memcpy(c.a, a + t, (n - t + 1) << 3);\n\n int l = n - t;\n t = k & 63;\n\n if (t) {\n for (int i = 0; i <= l; i++) {\n c.a[i] = (c.a[i] >> t) | (c.a[i + 1] << (64 - t));\n }\n }\n\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator&(const bignum &b) const {\n bignum c = *this;\n\n for (int i = 0; i <= b.n; i++) {\n c.a[i] &= b.a[i];\n }\n for (int i = b.n + 1; i <= c.n; i++) {\n c.a[i] = 0;\n }\n\n int l = c.n;\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator|(const bignum &b) const {\n bignum c = *this;\n\n for (int i = 0; i <= b.n; i++) {\n c.a[i] |= b.a[i];\n }\n c.n = max(c.n, b.n);\n\n return c;\n }\n\n bignum operator^(const bignum &b) const {\n bignum c = *this;\n\n for (int i = 0; i <= b.n; i++) {\n c.a[i] ^= b.a[i];\n }\n\n int l = max(c.n, b.n);\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n return c;\n }\n\n bignum operator<<=(int k) {\n int t = k >> 6;\n\n if (t) {\n for (int i = n; i != -1; i--) {\n a[i + t] = a[i];\n }\n memset(a, 0, t << 3);\n }\n n += t;\n\n t = k & 63;\n\n if (t) {\n for (int i = n + 1; i; i--) {\n a[i] = (a[i] << t) | (a[i - 1] >> (64 - t));\n }\n a[0] <<= t;\n }\n\n if (a[n + 1]) {\n n++;\n }\n\n return *this;\n }\n\n bignum operator>>=(int k) {\n int t = k >> 6;\n\n if (t > n) {\n memset(a, 0, (n + 1) << 3);\n n = 0;\n return *this;\n }\n\n for (int i = t; i <= n; i++) {\n a[i - t] = a[i];\n }\n memset(a + n - t + 1, 0, t << 3);\n n -= t;\n\n t = k & 63;\n\n if (t) {\n for (int i = 0; i <= n; i++) {\n a[i] = (a[i] >> t) | (a[i + 1] << (64 - t));\n }\n }\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n\n bignum operator&=(const bignum &b) {\n for (int i = 0; i <= b.n; i++) {\n a[i] &= b.a[i];\n }\n for (int i = b.n + 1; i <= n; i++) {\n a[i] = 0;\n }\n\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n\n bignum operator|=(const bignum &b) {\n for (int i = 0; i <= b.n; i++) {\n a[i] |= b.a[i];\n }\n n = max(n, b.n);\n\n return *this;\n }\n\n bignum operator^=(const bignum &b) {\n n = max(n, b.n);\n for (int i = 0; i <= b.n; i++) {\n a[i] ^= b.a[i];\n }\n\n while (n && !a[n]) {\n n--;\n }\n\n return *this;\n }\n};\n\nbool oa, ob;\n\nbignum read_bignum(bool &o) {\n static char str[100005];\n static u64 a[10005];\n static u64 bs = 1000000000000000000ll;\n\n cin >> str;\n int n = strlen(str);\n if (str[0] == '-') {\n o = 1;\n n--;\n for (int i = 0; i != n; i++) {\n str[i] = str[i + 1];\n }\n }\n reverse(str, str + n);\n\n for (int i = 0; i <= (n - 1) / 18; i++) {\n u64 v = 0;\n for (int j = min(n, (i + 1) * 18) - 1; j >= i * 18; j--) {\n v = v * 10 + str[j] - '0';\n }\n a[i] = v;\n }\n n = (n - 1) / 18;\n\n bignum c;\n memset(&c, 0, sizeof c);\n int m = 0;\n\n for (int i = n; i != -1; i--) {\n u128 ad = 0;\n for (int j = 0; j <= m; j++) {\n ad += (u128)c.a[j] * bs;\n c.a[j] = ad, ad >>= 64;\n }\n\n while (ad) {\n c.a[++m] = ad, ad >>= 64;\n }\n c.n = m;\n\n c += a[i], m = c.n;\n }\n\n return c;\n}\n\nvoid output(bignum a) {\n static u64 v[30005];\n const u64 bs = 1000000000000000000ll;\n\n int n = a.n, m = 0;\n\n for (int i = n; i != -1; i--) {\n u128 ad = 0;\n for (int j = 0; j <= m; j++) {\n ad += (u128)v[j] << 64;\n u128 gu = ad / bs;\n v[j] = ad - gu * bs, ad = gu;\n }\n\n while (ad) {\n u128 gu = ad / bs;\n v[++m] = ad - gu * bs, ad = gu;\n }\n\n ad = a.a[i];\n for (int j = 0; j <= m && ad; j++) {\n ad += v[j];\n u128 gu = ad / bs;\n v[j] = ad - gu * bs, ad = gu;\n }\n while (ad) {\n u128 gu = ad / bs;\n v[++m] = ad - gu * bs, ad = gu;\n }\n }\n\n cout << v[m];\n for (int i = m - 1; i != -1; i--) {\n cout << setw(18) << setfill('0') << v[i];\n }\n memset(v, 0, sizeof v);\n}\n\nbignum updiv(bignum &a, int m) {\n static bignum c;\n memset(&c, 0, sizeof c);\n\n if (m == 1) {\n return a;\n }\n\n u64 b = ((u128)1 << 64) / m, rr = ((u128)1 << 64) % m;\n\n int l = a.n;\n int r = 0;\n\n for (int i = l; i != -1; i--) {\n u128 v = (u128)r * rr + a.a[i];\n u64 q = (v * b) >> 64;\n int gu = v - (u128)q * m;\n if (gu >= m) {\n gu -= m, q++;\n }\n\n c.a[i] = r * b + q, r = gu;\n }\n\n while (l && !c.a[l]) {\n l--;\n }\n c.n = l;\n\n if (r) {\n bool o = 1;\n for (int i = 0; i <= l; i++) {\n if (c.a[i] == (u64)-1) {\n c.a[i] = 0;\n } else {\n c.a[i]++;\n o = 0;\n break;\n }\n }\n\n if (o) {\n c.a[++l] = 1;\n }\n }\n\n c.n = l;\n\n return c;\n}\n\nbignum gcd(bignum a, bignum b) {\n if (a > b) {\n swap(a, b);\n }\n\n if (a.n == 0 && !a.a[0]) {\n return b;\n }\n\n int l = min(a.ctz(), b.ctz());\n a >>= a.ctz(), b >>= b.ctz();\n\n while (1) {\n if (a.n == 0 && !a.a[0]) {\n return b << l;\n }\n\n if (!(a.a[0] & 1)) {\n a >>= 1;\n } else if (!(b.a[0] & 1)) {\n b >>= 1;\n } else {\n if (a < b) {\n swap(a, b);\n }\n a -= b;\n }\n }\n}\n\nint main() {\n ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n\n bignum a = read_bignum(oa), b = read_bignum(ob);\n if (oa && ob) {\n cout << '-';\n oa = ob = 0;\n }\n\n if (oa == 0 && ob == 0) {\n output(a + b);\n cout << endl;\n return 0;\n }\n\n if (oa) {\n swap(a, b);\n }\n\n if (a >= b) {\n output(a - b);\n cout << endl;\n } else {\n cout << '-';\n output(b - a);\n cout << endl;\n }\n}", "accuracy": 1, "time_ms": 320, "memory_kb": 4732, "score_of_the_acc": -0.4639, "final_rank": 9 }, { "submission_id": "aoj_NTL_2_A_7593476", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nsigned main() {\n boost::multiprecision::cpp_int A, B;\n cin >> A >> B;\n cout << A + B << endl;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3384, "score_of_the_acc": -1, "final_rank": 10 }, { "submission_id": "aoj_NTL_2_A_7484494", "code_snippet": "#include <bits/stdc++.h>\n#define forr(i,a,b) for(int i = (a); i <= (b); i++)\n#define forw(i,a,b) for(int i = (a); i >= (b); i--)\n#define pb push_back\n#define f first\n#define s second\n\nusing namespace std;\ntypedef pair <int,int> pii;\n\nconst int maxn = 1e5 + 5;\n\nstring t(string a,string b)\n{\n string c = \"\";\n int n1 = a.size();\n int n2 = b.size();\n if(n1 > n2) forr(i,1,n1 - n2) b = \"0\" + b;\n if(n1 < n2)\n {\n forr(i,1,n2 - n1) a = \"0\" + a;\n n1 = n2;\n }\n int nho = 0;\n forw(i,n1 - 1,0)\n {\n int res = a[i] - '0' + b[i] - '0' + nho;\n if(res > 9) nho = 1;\n else nho = 0;\n c = char(res%10 + 48) + c;\n }\n if(nho == 1) c = \"1\" + c;\n return c;\n}\n\nstring h(string a,string b)\n{\n string c = \"\";\n int n1 = a.size();\n int n2 = b.size();\n if(n2 < n1) forr(i,1,n1 - n2) b = \"0\" + b;\n int nho = 0;\n forw(i,n1 - 1,0)\n {\n int res = a[i] - '0' - (b[i] - '0') - nho;\n if(res < 0) nho = 1;\n else nho = 0;\n if(res < 0) c = char(res + 10 + 48) + c;\n else c = char(res + 48) + c;\n }\n while(c.size() > 1 && c[0] == '0') c.erase(0,1);\n return c;\n}\n\nstring a,b;\n\nint main()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n cin >> a >> b;\n if(a[0] == '-')\n {\n if(b[0] == '-')\n {\n a.erase(0,1);\n b.erase(0,1);\n cout << \"-\" << t(a,b) << \"\\n\";\n return 0;\n }\n a.erase(0,1);\n if(b.size() > a.size() || (b.size() == a.size() && b >= a))\n {\n cout << h(b,a) << \"\\n\";\n return 0;\n }\n else\n {\n cout << \"-\" << h(a,b) << \"\\n\";\n return 0;\n }\n }\n else\n {\n if(b[0] == '-')\n {\n b.erase(0,1);\n if(b.size() < a.size() || (b.size() == a.size() && b <= a))\n {\n cout << h(a,b) << \"\\n\";\n return 0;\n }\n else\n {\n cout << \"-\" << h(b,a) << \"\\n\";\n return 0;\n }\n }\n else cout << t(a,b) << \"\\n\";\n //cout << \"Vandeeptry\";\n }\n return 0;\n}", "accuracy": 1, "time_ms": 250, "memory_kb": 3988, "score_of_the_acc": -0.3544, "final_rank": 7 }, { "submission_id": "aoj_NTL_2_A_7338655", "code_snippet": "#line 2 \"nachia\\\\math-modulo\\\\modulo-primitive-root.hpp\"\n#include <vector>\n#include <utility>\n\nnamespace nachia{\n\ntemplate<unsigned int MOD>\nstruct PrimitiveRoot{\n using u64 = unsigned long long;\n static constexpr u64 powm(u64 a, u64 i) {\n u64 res = 1, aa = a;\n while(i){\n if(i & 1) res = res * aa % MOD;\n aa = aa * aa % MOD;\n i /= 2;\n }\n return res;\n }\n static constexpr bool ExamineVal(unsigned int g){\n unsigned int t = MOD - 1;\n for(u64 d=2; d*d<=t; d++) if(t % d == 0){\n if(powm(g, (MOD - 1) / d) == 1) return false;\n while(t % d == 0) t /= d;\n }\n if(t != 1) if(powm(g, (MOD - 1) / t) == 1) return false;\n return true;\n }\n static constexpr unsigned int GetVal(){\n for(unsigned int x=2; x<MOD; x++) if(ExamineVal(x)) return x;\n return 0;\n }\n static const unsigned int val = GetVal();\n};\n\n} // namespace nachia\n#line 1 \"nachia\\\\fps\\\\ntt-interface.hpp\"\n#include <algorithm>\n\nnamespace nachia {\n\ntemplate<class mint>\nstruct NttInterface{\n\ntemplate<class Iter>\nvoid Butterfly(Iter, int) const {}\n\ntemplate<class Iter>\nvoid IButterfly(Iter, int) const {}\n\ntemplate<class Iter>\nvoid BitReversal(Iter a, int N) const {\n for(int i=0, j=0; j<N; j++){\n if(i < j) std::swap(a[i], a[j]);\n for(int k = N>>1; k > (i^=k); k>>=1);\n }\n}\n\n};\n\n} // namespace nachia\n#line 4 \"nachia\\\\misc\\\\bit-operations.hpp\"\n\nnamespace nachia{\n\nint Popcount(unsigned long long c) noexcept {\n#ifdef __GNUC__\n return __builtin_popcountll(c);\n#else\n c = (c & (~0ull/3)) + ((c >> 1) & (~0ull/3));\n c = (c & (~0ull/5)) + ((c >> 2) & (~0ull/5));\n c = (c & (~0ull/17)) + ((c >> 4) & (~0ull/17));\n c = (c * (~0ull/257)) >> 56;\n return c;\n#endif\n}\n\n// please ensure x != 0\nint MsbIndex(unsigned long long x) noexcept {\n#ifdef __GNUC__\n return 63 - __builtin_clzll(x);\n#else\n int res = 0;\n for(int d=32; d>0; d>>=1) if(x >> d){ res |= d; x >>= d; }\n return res;\n#endif\n}\n\n// please ensure x != 0\nint LsbIndex(unsigned long long x) noexcept {\n#ifdef __GNUC__\n return __builtin_ctzll(x);\n#else\n return MsbIndex(x & -x);\n#endif\n}\n\n}\n\n#line 5 \"nachia\\\\bigint\\\\ntt.hpp\"\n#include <iterator>\n#include <cassert>\n#line 8 \"nachia\\\\bigint\\\\ntt.hpp\"\n#include <array>\n\nnamespace nachia{\nnamespace bigint{\n\nconstexpr int bsf_constexpr(unsigned int n) {\n\tint x = 0;\n\twhile (!(n & (1 << x))) x++;\n\treturn x;\n}\n\ntemplate <class mint>\nstruct NttFromAcl : NttInterface<mint> {\n\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\n \nstatic int ceil_pow2(int n) {\n\tint x = 0;\n\twhile ((1U << x) < (u32)(n)) x++;\n\treturn x;\n}\n\nstruct fft_info {\n\tstatic constexpr u32 g = nachia::PrimitiveRoot<mint::GetMod()>::val;\n\tstatic constexpr int rank2 = bsf_constexpr(mint::GetMod()-1);\n\tstd::array<mint, rank2+1> root;\n\tstd::array<mint, rank2+1> iroot;\n\n\tstd::array<mint, std::max(0, rank2-1)> rate2;\n\tstd::array<mint, std::max(0, rank2-1)> irate2;\n\n\tstd::array<mint, std::max(0, rank2-2)> rate3;\n\tstd::array<mint, std::max(0, rank2-2)> irate3;\n\n\tfft_info(){\n\t\troot[rank2] = mint(g).pow((mint::GetMod() - 1) >> rank2);\n\t\tiroot[rank2] = root[rank2].inv();\n\t\tfor(int i=rank2-1; i>=0; i--){\n\t\t\troot[i] = root[i+1] * root[i+1];\n\t\t\tiroot[i] = iroot[i+1] * iroot[i+1];\n\t\t}\n\t\tmint prod = 1u, iprod = 1u;\n\t\tfor(int i=0; i<=rank2-2; i++){\n\t\t\trate2[i] = root[i+2] * prod;\n\t\t\tirate2[i] = iroot[i+2] * iprod;\n\t\t\tprod *= iroot[i+2];\n\t\t\tiprod *= root[i+2];\n\t\t}\n\t\tprod = 1u; iprod = 1u;\n\t\tfor(int i=0; i<=rank2-3; i++){\n\t\t\trate3[i] = root[i+3] * prod;\n\t\t\tirate3[i] = iroot[i+3] * iprod;\n\t\t\tprod *= iroot[i+3];\n\t\t\tiprod *= root[i+3];\n\t\t}\n\t}\n};\n\ntemplate<class RandomAccessIterator>\nvoid Butterfly(RandomAccessIterator a, int n) const {\n\tint h = ceil_pow2(n);\n\n\tstatic const fft_info info;\n\n\tint len = 0;\n\twhile(len < h){\n\t\tif(h-len == 1){\n\t\t\tint p = 1 << (h-len-1);\n\t\t\tmint rot = 1u;\n\t\t\tfor(int s=0; s<(1<<len); s++){\n\t\t\t\tint offset = s << (h-len);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto l = a[i+offset];\n\t\t\t\t\tauto r = a[i+offset+p] * rot;\n\t\t\t\t\ta[i+offset] = l+r;\n\t\t\t\t\ta[i+offset+p] = l-r;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<len)) rot *= info.rate2[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen++;\n\t\t} else {\n\t\t\tint p = 1 << (h-len-2);\n\t\t\tmint rot = 1u, imag = info.root[2];\n\t\t\tfor(int s=0; s<(1<<len); s++){\n\t\t\t\tmint rot2 = rot * rot;\n\t\t\t\tmint rot3 = rot2 * rot;\n\t\t\t\tint offset = s << (h-len);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto a0 = a[i+offset];\n\t\t\t\t\tauto a1 = a[i+offset+p] * rot;\n\t\t\t\t\tauto a2 = a[i+offset+2*p] * rot2;\n\t\t\t\t\tauto a3 = a[i+offset+3*p] * rot3;\n\t\t\t\t\tauto a0a2 = a0 + a2;\n\t\t\t\t\tauto a0b2 = a0 - a2;\n\t\t\t\t\tauto a1a3 = a1 + a3;\n\t\t\t\t\tauto a1na3imag = (a1 - a3) * imag;\n\t\t\t\t\ta[i+offset] = a0a2 + a1a3;\n\t\t\t\t\ta[i+offset+1*p] = a0a2 - a1a3;\n\t\t\t\t\ta[i+offset+2*p] = a0b2 + a1na3imag;\n\t\t\t\t\ta[i+offset+3*p] = a0b2 - a1na3imag;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<len)) rot *= info.rate3[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen += 2;\n\t\t}\n\t}\n}\n\ntemplate<class RandomAccessIterator>\nvoid IButterfly(RandomAccessIterator a, int n) const {\n\tint h = ceil_pow2(n);\n\n\tstatic const fft_info info;\n\n\tint len = h;\n\twhile(len){\n\t\tif(len == 1){\n\t\t\tint p = 1 << (h-len);\n\t\t\tmint irot = 1u;\n\t\t\tfor(int s=0; s<(1<<(len-1)); s++){\n\t\t\t\tint offset = s << (h-len+1);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto l = a[i+offset];\n\t\t\t\t\tauto r = a[i+offset+p];\n\t\t\t\t\ta[i+offset] = l+r;\n\t\t\t\t\ta[i+offset+p] = (l-r)*irot;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<(len-1))) irot *= info.irate2[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen--;\n\t\t} else {\n\t\t\tint p = 1 << (h-len);\n\t\t\tmint irot = 1u, iimag = info.iroot[2];\n\t\t\tfor(int s=0; s<(1<<(len-2)); s++){\n\t\t\t\tmint irot2 = irot * irot;\n\t\t\t\tmint irot3 = irot2 * irot;\n\t\t\t\tint offset = s << (h-len+2);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto a0 = a[i+offset+0*p];\n\t\t\t\t\tauto a1 = a[i+offset+1*p];\n\t\t\t\t\tauto a2 = a[i+offset+2*p];\n\t\t\t\t\tauto a3 = a[i+offset+3*p];\n\t\t\t\t\tauto a0a1 = a0 + a1;\n\t\t\t\t\tauto a0b1 = a0 - a1;\n\t\t\t\t\tauto a2a3 = a2 + a3;\n\t\t\t\t\tauto a2na3iimag = (a2 - a3) * iimag;\n\n\t\t\t\t\ta[i+offset] = a0a1 + a2a3;\n\t\t\t\t\ta[i+offset+1*p] = (a0b1 + a2na3iimag) * irot;\n\t\t\t\t\ta[i+offset+2*p] = (a0a1 - a2a3) * irot2;\n\t\t\t\t\ta[i+offset+3*p] = (a0b1 - a2na3iimag) * irot3;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<(len-2))) irot *= info.irate3[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen -= 2;\n\t\t}\n\t}\n}\n\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 3 \"nachia\\\\bigint\\\\static-p-modint.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\ntemplate<unsigned int MxVal>\nclass Montgomery32Info{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static constexpr u32 u32inverse(u32 x){\n u32 v = 1;\n for(int i=0; i<5; i++) v = v * ((u32)2 - v * x);\n return v;\n }\n static constexpr u32 getMy(u32 mx){ return (-mx) % mx; }\n static constexpr u32 powMod(u32 a, u32 i, u32 m){\n if(i == 0) return 1 % m;\n if(i % 2 == 0) return powMod((u64)a*a%m, i/2, m);\n return (u64)a*powMod((u64)a*a%m, i/2, m)%m;\n }\n static constexpr u32 Mx = MxVal;\n static constexpr u32 iMx = u32inverse(Mx);\n static constexpr u32 My1 = getMy(Mx);\n static constexpr u32 My2 = powMod(getMy(Mx), 2, Mx);\n static constexpr u32 My3 = powMod(getMy(Mx), 3, Mx);\n // return z\n // + z % Mx == x % Mx\n // + x <= max(x>>32, Mx-1)\n static constexpr u32 red(u64 x){\n u32 z1 = x >> 32;\n u32 z2 = ((u64)Mx * ((u32)x*iMx)) >> 32;\n return z1 - z2 + (z1 < z2 ? Mx : 0);\n }\n};\n\ntemplate<unsigned int MOD>\nclass StaticPModint{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\nprivate:\n static constexpr u32 mod = MOD;\n using Tool = Montgomery32Info<MOD>;\n using MyType = StaticPModint;\n u32 _v;\n static MyType RAW(u32 v) { auto res = StaticPModint(); res._v = v; return res; }\npublic:\n StaticPModint() : _v(0) {}\n StaticPModint(u32 v) : _v(Tool::red((u64)v * Tool::My2)) {}\n StaticPModint(u64 v) : _v(Tool::red((u64)Tool::My3 * Tool::red(v))) {}\n u32 val() const { return Tool::red(_v); }\n u32 mrVal() const { return _v; }\n MyType& operator-=(MyType r) { _v = _v - r._v + (_v < r._v ? mod : 0); return *this; }\n MyType& operator+=(MyType r) { u32 t = mod - r._v; _v = _v - t + (_v < t ? mod : 0); return *this; }\n MyType& operator*=(MyType r) { _v = Tool::red((u64)_v * r._v); return *this; }\n MyType operator+(MyType r) const { auto v = *this; v += r; return v; }\n MyType operator-(MyType r) const { auto v = *this; v -= r; return v; }\n MyType operator*(MyType r) const { auto v = *this; v *= r; return v; }\n MyType operator-() const { return RAW(_v ? mod - _v : (u32)0); }\n MyType pow(unsigned long long i) const {\n MyType x = *this, r = RAW(Tool::My1);\n while(i){ if(i&1){ r *= x; } x*=x; i>>=1; }\n return r;\n }\n MyType inv() const { return pow(mod-2); }\n static constexpr u32 GetMod() { return mod; }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 2 \"nachia\\\\bigint\\\\dynamic-p-modint.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nclass DynMontgomery32Info{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static u32 u32inverse(u32 x) {\n u32 v = 1;\n for(int i=0; i<5; i++) v = v * ((u32)2 - v * x);\n return v;\n }\n static u32 getMy(u32 mx) { return (-mx) % mx; }\n static u32 powMod(u32 a, u32 i, u32 m) {\n if(i == 0) return 1 % m;\n if(i % 2 == 0) return powMod((u64)a*a%m, i/2, m);\n return (u64)a*powMod((u64)a*a%m, i/2, m)%m;\n }\n const u32 Mx;\n const u32 iMx;\n const u32 My1;\n const u32 My2;\n const u32 My3;\n DynMontgomery32Info(u32 newMod)\n : Mx(newMod)\n , iMx(u32inverse(Mx))\n , My1(getMy(Mx))\n , My2((u64)My1 * My1 % Mx)\n , My3((u64)My2 * My1 % Mx) {}\n\n // return z\n // + z % Mx == x % Mx\n // + x <= max(x>>32, Mx-1)\n u32 red(u64 x) const {\n u32 z1 = x >> 32;\n u32 z2 = ((u64)Mx * ((u32)x*iMx)) >> 32;\n return z1 - z2 + (z1 < z2 ? Mx : 0);\n }\n u32 add(u32 a, u32 b) const { b = Mx-b; return a - b + ((a < b) ? Mx : 0u); }\n u32 sub(u32 a, u32 b) const { return a - b + ((a < b) ? Mx : 0u); }\n u32 mul(u32 a, u32 b) const { return red((u64)a * b); }\n u32 pow(u32 a, u32 i) const {\n u32 x = a, r = My1;\n while(i){ if(i&1){ r=mul(r,x); } x=mul(x,x); i>>=1; }\n return r;\n }\n u32 inv(u32 a) const { return pow(a, Mx-2); }\n u32 input64(u64 a) const { return mul(red(a), My3); }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\garner.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nstruct GarnerU96{\n using u32 = unsigned int;\n using u64 = unsigned long long;\n std::vector<u32> mods;\n std::vector<DynMontgomery32Info> dynmods;\n std::vector<std::vector<u32>> table_coeff;\n std::vector<u32> table_coeffinv;\n\n void precalc(std::vector<u32> new_mods){\n mods = std::move(new_mods);\n for(std::size_t i=0; i<mods.size(); i++) dynmods.emplace_back(mods[i]);\n int nmods = mods.size();\n table_coeff.assign(nmods+1, std::vector<u32>(nmods, 0));\n for(int k=0; k<nmods; k++) table_coeff[0][k] = dynmods[k].My2;\n for(int j=0; j<nmods; j++){\n for(int k=0; k<nmods; k++) table_coeff[j+1][k] = table_coeff[j][k];\n for(int k=j+1; k<nmods; k++) table_coeff[j+1][k] = dynmods[k].mul(table_coeff[j+1][k], dynmods[k].input64(mods[j]));\n }\n table_coeffinv.resize(nmods);\n for(int i=0; i<nmods; i++) table_coeffinv[i] = dynmods[i].inv(table_coeff[i][i]);\n }\n\n u64 calc(const std::vector<u32>& x){\n int nmods = mods.size();\n std::vector<u32> table_const(nmods);\n u64 res = 0;\n u64 res_coeff = 1;\n for(int j=0; j<nmods; j++){\n u32 t = dynmods[j].mul(dynmods[j].sub(x[j], table_const[j]), table_coeffinv[j]);\n for(int k=j+1; k<nmods; k++){\n table_const[k] = dynmods[k].add(dynmods[k].mul(t, table_coeff[j][k]), table_const[k]);\n }\n res += res_coeff * u64(t);\n res_coeff *= mods[j];\n }\n return res;\n }\n\n std::pair<std::vector<u32>, std::vector<u64>> calc(std::vector<std::vector<u32>> x){\n int n = x[0].size(), m = x.size();\n std::vector<u64> resl(n);\n std::vector<u32> resh(n);\n std::vector<u32> buf(m);\n u32 inv64 = dynmods[0].inv(dynmods[0].mul(dynmods[0].My3, dynmods[0].My2));\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++) buf[j] = x[j][i];\n resl[i] = calc(buf);\n resh[i] = dynmods[0].mul(dynmods[0].sub(buf[0], dynmods[0].input64(resl[i])), inv64);\n }\n return std::make_pair(std::move(resh), std::move(resl));\n }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\convolution.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nstruct MultiplySupply {\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static constexpr u32 MODCNT = 3;\n static constexpr u32 MOD[3] = { 3892314113, 3489660929, 3221225473 };\n \n GarnerU96 garner;\n\n MultiplySupply(){\n garner.precalc(std::vector<u32>(MOD, MOD + MODCNT));\n }\n \n template<unsigned int P>\n static std::vector<u32> SubConvolution(\n const std::vector<u32>& a,\n const std::vector<u32>& b\n ) {\n using Elem = StaticPModint<P>;\n static NttFromAcl<Elem> ntt;\n int z = a.size() + b.size() - 1;\n int N = 1; while(N < z) N *= 2;\n std::vector<Elem> A(N), B(N);\n for(std::size_t i=0; i<a.size(); i++) A[i] = a[i];\n for(std::size_t i=0; i<b.size(); i++) B[i] = b[i];\n Elem iN = Elem((u32)N).inv();\n ntt.Butterfly(A.begin(), N);\n ntt.Butterfly(B.begin(), N);\n for(int i=0; i<N; i++) A[i] = A[i] * B[i] * iN;\n ntt.IButterfly(A.begin(), N);\n std::vector<u32> res(z);\n for(int i=0; i<z; i++) res[i] = A[i].mrVal();\n return res;\n }\n \n std::vector<u32> multiplyBin(\n const std::vector<u32>& a,\n const std::vector<u32>& b\n ){\n if(a.empty() || b.empty()) return {};\n std::vector<std::vector<u32>> cx(MODCNT);\n cx[0] = SubConvolution<MOD[0]>(a, b);\n cx[1] = SubConvolution<MOD[1]>(a, b);\n cx[2] = SubConvolution<MOD[2]>(a, b);\n auto q = garner.calc(std::move(cx));\n int n = q.first.size();\n std::vector<u32> res(n + 2);\n for(int i=0; i<n; i++) res[i] = q.second[i];\n u64 c = 0;\n for(int i=0; i<n; i++){ res[i+1] = c += (u64)res[i+1] + (q.second[i] >> 32); c >>= 32; }\n res[n+1] = c; c = 0;\n for(int i=0; i<n; i++){ res[i+2] = c += (u64)res[i+2] + q.first[i]; c >>= 32; }\n while(res.size() && res.back() == 0) res.pop_back();\n return res;\n }\n \n std::vector<u32> multiplyDec(\n std::vector<u32> a,\n std::vector<u32> b\n ){\n static constexpr u32 d = 1000000000;\n if(a.empty() || b.empty()) return {};\n std::vector<std::vector<u32>> cx(MODCNT);\n cx[0] = SubConvolution<MOD[0]>(a, b);\n cx[1] = SubConvolution<MOD[1]>(a, b);\n cx[2] = SubConvolution<MOD[2]>(a, b);\n auto q0 = garner.calc(std::move(cx));\n int n = q0.first.size();\n std::vector<u64> buf(n + 2);\n static constexpr u32 j11 = (1ull << 32) / d;\n static constexpr u32 j10 = (-d) % d;\n static constexpr u32 j22 = 1 + (0ull- 1ull * d * d) / d / d;\n static constexpr u32 j21 = (-1ull * j22 * d * d) / d;\n static constexpr u32 j20 = (0ull-d) % d;\n for(int i=0; i<n; i++) buf[i] = q0.second[i] & ((1ull << 32) - 1);\n for(int i=0; i<n; i++) buf[i] += 1ull * (q0.second[i] >> 32) * j10;\n for(int i=0; i<n; i++) buf[i+1] += 1ull * (q0.second[i] >> 32) * j11;\n for(int i=0; i<n; i++) buf[i] += 1ull * q0.first[i] * j20; // q0.first[i] is small enough\n for(int i=0; i<n; i++) buf[i+1] += 1ull * q0.first[i] * j21;\n for(int i=0; i<n; i++) buf[i+2] += 1ull * q0.first[i] * j22;\n std::vector<u32> res(n + 2);\n u64 c = 0;\n for(int i=0; i<n+2; i++){ c += buf[i]; res[i] = c % d; c /= d; }\n while(res.size() && res.back() == 0) res.pop_back();\n return res;\n }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\base-operators.hpp\"\n#include <iostream>\n\nnamespace nachia {\nnamespace bigint {\n\nclass UIntDec {\npublic:\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nstd::vector<u32> x;\nstatic constexpr u32 BASE = 1'000'000'000;\n\nvoid Regularize(){ while(!x.empty() & !x.back()) x.pop_back(); }\n\nUIntDec() = default;\nUIntDec(std::vector<u32> _x) : x(std::move(_x)) {}\nUIntDec& operator+=(const UIntDec& b){\n x.resize(std::max(x.size(), b.x.size()) + 1);\n u64 c = 0;\n for(std::size_t i=0; i<b.x.size(); i++){\n c += b.x[i]; c += x[i];\n if(c >= BASE){ x[i] = c - BASE; c = 1; }\n else{ x[i] = c; c = 0; }\n }\n for(int i=b.x.size(); c; i++){\n c += x[i];\n if(c >= BASE){\n x[i] = c - BASE;\n c = 1;\n } else {\n x[i] = c;\n c = 0;\n break;\n }\n }\n Regularize();\n return *this;\n}\nUIntDec operator*(const UIntDec& b) const { return MultiplySupply().multiplyDec(x, b.x); }\n\nUIntDec Pow(u32 c) const {\n if(c == 0) return std::vector<u32>{1};\n if(c == 1) return *this;\n auto aa = Pow(c/2);\n aa = aa * aa;\n return (c&1) ? aa * (*this) : aa;\n}\nvoid mulU32(unsigned int cx) {\n u64 c = cx;\n for(std::size_t i=0; i<x.size(); i++){ c += (u64)x[i] << 32; x[i] = c % BASE; c /= BASE; }\n while(c){ x.push_back(c % BASE); c /= BASE; }\n}\n\n};\n\nclass UIntBin {\npublic:\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nstd::vector<u32> x;\n\nvoid Regularize(){ while(!x.empty() & !x.back()) x.pop_back(); }\n\nUIntBin() = default;\nUIntBin(std::vector<u32> _x) : x(std::move(_x)) {}\nUIntBin& operator+=(const UIntBin& b){\n x.resize(std::max(x.size(), b.x.size()) + 1);\n u64 c = 0;\n for(std::size_t i=0; i<b.x.size(); i++){\n c += b.x[i]; c += x[i];\n x[i] = c; c >>= 32;\n }\n for(int i=b.x.size(); c; i++){ x[i] = c += x[i]; c >>= 32; }\n Regularize();\n return *this;\n}\nUIntBin operator*(const UIntBin& b) const { return MultiplySupply().multiplyBin(x, b.x); }\n\nUIntBin Pow(u32 c) const {\n if(c == 0) return std::vector<u32>{1};\n if(c == 1) return *this;\n auto aa = Pow(c/2);\n aa = aa * aa;\n return (c&1) ? aa * (*this) : aa;\n}\nvoid mulD(unsigned int d, unsigned int cx) {\n u64 c = cx;\n for(std::size_t i=0; i<x.size(); i++){ x[i] = (c += (u64)x[i] * d); c >>= 32; }\n if(c) x.push_back(c);\n}\n\n};\n\nstd::vector<unsigned int> DecToBin(std::string decstr){\n std::vector<UIntBin> pdec;\n auto dfs = [&](auto& dfs, int l, int r) -> UIntBin {\n if(r - l <= 308){\n UIntBin p;\n for(int j=l; j<l+(r-l)%9; j++) p.mulD(10, decstr[j] - '0');\n for(int j=l+(r-l)%9; j<r; j+=9) p.mulD(1000000000, std::stoi(decstr.substr(j, 9)));\n return p;\n }\n if(pdec.empty()) pdec.push_back(UIntBin({10}).Pow(308));\n int h = 0; while(((308*2)<<h) < r-l) h++;\n while((int)pdec.size() < h+1) pdec.push_back(pdec.back() * pdec.back());\n auto res = dfs(dfs, l, r-(308<<h)) * pdec[h];\n res += dfs(dfs, r-(308<<h), r);\n return res;\n };\n return std::move(dfs(dfs, 0, decstr.size()).x);\n}\n\nstd::string BinToDec(std::vector<unsigned int> b){\n while(!b.empty() && !b.back()) b.pop_back();\n std::reverse(b.begin(), b.end());\n if(b.empty()) return \"0\";\n std::vector<UIntDec> pbin;\n auto dfs = [&](auto& dfs, int l, int r) -> UIntDec {\n if(r - l <= 29){\n UIntDec p;\n for(int j=l; j<r; j++) p.mulU32(b[j]);\n return p;\n }\n if(pbin.empty()) pbin.push_back(UIntDec({2}).Pow(32*29));\n int h = 0; while(((29*2)<<h) < r-l) h++;\n while((int)pbin.size() < h+1) pbin.push_back(pbin.back() * pbin.back());\n auto res = dfs(dfs, l, r-(29<<h)) * pbin[h];\n res += dfs(dfs, r-(29<<h), r);\n return res;\n };\n auto x = std::move(dfs(dfs, 0, b.size()).x);\n while(!x.empty() && !x.back()) x.pop_back();\n std::string res = std::to_string(x.back());\n res.resize(res.size() + 9 * (int)(x.size()-1), '0');\n for(int i=(int)x.size()-2; i>=0; i--){\n int o = res.size() - i*9 - 9;\n for(int j=o+8; j>=o; j--){ res[j] += x[i] % 10; x[i] /= 10; }\n }\n return res;\n}\n\n} // namespace bigint\n} // namespace nachia\n#line 4 \"nachia\\\\bigint\\\\integer.hpp\"\n\nnamespace nachia{\n\nclass UnsignedIntegerBin{\npublic:\n using MyType = UnsignedIntegerBin;\n friend class SignedIntegerBin;\nprivate:\n using u32 = uint32_t;\n using u64 = uint64_t;\n std::vector<u32> x;\n static inline bool Cflag;\n static MyType FromVec(std::vector<u32> _x){ MyType res; res.x = std::move(_x); return res; }\npublic:\n UnsignedIntegerBin(){}\n MyType operator>>(int sh) const {\n int h = sh / 32, l = sh % 32;\n MyType res; res.memreserve(size() - h);\n for(int i=h; i<size(); i++) res[i-h] = x[i] >> l;\n if(l) for(int i=h+1; i<size(); i++) res[i-h-1] |= x[i] << (32-l);\n res.regularize();\n return res;\n }\n MyType operator<<(int sh) const {\n int h = sh / 32, l = sh % 32;\n MyType res; res.memreserve(size() + h + 1);\n for(int i=0; i<size(); i++) res[i+h] = x[i] << l;\n if(l) for(int i=0; i<size(); i++) res[i+h+1] |= x[i] >> (32-l);\n res.regularize();\n return res;\n }\n MyType& operator>>=(int sh) { return (*this) = operator>>(sh); }\n MyType& operator<<=(int sh) { return (*this) = operator<<(sh); }\n MyType& operator%=(const MyType& d) { divInternal(d); return *this; }\n MyType operator%(const MyType& d) const { auto p = *this; return p.divInternal(d); }\n MyType operator/(const MyType& d) const { auto p = *this; return p.divInternal(d); }\n MyType& operator/=(const MyType& d) { return (*this) = divInternal(d); }\n MyType& operator+=(const MyType& v){\n memreserve(std::max(size(), v.size()) + 1);\n u64 c = 0;\n for(int i=0; i<v.size(); i++){ x[i] = (c += (u64)x[i] + v[i]); c >>= 32; }\n for(int i=v.size(); c; i++){ x[i] = c += x[i]; c >>= 32; }\n regularize();\n return *this;\n }\n MyType& operator-=(const MyType& v){\n memreserve(std::max(size(), v.size()));\n u64 c = 0;\n for(int i=0; i<v.size(); i++){\n c += v[i];\n x[i] -= c;\n c = (c + x[i]) >> 32;\n }\n for(int i=v.size(); i<size() && c; i++){\n x[i] -= c;\n c = (c + x[i]) >> 32;\n }\n Cflag = c;\n if(c){ complement(); increment(); }\n regularize();\n return *this;\n }\n MyType operator*(const MyType& v) const {\n MyType res;\n res.x = bigint::MultiplySupply().multiplyBin(x, v.x);\n res.regularize();\n return res;\n }\n MyType& operator*=(const MyType& r) { return (*this) = operator*(r); }\n MyType operator+(const MyType& r) { auto p = *this; p += r; return p; }\n MyType operator-(const MyType& r) { auto p = *this; p -= r; return p; }\n bool operator<(const MyType& r) const {\n return (size() != r.size())\n ? (size() < r.size())\n : std::lexicographical_compare(x.rbegin(), x.rend(), r.x.rbegin(), r.x.rend());\n }\n bool operator>(const MyType& r) const { return r < (*this); }\n bool operator<=(const MyType& r) const { return !(r < (*this)); }\n bool operator>=(const MyType& r) const { return !operator<(r); }\n bool operator==(const MyType& r) const { return x == r.x; }\n bool operator!=(const MyType& r) const { return x != r.x; }\n bool operator!() const { return size(); }\n bool isZero() const { return size() == 0; }\n std::string toStringBin() const {\n std::string res;\n for(int i=size()-1; i>=0; i--) for(int j=31; j>=0; j--) res.push_back('0' + (x[i]>>j) % 2);\n return res;\n }\n std::string toStringDec() const {\n if(isZero()) return \"0\";\n \n //auto p = *this;\n //std::string s;\n //while(!p.isZero()) s.push_back('0' + p.div10());\n //std::reverse(s.begin(), s.end());\n //return s;\n \n return bigint::BinToDec(x);\n }\n static MyType FromStringDec(const std::string& s) {\n return FromVec(bigint::DecToBin(s));\n }\n int lsb() const { for(int i=0; i<size(); i++){ if(x[i]) return nachia::LsbIndex(x[i]) + i * 32; } return -1; }\n int msb() const { for(int i=size()-1; i>=0; i--){ if(x[i]) return nachia::MsbIndex(x[i]) + i * 32; } return -1; }\nprivate:\n int size() const { return x.size(); }\n u32& operator[](int at) { return x[at]; }\n u32 operator[](int at) const { return x[at]; }\n void memreserve(int sz) { if((int)x.size() < sz) x.resize(sz); }\n void setBit(int at, bool val){ memreserve(at/32+1); x[at/32] |= (u32)(val?1:0) << (at%32); regularize(); }\n MyType divInternal(const MyType& d) {\n if(d.isZero()) throw 1;\n MyType res;\n for(int s=(size()-d.size())*32+31; s>=0; s--){\n MyType x = d << s;\n if(operator>=(x)){\n res.setBit(s, true); operator-=(x);\n }\n }\n res.regularize();\n return res;\n }\n void complement() { for(u32& y:x){ y = ~y; } }\n void increment() { if(isZero()){ x = {1}; return; } int i=0; while(i < size() && !~x[i]){ x[i++]++; } if(i>=size()){ x.push_back(1); } else x[i]++; }\n void decrement() { if(isZero()){ x = {1}; return; } int i=0; while(x[i]){ x[i++]--; } x[i]--; regularize(); }\n void regularize() { while(!x.empty() && 0 == x.back()) x.pop_back(); }\n int div10() {\n u64 c = 0;\n for(int i=size()-1; i>=0; i--){\n c = (c << 32) | x[i];\n x[i] = c / 10;\n c %= 10;\n }\n regularize();\n return c;\n }\n void mul10(int d) {\n u64 c = d;\n for(int i=0; i<size(); i++){ x[i] = (c += (u64)x[i] * 10); c >>= 32; }\n if(c) x.push_back(c);\n }\n};\n\nclass SignedIntegerBin{\n using MyType = SignedIntegerBin;\n using UInt = UnsignedIntegerBin;\nprivate:\n UInt u;\n int sign = 1;\n void regularize(){ u.regularize(); if(u.isZero()) sign = 1; }\n static MyType Raw(UInt u, int s){ MyType res; res.u = std::move(u); res.sign = s; res.regularize(); return res; }\npublic:\n bool isZero() const { return u.isZero(); }\n MyType& operator+=(const MyType& r) {\n if(sign == r.sign) u += r.u;\n else{ u -= r.u; if(u.Cflag){ sign = -sign; } }\n regularize();\n return *this;\n }\n MyType& operator-=(const MyType& r) {\n if(sign != r.sign) u += r.u;\n else{ u -= r.u; if(u.Cflag){ sign = -sign; } }\n regularize();\n return *this;\n }\n MyType operator*(const MyType& r) const { return Raw(u*r.u, sign*r.sign); }\n MyType& operator*=(const MyType& r) { return (*this) = operator*(r); }\n MyType operator+(const MyType& r) const { auto p = *this; p += r; return p; }\n MyType operator-(const MyType& r) const { auto p = *this; p -= r; return p; }\n MyType operator-() const { return Raw(u, -sign); }\n MyType& operator<<=(int sh) { u <<= sh; return *this; }\n MyType& operator>>=(int sh) { u >>= sh; return *this; }\n MyType operator<<(int sh) const { return Raw(u<<sh, sign); }\n MyType operator>>(int sh) const { return Raw(u<<sh, sign); }\n MyType operator/(const MyType& r) const { return Raw(u/r.u, sign*r.sign); }\n MyType& operator/=(const MyType& r) { return (*this) = operator/(r); }\n MyType operator%(const MyType& r) const { return Raw(u%r.u, sign*r.sign); }\n MyType& operator%=(const MyType& r) { return (*this) = operator%(r); }\n std::string toStringDec() const {\n if(isZero()) return \"0\";\n return (sign>0 ? \"\" : \"-\") + u.toStringDec();\n }\n static MyType FromStringDec(const std::string& s) {\n if(s.empty()) return MyType();\n if(s[0] == '+') return Raw(UInt::FromStringDec(s.substr(1)), 1);\n if(s[0] == '-') return Raw(UInt::FromStringDec(s.substr(1)), -1);\n return Raw(UInt::FromStringDec(s), 1);\n }\n};\n\n} // namespace nachia\n#line 2 \"Main.cpp\"\n#include <cstdint>\n#line 5 \"Main.cpp\"\n#include <string>\n#line 7 \"Main.cpp\"\n\n\nint main() {\n using Int = nachia::SignedIntegerBin;\n std::string s;\n std::cin >> s;\n Int a = Int::FromStringDec(s);\n std::cin >> s;\n Int b = Int::FromStringDec(s);\n Int c = a + b;\n std::cout << c.toStringDec() << '\\n';\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 4312, "score_of_the_acc": -0.0825, "final_rank": 5 }, { "submission_id": "aoj_NTL_2_A_7338649", "code_snippet": "#line 2 \"nachia\\\\math-modulo\\\\modulo-primitive-root.hpp\"\n#include <vector>\n#include <utility>\n\nnamespace nachia{\n\ntemplate<unsigned int MOD>\nstruct PrimitiveRoot{\n using u64 = unsigned long long;\n static constexpr u64 powm(u64 a, u64 i) {\n u64 res = 1, aa = a;\n while(i){\n if(i & 1) res = res * aa % MOD;\n aa = aa * aa % MOD;\n i /= 2;\n }\n return res;\n }\n static constexpr bool ExamineVal(unsigned int g){\n unsigned int t = MOD - 1;\n for(u64 d=2; d*d<=t; d++) if(t % d == 0){\n if(powm(g, (MOD - 1) / d) == 1) return false;\n while(t % d == 0) t /= d;\n }\n if(t != 1) if(powm(g, (MOD - 1) / t) == 1) return false;\n return true;\n }\n static constexpr unsigned int GetVal(){\n for(unsigned int x=2; x<MOD; x++) if(ExamineVal(x)) return x;\n return 0;\n }\n static const unsigned int val = GetVal();\n};\n\n} // namespace nachia\n#line 1 \"nachia\\\\fps\\\\ntt-interface.hpp\"\n#include <algorithm>\n\nnamespace nachia {\n\ntemplate<class mint>\nstruct NttInterface{\n\ntemplate<class Iter>\nvoid Butterfly(Iter, int) const {}\n\ntemplate<class Iter>\nvoid IButterfly(Iter, int) const {}\n\ntemplate<class Iter>\nvoid BitReversal(Iter a, int N) const {\n for(int i=0, j=0; j<N; j++){\n if(i < j) std::swap(a[i], a[j]);\n for(int k = N>>1; k > (i^=k); k>>=1);\n }\n}\n\n};\n\n} // namespace nachia\n#line 4 \"nachia\\\\misc\\\\bit-operations.hpp\"\n\nnamespace nachia{\n\nint Popcount(unsigned long long c) noexcept {\n#ifdef __GNUC__\n return __builtin_popcountll(c);\n#else\n c = (c & (~0ull/3)) + ((c >> 1) & (~0ull/3));\n c = (c & (~0ull/5)) + ((c >> 2) & (~0ull/5));\n c = (c & (~0ull/17)) + ((c >> 4) & (~0ull/17));\n c = (c * (~0ull/257)) >> 56;\n return c;\n#endif\n}\n\n// please ensure x != 0\nint MsbIndex(unsigned long long x) noexcept {\n#ifdef __GNUC__\n return 63 - __builtin_clzll(x);\n#else\n int res = 0;\n for(int d=32; d>0; d>>=1) if(x >> d){ res |= d; x >>= d; }\n return res;\n#endif\n}\n\n// please ensure x != 0\nint LsbIndex(unsigned long long x) noexcept {\n#ifdef __GNUC__\n return __builtin_ctzll(x);\n#else\n return MsbIndex(x & -x);\n#endif\n}\n\n}\n\n#line 5 \"nachia\\\\bigint\\\\ntt.hpp\"\n#include <iterator>\n#include <cassert>\n#line 8 \"nachia\\\\bigint\\\\ntt.hpp\"\n#include <array>\n\nnamespace nachia{\nnamespace bigint{\n\nconstexpr int bsf_constexpr(unsigned int n) {\n\tint x = 0;\n\twhile (!(n & (1 << x))) x++;\n\treturn x;\n}\n\ntemplate <class mint>\nstruct NttFromAcl : NttInterface<mint> {\n\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\n \nstatic int ceil_pow2(int n) {\n\tint x = 0;\n\twhile ((1U << x) < (u32)(n)) x++;\n\treturn x;\n}\n\nstruct fft_info {\n\tstatic constexpr u32 g = nachia::PrimitiveRoot<mint::GetMod()>::val;\n\tstatic constexpr int rank2 = bsf_constexpr(mint::GetMod()-1);\n\tstd::array<mint, rank2+1> root;\n\tstd::array<mint, rank2+1> iroot;\n\n\tstd::array<mint, std::max(0, rank2-1)> rate2;\n\tstd::array<mint, std::max(0, rank2-1)> irate2;\n\n\tstd::array<mint, std::max(0, rank2-2)> rate3;\n\tstd::array<mint, std::max(0, rank2-2)> irate3;\n\n\tfft_info(){\n\t\troot[rank2] = mint(g).pow((mint::GetMod() - 1) >> rank2);\n\t\tiroot[rank2] = root[rank2].inv();\n\t\tfor(int i=rank2-1; i>=0; i--){\n\t\t\troot[i] = root[i+1] * root[i+1];\n\t\t\tiroot[i] = iroot[i+1] * iroot[i+1];\n\t\t}\n\t\tmint prod = 1u, iprod = 1u;\n\t\tfor(int i=0; i<=rank2-2; i++){\n\t\t\trate2[i] = root[i+2] * prod;\n\t\t\tirate2[i] = iroot[i+2] * iprod;\n\t\t\tprod *= iroot[i+2];\n\t\t\tiprod *= root[i+2];\n\t\t}\n\t\tprod = 1u; iprod = 1u;\n\t\tfor(int i=0; i<=rank2-3; i++){\n\t\t\trate3[i] = root[i+3] * prod;\n\t\t\tirate3[i] = iroot[i+3] * iprod;\n\t\t\tprod *= iroot[i+3];\n\t\t\tiprod *= root[i+3];\n\t\t}\n\t}\n};\n\ntemplate<class RandomAccessIterator>\nvoid Butterfly(RandomAccessIterator a, int n) const {\n\tint h = ceil_pow2(n);\n\n\tstatic const fft_info info;\n\n\tint len = 0;\n\twhile(len < h){\n\t\tif(h-len == 1){\n\t\t\tint p = 1 << (h-len-1);\n\t\t\tmint rot = 1u;\n\t\t\tfor(int s=0; s<(1<<len); s++){\n\t\t\t\tint offset = s << (h-len);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto l = a[i+offset];\n\t\t\t\t\tauto r = a[i+offset+p] * rot;\n\t\t\t\t\ta[i+offset] = l+r;\n\t\t\t\t\ta[i+offset+p] = l-r;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<len)) rot *= info.rate2[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen++;\n\t\t} else {\n\t\t\tint p = 1 << (h-len-2);\n\t\t\tmint rot = 1u, imag = info.root[2];\n\t\t\tfor(int s=0; s<(1<<len); s++){\n\t\t\t\tmint rot2 = rot * rot;\n\t\t\t\tmint rot3 = rot2 * rot;\n\t\t\t\tint offset = s << (h-len);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto a0 = a[i+offset];\n\t\t\t\t\tauto a1 = a[i+offset+p] * rot;\n\t\t\t\t\tauto a2 = a[i+offset+2*p] * rot2;\n\t\t\t\t\tauto a3 = a[i+offset+3*p] * rot3;\n\t\t\t\t\tauto a0a2 = a0 + a2;\n\t\t\t\t\tauto a0b2 = a0 - a2;\n\t\t\t\t\tauto a1a3 = a1 + a3;\n\t\t\t\t\tauto a1na3imag = (a1 - a3) * imag;\n\t\t\t\t\ta[i+offset] = a0a2 + a1a3;\n\t\t\t\t\ta[i+offset+1*p] = a0a2 - a1a3;\n\t\t\t\t\ta[i+offset+2*p] = a0b2 + a1na3imag;\n\t\t\t\t\ta[i+offset+3*p] = a0b2 - a1na3imag;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<len)) rot *= info.rate3[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen += 2;\n\t\t}\n\t}\n}\n\ntemplate<class RandomAccessIterator>\nvoid IButterfly(RandomAccessIterator a, int n) const {\n\tint h = ceil_pow2(n);\n\n\tstatic const fft_info info;\n\n\tint len = h;\n\twhile(len){\n\t\tif(len == 1){\n\t\t\tint p = 1 << (h-len);\n\t\t\tmint irot = 1u;\n\t\t\tfor(int s=0; s<(1<<(len-1)); s++){\n\t\t\t\tint offset = s << (h-len+1);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto l = a[i+offset];\n\t\t\t\t\tauto r = a[i+offset+p];\n\t\t\t\t\ta[i+offset] = l+r;\n\t\t\t\t\ta[i+offset+p] = (l-r)*irot;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<(len-1))) irot *= info.irate2[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen--;\n\t\t} else {\n\t\t\tint p = 1 << (h-len);\n\t\t\tmint irot = 1u, iimag = info.iroot[2];\n\t\t\tfor(int s=0; s<(1<<(len-2)); s++){\n\t\t\t\tmint irot2 = irot * irot;\n\t\t\t\tmint irot3 = irot2 * irot;\n\t\t\t\tint offset = s << (h-len+2);\n\t\t\t\tfor(int i=0; i<p; i++){\n\t\t\t\t\tauto a0 = a[i+offset+0*p];\n\t\t\t\t\tauto a1 = a[i+offset+1*p];\n\t\t\t\t\tauto a2 = a[i+offset+2*p];\n\t\t\t\t\tauto a3 = a[i+offset+3*p];\n\t\t\t\t\tauto a0a1 = a0 + a1;\n\t\t\t\t\tauto a0b1 = a0 - a1;\n\t\t\t\t\tauto a2a3 = a2 + a3;\n\t\t\t\t\tauto a2na3iimag = (a2 - a3) * iimag;\n\n\t\t\t\t\ta[i+offset] = a0a1 + a2a3;\n\t\t\t\t\ta[i+offset+1*p] = (a0b1 + a2na3iimag) * irot;\n\t\t\t\t\ta[i+offset+2*p] = (a0a1 - a2a3) * irot2;\n\t\t\t\t\ta[i+offset+3*p] = (a0b1 - a2na3iimag) * irot3;\n\t\t\t\t}\n\t\t\t\tif(s+1 != (1<<(len-2))) irot *= info.irate3[LsbIndex(~(u32)(s))];\n\t\t\t}\n\t\t\tlen -= 2;\n\t\t}\n\t}\n}\n\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 3 \"nachia\\\\bigint\\\\static-p-modint.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\ntemplate<unsigned int MxVal>\nclass Montgomery32Info{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static constexpr u32 u32inverse(u32 x){\n u32 v = 1;\n for(int i=0; i<5; i++) v = v * ((u32)2 - v * x);\n return v;\n }\n static constexpr u32 getMy(u32 mx){ return (-mx) % mx; }\n static constexpr u32 powMod(u32 a, u32 i, u32 m){\n if(i == 0) return 1 % m;\n if(i % 2 == 0) return powMod((u64)a*a%m, i/2, m);\n return (u64)a*powMod((u64)a*a%m, i/2, m)%m;\n }\n static constexpr u32 Mx = MxVal;\n static constexpr u32 iMx = u32inverse(Mx);\n static constexpr u32 My1 = getMy(Mx);\n static constexpr u32 My2 = powMod(getMy(Mx), 2, Mx);\n static constexpr u32 My3 = powMod(getMy(Mx), 3, Mx);\n // return z\n // + z % Mx == x % Mx\n // + x <= max(x>>32, Mx-1)\n static constexpr u32 red(u64 x){\n u32 z1 = x >> 32;\n u32 z2 = ((u64)Mx * ((u32)x*iMx)) >> 32;\n return z1 - z2 + (z1 < z2 ? Mx : 0);\n }\n};\n\ntemplate<unsigned int MOD>\nclass StaticPModint{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\nprivate:\n static constexpr u32 mod = MOD;\n using Tool = Montgomery32Info<MOD>;\n using MyType = StaticPModint;\n u32 _v;\n static MyType RAW(u32 v) { auto res = StaticPModint(); res._v = v; return res; }\npublic:\n StaticPModint() : _v(0) {}\n StaticPModint(u32 v) : _v(Tool::red((u64)v * Tool::My2)) {}\n StaticPModint(u64 v) : _v(Tool::red((u64)Tool::My3 * Tool::red(v))) {}\n u32 val() const { return Tool::red(_v); }\n u32 mrVal() const { return _v; }\n MyType& operator-=(MyType r) { _v = _v - r._v + (_v < r._v ? mod : 0); return *this; }\n MyType& operator+=(MyType r) { u32 t = mod - r._v; _v = _v - t + (_v < t ? mod : 0); return *this; }\n MyType& operator*=(MyType r) { _v = Tool::red((u64)_v * r._v); return *this; }\n MyType operator+(MyType r) const { auto v = *this; v += r; return v; }\n MyType operator-(MyType r) const { auto v = *this; v -= r; return v; }\n MyType operator*(MyType r) const { auto v = *this; v *= r; return v; }\n MyType operator-() const { return RAW(_v ? mod - _v : (u32)0); }\n MyType pow(unsigned long long i) const {\n MyType x = *this, r = RAW(Tool::My1);\n while(i){ if(i&1){ r *= x; } x*=x; i>>=1; }\n return r;\n }\n MyType inv() const { return pow(mod-2); }\n static constexpr u32 GetMod() { return mod; }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 2 \"nachia\\\\bigint\\\\dynamic-p-modint.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nclass DynMontgomery32Info{\npublic:\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static u32 u32inverse(u32 x) {\n u32 v = 1;\n for(int i=0; i<5; i++) v = v * ((u32)2 - v * x);\n return v;\n }\n static u32 getMy(u32 mx) { return (-mx) % mx; }\n static u32 powMod(u32 a, u32 i, u32 m) {\n if(i == 0) return 1 % m;\n if(i % 2 == 0) return powMod((u64)a*a%m, i/2, m);\n return (u64)a*powMod((u64)a*a%m, i/2, m)%m;\n }\n const u32 Mx;\n const u32 iMx;\n const u32 My1;\n const u32 My2;\n const u32 My3;\n DynMontgomery32Info(u32 newMod)\n : Mx(newMod)\n , iMx(u32inverse(Mx))\n , My1(getMy(Mx))\n , My2((u64)My1 * My1 % Mx)\n , My3((u64)My2 * My1 % Mx) {}\n\n // return z\n // + z % Mx == x % Mx\n // + x <= max(x>>32, Mx-1)\n u32 red(u64 x) const {\n u32 z1 = x >> 32;\n u32 z2 = ((u64)Mx * ((u32)x*iMx)) >> 32;\n return z1 - z2 + (z1 < z2 ? Mx : 0);\n }\n u32 add(u32 a, u32 b) const { b = Mx-b; return a - b + ((a < b) ? Mx : 0u); }\n u32 sub(u32 a, u32 b) const { return a - b + ((a < b) ? Mx : 0u); }\n u32 mul(u32 a, u32 b) const { return red((u64)a * b); }\n u32 pow(u32 a, u32 i) const {\n u32 x = a, r = My1;\n while(i){ if(i&1){ r=mul(r,x); } x=mul(x,x); i>>=1; }\n return r;\n }\n u32 inv(u32 a) const { return pow(a, Mx-2); }\n u32 input64(u64 a) const { return mul(red(a), My3); }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\garner.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nstruct GarnerU96{\n using u32 = unsigned int;\n using u64 = unsigned long long;\n std::vector<u32> mods;\n std::vector<DynMontgomery32Info> dynmods;\n std::vector<std::vector<u32>> table_coeff;\n std::vector<u32> table_coeffinv;\n\n void precalc(std::vector<u32> new_mods){\n mods = std::move(new_mods);\n for(std::size_t i=0; i<mods.size(); i++) dynmods.emplace_back(mods[i]);\n int nmods = mods.size();\n table_coeff.assign(nmods+1, std::vector<u32>(nmods, 0));\n for(int k=0; k<nmods; k++) table_coeff[0][k] = dynmods[k].My2;\n for(int j=0; j<nmods; j++){\n for(int k=0; k<nmods; k++) table_coeff[j+1][k] = table_coeff[j][k];\n for(int k=j+1; k<nmods; k++) table_coeff[j+1][k] = dynmods[k].mul(table_coeff[j+1][k], dynmods[k].input64(mods[j]));\n }\n table_coeffinv.resize(nmods);\n for(int i=0; i<nmods; i++) table_coeffinv[i] = dynmods[i].inv(table_coeff[i][i]);\n }\n\n u64 calc(const std::vector<u32>& x){\n int nmods = mods.size();\n std::vector<u32> table_const(nmods);\n u64 res = 0;\n u64 res_coeff = 1;\n for(int j=0; j<nmods; j++){\n u32 t = dynmods[j].mul(dynmods[j].sub(x[j], table_const[j]), table_coeffinv[j]);\n for(int k=j+1; k<nmods; k++){\n table_const[k] = dynmods[k].add(dynmods[k].mul(t, table_coeff[j][k]), table_const[k]);\n }\n res += res_coeff * u64(t);\n res_coeff *= mods[j];\n }\n return res;\n }\n\n std::pair<std::vector<u32>, std::vector<u64>> calc(std::vector<std::vector<u32>> x){\n int n = x[0].size(), m = x.size();\n std::vector<u64> resl(n);\n std::vector<u32> resh(n);\n std::vector<u32> buf(m);\n u32 inv64 = dynmods[0].inv(dynmods[0].mul(dynmods[0].My3, dynmods[0].My2));\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++) buf[j] = x[j][i];\n resl[i] = calc(buf);\n resh[i] = dynmods[0].mul(dynmods[0].sub(buf[0], dynmods[0].input64(resl[i])), inv64);\n }\n return std::make_pair(std::move(resh), std::move(resl));\n }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\convolution.hpp\"\n\nnamespace nachia{\nnamespace bigint{\n\nstruct MultiplySupply {\n using u32 = unsigned int;\n using u64 = unsigned long long;\n static constexpr u32 MODCNT = 3;\n static constexpr u32 MOD[3] = { 3892314113, 3489660929, 3221225473 };\n \n GarnerU96 garner;\n\n MultiplySupply(){\n garner.precalc(std::vector<u32>(MOD, MOD + MODCNT));\n }\n \n template<unsigned int P>\n static std::vector<u32> SubConvolution(\n const std::vector<u32>& a,\n const std::vector<u32>& b\n ) {\n using Elem = StaticPModint<P>;\n static NttFromAcl<Elem> ntt;\n int z = a.size() + b.size() - 1;\n int N = 1; while(N < z) N *= 2;\n std::vector<Elem> A(N), B(N);\n for(std::size_t i=0; i<a.size(); i++) A[i] = a[i];\n for(std::size_t i=0; i<b.size(); i++) B[i] = b[i];\n Elem iN = Elem((u32)N).inv();\n ntt.Butterfly(A.begin(), N);\n ntt.Butterfly(B.begin(), N);\n for(int i=0; i<N; i++) A[i] = A[i] * B[i] * iN;\n ntt.IButterfly(A.begin(), N);\n std::vector<u32> res(z);\n for(int i=0; i<z; i++) res[i] = A[i].mrVal();\n return res;\n }\n \n std::vector<u32> multiplyBin(\n const std::vector<u32>& a,\n const std::vector<u32>& b\n ){\n if(a.empty() || b.empty()) return {};\n std::vector<std::vector<u32>> cx(MODCNT);\n cx[0] = SubConvolution<MOD[0]>(a, b);\n cx[1] = SubConvolution<MOD[1]>(a, b);\n cx[2] = SubConvolution<MOD[2]>(a, b);\n auto q = garner.calc(std::move(cx));\n int n = q.first.size();\n std::vector<u32> res(n + 2);\n for(int i=0; i<n; i++) res[i] = q.second[i];\n u64 c = 0;\n for(int i=0; i<n; i++){ res[i+1] = c += (u64)res[i+1] + (q.second[i] >> 32); c >>= 32; }\n res[n+1] = c; c = 0;\n for(int i=0; i<n; i++){ res[i+2] = c += (u64)res[i+2] + q.first[i]; c >>= 32; }\n while(res.size() && res.back() == 0) res.pop_back();\n return res;\n }\n \n std::vector<u32> multiplyDec(\n std::vector<u32> a,\n std::vector<u32> b\n ){\n static constexpr u32 d = 1000000000;\n if(a.empty() || b.empty()) return {};\n std::vector<std::vector<u32>> cx(MODCNT);\n cx[0] = SubConvolution<MOD[0]>(a, b);\n cx[1] = SubConvolution<MOD[1]>(a, b);\n cx[2] = SubConvolution<MOD[2]>(a, b);\n auto q0 = garner.calc(std::move(cx));\n int n = q0.first.size();\n std::vector<u64> buf(n + 2);\n static constexpr u32 j11 = (1ull << 32) / d;\n static constexpr u32 j10 = (-d) % d;\n static constexpr u32 j22 = 1 + (0ull- 1ull * d * d) / d / d;\n static constexpr u32 j21 = (-1ull * j22 * d * d) / d;\n static constexpr u32 j20 = (0ull-d) % d;\n for(int i=0; i<n; i++) buf[i] = q0.second[i] & ((1ull << 32) - 1);\n for(int i=0; i<n; i++) buf[i] += 1ull * (q0.second[i] >> 32) * j10;\n for(int i=0; i<n; i++) buf[i+1] += 1ull * (q0.second[i] >> 32) * j11;\n for(int i=0; i<n; i++) buf[i] += 1ull * q0.first[i] * j20; // q0.first[i] is small enough\n for(int i=0; i<n; i++) buf[i+1] += 1ull * q0.first[i] * j21;\n for(int i=0; i<n; i++) buf[i+2] += 1ull * q0.first[i] * j22;\n std::vector<u32> res(n + 2);\n u64 c = 0;\n for(int i=0; i<n+2; i++){ c += buf[i]; res[i] = c % d; c /= d; }\n while(res.size() && res.back() == 0) res.pop_back();\n return res;\n }\n};\n\n} // namespace bigint\n} // namespace nachia\n#line 5 \"nachia\\\\bigint\\\\base-operators.hpp\"\n#include <iostream>\n\nnamespace nachia {\nnamespace bigint {\n\nclass UIntDec {\npublic:\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nstd::vector<u32> x;\nstatic constexpr u32 BASE = 1'000'000'000;\n\nvoid Regularize(){ while(!x.empty() & !x.back()) x.pop_back(); }\n\nUIntDec() = default;\nUIntDec(std::vector<u32> _x) : x(std::move(_x)) {}\nUIntDec& operator+=(const UIntDec& b){\n x.resize(std::max(x.size(), b.x.size()) + 1);\n u64 c = 0;\n for(std::size_t i=0; i<b.x.size(); i++){\n c += b.x[i]; c += x[i];\n if(c >= BASE){ x[i] = c - BASE; c = 1; }\n else{ x[i] = c; c = 0; }\n }\n for(int i=b.x.size(); c; i++){\n x[i] = c += x[i];\n if(c < BASE) break;\n c = x[i] -= BASE;\n }\n Regularize();\n return *this;\n}\nUIntDec operator*(const UIntDec& b) const { return MultiplySupply().multiplyDec(x, b.x); }\n\nUIntDec Pow(u32 c) const {\n if(c == 0) return std::vector<u32>{1};\n if(c == 1) return *this;\n auto aa = Pow(c/2);\n aa = aa * aa;\n return (c&1) ? aa * (*this) : aa;\n}\nvoid mulU32(unsigned int cx) {\n u64 c = cx;\n for(std::size_t i=0; i<x.size(); i++){ c += (u64)x[i] << 32; x[i] = c % BASE; c /= BASE; }\n while(c){ x.push_back(c % BASE); c /= BASE; }\n}\n\n};\n\nclass UIntBin {\npublic:\nusing u32 = unsigned int;\nusing u64 = unsigned long long;\nstd::vector<u32> x;\n\nvoid Regularize(){ while(!x.empty() & !x.back()) x.pop_back(); }\n\nUIntBin() = default;\nUIntBin(std::vector<u32> _x) : x(std::move(_x)) {}\nUIntBin& operator+=(const UIntBin& b){\n x.resize(std::max(x.size(), b.x.size()) + 1);\n u64 c = 0;\n for(std::size_t i=0; i<b.x.size(); i++){\n c += b.x[i]; c += x[i];\n x[i] = c; c >>= 32;\n }\n for(int i=b.x.size(); c; i++){ x[i] = c += x[i]; c >>= 32; }\n Regularize();\n return *this;\n}\nUIntBin operator*(const UIntBin& b) const { return MultiplySupply().multiplyBin(x, b.x); }\n\nUIntBin Pow(u32 c) const {\n if(c == 0) return std::vector<u32>{1};\n if(c == 1) return *this;\n auto aa = Pow(c/2);\n aa = aa * aa;\n return (c&1) ? aa * (*this) : aa;\n}\nvoid mulD(unsigned int d, unsigned int cx) {\n u64 c = cx;\n for(std::size_t i=0; i<x.size(); i++){ x[i] = (c += (u64)x[i] * d); c >>= 32; }\n if(c) x.push_back(c);\n}\n\n};\n\nstd::vector<unsigned int> DecToBin(std::string decstr){\n std::vector<UIntBin> pdec;\n auto dfs = [&](auto& dfs, int l, int r) -> UIntBin {\n if(r - l <= 308){\n UIntBin p;\n for(int j=l; j<l+(r-l)%9; j++) p.mulD(10, decstr[j] - '0');\n for(int j=l+(r-l)%9; j<r; j+=9) p.mulD(1000000000, std::stoi(decstr.substr(j, 9)));\n return p;\n }\n if(pdec.empty()) pdec.push_back(UIntBin({10}).Pow(308));\n int h = 0; while(((308*2)<<h) < r-l) h++;\n while((int)pdec.size() < h+1) pdec.push_back(pdec.back() * pdec.back());\n auto res = dfs(dfs, l, r-(308<<h)) * pdec[h];\n res += dfs(dfs, r-(308<<h), r);\n return res;\n };\n return std::move(dfs(dfs, 0, decstr.size()).x);\n}\n\nstd::string BinToDec(std::vector<unsigned int> b){\n while(!b.empty() && !b.back()) b.pop_back();\n std::reverse(b.begin(), b.end());\n if(b.empty()) return \"0\";\n std::vector<UIntDec> pbin;\n auto dfs = [&](auto& dfs, int l, int r) -> UIntDec {\n if(r - l <= 29){\n UIntDec p;\n for(int j=l; j<r; j++) p.mulU32(b[j]);\n return p;\n }\n if(pbin.empty()) pbin.push_back(UIntDec({2}).Pow(32*29));\n int h = 0; while(((29*2)<<h) < r-l) h++;\n while((int)pbin.size() < h+1) pbin.push_back(pbin.back() * pbin.back());\n auto res = dfs(dfs, l, r-(29<<h)) * pbin[h];\n res += dfs(dfs, r-(29<<h), r);\n return res;\n };\n auto x = std::move(dfs(dfs, 0, b.size()).x);\n while(!x.empty() && !x.back()) x.pop_back();\n std::string res = std::to_string(x.back());\n res.resize(res.size() + 9 * (int)(x.size()-1), '0');\n for(int i=(int)x.size()-2; i>=0; i--){\n int o = res.size() - i*9 - 9;\n for(int j=o+8; j>=o; j--){ res[j] += x[i] % 10; x[i] /= 10; }\n }\n return res;\n}\n\n} // namespace bigint\n} // namespace nachia\n#line 4 \"nachia\\\\bigint\\\\integer.hpp\"\n\nnamespace nachia{\n\nclass UnsignedIntegerBin{\npublic:\n using MyType = UnsignedIntegerBin;\n friend class SignedIntegerBin;\nprivate:\n using u32 = uint32_t;\n using u64 = uint64_t;\n std::vector<u32> x;\n static inline bool Cflag;\n static MyType FromVec(std::vector<u32> _x){ MyType res; res.x = std::move(_x); return res; }\npublic:\n UnsignedIntegerBin(){}\n MyType operator>>(int sh) const {\n int h = sh / 32, l = sh % 32;\n MyType res; res.memreserve(size() - h);\n for(int i=h; i<size(); i++) res[i-h] = x[i] >> l;\n if(l) for(int i=h+1; i<size(); i++) res[i-h-1] |= x[i] << (32-l);\n res.regularize();\n return res;\n }\n MyType operator<<(int sh) const {\n int h = sh / 32, l = sh % 32;\n MyType res; res.memreserve(size() + h + 1);\n for(int i=0; i<size(); i++) res[i+h] = x[i] << l;\n if(l) for(int i=0; i<size(); i++) res[i+h+1] |= x[i] >> (32-l);\n res.regularize();\n return res;\n }\n MyType& operator>>=(int sh) { return (*this) = operator>>(sh); }\n MyType& operator<<=(int sh) { return (*this) = operator<<(sh); }\n MyType& operator%=(const MyType& d) { divInternal(d); return *this; }\n MyType operator%(const MyType& d) const { auto p = *this; return p.divInternal(d); }\n MyType operator/(const MyType& d) const { auto p = *this; return p.divInternal(d); }\n MyType& operator/=(const MyType& d) { return (*this) = divInternal(d); }\n MyType& operator+=(const MyType& v){\n memreserve(std::max(size(), v.size()) + 1);\n u64 c = 0;\n for(int i=0; i<v.size(); i++){ x[i] = (c += (u64)x[i] + v[i]); c >>= 32; }\n for(int i=v.size(); c; i++){ x[i] = c += x[i]; c >>= 32; }\n regularize();\n return *this;\n }\n MyType& operator-=(const MyType& v){\n memreserve(std::max(size(), v.size()));\n u64 c = 0;\n for(int i=0; i<v.size(); i++){\n c += v[i];\n x[i] -= c;\n c = (c + x[i]) >> 32;\n }\n for(int i=v.size(); i<size() && c; i++){\n x[i] -= c;\n c = (c + x[i]) >> 32;\n }\n Cflag = c;\n if(c){ complement(); increment(); }\n regularize();\n return *this;\n }\n MyType operator*(const MyType& v) const {\n MyType res;\n res.x = bigint::MultiplySupply().multiplyBin(x, v.x);\n res.regularize();\n return res;\n }\n MyType& operator*=(const MyType& r) { return (*this) = operator*(r); }\n MyType operator+(const MyType& r) { auto p = *this; p += r; return p; }\n MyType operator-(const MyType& r) { auto p = *this; p -= r; return p; }\n bool operator<(const MyType& r) const {\n return (size() != r.size())\n ? (size() < r.size())\n : std::lexicographical_compare(x.rbegin(), x.rend(), r.x.rbegin(), r.x.rend());\n }\n bool operator>(const MyType& r) const { return r < (*this); }\n bool operator<=(const MyType& r) const { return !(r < (*this)); }\n bool operator>=(const MyType& r) const { return !operator<(r); }\n bool operator==(const MyType& r) const { return x == r.x; }\n bool operator!=(const MyType& r) const { return x != r.x; }\n bool operator!() const { return size(); }\n bool isZero() const { return size() == 0; }\n std::string toStringBin() const {\n std::string res;\n for(int i=size()-1; i>=0; i--) for(int j=31; j>=0; j--) res.push_back('0' + (x[i]>>j) % 2);\n return res;\n }\n std::string toStringDec() const {\n if(isZero()) return \"0\";\n return bigint::BinToDec(x);\n }\n static MyType FromStringDec(const std::string& s) {\n return FromVec(bigint::DecToBin(s));\n }\n int lsb() const { for(int i=0; i<size(); i++){ if(x[i]) return nachia::LsbIndex(x[i]) + i * 32; } return -1; }\n int msb() const { for(int i=size()-1; i>=0; i--){ if(x[i]) return nachia::MsbIndex(x[i]) + i * 32; } return -1; }\nprivate:\n int size() const { return x.size(); }\n u32& operator[](int at) { return x[at]; }\n u32 operator[](int at) const { return x[at]; }\n void memreserve(int sz) { if((int)x.size() < sz) x.resize(sz); }\n void setBit(int at, bool val){ memreserve(at/32+1); x[at/32] |= (u32)(val?1:0) << (at%32); regularize(); }\n MyType divInternal(const MyType& d) {\n if(d.isZero()) throw 1;\n MyType res;\n for(int s=(size()-d.size())*32+31; s>=0; s--){\n MyType x = d << s;\n if(operator>=(x)){\n res.setBit(s, true); operator-=(x);\n }\n }\n res.regularize();\n return res;\n }\n void complement() { for(u32& y:x){ y = ~y; } }\n void increment() { if(isZero()){ x = {1}; return; } int i=0; while(i < size() && !~x[i]){ x[i++]++; } if(i>=size()){ x.push_back(1); } else x[i]++; }\n void decrement() { if(isZero()){ x = {1}; return; } int i=0; while(x[i]){ x[i++]--; } x[i]--; regularize(); }\n void regularize() { while(!x.empty() && 0 == x.back()) x.pop_back(); }\n int div10() {\n u64 c = 0;\n for(int i=size()-1; i>=0; i--){\n c = (c << 32) | x[i];\n x[i] = c / 10;\n c %= 10;\n }\n regularize();\n return c;\n }\n void mul10(int d) {\n u64 c = d;\n for(int i=0; i<size(); i++){ x[i] = (c += (u64)x[i] * 10); c >>= 32; }\n if(c) x.push_back(c);\n }\n};\n\nclass SignedIntegerBin{\n using MyType = SignedIntegerBin;\n using UInt = UnsignedIntegerBin;\nprivate:\n UInt u;\n int sign = 1;\n void regularize(){ u.regularize(); if(u.isZero()) sign = 1; }\n static MyType Raw(UInt u, int s){ MyType res; res.u = std::move(u); res.sign = s; res.regularize(); return res; }\npublic:\n bool isZero() const { return u.isZero(); }\n MyType& operator+=(const MyType& r) {\n if(sign == r.sign) u += r.u;\n else{ u -= r.u; if(u.Cflag){ sign = -sign; } }\n regularize();\n return *this;\n }\n MyType& operator-=(const MyType& r) {\n if(sign != r.sign) u += r.u;\n else{ u -= r.u; if(u.Cflag){ sign = -sign; } }\n regularize();\n return *this;\n }\n MyType operator*(const MyType& r) const { return Raw(u*r.u, sign*r.sign); }\n MyType& operator*=(const MyType& r) { return (*this) = operator*(r); }\n MyType operator+(const MyType& r) const { auto p = *this; p += r; return p; }\n MyType operator-(const MyType& r) const { auto p = *this; p -= r; return p; }\n MyType operator-() const { return Raw(u, -sign); }\n MyType& operator<<=(int sh) { u <<= sh; return *this; }\n MyType& operator>>=(int sh) { u >>= sh; return *this; }\n MyType operator<<(int sh) const { return Raw(u<<sh, sign); }\n MyType operator>>(int sh) const { return Raw(u<<sh, sign); }\n MyType operator/(const MyType& r) const { return Raw(u/r.u, sign*r.sign); }\n MyType& operator/=(const MyType& r) { return (*this) = operator/(r); }\n MyType operator%(const MyType& r) const { return Raw(u%r.u, sign*r.sign); }\n MyType& operator%=(const MyType& r) { return (*this) = operator%(r); }\n std::string toStringDec() const {\n if(isZero()) return \"0\";\n return (sign>0 ? \"\" : \"-\") + u.toStringDec();\n }\n static MyType FromStringDec(const std::string& s) {\n if(s.empty()) return MyType();\n if(s[0] == '+') return Raw(UInt::FromStringDec(s.substr(1)), 1);\n if(s[0] == '-') return Raw(UInt::FromStringDec(s.substr(1)), -1);\n return Raw(UInt::FromStringDec(s), 1);\n }\n};\n\n} // namespace nachia\n#line 2 \"Main.cpp\"\n#include <cstdint>\n#line 5 \"Main.cpp\"\n#include <string>\n#line 7 \"Main.cpp\"\n\n\nint main() {\n using Int = nachia::SignedIntegerBin;\n std::string s;\n std::cin >> s;\n Int a = Int::FromStringDec(s);\n std::cin >> s;\n Int b = Int::FromStringDec(s);\n Int c = a + b;\n std::cout << c.toStringDec() << '\\n';\n return 0;\n}", "accuracy": 0.84, "time_ms": 60, "memory_kb": 4204, "score_of_the_acc": -0.0814, "final_rank": 18 }, { "submission_id": "aoj_NTL_2_A_6975961", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<int> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = str[id++] - '0';\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<int> v( 8, 0 );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n int top = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n // sizeの再計算\n void resize(){\n\n size = 0;\n for( int i = dat.size()-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- ){\n if( dat[i][j] != 0 ){\n size = i;\n return;\n }\n }\n }\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n int up = 0; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.minus = l.minus;\n }\n res.resize();\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l.minus & r.minus ){\n if( l < r ){\n l.minus = false;\n r.minus = false;\n res = l - r;\n res.minus = true;\n }\n else{\n l.minus = false;\n r.minus = false;\n res = r - l;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n int maxSize = max( l.size, r.size );\n int down = 0; // 繰り下がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n }\n }\n }\n res.resize();\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt sum = a + b;\n sum.print();\n\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 95404, "score_of_the_acc": -1.1003, "final_rank": 16 }, { "submission_id": "aoj_NTL_2_A_6975930", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<int> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = str[id++] - '0';\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<int> v( 8, 0 );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n int top = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n int up = 0; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.size = ( up != 0 ? maxSize+1 : maxSize );\n res.minus = l.minus;\n }\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n res.size = max( l.size, r.size );\n int down = 0; // 繰り下がり\n for( int i = 0 ; i <= res.size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n if( res.dat[res.size][0] == 0 && res.dat[res.size][1] == 0 && res.dat[res.size][2] == 0 && res.dat[res.size][3] == 0 )\n res.size = max( res.size-1, 0 );\n }\n }\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt sum = a + b;\n sum.print();\n\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 95512, "score_of_the_acc": -1.1014, "final_rank": 17 }, { "submission_id": "aoj_NTL_2_A_6975926", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<int> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = str[id++] - '0';\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<int> v( 8, 0 );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n int top = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n int up = 0; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.size = ( up != 0 ? maxSize+1 : maxSize );\n res.minus = l.minus;\n }\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n res.size = max( l.size, r.size );\n int down = 0; // 繰り下がり\n for( int i = 0 ; i <= res.size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n if( res.dat[res.size][0] == 0 && res.dat[res.size][1] == 0 && res.dat[res.size][2] == 0 && res.dat[res.size][3] == 0 )\n res.size--;\n }\n }\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt sum = a + b;\n sum.print();\n\n}", "accuracy": 0.04, "time_ms": 20, "memory_kb": 38720, "score_of_the_acc": -0.398, "final_rank": 20 }, { "submission_id": "aoj_NTL_2_A_6975914", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<int> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = str[id++] - '0';\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<int> v( 8, 0 );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n int top = 0;\n int order = 1;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += l.dat[l.size][i];\n lVal *= 10;\n rVal += r.dat[r.size][i];\n rVal *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n int lVal = 0, rVal = 0;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += l.dat[l.size][i];\n lVal *= 10;\n rVal += r.dat[r.size][i];\n rVal *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n int up = 0; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.size = ( up != 0 ? maxSize+1 : maxSize );\n res.minus = l.minus;\n }\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n res.size = max( l.size, r.size );\n int down = 0; // 繰り下がり\n for( int i = 0 ; i <= res.size ; i++ ){\n if( i == res.size && down == 1 ){\n res.size--;\n break;\n }\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n }\n }\n }\n }\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt sum = a + b;\n sum.print();\n\n}", "accuracy": 0.06, "time_ms": 70, "memory_kb": 95232, "score_of_the_acc": -1.0839, "final_rank": 19 }, { "submission_id": "aoj_NTL_2_A_6814556", "code_snippet": "#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nint main(){\n boost::multiprecision::cpp_int a,b;\n std::cin>>a>>b;\n std::cout<<a+b<<std::endl;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3408, "score_of_the_acc": -1.0003, "final_rank": 11 }, { "submission_id": "aoj_NTL_2_A_6691773", "code_snippet": "#include<bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(n);i++)\ntypedef long long ll;\nusing namespace boost::multiprecision;\n\nint main() {\n cpp_int a,b;cin>>a>>b;\n cpp_int ans=a+b;\n cout<<ans<<endl;\n return 0;\n\n\n\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3428, "score_of_the_acc": -1.0005, "final_rank": 13 }, { "submission_id": "aoj_NTL_2_A_6677813", "code_snippet": "#include<bits/stdc++.h>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\nconst int mod=1e9+7;\n\nint32_t main()\n{\n boost::multiprecision::cpp_int a, b;\n cin >> a >> b;\n \n cout << a+b << endl;\n \n return 0;\n}", "accuracy": 1, "time_ms": 700, "memory_kb": 3456, "score_of_the_acc": -1.0008, "final_rank": 15 }, { "submission_id": "aoj_NTL_2_A_6663111", "code_snippet": "// 多倍長整数\n//#include <atcoder/convolution>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nstruct multiprecision{\n private:\n const long long base=100;\n const int lg = 2;\n std::vector<long long> num;\n\n void adjust(){\n for(int i=0;i<num.size();i++){\n long long z=num[i]/base;\n num[i]%=base;\n if(num[i]<0){\n if(z!=0||i<num.size()-1){\n z--;\n num[i]+=base;\n }\n }\n if(z==0)continue;\n if(i==num.size()-1){\n num.emplace_back(z);\n }\n else{\n num[i+1]+=z;\n }\n }\n\n while(num.size()>0&&num[num.size()-1]==0)num.pop_back();\n if(num.size()==0)num.emplace_back(0);\n while(num[num.size()-1]==-1&&num.size()>1&&num[num.size()-2]!=0){\n num[num.size()-2]-=base;\n num.pop_back();\n }\n }\n\n public:\n multiprecision(long long val){\n if(val==0){\n num.emplace_back(0);\n }\n else{\n long long cpy=val;\n while(cpy!=0){\n num.emplace_back(cpy%base);\n cpy/=base;\n }\n }\n adjust();\n }\n\n multiprecision(std::vector<long long> val){\n num=val;\n adjust();\n }\n\n multiprecision(std::string s){\n reverse(s.begin(),s.end());\n bool neg=0;\n if(s[s.size()-1]=='-'){\n s[s.size()-1]='0';\n neg=1;\n }\n while(s.size()%lg!=0){\n s+='0';\n }\n\n for(int i=0;i<s.size()/lg;i++){\n std::string t=\"\";\n for(int j=0;j<lg;j++){\n t+=s[i*lg+j];\n }\n reverse(t.begin(),t.end());\n num.emplace_back(std::stoll(t));\n }\n\n if(neg){\n multiprecision zero=multiprecision(0);\n zero-=*this;\n *this=zero;\n }\n\n adjust();\n }\n\n std::vector<long long> val(){\n return num;\n }\n\n std::string s_val(){\n bool flg=0;\n if(num[num.size()-1]<0){\n flg=1;\n for(int i=0;i<num.size();i++){\n num[i]*=-1;\n }\n adjust();\n }\n std::string res=\"\";\n if(flg)res+='-';\n for(int i=num.size()-1;i>=0;i--){\n std::string t=std::to_string(num[i]);\n if(i==num.size()-1){\n res+=t;\n continue;\n }\n for(int j=0;j<lg-t.size();j++){\n res+='0';\n }\n res+=t;\n }\n\n if(flg){\n for(int i=0;i<num.size();i++){\n num[i]*=-1;\n }\n adjust();\n }\n\n return res;\n }\n\n multiprecision& operator =(const multiprecision& other){\n this->num=other.num;\n return *this;\n }\n\n multiprecision& operator +=(const multiprecision& other){\n for(int i=0;i<other.num.size();i++){\n if(i>=this->num.size()){\n this->num.emplace_back(other.num[i]);\n }\n else{\n this->num[i]+=other.num[i];\n }\n }\n this->adjust();\n return *this;\n }\n\n multiprecision& operator -=(const multiprecision& other){\n for(int i=0;i<other.num.size();i++){\n if(i>=this->num.size()){\n this->num.emplace_back(-other.num[i]);\n }\n else{\n this->num[i]-=other.num[i];\n }\n }\n this->adjust();\n return *this;\n }\n};\n\n\n#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\n \nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing vll = vector<ll>;\nusing vvll = vector<vll>;\nusing vld = vector<ld>;\nusing vvld = vector<vld>;\nusing vst = vector<string>;\nusing vvst = vector<vst>;\n \n#define fi first\n#define se second\n#define pb push_back\n#define eb emplace_back\n#define pq_big(T) priority_queue<T,vector<T>,less<T>>\n#define pq_small(T) priority_queue<T,vector<T>,greater<T>>\n#define all(a) a.begin(),a.end()\n#define rep(i,start,end) for(ll i=start;i<(ll)(end);i++)\n#define per(i,start,end) for(ll i=start;i>=(ll)(end);i--)\n#define uniq(a) sort(all(a));a.erase(unique(all(a)),a.end())\n\nint main(){\n string a,b;\n cin>>a>>b;\n\n multiprecision mp1(a),mp2(b);\n mp1+=mp2;\n\n cout<<mp1.s_val()<<endl;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 5012, "score_of_the_acc": -0.0177, "final_rank": 1 } ]
aoj_0030_cpp
整数の和 0 から 9 の数字から異なる n 個の数を取り出して合計が s となる組み合わせの数を出力するプログラムを作成してください。 n 個の数はおのおの 0 から 9 までとし、1つの組み合わせに同じ数字は使えません。たとえば、 n が 3 で s が 6 のとき、3 個の数字の合計が 6 になる組み合わせは、 1 + 2 + 3 = 6 0 + 1 + 5 = 6 0 + 2 + 4 = 6 の 3 通りとなります。 Input 複数のデータセットが与えられます。各データセットに n (1 ≤ n ≤ 9) と s (0 ≤ s ≤ 100) が1つのスペースで区切られて1行に与えられます。 n と s が共に 0 のとき入力の最後とします(この場合は処理せずにプログラムを終了する)。 データセットの数は 50 を超えません。 Output 各データセットに対して、 n 個の整数の和が s になる組み合わせの数を1行に出力して下さい。 Sample Input 3 6 3 1 0 0 Output for the Sample Input 3 0
[ { "submission_id": "aoj_0030_7937516", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nint n, s;\nbool used[10];\nlli dfs(bool used[10], int now, int sum) {\n if (sum > s)\n return 0;\n if (now == n) {\n if (sum == s)\n return 1;\n return 0;\n }\n int res = 0;\n for (int i = 0; i < 10; ++i) {\n if (used[i])\n continue;\n used[i] = true;\n res += dfs(used, now + 1, sum + i);\n used[i] = false;\n }\n return res;\n}\nlli fact(int n) {\n if (n <= 1)\n return 1;\n return n * fact(n - 1);\n}\nint main() {\n int f[10];\n for (int i = 1; i < 10; ++i)\n f[i] = fact(i);\n while (cin >> n >> s, n || s) {\n memset(used, false, sizeof(used));\n cout << dfs(used, 0, 0) / f[n] << endl;\n }\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 3096, "score_of_the_acc": -0.1054, "final_rank": 3 }, { "submission_id": "aoj_0030_7937514", "code_snippet": "#include <iostream>\nusing namespace std;\nint n, s, spn;\nvoid sp(int ne, int ns, bool *flag) {\n if (ne > n)\n return;\n if (ne == n && ns == s)\n spn++;\n for (int i = 0; i < 10; ++i) {\n if (!flag[i]) {\n flag[i] = true;\n sp(ne + 1, ns + i, flag);\n flag[i] = false;\n }\n }\n}\nint perm(int n) { return (n ? n * perm(n - 1) : 1); }\nint main() {\n while (1) {\n cin >> n >> s;\n if (!n)\n return 0;\n spn = 0;\n bool flag[10] = {false};\n sp(0, 0, flag);\n spn /= perm(n);\n cout << spn << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 270, "memory_kb": 3084, "score_of_the_acc": -0.2791, "final_rank": 4 }, { "submission_id": "aoj_0030_5975808", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint xx(int a,int b,int c,int d){\n if(c == 1){\n if(d - b > a && d - b <= 9) return 1;\n else return 0;\n }\n else{\n if(d - b <= a) return 0;\n else{\n int sum=0;\n for(int i = a+1;i <= d-b;i++){\n sum += xx(i,b+i,c-1,d);\n }\n return sum;\n }\n } \n}\n\nint main(){\n while(true){\n int n,x;\n cin >> n >> x;\n if(n == 0 && x == 0){\n return 0;\n }\n cout << xx(-1,0,n,x) << endl;\n } \n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3080, "score_of_the_acc": -0.0105, "final_rank": 2 }, { "submission_id": "aoj_0030_5216656", "code_snippet": "#include <bits/stdc++.h>\n#define NIL (-1)\n#define LL long long\nusing namespace std;\nconst int64_t MOD = 1e9 + 7;\nconst int INF = INT_MAX;\nconst double PI = acos(-1.0);\n\nvoid sub(int n, int s, vector<bool> used, int& cnt) {\n\tif (!n) {\n\t\tif (!s) cnt++;\n\t\treturn;\n\t}\n\telse {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tif (used[i]) continue;\n\t\t\tused[i] = 1;\n\t\t\tsub(n - 1, s - i, used, cnt);\n\t\t\tused[i] = 0;\n\t\t}\n\t}\n\treturn;\n}\n\nint main() {\n\tint n, s;\n\twhile (cin >> n >> s) {\n\t\tif (!n && !s) break;\n\t\tint cnt = 0;\n\t\tvector<bool> used(10);\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tif (used[i]) continue;\n\t\t\tused[i] = 1;\n\t\t\tsub(n - 1, s - i, used, cnt);\n\t\t\tused[i] = 0;\n\t\t}\n\t\tint m = 1;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tm *= (n - i);\n\t\t}\n\t\t//cout << m << endl;\n\t\tcout << cnt / m << endl;\n\t}\n}", "accuracy": 1, "time_ms": 980, "memory_kb": 3000, "score_of_the_acc": -1, "final_rank": 6 }, { "submission_id": "aoj_0030_5070224", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\n#include<queue>\n#include<iomanip>\n#include <string>\n#include <math.h>\nusing namespace std;\nint main(){\n long long int n,s,q=0;\n vector<int>a={0,1,2,3,4,5,6,7,8,9};\n vector<long long int>c(100);\n c[0]=1;\n vector<vector<long long int>> b(1000,vector<long long int>(1000));\n for(int i=0;i<10;i++){\n c[i+1]=c[i]*(i+1);\n }\n do {\n for(int i=0;i<10;i++){\n q+=a[i];\n b[i+1][q]++;\n }\n q=0;\n } while (next_permutation(a.begin(), a.end()));\n cin>>n;\n while(n!=0){\n cin>>s;\n cout<<b[n][s]/(c[10-n]*c[n])<<endl;\n cin>>n;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 10592, "score_of_the_acc": -1.0309, "final_rank": 7 }, { "submission_id": "aoj_0030_3727596", "code_snippet": "#include<iostream>\n#include<string>\n#include<vector>\n#include<algorithm>\n#include<cmath>\n#include<stdio.h>\n#include<queue>\n#include <climits>\n#include <map>\n#include <set>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,int> P;\nconst int mod = 1e9 + 7;\nconst long long INF = 1LL << 60;\n\nbool notuse[10];\nint cnt;\n\nvoid dfs(int n,int k)\n{\n if(n==0 && k == 0){\n cnt++;\n return ;\n }else{\n for(int i = 0; i < 10; i++){\n if(notuse[i] && k - i >= 0){\n notuse[i] = false;\n dfs(n-1,k-i);\n notuse[i] = true;\n }\n }\n }\n}\n\nint main() \n{\n ll div[9] = {1};\n for(int i = 1; i < 9; i++){\n div[i]=div[i-1]*(i+1);\n }\n while(true){\n int n,s; cin >> n >> s;\n if(n==0 && s == 0) break;\n for(int i = 0; i < 10; i++){\n notuse[i] = true;\n }\n cnt = 0;\n dfs(n,s);\n cout << cnt/div[n-1] << endl;\n }\n}", "accuracy": 1, "time_ms": 500, "memory_kb": 3064, "score_of_the_acc": -0.5136, "final_rank": 5 }, { "submission_id": "aoj_0030_3598222", "code_snippet": "#include<iostream>\n\nusing namespace std;\n\nint count(int n, int s, int a) {\n if (n == 1) {\n if (0 <= s && s <= 9 && a <= s) {\n return 1;\n } else {\n return 0;\n }\n }\n else {\n int c = 0;\n for (int b = a; s - b > 0; b++) {\n c += count(n - 1, s - b, b + 1);\n }\n return c;\n}\n}\nint main() {\n int n, s;\n while (cin >> n >> s, n || s) {\n cout << count(n, s, 0) << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3044, "score_of_the_acc": -0.0058, "final_rank": 1 } ]
aoj_NTL_2_C_cpp
Multiplication of Big Integers Given two integers $A$ and $B$, compute the product, $A \times B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the product in a line. Constraints $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$ Sample Input 1 5 8 Sample Output 1 40 Sample Input 2 100 25 Sample Output 2 2500 Sample Input 3 -1 0 Sample Output 3 0 Sample Input 4 12 -3 Sample Output 4 -36
[ { "submission_id": "aoj_NTL_2_C_10940298", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\n\nstring fixedNum( string a )\n{\n if( a.size() == 1 )\n return a;\n for( int i = 0; i < a.size(); i++ )\n if( '1'<= a[i] && a[i] <= '9' )\n return a.substr( i, a.size() );\n return \"0\";\n}\n\nstring calcAddition( string a, string b )\n{\n a = fixedNum(a); b = fixedNum(b);\n int as = a.size(), bs = b.size(), d = as > bs ? as - bs : bs - as;\n string s = \"0\", t = \"0\";\n for( int i = 0; i < d; i++ )\n as > bs ? t += \"0\" : s += \"0\";\n s += a; t += b;\n\n for( int i = s.size() - 1; i >= 1; i-- )\n {\n s[i] += t[i] - '0';\n if( s[i] > '9' )\n {\n s[i] -= 10;\n s[i-1]++;\n }\n }\n\n return s[0] == '0' ? s.substr( 1, s.size() ) : s;\n}\n\nstring calcMultiplication( string a, string b )\n{\n a = fixedNum(a); b = fixedNum(b);\n int as = a.size(), bs = b.size(), d = as > bs ? as - bs : bs - as;\n string s = \"0\", t = \"0\", x = \"\", sum = \"\", zero = \"\", digit = \"\";\n for( int i = 0; i < d; i++ )\n as > bs ? t += \"0\" : s += \"0\";\n s += a; t += b;\n\n for( int i = 0; i < s.size(); i++ )\n zero += \"0\";\n \n x = zero;\n sum = zero;\n\n for( int i = s.size() - 1; i >= 1; i-- )\n {\n for( int j = s.size() - 1; j >= 1; j-- )\n x[j] = ( t[i] - '0' ) * ( s[j] - '0' );\n for( int j = s.size() - 1; j >= 1; j-- )\n {\n int f = x[j] / 10;\n x[j-1] += f;\n x[j] = x[j] - 10 * f + '0';\n }\n x += digit;\n sum = calcAddition( x, sum );\n digit += \"0\";\n x = zero;\n }\n return sum;\n}\n\nint main()\n{\n string a, b;\n\n cin >> a >> b;\n\n int as = a.size(), bs = b.size();\n string s = a.substr( 1, as ), t = b.substr( 1, bs );\n\n if( a[0] == '-' && b[0] == '-' )\n cout << calcMultiplication( s, t ) << endl;\n else if( a[0] >= '0' && b[0] >= '0' )\n cout << calcMultiplication( a, b ) << endl;\n else\n {\n if( a == \"0\" || b == \"0\" )\n cout << \"0\" << endl;\n else if( a[0] == '-' )\n cout << '-' << calcMultiplication( s, b ) << endl;\n else\n cout << '-' << calcMultiplication( a, t ) << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3512, "score_of_the_acc": -0.0031, "final_rank": 2 }, { "submission_id": "aoj_NTL_2_C_9796169", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n\ntemplate <int BASE>\nclass BigDecimal {\n public:\n static constexpr std::string_view NUMERAL{\n \"0123456789ABCDEF\"}; // 16進数まで対応\n\n private: // 静的関数\n static int CompareIgnoreSign(const BigDecimal& a, const BigDecimal& b) {\n // a-bの符号で覚えてもよいかも。\n // a<b: -1\n // a>b: +1\n // a==b: 0\n if (a._digit.size() != b._digit.size())\n return a._digit.size() < b._digit.size() ? -1 : 1;\n for (int i = a._digit.size() - 1; i >= 0; --i) {\n if (a._digit[i] == b._digit[i]) continue;\n return a._digit[i] < b._digit[i] ? -1 : 1;\n }\n return 0;\n }\n\n static BigDecimal Karatsuba(const BigDecimal& a, const BigDecimal& b) {\n // |a| >= |b|にする\n if (a._digit.size() < b._digit.size()) return Karatsuba(b, a);\n // 1桁に絞ったら直に計算して返す\n if (b._digit.size() == 1) {\n BigDecimal ret(a);\n for (int i = 0; i < a._digit.size(); ++i) {\n ret._digit[i] *= b._digit[0];\n }\n ret.carry_and_fix();\n if (b._positive)\n return ret;\n else\n return -ret;\n }\n int N = a._digit.size() / 2; // 下半分の桁数\n bool sign = !(a._positive xor b._positive); // 符号を計算しておく\n BigDecimal a0(a), a1(a), b0(b), b1(b); // x = concat(x0, x1)\n // aの処理\n // x1の下N桁を残す形で上の桁を取り除く\n while (a1._digit.size() > N) a1._digit.pop_back();\n // x0のデータを消去\n a0._digit.clear();\n // x0に下N桁より上の桁を保存しなおす\n for (int i = 0; N + i < a._digit.size(); ++i)\n a0._digit.emplace_back(a._digit[N + i]);\n if (a0._digit.size() == 0) a0._digit.emplace_back(0);\n // x0, x1の符号を取り除く\n a0._positive = a1._positive = true;\n if (b._digit.size() < N) { // 一方が他方の半分もない\n BigDecimal p0, c1;\n p0 = Karatsuba(a0, b);\n c1 = Karatsuba(a1, b);\n BigDecimal c0;\n for (int i = 0; i < N - 1; ++i) c0._digit.emplace_back(0);\n for (const auto& d : p0._digit) c0._digit.emplace_back(d);\n BigDecimal ret = c0 + c1;\n ret._positive = sign;\n return ret;\n }\n // bの処理\n // x1の下N桁を残す形で上の桁を取り除く\n while (b1._digit.size() > N) b1._digit.pop_back();\n // x0のデータを消去\n b0._digit.clear();\n // x0に下N桁より上の桁を保存しなおす\n for (int i = 0; N + i < b._digit.size(); ++i)\n b0._digit.emplace_back(b._digit[N + i]);\n if (b0._digit.size() == 0) b0._digit.emplace_back(0);\n // x0, x1の符号を取り除く\n b0._positive = b1._positive = true;\n // 3種類の積\n BigDecimal p0, p1, p2;\n p0 = Karatsuba(a0, b0);\n p2 = Karatsuba(a1, b1);\n p1 = Karatsuba(a0 + a1, b0 + b1) - p0 - p2;\n // 積に対応する数\n BigDecimal c0, c1, c2;\n c0._digit.clear();\n c1._digit.clear();\n c2._digit.clear();\n for (int i = 0; i < N; ++i) {\n c0._digit.emplace_back(0);\n c0._digit.emplace_back(0);\n c1._digit.emplace_back(0);\n }\n for (const auto& d : p0._digit) c0._digit.emplace_back(d);\n for (const auto& d : p1._digit) c1._digit.emplace_back(d);\n for (const auto& d : p2._digit) c2._digit.emplace_back(d);\n BigDecimal ret = c0 + c1 + c2;\n ret._positive = sign;\n return ret;\n }\n\n private:\n std::vector<int> _digit;\n bool _positive;\n bool is_zero() const { return _digit.size() == 1 && _digit[0] == 0; }\n\n void carry_and_fix() {\n // 新規の桁が発生しない範疇(最後の桁以外)を処理\n for (int i = 0; i < _digit.size() - 1; ++i) {\n if (_digit[i] >= BASE) {\n // 桁の数が基数以上: 繰り上げる必要あり\n int k = _digit[i] / BASE; // 繰り上がり発生回数\n _digit[i] -= k * BASE;\n _digit[i + 1] += k;\n } else if (_digit[i] < 0) {\n // 桁の数が負: 繰り下げが必要\n int k = (-_digit[i] - 1) / BASE + 1;\n _digit[i] += k * BASE;\n _digit[i + 1] -= k;\n }\n }\n // 最後の桁を処理する場合\n while (_digit.back() >= BASE) {\n int k = _digit.back() / BASE; // 繰り上がり発生回数\n _digit.back() -= k * BASE;\n _digit.emplace_back(k);\n }\n // 計算結果がマイナスなら全体に-1をかけて符号反転\n if (_digit.back() < 0) {\n this->_positive = !this->_positive;\n for (int i = 0; i < _digit.size(); ++i) {\n _digit[i] *= -1;\n }\n this->carry_and_fix();\n }\n // 0の桁を上から消す\n while (_digit.size() >= 2 && _digit.back() == 0) _digit.pop_back();\n // 0になったら正の数にしておく(-0表記は困るため)\n if (this->is_zero()) _positive = true;\n }\n\n public:\n // コンストラクタ\n BigDecimal(int num = 0) : _digit(0), _positive(num >= 0) {\n if (!_positive) num *= -1;\n while (num > 0) {\n _digit.emplace_back(num % BASE);\n num /= BASE;\n }\n if (_digit.size() == 0) _digit.emplace_back(0);\n }\n BigDecimal(std::string s) {\n if (s[0] == '-') {\n s = s.substr(1);\n _positive = false;\n } else {\n _positive = true;\n }\n while (s.size() > 0) {\n int i = NUMERAL.find(s.back());\n _digit.emplace_back(i);\n s.pop_back();\n }\n }\n // コピーコンストラクタ\n BigDecimal(const BigDecimal& x)\n : _digit(x._digit.size()), _positive(x._positive) {\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] = x._digit[i];\n }\n }\n\n // 比較演算子\n bool operator==(const BigDecimal& x) const {\n if (this->_positive != x._positive) return false;\n if (this->_digit.size() != x._digit.size()) return false;\n for (int i = 0; i < this->_digit.size(); ++i) {\n if (this->_digit[i] != x._digit[i]) return false;\n }\n return true;\n }\n bool operator!=(const BigDecimal& x) const { return !(*this == x); }\n bool operator<(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return false; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) < 0;\n } else {\n if (x._positive) return true; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) > 0;\n }\n }\n bool operator>(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return true; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) > 0;\n } else {\n if (x._positive) return false; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) < 0;\n }\n }\n bool operator<=(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return false; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) <= 0;\n } else {\n if (x._positive) return true; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) >= 0;\n }\n }\n bool operator>=(const BigDecimal& x) const {\n if (this->_positive) {\n if (!x._positive) return true; // x < 0 <= this -> this>x\n return CompareIgnoreSign(*this, x) >= 0;\n } else {\n if (x._positive) return false; // this < 0 <= x -> this<x\n return CompareIgnoreSign(*this, x) <= 0;\n }\n }\n\n // 単項演算子\n BigDecimal operator+() const { return *this; }\n BigDecimal operator-() const {\n BigDecimal ret = *this;\n if (!this->is_zero()) ret._positive = !ret._positive;\n return ret;\n }\n // 複号代入演算子\n BigDecimal& operator+=(const BigDecimal& x) {\n // 符号が異なる場合は符号をそろえて引き算に\n if (this->_positive != x._positive) {\n return *this -= (-x);\n }\n // 符号が同じ物にのみ足し算を行う\n while (this->_digit.size() < x._digit.size()) {\n this->_digit.emplace_back(0);\n }\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] += x._digit[i];\n }\n this->carry_and_fix();\n return *this;\n }\n BigDecimal& operator-=(const BigDecimal& x) {\n // 符号が異なる場合は符号をそろえて足し算に\n if (this->_positive != x._positive) {\n return *this += (-x);\n }\n // 符号が同じ物にのみ引き算を行う\n while (this->_digit.size() < x._digit.size()) {\n this->_digit.emplace_back(0);\n }\n for (int i = 0; i < x._digit.size(); ++i) {\n this->_digit[i] -= x._digit[i];\n }\n this->carry_and_fix();\n return *this;\n }\n BigDecimal& operator*=(const BigDecimal& x) { return *this; }\n BigDecimal& operator/=(const BigDecimal& x) { return *this; }\n BigDecimal& operator%=(const BigDecimal& x) { return *this; }\n\n // 二項演算子\n BigDecimal operator+(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret += x);\n }\n BigDecimal operator-(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret -= x);\n }\n BigDecimal operator*(const BigDecimal& x) const {\n return Karatsuba(*this, x);\n }\n BigDecimal operator/(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret /= x);\n }\n BigDecimal operator%(const BigDecimal& x) const {\n BigDecimal ret(*this);\n return (ret %= x);\n }\n\n // キャスト\n operator std::string() const {\n std::string ret = \"\";\n for (const auto& c : _digit) {\n ret = NUMERAL.at(c) + ret;\n }\n if (!_positive) ret = \"-\" + ret;\n return ret;\n }\n};\n\nint main() {\n std::string A, B;\n std::cin >> A >> B;\n BigDecimal<10> a(A), b(B);\n std::cout << std::string(a*b) << std::endl;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3608, "score_of_the_acc": -0.0782, "final_rank": 7 }, { "submission_id": "aoj_NTL_2_C_8873472", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n#define SWAP( A, B ) { auto tmp = A; A = B; B = tmp; }\n\nstruct BigInteger{\n\n bool minus;\n int size;\n vector<int> val;\n\n BigInteger(){\n\n minus = false;\n size = 0;\n\n }\n\n BigInteger( string str ){\n\n minus = ( str[0] == '-' );\n if( minus )\n str = str.substr( 1 );\n size = str.length();\n for( int i = size-1 ; i >= 0 ; i-- )\n val.push_back( str[i] - '0' );\n adjust();\n\n }\n\n void adjust(){\n\n while( size != 0 && val[size-1] == 0 ){\n size--;\n val.pop_back();\n }\n if( size == 0 )\n minus = false;\n\n }\n\n bool same( BigInteger bi ){\n\n if( size != bi.size ) return false;\n for( int i = 0 ; i < size ; i++ ){\n if( val[i] != bi.val[i] )\n return false;\n }\n return true;\n\n }\n\n bool greater( BigInteger bi ){\n\n if( size > bi.size ) return true;\n else if( size < bi.size ) return false;\n if( size == 0 ) return true;\n int id = size - 1;\n while( id >= 0 ){\n if( val[id] > bi.val[id] ) return true;\n else if( val[id] < bi.val[id] ) return false;\n id--;\n }\n return true;\n \n }\n\n\n\n void print(){\n\n if( size == 0 ){\n minus = false;\n cout << \"0\" << endl;\n return;\n } \n if( minus ) cout << \"-\";\n for( int i = size-1 ; i >= 0 ; i-- )\n cout << val[i];\n cout << endl;\n\n }\n\n};\n\nBigInteger operator+( BigInteger bi1, BigInteger bi2 );\nBigInteger operator-( BigInteger bi1, BigInteger bi2 );\nBigInteger operator*( BigInteger bi1, BigInteger bi2 );\nBigInteger operator/( BigInteger bi1, BigInteger bi2 );\nBigInteger operator%( BigInteger bi1, BigInteger bi2 );\n\n\nBigInteger operator+( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n if( bi1.minus && !bi2.minus ){\n bi1.minus = false;\n res = bi2 - bi1;\n return res;\n }\n if( !bi1.minus && bi2.minus ){\n bi2.minus = false;\n res = bi1 - bi2;\n return res;\n }\n res.minus = bi1.minus;\n res.size = max( bi1.size, bi2.size );\n vector<int> a;\n vector<int> b;\n for( int i = 0 ; i < res.size ; i++ ){\n if( i < bi1.size )\n a.push_back( bi1.val[i] );\n else\n a.push_back( 0 );\n if( i < bi2.size )\n b.push_back( bi2.val[i] );\n else\n b.push_back( 0 );\n }\n\n int up = 0;\n for( int i = 0 ; i < res.size ; i++ ){\n int sum = a[i] + b[i];\n sum += up;\n up = sum / 10;\n sum %= 10;\n res.val.push_back( sum );\n }\n while( up != 0 ){\n res.size++;\n res.val.push_back( up % 10 );\n up /= 10;\n }\n\n res.adjust();\n return res;\n\n}\n\nBigInteger operator-( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n if( ( bi1.minus && !bi2.minus ) || ( !bi1.minus && bi2.minus ) ){\n bi2.minus = !bi2.minus;\n return bi1 + bi2;\n }\n res.size = max( bi1.size, bi2.size );\n if( bi1.greater( bi2 ) )\n res.minus = bi1.minus;\n else{\n res = bi2 - bi1;\n res.minus = !res.minus;\n return res;\n }\n vector<int> a;\n vector<int> b;\n for( int i = 0 ; i < res.size ; i++ ){\n if( i < bi1.size )\n a.push_back( bi1.val[i] );\n else\n a.push_back( 0 );\n if( i < bi2.size )\n b.push_back( bi2.val[i] );\n else\n b.push_back( 0 );\n }\n\n int down = 0;\n for( int i = 0 ; i < res.size ; i++ ){\n int diff = a[i] - b[i];\n diff -= down;\n if( diff >= 0 ){\n down = -( diff / 10 );\n diff %= 10;\n }\n else{\n down = ( -diff + 9 ) / 10;\n diff = ( 10 - ( -diff % 10 ) ) % 10;\n }\n res.val.push_back( diff );\n }\n \n res.adjust();\n return res;\n\n}\n\n/*\nBigInteger operator*( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n if( ( bi1.minus && !bi2.minus ) || ( !bi1.minus && bi2.minus ) ) res.minus = true;\n bi1.minus = bi2.minus = false;\n res.size = bi1.size + bi2.size - 1;\n for( int i = 0 ; i < res.size ; i++ )\n res.val.push_back( 0 );\n \n for( int i = 0 ; i < bi1.size ; i++ ){\n for( int j = 0 ; j < bi2.size ; j++ )\n res.val[i+j] += bi1.val[i] * bi2.val[j];\n }\n int up = 0;\n for( int i = 0 ; i < res.size ; i++ ){\n res.val[i] += up;\n up = res.val[i] / 10;\n res.val[i] %= 10;\n }\n while( up != 0 ){\n res.size++;\n res.val.push_back( up % 10 );\n up /= 10;\n }\n\n res.adjust();\n return res;\n \n}\n*/\n\nBigInteger operator*( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n if( bi1.size == 0 || bi2.size == 0 ) return res;\n if( ( bi1.minus && !bi2.minus ) || ( !bi1.minus && bi2.minus ) ) res.minus = true;\n bi1.minus = bi2.minus = false;\n if( bi1.size == 1 && bi2.size == 1 ){\n int m = bi1.val[0] * bi2.val[0];\n BigInteger mult( to_string( m ) );\n mult.minus = res.minus;\n mult.adjust();\n return mult;\n }\n int digit = 1;\n while( digit < max( bi1.size, bi2.size ) ) \n digit *= 2;\n res.size = 2 * digit;\n for( int i = 0 ; i < res.size ; i++ )\n res.val.push_back( 0 );\n vector<int> a;\n vector<int> b;\n for( int i = 0 ; i < digit ; i++ ){\n if( i < bi1.size )\n a.push_back( bi1.val[i] );\n else\n a.push_back( 0 );\n if( i < bi2.size )\n b.push_back( bi2.val[i] );\n else\n b.push_back( 0 );\n }\n\n BigInteger num1, num2, num3, num4;\n num1.size = num2.size = num3.size = num4.size = digit / 2;\n for( int i = 0 ; i < digit / 2 ; i++ ){\n num1.val.push_back( a[ i + digit / 2 ] );\n num2.val.push_back( a[i]);\n num3.val.push_back( b[ i + digit / 2 ] );\n num4.val.push_back( b[i] );\n }\n num1.adjust();\n num2.adjust();\n num3.adjust();\n num4.adjust();\n BigInteger num5 = num1 * num3;\n BigInteger num6 = num2 * num4;\n BigInteger num7 = ( num1 + num2 ) * ( num3 + num4 ) - num5 - num6;\n\n for( int i = 0 ; i < num6.size ; i++ )\n res.val[i] += num6.val[i];\n for( int i = 0 ; i < num7.size; i++ )\n res.val[ i + digit / 2 ] += num7.val[i];\n for( int i = 0 ; i < num5.size ; i++ )\n res.val[ i + digit ] += num5.val[i];\n int up = 0;\n for( int i = 0 ; i < res.size ; i++ ){\n res.val[i] += up;\n up = res.val[i] / 10;\n res.val[i] %= 10;\n }\n\n res.adjust();\n return res;\n \n}\n\nBigInteger operator/( BigInteger bi1, BigInteger bi2 ){\n\n BigInteger res;\n if( !bi1.greater( bi2 ) ) return res;\n if( ( bi1.minus && !bi2.minus ) || ( !bi1.minus && bi2.minus ) ) res.minus = true;\n bi1.minus = bi2.minus = false;\n res.size = bi1.size - bi2.size + 1;\n\n BigInteger num;\n int id = bi1.size;\n while( id >= 0 ){\n BigInteger tmp;\n for( int i = 1 ; i <= 10 ; i++ ){\n tmp = tmp + bi2;\n if( tmp.greater( num ) ){\n if( tmp.same( num ) ){ \n res.val.insert( res.val.begin(), i );\n }\n else{\n tmp = tmp - bi2;\n res.val.insert( res.val.begin(), i - 1 );\n }\n num = num - tmp;\n id--;\n if( id >= 0 ){\n num.val.insert( num.val.begin(), bi1.val[id] );\n num.size++;\n }\n break;\n }\n }\n }\n\n res.adjust();\n return res;\n\n}\n\nBigInteger operator%( BigInteger bi1, BigInteger bi2 ){\n\n return bi1 - bi2 * ( bi1 / bi2 );\n\n}\n\n\n\nint main(){\n\n string A, B;\n cin >> A >> B;\n \n BigInteger a( A );\n BigInteger b( B );\n BigInteger c = a * b;\n c.print();\n\n}", "accuracy": 1, "time_ms": 280, "memory_kb": 3720, "score_of_the_acc": -1.0053, "final_rank": 14 }, { "submission_id": "aoj_NTL_2_C_7525143", "code_snippet": "#include <bits/stdc++.h>\n#define forr(i,a,b) for(int i = (a); i <= (b); i++)\n#define forw(i,a,b) for(int i = (a); i >= (b); i--)\n#define pb push_back\n#define f first\n#define s second\n\nusing namespace std;\ntypedef pair <int,int> pii;\n\nconst int maxn = 1e5 + 5;\n\nstring t(string a, string b)\n{\n string c;\n long n1= a.length(), n2=b.length(),t,n=0;\n if(n1>n2) b.insert(0,n1-n2,'0');\n if(n2>n1) a.insert(0,n2-n1,'0');\n c=a;\n for(int i=a.length()-1;i>=0;i--)\n {\n t=(a[i]-48)+(b[i]-48)+n;\n n=t/10;\n t=t%10;\n c[i]=char(t+48);\n }\n if(n>0) c= char(n+48) +c;\n return c;\n}\n\nstring h(string a, string b)\n{\n string c;\n long n1= a.length(), n2=b.length(),t,n=0;\n if(n1>n2) b.insert(0,n1-n2,'0');\n c=\"\";\n for(int i=n1-1;i>=0;i--)\n {\n t=(a[i]-48)-(b[i]-48)-n;\n if(t<0)\n {\n t+=10;\n n=1;\n }\n else n=0;\n c=char(t+48)+c;\n }\n while(c.length()>1&&c[0]=='0') c.erase(0,1);\n return c;\n}\n\nstring n1(string a,int k)\n{\n string b;\n long i,n=0,t;\n for(i=a.length()-1;i>=0;i--)\n {\n t=n+(a[i]-48)*k;\n n=t/10;\n t=t%10;\n b=char(t+48) + b;\n }\n if(n!=0) b=char(n+48)+b;\n while(b.length()>1&&b[0]=='0') b.erase(0,1);\n return b;\n}\n\nstring nhan(string a, string b)\n{\n string x,tg1=\"0\",tg2,c;\n long i,j=0;\n for(i=b.length()-1;i>=0;i--)\n {\n tg2=n1(a,(b[i]-48));\n tg2.insert(tg2.length(),j,'0');\n j++;\n c=t(tg2,tg1);\n tg1=c;\n }\n while(c.length()>1&&c[0]=='0') c.erase(0,1);\n return c;\n}\nstring a,b;\n\nint main()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n cin >> a >> b;\n if(a[0] == '-' && b[0] == '-')\n {\n a.erase(0,1);\n b.erase(0,1);\n cout << nhan(a,b) << \"\\n\";\n return 0;\n }\n else if(a[0] == '-' && b[0] != '-')\n {\n a.erase(0,1);\n string s1 = nhan(a,b);\n if(s1 != \"0\") s1 = \"-\" + s1;\n cout << s1 << \"\\n\";\n return 0;\n }\n else if(a[0] != '-' && b[0] == '-')\n {\n b.erase(0,1);\n string s1 = nhan(a,b);\n if(s1 != \"0\") s1 = \"-\" + s1;\n cout << s1 << \"\\n\";\n return 0;\n }\n cout << nhan(a,b) << \"\\n\";\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 3580, "score_of_the_acc": -0.0779, "final_rank": 6 }, { "submission_id": "aoj_NTL_2_C_7525139", "code_snippet": "#include <bits/stdc++.h>\n#define forr(i,a,b) for(int i = (a); i <= (b); i++)\n#define forw(i,a,b) for(int i = (a); i >= (b); i--)\n#define pb push_back\n#define f first\n#define s second\n\nusing namespace std;\ntypedef pair <int,int> pii;\n\nconst int maxn = 1e5 + 5;\n\nstring t(string a, string b)\n{\n string c;\n long n1= a.length(), n2=b.length(),t,n=0;\n if(n1>n2) b.insert(0,n1-n2,'0');\n if(n2>n1) a.insert(0,n2-n1,'0');\n c=a;\n for(int i=a.length()-1;i>=0;i--)\n {\n t=(a[i]-48)+(b[i]-48)+n;\n n=t/10;\n t=t%10;\n c[i]=char(t+48);\n }\n if(n>0) c= char(n+48) +c;\n return c;\n}\n\nstring h(string a, string b)\n{\n string c;\n long n1= a.length(), n2=b.length(),t,n=0;\n if(n1>n2) b.insert(0,n1-n2,'0');\n c=\"\";\n for(int i=n1-1;i>=0;i--)\n {\n t=(a[i]-48)-(b[i]-48)-n;\n if(t<0)\n {\n t+=10;\n n=1;\n }\n else n=0;\n c=char(t+48)+c;\n }\n while(c.length()>1&&c[0]=='0') c.erase(0,1);\n return c;\n}\n\nstring n1(string a,int k)\n{\n string b;\n long i,n=0,t;\n for(i=a.length()-1;i>=0;i--)\n {\n t=n+(a[i]-48)*k;\n n=t/10;\n t=t%10;\n b=char(t+48) + b;\n }\n if(n!=0) b=char(n+48)+b;\n while(b.length()>1&&b[0]=='0') b.erase(0,1);\n return b;\n}\n\nstring nhan(string a, string b)\n{\n string x,tg1=\"0\",tg2,c;\n long i,j=0;\n for(i=b.length()-1;i>=0;i--)\n {\n tg2=n1(a,(b[i]-48));\n tg2.insert(tg2.length(),j,'0');\n j++;\n c=t(tg2,tg1);\n tg1=c;\n }\n return c;\n}\nstring a,b;\n\nint main()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n cin >> a >> b;\n if(a[0] == '-' && b[0] == '-')\n {\n a.erase(0,1);\n b.erase(0,1);\n cout << nhan(a,b) << \"\\n\";\n return 0;\n }\n else if(a[0] == '-' && b[0] != '-')\n {\n a.erase(0,1);\n string s1 = nhan(a,b);\n if(s1 != \"0\") s1 = \"-\" + s1;\n cout << s1 << \"\\n\";\n return 0;\n }\n else if(a[0] != '-' && b[0] == '-')\n {\n b.erase(0,1);\n string s1 = nhan(a,b);\n if(s1 != \"0\") s1 = \"-\" + s1;\n cout << s1 << \"\\n\";\n return 0;\n }\n cout << nhan(a,b) << \"\\n\";\n return 0;\n}", "accuracy": 0.84, "time_ms": 30, "memory_kb": 3612, "score_of_the_acc": -0.0783, "final_rank": 16 }, { "submission_id": "aoj_NTL_2_C_6978051", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\nbigInt operator* ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<ll> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = (ll)( str[id++] - '0' );\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<ll> v( 4, 0LL );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n ll top = 0LL;\n ll order = 1LL;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n if( minus && ( size != 0 || top != 0LL ) )\n cout << '-';\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n // sizeの再計算\n void resize(){\n\n size = 0;\n for( int i = dat.size()-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- ){\n if( dat[i][j] != 0 ){\n size = i;\n return;\n }\n }\n }\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n ll lVal = 0LL, rVal = 0LL;\n ll order = 1LL;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n ll lVal = 0LL, rVal = 0LL;\n ll order = 1LL;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n ll up = 0LL; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.minus = l.minus;\n }\n res.resize();\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l.minus & r.minus ){\n if( l < r ){\n l.minus = false;\n r.minus = false;\n res = l - r;\n res.minus = true;\n }\n else{\n l.minus = false;\n r.minus = false;\n res = r - l;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n int maxSize = max( l.size, r.size );\n ll down = 0LL; // 繰り下がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n }\n }\n }\n res.resize();\n return res;\n\n}\n\nbigInt operator* ( bigInt l, bigInt r ){\n\n bigInt res;\n res.minus = l.minus ^ r.minus;\n for( int li = 0 ; li <= l.size ; li++ ){\n for( int lj = 0 ; lj < 4 ; lj++ ){\n for( int ri = 0 ; ri <= r.size ; ri++ ){\n for( int rj = 0 ; rj < 4 ; rj++ )\n res.dat[li+ri+((lj+rj)/4)][(lj+rj)%4] += l.dat[li][lj] * r.dat[ri][rj];\n }\n }\n }\n ll up = 0LL; // 繰り上がり\n for( int i = 0 ; i < res.dat.size() ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n ll now = res.dat[i][j] + up;\n res.dat[i][j] = now % 10;\n up = now / 10;\n }\n }\n res.resize();\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt mult = a * b;\n mult.print();\n\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 39140, "score_of_the_acc": -0.4569, "final_rank": 13 }, { "submission_id": "aoj_NTL_2_C_6978050", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<string>\n#include<cmath>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<set>\n#include<deque>\n#include<list>\n#include<bitset>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing P = pair<ll,ll>;\n\nconst ld EPS = 1e-10;\nconst ll MOD = 1000000007LL;\nconst ll INF = 1LL << 60;\nconst double PI = M_PI;\n\n/////////////////////////////////\n// 多倍長整数\n// [-10^400000,10^400000] を表せる\n\nstruct bigInt;\nbool operator< ( bigInt l, bigInt r );\nbigInt operator+ ( bigInt l, bigInt r );\nbigInt operator- ( bigInt l, bigInt r );\nbigInt operator* ( bigInt l, bigInt r );\n\nstruct bigInt{\n\n bool minus;\n int size;\n vector< vector<ll> > dat;\n\n // コンストラクタ\n bigInt(){\n\n Init();\n\n }\n\n bigInt( string str ){\n\n Init();\n if( str[0] == '-' ){\n minus = true;\n str = str.substr(1);\n }\n size = ( str.length() - 1 ) / 4;\n reverse( str.begin(), str.end() );\n int id = 0;\n for( int i = 0 ; i <= size ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n if( id < str.length() ){\n dat[i][j] = (ll)( str[id++] - '0' );\n }\n }\n }\n\n }\n\n // 初期化\n void Init(){\n\n minus = false;\n size = 0;\n for( int i = 0 ; i < 100000 ; i++ ){\n vector<ll> v( 4, 0LL );\n dat.push_back( v );\n }\n\n }\n\n // 表示\n void print(){\n\n if( minus )\n cout << '-';\n ll top = 0LL;\n ll order = 1LL;\n for( int i = 0 ; i < 4 ; i++ ){\n top += dat[size][i] * order;\n order *= 10;\n }\n cout << top;\n for( int i = size-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- )\n cout << dat[i][j];\n }\n cout << endl;\n\n }\n\n // sizeの再計算\n void resize(){\n\n size = 0;\n for( int i = dat.size()-1 ; i >= 0 ; i-- ){\n for( int j = 3 ; j >= 0 ; j-- ){\n if( dat[i][j] != 0 ){\n size = i;\n return;\n }\n }\n }\n\n }\n\n};\n\n/////////////////////////////////////////////\n// 演算子の定義\nbool operator< ( bigInt l, bigInt r ){\n\n if( l.minus ){\n if( !r.minus ) return true;\n if( l.size == r.size ){\n ll lVal = 0LL, rVal = 0LL;\n ll order = 1LL;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal > rVal;\n }\n return l.size > r.size;\n }\n else{\n if( r.minus ) return false;\n if( l.size == r.size ){\n ll lVal = 0LL, rVal = 0LL;\n ll order = 1LL;\n for( int i = 0 ; i < 4 ; i++ ){\n lVal += order * l.dat[l.size][i];\n rVal += order * r.dat[r.size][i];\n order *= 10;\n }\n return lVal < rVal;\n }\n return l.size < r.size;\n }\n\n}\n\nbigInt operator+ ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = r - l;\n }\n else{\n r.minus = false;\n res = l - r;\n }\n }\n else{\n int maxSize = max( l.size, r.size );\n ll up = 0LL; // 繰り上がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = ( l.dat[i][j] + r.dat[i][j] + up ) % 10;\n up = ( l.dat[i][j] + r.dat[i][j] + up ) / 10;\n }\n }\n res.dat[maxSize+1][0] = up;\n res.minus = l.minus;\n }\n res.resize();\n return res;\n\n}\n\nbigInt operator- ( bigInt l, bigInt r ){\n\n bigInt res;\n if( l.minus ^ r.minus ){\n if( l.minus ){\n l.minus = false;\n res = l + r;\n res.minus = true;\n }\n else{\n r.minus = false;\n res = l + r;\n }\n }\n else{\n if( l.minus & r.minus ){\n if( l < r ){\n l.minus = false;\n r.minus = false;\n res = l - r;\n res.minus = true;\n }\n else{\n l.minus = false;\n r.minus = false;\n res = r - l;\n }\n }\n else{\n if( l < r ){\n res = r - l;\n res.minus = true;\n }\n else{\n int maxSize = max( l.size, r.size );\n ll down = 0LL; // 繰り下がり\n for( int i = 0 ; i <= maxSize ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n res.dat[i][j] = l.dat[i][j] - down - r.dat[i][j];\n if( res.dat[i][j] < 0 ){\n res.dat[i][j] += 10;\n down = 1;\n }\n else\n down = 0;\n }\n }\n }\n }\n }\n res.resize();\n return res;\n\n}\n\nbigInt operator* ( bigInt l, bigInt r ){\n\n bigInt res;\n res.minus = l.minus ^ r.minus;\n for( int li = 0 ; li <= l.size ; li++ ){\n for( int lj = 0 ; lj < 4 ; lj++ ){\n for( int ri = 0 ; ri <= r.size ; ri++ ){\n for( int rj = 0 ; rj < 4 ; rj++ )\n res.dat[li+ri+((lj+rj)/4)][(lj+rj)%4] += l.dat[li][lj] * r.dat[ri][rj];\n }\n }\n }\n ll up = 0LL; // 繰り上がり\n for( int i = 0 ; i < res.dat.size() ; i++ ){\n for( int j = 0 ; j < 4 ; j++ ){\n ll now = res.dat[i][j] + up;\n res.dat[i][j] = now % 10;\n up = now / 10;\n }\n }\n res.resize();\n return res;\n\n}\n\n/////////////////////////////////////////////////\n\nint main(){\n\n string strA, strB;\n cin >> strA >> strB;\n bigInt a( strA );\n bigInt b( strB );\n bigInt mult = a * b;\n mult.print();\n\n}", "accuracy": 0.04, "time_ms": 20, "memory_kb": 39072, "score_of_the_acc": -0.4191, "final_rank": 20 }, { "submission_id": "aoj_NTL_2_C_6679630", "code_snippet": "#include <bits/stdc++.h>\n//#include <atcoder/all>\nusing namespace std;\n\n#define all(x) (x).begin(),(x).end()\n#define print(x) cout << (x) << '\\n'\ntypedef long long ll;\ntypedef long double ld;\nusing P = pair<int,int>;\nusing pll = pair<ll,ll>;\nusing Graph = vector<vector<int>>;\n\n//const ll MOD = 1000000007;\n//const ll MOD = 998244353;\n\ntemplate <typename T> inline bool chmax(T &a, T b) {return a < b ? a = b, true : false;}\ntemplate <typename T> inline bool chmin(T &a, T b) {return a > b ? a = b, true : false;}\n\ntemplate <typename T>\nvoid vin(vector<T> &v) {\n int l = v.size();\n for(int i = 0; i < l; i++) cin >> v[i];\n}\n\ntemplate <typename T>\nvoid vout(vector<T> &v) {\n int l = v.size();\n for(int i = 0; i < l; i++) cout << v[i] << (i < l - 1 ? ' ' : '\\n');\n}\n\nstring calc1(string x, string y, int la, int lb) {\n string ret = \"\";\n int nex = 0;\n for(int i = la - 1; i >= la - lb; i--) {\n int t = x[i] - '0' + y[i - la + lb] - '0' + nex;\n if(t >= 10) {\n nex = t / 10;\n ret += char('0' + t % 10);\n } else {\n nex = 0;\n ret += char('0' + t);\n }\n }\n for(int i = la - lb - 1; i >= 0; i--) {\n int t = x[i] - '0' + nex;\n if(t >= 10) {\n nex = t / 10;\n ret += char('0' + t % 10);\n } else {\n nex = 0;\n ret += char('0' + t);\n }\n }\n if(nex > 0) {\n ret += char('0' + nex);\n }\n reverse(all(ret));\n int L = ret.length();\n int zero = 0;\n for(int i = 0; i < L; i++) {\n if(ret[i] == '0') {\n zero++;\n } else {\n break;\n }\n }\n ret = ret.substr(zero, L - zero);\n if(ret == \"\") {\n ret = \"0\";\n }\n return ret;\n}\n\nstring calc2(string x, string y, int la, int lb) {\n bool p = true;\n if(la < lb) {\n p = false;\n } else if(la == lb && x < y) {\n p = false;\n }\n if(!p) {\n swap(x, y);\n swap(la, lb);\n }\n\n string ret = \"\";\n int nex = 0;\n for(int i = la - 1; i >= la - lb; i--) {\n int t = x[i] - '0' - (y[i - (la - lb)] - '0') - nex;\n if(t < 0) {\n nex = 1;\n ret += char('0' + t + 10);\n } else {\n ret += char('0' + t);\n nex = 0;\n }\n }\n for(int i = la - lb - 1; i >= 0; i--) {\n int t = x[i] - '0' - nex;\n if(t < 0) {\n nex = 1;\n ret += char('0' + t + 10);\n } else {\n nex = 0;\n ret += char('0' + t);\n }\n }\n reverse(all(ret));\n int L = ret.length();\n int zero = 0;\n for(int i = 0; i < L; i++) {\n if(ret[i] == '0') {\n zero++;\n } else {\n break;\n }\n }\n ret = ret.substr(zero, L - zero);\n if(p) {\n ret = \"-\" + ret;\n }\n if(ret == \"-\") {\n ret = \"0\";\n }\n return ret;\n}\n\nstring calc(string A, string B) {\n int la = A.length();\n int lb = B.length();\n\n string RET;\n if(A[0] == '-' && B[0] == '-') {\n A = A.substr(1, la - 1);\n B = B.substr(1, lb - 1);\n la--;\n lb--;\n if(la < lb) {\n swap(A, B);\n swap(la, lb);\n }\n RET = calc1(A, B, la, lb);\n RET = \"-\" + RET;\n } else if(A[0] == '-') {\n A = A.substr(1, la - 1);\n la--;\n RET = calc2(A, B, la, lb);\n } else if(B[0] == '-') {\n swap(A, B);\n swap(la, lb);\n A = A.substr(1, la - 1);\n la--;\n RET = calc2(A, B, la, lb);\n } else {\n if(la < lb) {\n swap(A, B);\n swap(la, lb);\n }\n RET = calc1(A, B, la, lb);\n }\n return RET;\n}\n\nstring Mcalc2(string A, char b, int la) {\n string ret = \"\";\n int nex = 0;\n for(int i = la - 1; i >= 0; i--) {\n int t = int(A[i] - '0') * int(b - '0') + nex;\n nex = t / 10;\n ret += char('0' + t % 10);\n\n }\n while(nex > 0) {\n ret += char('0' + nex % 10);\n nex /= 10;\n }\n reverse(all(ret));\n int L = ret.length();\n int zero = 0;\n for(int i = 0; i < L; i++) {\n if(ret[i] == '0') {\n zero++;\n } else {\n break;\n }\n }\n ret = ret.substr(zero, L - zero);\n if(ret == \"\") {\n ret = \"0\";\n }\n return ret;\n}\n\nstring Mcalc1(string A, string B, int la, int lb) {\n string ret = \"0\";\n for(int i = lb - 1; i >= 0; i--) {\n string tmp = Mcalc2(A, B[i], la);\n for(int j = 0; j < lb - 1 - i; j++) {\n tmp += '0';\n }\n ret = calc(ret, tmp);\n }\n return ret;\n}\n\nstring Mcalc(string A, string B) {\n int la = A.length();\n int lb = B.length();\n string Mret;\n if(A[0] == '-' && B[0] == '-') {\n A = A.substr(1, la - 1);\n B = B.substr(1, lb - 1);\n la--;\n lb--;\n Mret = Mcalc1(A, B, la, lb);\n } else if(A[0] == '-') {\n A = A.substr(1, la - 1);\n la--;\n Mret = Mcalc1(A, B, la, lb);\n if(Mret != \"0\") {\n Mret = \"-\" + Mret;\n }\n } else if(B[0] == '-') {\n B = B.substr(1, lb - 1);\n lb--;\n Mret = Mcalc1(A, B, la, lb);\n if(Mret != \"0\") {\n Mret = \"-\" + Mret;\n }\n } else {\n Mret = Mcalc1(A, B, la, lb);\n }\n return Mret;\n}\n\nint main() {\n cin.tie(0); cout.tie(0);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(18);\n\n string A, B;\n cin >> A >> B;\n string ans = Mcalc(A, B);\n print(ans);\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3556, "score_of_the_acc": -0.0036, "final_rank": 3 }, { "submission_id": "aoj_NTL_2_C_6679022", "code_snippet": "#include <bits/stdc++.h>\n\n\n// #include <atcoder/convolution>\n#include <iostream>\n\n#include <algorithm>\n#include <cassert>\n#include <vector>\n\nnamespace rklib {\n\ntemplate <class T>\nbool chmax(T &a, const T &b) {\n if (a < b) {\n a = b;\n return true;\n }\n return false;\n}\n\ntemplate <class T>\nbool chmin(T &a, const T &b) {\n if (a > b) {\n a = b;\n return true;\n }\n return false;\n}\n\ntemplate <class T>\nbool chmin_non_negative(T &a, const T &b) {\n if (a < 0 || a > b) {\n a = b;\n return true;\n }\n return false;\n}\n\ntemplate <class T>\nT div_floor(T a, T b) {\n if (b < 0) a *= -1, b *= -1;\n return a >= 0 ? a / b : (a + 1) / b - 1;\n}\n\ntemplate <class T>\nT div_ceil(T a, T b) {\n if (b < 0) a *= -1, b *= -1;\n return a > 0 ? (a - 1) / b + 1 : a / b;\n}\n\n} // namespace rklib\n\n#include <string>\n#include <type_traits>\n#include <vector>\n\nnamespace rklib {\n\nstruct BigInt {\n public:\n BigInt() : BigInt(0) {}\n template <typename T, std::enable_if_t<std::is_integral<T>::value,\n std::nullptr_t> = nullptr>\n BigInt(T x) : BigInt(std::vector<T>(1, x)) {}\n template <typename T, std::enable_if_t<std::is_integral<T>::value,\n std::nullptr_t> = nullptr>\n BigInt(std::vector<T> a) {\n while (a.size() >= 2 && a.back() == 0) a.pop_back();\n if (a.size() == 1 && a[0] == 0) {\n sgn = 0;\n return;\n }\n sgn = (a.back() > 0 ? 1 : -1);\n if (sgn < 0) {\n std::transform(a.begin(), a.end(), a.begin(),\n [](T x) { return -x; });\n }\n v = normalize(a);\n }\n BigInt(std::string s) : sgn(1) {\n if (s[0] == '-') {\n s.erase(s.begin());\n sgn = -1;\n }\n if (s == \"0\") {\n sgn = 0;\n v = {0};\n return;\n }\n for (int r = int(s.size()), l = std::max(0, r - log10_base); r > 0;\n r = l, l = std::max(0, r - log10_base)) {\n int tmp = 0;\n for (int i = l; i < r; ++i) {\n tmp = tmp * 10 + (s[i] - '0');\n }\n v.push_back(tmp);\n }\n }\n\n BigInt& operator+=(const BigInt& rhs) {\n int r_sgn = rhs.sgn;\n if (r_sgn == 0) return *this;\n if (sgn == 0) return *this = rhs;\n if (v.size() < rhs.v.size()) v.resize(rhs.v.size(), 0);\n for (size_t i = 0; i < rhs.v.size(); i++) {\n if (sgn == r_sgn)\n v[i] += rhs.v[i];\n else\n v[i] -= rhs.v[i];\n }\n normalize();\n return *this;\n }\n BigInt& operator-=(const BigInt& rhs) {\n int r_sgn = rhs.sgn;\n if (r_sgn == 0) return *this;\n if (sgn == 0) return *this = -rhs;\n if (v.size() < rhs.v.size()) v.resize(rhs.v.size(), 0);\n for (size_t i = 0; i < rhs.v.size(); i++) {\n if (sgn == r_sgn)\n v[i] -= rhs.v[i];\n else\n v[i] += rhs.v[i];\n }\n normalize();\n return *this;\n }\n BigInt& operator*=(const BigInt& rhs) {\n int r_sgn = rhs.sgn;\n if (sgn == 0) return *this;\n if (r_sgn == 0) return *this = rhs;\n\n int res_sgn = sgn * r_sgn;\n\n // if (v.size() <= 10 || rhs.v.size() <= 10) {\n // v = multiply_naive(v, rhs.v);\n // } else if (v.size() + rhs.v.size() - 1 <= (1 << 24)) {\n // v = multiply_ntt(v, rhs.v);\n // }\n\n if (v.size() <= 2 || rhs.v.size() <= 2) {\n v = multiply_naive(v, rhs.v);\n } else {\n BigInt a = *this, b = rhs;\n a.sgn = b.sgn = 1;\n *this = multiply_karatsuba(a, b);\n }\n\n this->sgn = res_sgn;\n\n return *this;\n }\n\n friend BigInt operator+(const BigInt& lhs, const BigInt& rhs) {\n return BigInt(lhs) += rhs;\n }\n friend BigInt operator-(const BigInt& lhs, const BigInt& rhs) {\n return BigInt(lhs) -= rhs;\n }\n friend BigInt operator*(const BigInt& lhs, const BigInt& rhs) {\n return BigInt(lhs) *= rhs;\n }\n\n BigInt operator+() const { return *this; }\n BigInt operator-() const { return {-sgn, v}; }\n\n friend std::istream& operator>>(std::istream& is, BigInt& rhs) {\n std::string s;\n is >> s;\n rhs = BigInt(s);\n return is;\n }\n friend std::ostream& operator<<(std::ostream& os, const BigInt& rhs) {\n if (rhs.sgn < 0) os << \"-\";\n for (int i = int(rhs.v.size()) - 1; i >= 0; i--) {\n if (i == int(rhs.v.size()) - 1) {\n os << rhs.v[i];\n } else {\n os << std::to_string(rhs.v[i] + base).substr(1, log10_base);\n }\n }\n return os;\n }\n\n private:\n static constexpr int base = 10, log10_base = 1;\n int sgn;\n std::vector<int> v;\n\n BigInt(int sgn, std::vector<int> v) : sgn(sgn), v(v) {}\n\n void normalize() {\n if (v.back() < 0) {\n sgn = -sgn;\n std::transform(v.begin(), v.end(), v.begin(),\n [](int x) { return -x; });\n }\n int carry = 0;\n for (size_t i = 0; i < v.size(); i++) {\n v[i] += carry;\n if (0 <= v[i] && v[i] < base) {\n carry = 0;\n continue;\n }\n carry = div_floor(v[i], base);\n v[i] -= carry * base;\n if (i == v.size() - 1 && carry != 0) {\n v.push_back(carry % base);\n carry /= base;\n }\n }\n\n while (v.size() >= 2 && v.back() == 0) v.pop_back();\n if (v.size() == 1 && v[0] == 0) sgn = 0;\n }\n\n template <class T>\n static std::vector<int> normalize(const std::vector<T>& c) {\n std::vector<int> res(c.size());\n T carry = 0;\n for (size_t i = 0; i < c.size(); i++) {\n T tmp = c[i];\n tmp += carry;\n if (0 <= tmp && tmp < T(base)) {\n carry = 0;\n res[i] = int(tmp);\n continue;\n }\n carry = div_floor(tmp, T(base));\n res[i] = int(tmp - carry * base);\n }\n while (carry > 0) {\n res.push_back(int(carry % base));\n carry /= base;\n }\n\n while (res.size() >= 2 && res.back() == 0) res.pop_back();\n\n return res;\n }\n\n static std::vector<int> multiply_naive(const std::vector<int>& a,\n const std::vector<int>& b) {\n std::vector<long long> c(a.size() + b.size() - 1, 0);\n for (size_t i = 0; i < a.size(); i++) {\n for (size_t j = 0; j < b.size(); j++) {\n c[i + j] += a[i] * b[j];\n }\n }\n\n return normalize(c);\n }\n // static std::vector<int> multiply_ntt(const std::vector<int>& a,\n // const std::vector<int>& b) {\n // std::vector<long long> al(a.size()), bl(b.size());\n // for (size_t i = 0; i < a.size(); i++) {\n // al[i] = (long long)a[i];\n // }\n // for (size_t i = 0; i < b.size(); i++) {\n // bl[i] = (long long)b[i];\n // }\n\n // std::vector<long long> c = atcoder::convolution_ll(al, bl);\n\n // return normalize(c);\n // }\n static BigInt multiply_karatsuba(BigInt a, BigInt b) {\n // std::cout << a << \" \" << b << std::endl;\n int na = a.v.size(), nb = b.v.size();\n if (na <= 2 || nb <= 2) return a * b;\n\n int n = std::max(na, nb);\n if (na < n) a.v.resize(n, 0);\n if (nb < n) b.v.resize(n, 0);\n\n int k = n / 2;\n BigInt x(std::vector<int>(a.v.begin() + k, a.v.end()));\n BigInt y(std::vector<int>(a.v.begin(), a.v.begin() + k));\n BigInt z(std::vector<int>(b.v.begin() + k, b.v.end()));\n BigInt w(std::vector<int>(b.v.begin(), b.v.begin() + k));\n\n BigInt xz = multiply_karatsuba(x, z);\n BigInt yw = multiply_karatsuba(y, w);\n BigInt t = multiply_karatsuba(x + y, z + w) - xz - yw;\n\n a.v = std::vector<int>(2 * k, 0);\n a.v.insert(a.v.end(), xz.v.begin(), xz.v.end());\n b.v = std::vector<int>(k, 0);\n b.v.insert(b.v.end(), t.v.begin(), t.v.end());\n\n return a + b + yw;\n }\n};\n\n} // namespace rklib\n\n\n#define For(i, a, b) for (int i = (int)(a); (i) < (int)(b); ++(i))\n#define rFor(i, a, b) for (int i = (int)(a)-1; (i) >= (int)(b); --(i))\n#define rep(i, n) For(i, 0, n)\n#define rrep(i, n) rFor(i, n, 0)\n#define fi first\n#define se second\n\nusing namespace std;\nusing namespace rklib;\n\nusing lint = long long;\nusing pii = pair<int, int>;\nusing pll = pair<lint, lint>;\n\nint main() {\n BigInt a, b;\n cin >> a >> b;\n cout << a * b << \"\\n\";\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3660, "score_of_the_acc": -0.0047, "final_rank": 4 }, { "submission_id": "aoj_NTL_2_C_6347786", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nstruct BigIntTiny {\n int sign;\n std::vector<int> v;\n\n BigIntTiny() : sign(1) {}\n BigIntTiny(const std::string& s) { *this = s; }\n BigIntTiny(int v) {\n char buf[21];\n sprintf(buf, \"%d\", v);\n *this = buf;\n }\n void zip(int unzip) {\n if (unzip == 0) {\n for (int i = 0; i < (int)v.size(); i++)\n v[i] = get_pos(i * 4) + get_pos(i * 4 + 1) * 10 + get_pos(i * 4 + 2) * 100 + get_pos(i * 4 + 3) * 1000;\n }\n else\n for (int i = (v.resize(v.size() * 4), (int)v.size() - 1), a; i >= 0; i--)\n a = (i % 4 >= 2) ? v[i / 4] / 100 : v[i / 4] % 100, v[i] = (i & 1) ? a / 10 : a % 10;\n setsign(1, 1);\n }\n int get_pos(unsigned pos) const { return pos >= v.size() ? 0 : v[pos]; }\n BigIntTiny& setsign(int newsign, int rev) {\n for (int i = (int)v.size() - 1; i > 0 && v[i] == 0; i--)\n v.erase(v.begin() + i);\n sign = (v.size() == 0 || (v.size() == 1 && v[0] == 0)) ? 1 : (rev ? newsign * sign : newsign);\n return *this;\n }\n std::string to_str() const {\n BigIntTiny b = *this;\n std::string s;\n for (int i = (b.zip(1), 0); i < (int)b.v.size(); ++i)\n s += char(*(b.v.rbegin() + i) + '0');\n return (sign < 0 ? \"-\" : \"\") + (s.empty() ? std::string(\"0\") : s);\n }\n bool absless(const BigIntTiny& b) const {\n if (v.size() != b.v.size()) return v.size() < b.v.size();\n for (int i = (int)v.size() - 1; i >= 0; i--)\n if (v[i] != b.v[i]) return v[i] < b.v[i];\n return false;\n }\n BigIntTiny operator-() const {\n BigIntTiny c = *this;\n c.sign = (v.size() > 1 || v[0]) ? -c.sign : 1;\n return c;\n }\n BigIntTiny& operator=(const std::string& s) {\n if (s[0] == '-')\n *this = s.substr(1);\n else {\n for (int i = (v.clear(), 0); i < (int)s.size(); ++i)\n v.push_back(*(s.rbegin() + i) - '0');\n zip(0);\n }\n return setsign(s[0] == '-' ? -1 : 1, sign = 1);\n }\n bool operator<(const BigIntTiny& b) const {\n return sign != b.sign ? sign < b.sign : (sign == 1 ? absless(b) : b.absless(*this));\n }\n bool operator==(const BigIntTiny& b) const { return v == b.v && sign == b.sign; }\n BigIntTiny& operator+=(const BigIntTiny& b) {\n if (sign != b.sign) return *this = (*this) - -b;\n v.resize(std::max(v.size(), b.v.size()) + 1);\n for (int i = 0, carry = 0; i < (int)b.v.size() || carry; i++) {\n carry += v[i] + b.get_pos(i);\n v[i] = carry % 10000, carry /= 10000;\n }\n return setsign(sign, 0);\n }\n BigIntTiny operator+(const BigIntTiny& b) const {\n BigIntTiny c = *this;\n return c += b;\n }\n void add_mul(const BigIntTiny& b, int mul) {\n v.resize(std::max(v.size(), b.v.size()) + 2);\n for (int i = 0, carry = 0; i < (int)b.v.size() || carry; i++) {\n carry += v[i] + b.get_pos(i) * mul;\n v[i] = carry % 10000, carry /= 10000;\n }\n }\n BigIntTiny operator-(const BigIntTiny& b) const {\n if (sign != b.sign) return (*this) + -b;\n if (absless(b)) return -(b - *this);\n BigIntTiny c;\n for (int i = 0, borrow = 0; i < (int)v.size(); i++) {\n borrow += v[i] - b.get_pos(i);\n c.v.push_back(borrow);\n c.v.back() -= 10000 * (borrow >>= 31);\n }\n return c.setsign(sign, 0);\n }\n BigIntTiny operator*(const BigIntTiny& b) const {\n if (b < *this) return b * *this;\n BigIntTiny c, d = b;\n for (int i = 0; i < (int)v.size(); i++, d.v.insert(d.v.begin(), 0))\n c.add_mul(d, v[i]);\n return c.setsign(sign * b.sign, 0);\n }\n BigIntTiny operator/(const BigIntTiny& b) const {\n BigIntTiny c, d;\n d.v.resize(v.size());\n double db = 1.0 / (b.v.back() + (b.get_pos((unsigned)b.v.size() - 2) / 1e4) +\n (b.get_pos((unsigned)b.v.size() - 3) + 1) / 1e8);\n for (int i = (int)v.size() - 1; i >= 0; i--) {\n c.v.insert(c.v.begin(), v[i]);\n int m = (int)((c.get_pos((int)b.v.size()) * 10000 + c.get_pos((int)b.v.size() - 1)) * db);\n c = c - b * m, d.v[i] += m;\n while (!(c < b))\n c = c - b, d.v[i] += 1;\n }\n return d.setsign(sign * b.sign, 0);\n }\n BigIntTiny operator%(const BigIntTiny& b) const { return *this - *this / b * b; }\n bool operator>(const BigIntTiny& b) const { return b < *this; }\n bool operator<=(const BigIntTiny& b) const { return !(b < *this); }\n bool operator>=(const BigIntTiny& b) const { return !(*this < b); }\n bool operator!=(const BigIntTiny& b) const { return !(*this == b); }\n};\n//FFT部分 \nconst double PI = acos(-1);\ntypedef complex<double> Complex;\nconst int maxn = 3e6 + 10;\n\nComplex a[maxn], b[maxn];\nint m, n;\nint bit = 2, rev[maxn];\nint ans[maxn];\n\nvoid get_rev() {\n memset(rev, 0, sizeof(rev));\n while (bit <= n + m) bit <<= 1;\n for (int i = 0; i < bit; ++i) {\n rev[i] = (rev[i >> 1] >> 1) | (bit >> 1) * (i & 1);\n }\n}\n\nvoid FFT(Complex* a, int op) {\n for (int i = 0; i < bit; ++i) {\n if (i < rev[i]) swap(a[i], a[rev[i]]);\n }\n for (int mid = 1; mid < bit; mid <<= 1) {\n Complex wn = Complex(cos(PI / mid), op * sin(PI / mid));\n for (int j = 0; j < bit; j += mid << 1) {\n Complex w(1, 0);\n for (int k = 0; k < mid; ++k, w = w * wn) {\n Complex x = a[j + k], y = w * a[j + k + mid];\n a[j + k] = x + y, a[j + k + mid] = x - y;\n }\n }\n }\n}\n\nstring fftmul(string s1, string s2) {\n //cout<<s1<<endl<<s2<<endl;\n n = s1.size(), m = s2.size();\n memset(a, 0, sizeof(a));\n memset(b, 0, sizeof(b));\n for (int i = 0; i < n; ++i) {\n a[i] = s1[n - i - 1] - '0';\n }\n for (int i = 0; i < m; ++i) {\n b[i] = s2[m - i - 1] - '0';\n }\n get_rev();\n FFT(a, 1);\n FFT(b, 1);\n for (int i = 0; i <= bit; ++i) {\n a[i] *= b[i];\n }\n FFT(a, -1);\n for (int i = 0; i < n + m; ++i) {\n ans[i] = (int)(a[i].real() / bit + 0.5);\n }\n for (int i = 1; i < n + m; ++i) {\n ans[i] = ans[i] + ans[i - 1] / 10;\n ans[i - 1] = ans[i - 1] % 10;\n }\n int s = n + m - 1;\n for (; s >= 0; --s) {\n if (ans[s]) break;\n }\n string ret;\n if (s < 0) ret.push_back('0');//printf(\"0\\n\");\n else {\n for (int i = s; i >= 0; --i) {\n ret.push_back(ans[i] + '0');//printf(\"%d\", ans[i]);\n }\n //printf(\"\\n\");\n }\n return ret;\n}\n\nBigIntTiny fastmul(BigIntTiny b1, BigIntTiny b2) {\n //cout<<b1.to_str()<<'\\n'<<b2.to_str()<<endl;\n //cout<<fftmul(b1.to_str(),b2.to_str())<<endl;\n bool flag = 0;//要不要变负,1负\n if (b1 < 0)b1 = -b1, flag ^= 1;\n if (b2 < 0)b2 = -b2, flag ^= 1;\n BigIntTiny ans = fftmul(b1.to_str(), b2.to_str());\n return flag ? -ans : ans;\n}\nconst int p = 998244353;\nBigIntTiny qpow(BigIntTiny a, BigIntTiny n, BigIntTiny p) {\n BigIntTiny res = 1;\n while (n>0) {\n if (n % 2 == 1) res = res * a % p;\n a = a * a % p;\n n = n / 2;\n }\n return res;\n}\nBigIntTiny qpow1(BigIntTiny a, BigIntTiny n) {\n BigIntTiny res = 1;\n while (n > 0) {\n if (n % 2 == 1) res = res * a;\n a = a * a;\n n = n / 2;\n }\n return res;\n}\nBigIntTiny v[51], sum[51];\nint main(){\n string a, b;\n cin>>a>>b;\n cout<<(BigIntTiny(a)*BigIntTiny(b)).to_str()<<'\\n';\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 97060, "score_of_the_acc": -1.037, "final_rank": 15 }, { "submission_id": "aoj_NTL_2_C_5535128", "code_snippet": "#include <bits/stdc++.h>\n#include <sstream>\n\nusing namespace std;\n\n//#define InputOutputOperatorOverload\n\nclass BigData {\npublic:\n\tBigData() {\n\t\tthis->data = \"\";\n\t\tthis->minFlag = false;\n\t}\n\n#ifdef InputOutputOperatorOverload\n\tfriend istream& operator >>(istream& in, BigData& bigdata) {\n\t\tin >> bigdata.data;\n\t\treturn in;\n\t}\n\n\tfriend ostream& operator <<(ostream& out, BigData& bigdata) {\n\t\tout << bigdata.data;\n\t\treturn out;\n\t}\n#else\n\tstring getValue() {\n\t\treturn this->data;\n\t}\n\n\tvoid setValue(string value) {\n\t\tthis->data = value;\n\t}\n#endif\n\n\tBigData operator +(const BigData& add) {\n\t\tstring add1, add2;\n\t\tBigData ans;\n\n\t\tadd1 = this->data;\n\t\tadd2 = add.data;\n\t\tif (add1[0] != '-' && add2[0] != '-') {\n\t\t\tminFlag = false;\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = getAdd(add1, add2);\n\t\t}\n\t\telse if (add1[0] == '-' && add2[0] == '-') {\n\t\t\tminFlag = true;\n\t\t\tadd1 = add1.substr(1);\n\t\t\tadd2 = add2.substr(1);\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = getAdd(add1, add2);\n\t\t}\n\t\telse if (add1[0] == '-' && add2[0] != '-') {\n\t\t\tadd1 = add1.substr(1);\n\t\t\tminFlag = compareAndChange(add1, add2) ? false : true;\n\t\t\tif (add1 == add2) {\n\t\t\t\tminFlag = false;\n\t\t\t}\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = calculate(add1, add2);\n\t\t}\n\t\telse if (add1[0] != '-' && add2[0] == '-') {\n\t\t\tadd2 = add2.substr(1);\n\t\t\tminFlag = compareAndChange(add1, add2);\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = calculate(add1, add2);\n\t\t}\n\n\t\tif (minFlag) {\n\t\t\tans.data += \"-\";\n\t\t}\n\t\treverse(ans.data.begin(), ans.data.end());\n\n\t\treturn ans;\n\t}\n\n\tBigData operator -(const BigData& sub) {\n\t\tstring sub1, sub2;\n\t\tBigData ans;\n\n\t\tsub1 = this->data;\n\t\tsub2 = sub.data;\n\t\tif (sub1[0] != '-' && sub2[0] == '-') {\n\t\t\tminFlag = false;\n\t\t\tsub2 = sub2.substr(1);\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = getAdd(sub1, sub2);\n\t\t}\n\t\telse if (sub1[0] == '-' && sub2[0] != '-') {\n\t\t\tminFlag = true;\n\t\t\tsub1 = sub1.substr(1);\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = getAdd(sub1, sub2);\n\t\t}\n\t\telse if (sub1[0] != '-' && sub2[0] != '-') {\n\t\t\tminFlag = compareAndChange(sub1, sub2);\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = calculate(sub1, sub2);\n\t\t}\n\t\telse if (sub1[0] == '-' && sub2[0] == '-') {\n\t\t\tsub1 = sub1.substr(1);\n\t\t\tsub2 = sub2.substr(1);\n\t\t\tminFlag = compareAndChange(sub1, sub2) ? false : true;\n\t\t\tif (sub1 == sub2) {\n\t\t\t\tminFlag = false;\n\t\t\t}\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = calculate(sub1, sub2);\n\t\t}\n\n\t\tif (minFlag) {\n\t\t\tans.data += \"-\";\n\t\t}\n\t\treverse(ans.data.begin(), ans.data.end());\n\n\t\treturn ans;\n\t}\n\n\tBigData operator *(const BigData& mul) {\n\t\tstring mul1, mul2;\n\t\tBigData ans;\n\n\t\tmul1 = this->data;\n\t\tmul2 = mul.data;\n\t\tif (mul1[0] != '-' && mul2[0] != '-') {\n\t\t\tminFlag = false;\n\t\t}\n\t\telse if (mul1[0] == '-' && mul2[0] == '-') {\n\t\t\tminFlag = false;\n\t\t\tmul1 = mul1.substr(1);\n\t\t\tmul2 = mul2.substr(1);\n\t\t}\n\t\telse if (mul1[0] == '-' && mul2[0] != '-') {\n\t\t\tminFlag = true;\n\t\t\tmul1 = mul1.substr(1);\n\t\t}\n\t\telse if (mul1[0] != '-' && mul2[0] == '-') {\n\t\t\tminFlag = true;\n\t\t\tmul2 = mul2.substr(1);\n\t\t}\n\n\t\treverse(mul1.begin(), mul1.end());\n\t\treverse(mul2.begin(), mul2.end());\n\t\tans.data = getMul(mul1, mul2);\n\n\t\tif (ans.data != \"0\" && minFlag) {\n\t\t\tans.data += \"-\";\n\t\t}\n\t\treverse(ans.data.begin(), ans.data.end());\n\n\t\treturn ans;\n\t}\n\n\tBigData operator /(const BigData& div) {\n\t\tstring div1, div2, rem;\n\t\tBigData ans;\n\n\t\tdiv1 = this->data;\n\t\tdiv2 = div.data;\n\t\tif (div1[0] != '-' && div2[0] != '-') {\n\t\t\tminFlag = false;\n\t\t}\n\t\telse if (div1[0] == '-' && div2[0] == '-') {\n\t\t\tminFlag = false;\n\t\t\tdiv1 = div1.substr(1);\n\t\t\tdiv2 = div2.substr(1);\n\t\t}\n\t\telse if (div1[0] == '-' && div2[0] != '-') {\n\t\t\tminFlag = true;\n\t\t\tdiv1 = div1.substr(1);\n\t\t}\n\t\telse if (div1[0] != '-' && div2[0] == '-') {\n\t\t\tminFlag = true;\n\t\t\tdiv2 = div2.substr(1);\n\t\t}\n\t\t\n\t\tans.data = getDiv(div1, div2, rem);\n\t\tif (ans.data != \"0\" && minFlag) {\n\t\t\tans.data = \"-\" + ans.data;\n\t\t}\n\n\t\treturn ans;\n\t}\n\n\tBigData operator %(const BigData& div) {\n\t\tstring div1, div2, rem;\n\t\tBigData ans;\n\n\t\tdiv1 = this->data;\n\t\tdiv2 = div.data;\n\t\tif (div1[0] != '-' && div2[0] != '-') {\n\t\t\tminFlag = false;\n\t\t}\n\t\telse if (div1[0] == '-' && div2[0] == '-') {\n\t\t\tminFlag = true;\n\t\t\tdiv1 = div1.substr(1);\n\t\t\tdiv2 = div2.substr(1);\n\t\t}\n\t\telse if (div1[0] == '-' && div2[0] != '-') {\n\t\t\tminFlag = true;\n\t\t\tdiv1 = div1.substr(1);\n\t\t}\n\t\telse if (div1[0] != '-' && div2[0] == '-') {\n\t\t\tminFlag = false;\n\t\t\tdiv2 = div2.substr(1);\n\t\t}\n\n\t\tans.data = getDiv(div1, div2, rem);\n\t\tans.data = rem;\n\t\tif (ans.data != \"0\" && minFlag) {\n\t\t\tans.data = \"-\" + ans.data;\n\t\t}\n\t\t\n\t\treturn ans;\n\t}\n\n\nprivate:\n\tstring data;\n\tbool minFlag;\n\n\tbool compareAndChange(string& d1, string& d2) {\n\t\tunsigned int len1, len2;\n\n\t\tlen1 = d1.size();\n\t\tlen2 = d2.size();\n\t\tif (len1 > len2) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (len1 < len2 || d1 < d2) {\n\t\t\td1.swap(d2);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool compare(const string& d1, const string& d2) {\n\t\tunsigned int len1, len2;\n\n\t\tlen1 = d1.size();\n\t\tlen2 = d2.size();\n\t\tif (len1 > len2) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (len1 < len2 || d1 < d2) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstring getAdd(const string& add1, const string& add2) {\n\t\tunsigned int len1, len2, i;\n\t\tint acc, sum;\n\t\tstringstream ss;\n\n\t\tlen1 = add1.size();\n\t\tlen2 = add2.size();\n\t\t//cout << add1 << endl << add2 << endl;\n\n\t\ti = 0;\n\t\tacc = 0;\n\t\tss.clear();\n\t\tss.str(\"\");\n\t\twhile (i < len1 && i < len2) {\n\t\t\tsum = (add1[i] - '0') + (add2[i] - '0') + acc;\n\t\t\tacc = sum / 10;\n\t\t\tsum %= 10;\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len1) {\n\t\t\tsum = (add1[i] - '0') + acc;\n\t\t\tacc = sum / 10;\n\t\t\tsum %= 10;\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len2) {\n\t\t\tsum = (add2[i] - '0') + acc;\n\t\t\tacc = sum / 10;\n\t\t\tsum %= 10;\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\tif (acc == 1) {\n\t\t\tss << 1;\n\t\t}\n\n\t\treturn ss.str();\n\t}\n\n\tstring getSub(const string& sub1, const string& sub2) {\n\t\tunsigned int len1, len2, i;\n\t\tint acc, sum;\n\t\tstringstream ss;\n\n\t\tlen1 = sub1.size();\n\t\tlen2 = sub2.size();\n\t\t//cout << sub1 << endl << sub2 << endl;\n\n\t\ti = 0;\n\t\tacc = 0;\n\t\tss.clear();\n\t\tss.str(\"\");\n\t\twhile (i < len1 && i < len2) {\n\t\t\tsum = (sub1[i] - '0') - acc - (sub2[i] - '0');\n\t\t\tif (sum < 0) {\n\t\t\t\tacc = 1;\n\t\t\t\tsum += 10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tacc = 0;\n\t\t\t}\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len1) {\n\t\t\tsum = (sub1[i] - '0') - acc;\n\t\t\tif (sum < 0) {\n\t\t\t\tacc = 1;\n\t\t\t\tsum += 10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tacc = 0;\n\t\t\t}\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len2) {\n\t\t\tsum = (sub2[i] - '0') - acc;\n\t\t\tif (sum < 0) {\n\t\t\t\tacc = 1;\n\t\t\t\tsum += 10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tacc = 0;\n\t\t\t}\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\treturn ss.str();\n\t}\n\n\tstring calculate(const string& data1, const string& data2) {\n\t\tstring ans;\n\n\t\tans = getSub(data1, data2);\n\t\twhile (true) {\n\t\t\tauto it = ans.rbegin();\n\t\t\tif (ans.size() == 1 || *it != '0') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tans.pop_back();\n\t\t}\n\t\treturn ans;\n\t}\n\n\tstring getMul(const string& mul1, const string& mul2) {\n\t\tunsigned int len1, len2;\n\t\tint acc, sum, base;\n\t\tstringstream ss;\n\t\tstring curSum;\n\n\t\tif (mul1 == \"0\" || mul2 == \"0\") {\n\t\t\treturn \"0\";\n\t\t}\n\n\t\tlen1 = mul1.size();\n\t\tlen2 = mul2.size();\n\t\t//cout << mul1 << endl << mul2 << endl;\n\n\t\tcurSum = \"\";\n\t\tfor (unsigned int i = 0; i < len2; ++i) {\n\t\t\tstring temp(\"\"), res(\"\");\n\t\t\tfor (unsigned int k = 0; k < i; ++k) {\n\t\t\t\ttemp += \"0\";\n\t\t\t}\n\t\t\tbase = mul2[i] - '0';\n\t\t\tacc = 0;\n\t\t\tss.clear();\n\t\t\tss.str(\"\");\n\t\t\tfor (unsigned int j = 0; j < len1; ++j) {\n\t\t\t\tsum = base * (mul1[j] - '0') + acc;\n\t\t\t\tacc = sum / 10;\n\t\t\t\tsum %= 10;\n\t\t\t\tss << sum;\n\t\t\t}\n\t\t\tif (acc != 0) {\n\t\t\t\tss << acc;\n\t\t\t}\n\t\t\tres = temp + ss.str();\n\t\t\t//cout << \"res=\" << res << endl;\n\t\t\tcurSum = getAdd(curSum, res);\n\t\t\t//cout << \"curSum=\" << curSum << endl;\n\t\t}\n\n\t\treturn curSum;\n\t}\n\n\tstring getDiv(const string& div1, const string& div2, string &rem) {\n\t\tunsigned int len1, len2, i;\n\t\tunsigned int k;\n\t\tstringstream ss;\n\t\tstring curSum, curSumTmp, curNum, div2Tmp, ans;\n\n\t\tif (compare(div1, div2)) {\n\t\t\trem = \"0\";\n\t\t\treturn \"0\";\n\t\t}\n\n\t\tlen1 = div1.size();\n\t\tlen2 = div2.size();\n\t\t//cout << div1 << endl << div2 << endl;\n\n\t\tans = \"\";\n\t\tcurSum = div1.substr(0, len2);\n\t\ti = len2 - 1;\n\t\tif (curSum < div2) {\n\t\t\tcurSum += div1[len2];\n\t\t\ti = len2;\n\t\t}\n\t\t//cout << \"curSum=\" << curSum << endl;\n\t\tfor (; i < len1; ++i) {\n\t\t\tif (compare(curSum, div2)) {\n\t\t\t\tcurSum += div1[i];\n\t\t\t}\n\t\t\t//cout << \"1:curSum=\" << curSum << endl;\n\t\t\tcurSumTmp = curSum;\n\t\t\tdiv2Tmp = div2;\n\t\t\treverse(curSumTmp.begin(), curSumTmp.end());\n\t\t\treverse(div2Tmp.begin(), div2Tmp.end());\n\t\t\tfor (k = 0; k < 10; ++k) {\n\t\t\t\tss.clear();\n\t\t\t\tss.str(\"\");\n\t\t\t\tss << k;\n\t\t\t\tcurNum = ss.str();\n\t\t\t\tstring res = getMul(div2Tmp, curNum);\n\t\t\t\t//cout << \" 1:res=\" << res << endl;\n\t\t\t\tres = calculate(curSumTmp, res);\n\t\t\t\t//cout << \" 2:res=\" << res << endl;\n\t\t\t\treverse(res.begin(), res.end());\n\t\t\t\t//cout << \" 3:res=\" << res << endl;\n\t\t\t\tif (compare(res, div2)) {\n\t\t\t\t\tans += curNum;\n\t\t\t\t\tcurSum = res;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trem = curSum;\n\t\t//cout << \" rem=\" << rem << endl;\n\t\treturn ans;\n\t}\n};\n\n\n\nint main(void) {\n\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n\n\tBigData data1, data2;\n\n#ifdef InputOutputOperatorOverload\n\tcin >> data1 >> data2;\n\n\t//cout << \"data1=\" << data1 << endl << \"data2=\" << data2 << endl;\n\tcout << data1 + data2 << endl;\n\tcout << data1 - data2 << endl;\n\tcout << data1 * data2 << endl;\n\tcout << data1 / data2 << endl;\n\tcout << data1 % data2 << endl;\n#else\n\tstring d1, d2;\n\tcin >> d1 >> d2;\n\tdata1.setValue(d1);\n\tdata2.setValue(d2);\n\n\t//cout << \"data1=\" << data1.getValue() << endl << \"data2=\" << data2.getValue() << endl;\n\t//cout << (data1 + data2).getValue() << endl;\n\t//cout << (data1 - data2).getValue() << endl;\n\tcout << (data1 * data2).getValue() << endl;\n\t//cout << (data1 / data2).getValue() << endl;\n\t//cout << (data1 % data2).getValue() << endl;\n#endif\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 3508, "score_of_the_acc": -0.2253, "final_rank": 11 }, { "submission_id": "aoj_NTL_2_C_5518695", "code_snippet": "#include <bits/stdc++.h>\n#include <sstream>\n\nusing namespace std;\n\n//#define InputOutputOperatorOverload\n\nclass BigData {\npublic:\n#ifdef InputOutputOperatorOverload\n\tfriend istream& operator >>(istream& in, BigData& bigdata) {\n\t\tin >> bigdata.data;\n\t\treturn in;\n\t}\n\n\tfriend ostream& operator <<(ostream& out, BigData& bigdata) {\n\t\tout << bigdata.data;\n\t\treturn out;\n\t}\n#else\n\tstring getValue() {\n\t\treturn this->data;\n\t}\n\n\tvoid setValue(string value) {\n\t\tthis->data = value;\n\t}\n#endif\n\n\tBigData operator +(const BigData& add) {\n\t\tstring add1, add2;\n\t\tBigData ans;\n\n\t\tadd1 = this->data;\n\t\tadd2 = add.data;\n\t\tif (add1[0] != '-' && add2[0] != '-') {\n\t\t\tminFlag = false;\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = getAdd(add1, add2);\n\t\t}\n\t\telse if (add1[0] == '-' && add2[0] == '-') {\n\t\t\tminFlag = true;\n\t\t\tadd1 = add1.substr(1);\n\t\t\tadd2 = add2.substr(1);\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = getAdd(add1, add2);\n\t\t}\n\t\telse if (add1[0] == '-' && add2[0] != '-') {\n\t\t\tadd1 = add1.substr(1);\n\t\t\tminFlag = compare(add1, add2) ? false : true;\n\t\t\tif (add1 == add2) {\n\t\t\t\tminFlag = false;\n\t\t\t}\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = calculate(add1, add2);\n\t\t}\n\t\telse if (add1[0] != '-' && add2[0] == '-') {\n\t\t\tadd2 = add2.substr(1);\n\t\t\tminFlag = compare(add1, add2);\n\t\t\treverse(add1.begin(), add1.end());\n\t\t\treverse(add2.begin(), add2.end());\n\t\t\tans.data = calculate(add1, add2);\n\t\t}\n\n\t\tif (minFlag) {\n\t\t\tans.data += \"-\";\n\t\t}\n\t\treverse(ans.data.begin(), ans.data.end());\n\n\t\treturn ans;\n\t}\n\n\tBigData operator -(const BigData& sub) {\n\t\tstring sub1, sub2;\n\t\tBigData ans;\n\n\t\tsub1 = this->data;\n\t\tsub2 = sub.data;\n\t\tif (sub1[0] != '-' && sub2[0] == '-') {\n\t\t\tminFlag = false;\n\t\t\tsub2 = sub2.substr(1);\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = getAdd(sub1, sub2);\n\t\t}\n\t\telse if (sub1[0] == '-' && sub2[0] != '-') {\n\t\t\tminFlag = true;\n\t\t\tsub1 = sub1.substr(1);\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = getAdd(sub1, sub2);\n\t\t}\n\t\telse if (sub1[0] != '-' && sub2[0] != '-') {\n\t\t\tminFlag = compare(sub1, sub2);\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = calculate(sub1, sub2);\n\t\t}\n\t\telse if (sub1[0] == '-' && sub2[0] == '-') {\n\t\t\tsub1 = sub1.substr(1);\n\t\t\tsub2 = sub2.substr(1);\n\t\t\tminFlag = compare(sub1, sub2) ? false : true;\n\t\t\tif (sub1 == sub2) {\n\t\t\t\tminFlag = false;\n\t\t\t}\n\t\t\treverse(sub1.begin(), sub1.end());\n\t\t\treverse(sub2.begin(), sub2.end());\n\t\t\tans.data = calculate(sub1, sub2);\n\t\t}\n\n\t\tif (minFlag) {\n\t\t\tans.data += \"-\";\n\t\t}\n\t\treverse(ans.data.begin(), ans.data.end());\n\n\t\treturn ans;\n\t}\n\n\tBigData operator *(const BigData& mul) {\n\t\tstring mul1, mul2;\n\t\tBigData ans;\n\n\t\tmul1 = this->data;\n\t\tmul2 = mul.data;\n\t\tif (mul1[0] != '-' && mul2[0] != '-') {\n\t\t\tminFlag = false;\n\t\t}\n\t\telse if (mul1[0] == '-' && mul2[0] == '-') {\n\t\t\tminFlag = false;\n\t\t\tmul1 = mul1.substr(1);\n\t\t\tmul2 = mul2.substr(1);\n\t\t}\n\t\telse if (mul1[0] == '-' && mul2[0] != '-') {\n\t\t\tminFlag = true;\n\t\t\tmul1 = mul1.substr(1);\n\t\t}\n\t\telse if (mul1[0] != '-' && mul2[0] == '-') {\n\t\t\tminFlag = true;\n\t\t\tmul2 = mul2.substr(1);\n\t\t}\n\t\tif (mul1 == \"0\" || mul2 == \"0\") {\n\t\t\tans.data = \"0\";\n\t\t\treturn ans;\n\t\t}\n\n\t\treverse(mul1.begin(), mul1.end());\n\t\treverse(mul2.begin(), mul2.end());\n\t\tans.data = getMul(mul1, mul2);\n\n\t\tif (minFlag) {\n\t\t\tans.data += \"-\";\n\t\t}\n\t\treverse(ans.data.begin(), ans.data.end());\n\n\t\treturn ans;\n\t}\n\n\nprivate:\n\tstring data;\n\tbool minFlag;\n\n\tbool compare(string& d1, string& d2) {\n\t\tunsigned int len1, len2;\n\n\t\tlen1 = d1.size();\n\t\tlen2 = d2.size();\n\t\tif (len1 > len2) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (len1 < len2 || d1 < d2) {\n\t\t\td1.swap(d2);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstring getAdd(string& add1, string& add2) {\n\t\tunsigned int len1, len2, i;\n\t\tint acc, sum;\n\t\tstringstream ss;\n\n\t\tlen1 = add1.size();\n\t\tlen2 = add2.size();\n\t\t//cout << add1 << endl << add2 << endl;\n\n\t\ti = 0;\n\t\tacc = 0;\n\t\tss.clear();\n\t\tss.str(\"\");\n\t\twhile (i < len1 && i < len2) {\n\t\t\tsum = (add1[i] - '0') + (add2[i] - '0') + acc;\n\t\t\tacc = sum / 10;\n\t\t\tsum %= 10;\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len1) {\n\t\t\tsum = (add1[i] - '0') + acc;\n\t\t\tacc = sum / 10;\n\t\t\tsum %= 10;\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len2) {\n\t\t\tsum = (add2[i] - '0') + acc;\n\t\t\tacc = sum / 10;\n\t\t\tsum %= 10;\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\tif (acc == 1) {\n\t\t\tss << 1;\n\t\t}\n\n\t\treturn ss.str();\n\t}\n\n\tstring getSub(string& sub1, string& sub2) {\n\t\tunsigned int len1, len2, i;\n\t\tint acc, sum;\n\t\tstringstream ss;\n\n\t\tlen1 = sub1.size();\n\t\tlen2 = sub2.size();\n\t\t//cout << sub1 << endl << sub2 << endl;\n\n\t\ti = 0;\n\t\tacc = 0;\n\t\tss.clear();\n\t\tss.str(\"\");\n\t\twhile (i < len1 && i < len2) {\n\t\t\tsum = (sub1[i] - '0') - acc - (sub2[i] - '0');\n\t\t\tif (sum < 0) {\n\t\t\t\tacc = 1;\n\t\t\t\tsum += 10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tacc = 0;\n\t\t\t}\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len1) {\n\t\t\tsum = (sub1[i] - '0') - acc;\n\t\t\tif (sum < 0) {\n\t\t\t\tacc = 1;\n\t\t\t\tsum += 10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tacc = 0;\n\t\t\t}\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\twhile (i < len2) {\n\t\t\tsum = (sub2[i] - '0') - acc;\n\t\t\tif (sum < 0) {\n\t\t\t\tacc = 1;\n\t\t\t\tsum += 10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tacc = 0;\n\t\t\t}\n\t\t\tss << sum;\n\t\t\t++i;\n\t\t}\n\n\t\treturn ss.str();\n\t}\n\n\tstring calculate(string& data1, string& data2) {\n\t\tstring ans;\n\n\t\tans = getSub(data1, data2);\n\t\twhile (true) {\n\t\t\tauto it = ans.rbegin();\n\t\t\tif (ans.size() == 1 || *it != '0') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tans.pop_back();\n\t\t}\n\t\treturn ans;\n\t}\n\n\tstring getMul(string& mul1, string& mul2) {\n\t\tunsigned int len1, len2;\n\t\tint acc, sum, base;\n\t\tstringstream ss;\n\t\tstring curSum;\n\n\t\tlen1 = mul1.size();\n\t\tlen2 = mul2.size();\n\t\t//cout << mul1 << endl << mul2 << endl;\n\n\t\tcurSum = \"\";\n\t\tfor (unsigned int i = 0; i < len2; ++i) {\n\t\t\tstring temp(\"\"), res(\"\");\n\t\t\tfor (unsigned int k = 0; k < i; ++k) {\n\t\t\t\ttemp += \"0\";\n\t\t\t}\n\t\t\tbase = mul2[i] - '0';\n\t\t\tacc = 0;\n\t\t\tss.clear();\n\t\t\tss.str(\"\");\n\t\t\tfor (unsigned int j = 0; j < len1; ++j) {\n\t\t\t\tsum = base * (mul1[j] - '0') + acc;\n\t\t\t\tacc = sum / 10;\n\t\t\t\tsum %= 10;\n\t\t\t\tss << sum;\n\t\t\t}\n\t\t\tif (acc != 0) {\n\t\t\t\tss << acc;\n\t\t\t}\n\t\t\tres = temp + ss.str();\n\t\t\t//cout << \"res=\" << res << endl;\n\t\t\tcurSum = getAdd(curSum, res);\n\t\t\t//cout << \"curSum=\" << curSum << endl;\n\t\t}\n\n\t\treturn curSum;\n\t}\n};\n\n\n\nint main(void) {\n\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n\n\tBigData data1, data2;\n\n#ifdef InputOutputOperatorOverload\n\tcin >> data1 >> data2;\n\n\t//cout << \"data1=\" << data1 << endl << \"data2=\" << data2 << endl;\n\t//cout << data1 + data2 << endl;\n\t//cout << data1 - data2 << endl;\n\t//cout << data1 * data2 << endl;\n#else\n\tstring d1, d2;\n\tcin >> d1 >> d2;\n\tdata1.setValue(d1);\n\tdata2.setValue(d2);\n\n\t//cout << \"data1=\" << data1.getValue() << endl << \"data2=\" << data2.getValue() << endl;\n\t//cout << (data1 + data2).getValue() << endl;\n\t//cout << (data1 - data2).getValue() << endl;\n\tcout << (data1 * data2).getValue() << endl;\n#endif\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3504, "score_of_the_acc": -0.1512, "final_rank": 9 }, { "submission_id": "aoj_NTL_2_C_4589998", "code_snippet": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\n\n//template\n#define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)\n#define ALL(v) (v).begin(),(v).end()\ntypedef long long int ll;\nconst int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12;\ntemplate<typename T>inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}\ntemplate<typename T>inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}\n//end\n\ntemplate<typename T>struct FFT{\n struct C{\n T x,y;\n C(T _x=0,T _y=0):x(_x),y(_y){}\n C operator~()const{return {x,-y};}\n C operator+(const C& c)const{return {x+c.x,y+c.y};}\n C operator-(const C& c)const{return {x-c.x,y-c.y};}\n C operator*(const C& c)const{return {x*c.x-y*c.y,x*c.y+y*c.x};}\n };\n vector<C> rt;\n FFT(int lg=20){\n rt.resize(1<<lg,1);\n rep(k,1,lg){\n int d=1<<k;\n rep(i,0,d){\n if(i&1)rt[d+i]=C(cos(2*M_PI*i/d),sin(2*M_PI*i/d));\n else rt[d+i]=rt[(d+i)>>1];\n }\n }\n }\n void fft(vector<C>& a,bool inv=0){\n int n=a.size(); assert((n&(n-1))==0);\n if(inv){\n for(int i=1;i<n;i<<=1)for(int j=0;j<n;j+=i*2)for(int k=0;k<i;k++){\n a[i+j+k]=a[i+j+k]*~rt[i*2+k]; C tmp=a[j+k]-a[i+j+k];\n a[j+k]=a[j+k]+a[i+j+k]; a[i+j+k]=tmp;\n } rep(i,0,n)a[i].x/=n,a[i].y/=n;\n }\n else{\n for(int i=n>>1;i;i>>=1)for(int j=0;j<n;j+=i*2)for(int k=0;k<i;k++){\n C tmp=a[j+k]-a[i+j+k];\n a[j+k]=a[j+k]+a[i+j+k]; a[i+j+k]=tmp*rt[i*2+k];\n }\n }\n for(int i=0,j=1;j<n-1;j++){\n for(int k=n>>1;k>(i^=k);k>>=1);\n if(j<i)swap(a[i],a[j]);\n }\n }\n vector<ll> conv(vector<ll> a,vector<ll> b){\n if(a.empty() or b.empty())return vector<ll>();\n int n=a.size()+b.size()-1,m=1; vector<ll> res(n); while(m<n)m<<=1;\n vector<C> c(m); rep(i,0,a.size())c[i].x=a[i]; rep(i,0,b.size())c[i].y=b[i];\n fft(c); C rad(0,-0.25/m);\n for(int i=0,j=0;i<=m/2;i++,j=(m-i)&(m-1)){\n C z=(c[j]*c[j]-~(c[i]*c[i]))*rad;\n if(i!=j)c[j]=(c[i]*c[i]-~(c[j]*c[j]))*rad;\n c[i]=z;\n } fft(c); rep(i,0,n)res[i]=c[i].x+0.5; return res;\n }\n};\n\nFFT<double> fft;\ntemplate<int D=4>struct bigint{\n int B,sign; vector<ll> v;\n bigint(ll x=0){\n B=1; rep(_,0,D)B*=10; sign=1;\n if(x<0)x*=-1,sign=0;\n do{v.push_back(x%B); x/=B;\n }while(x);\n }\n bigint(string s){\n B=1; rep(_,0,D)B*=10; sign=1;\n if(s[0]=='-')s.erase(s.begin()),sign=0;\n int add=0,cnt=0,base=1;\n while(s.size()){\n if(cnt==D){\n v.push_back(add);\n cnt=0; add=0; base=1;\n }\n add=(s.back()-'0')*base+add;\n cnt++; base*=10;\n s.pop_back();\n }\n if(add)v.push_back(add);\n }\n bigint operator-()const{\n bigint res=*this;\n res.sign^=1; return res;\n }\n bigint abs()const{\n bigint res=*this;\n res.sign=1; return res;\n }\n ll& operator[](const int i){return v[i];}\n int size()const{return v.size();}\n void norm(){\n rep(i,0,v.size()-1){\n if(v[i]>=0){v[i+1]+=v[i]/B; v[i]%=B;}\n else{\n int c=(-v[i]+B-1)/B;\n v[i]+=c*B; v[i+1]-=c;\n }\n }\n while(!v.empty() and v.back()>=B){\n int c=v.back()/B;\n v.back()%=B; v.push_back(c);\n }\n while(v.size()>1 and v.back()==0)v.pop_back();\n }\n friend istream& operator>>(istream& is,bigint<D>& x){\n string tmp; is>>tmp;\n x=bigint(tmp); return is;\n }\n friend ostream& operator<<(ostream& os,bigint<D> x){\n if(x.v.empty() or ((int)x.size()==1 and x[0]==0))os<<\"0\";\n else{\n if(!x.sign)os<<\"-\";\n string res=to_string(x.v.back());\n for(int i=x.size()-2;i>=0;i--){\n string add; int w=x[i];\n rep(_,0,D){\n add+=('0'+(w%10)); w/=10;\n } reverse(ALL(add)); res+=add;\n } os<<res;\n }\n return os;\n }\n bigint& operator+=(const bigint& x){\n if(sign!=x.sign){*this-=(-x); return *this;}\n if((int)v.size()<(int)x.size())v.resize(x.size(),0);\n rep(i,0,x.size())v[i]+=x.v[i];\n norm(); return *this;\n }\n bigint& operator-=(const bigint& x){\n if(sign!=x.sign){*this+=(-x); return *this;}\n if(abs()<x.abs()){*this=x-(*this); sign^=1; return *this;}\n rep(i,0,x.size())v[i]-=x.v[i];\n norm(); return *this;\n }\n bigint& operator*=(const bigint& x){\n if(!x.sign)sign^=1; v=fft.conv(v,x.v);\n norm(); return *this;\n } /*\n bigint& operator/=(const bigint& x){\n \n } */\n bigint operator+(const bigint& x)const{return bigint(*this)+=x;}\n bigint operator-(const bigint& x)const{return bigint(*this)-=x;}\n bigint operator*(const bigint& x)const{return bigint(*this)*=x;}\n bigint operator/(const bigint& x)const{return bigint(*this)/=x;}\n bool operator<(const bigint& x)const{\n if(sign!=x.sign)return sign<x.sign;\n if((int)v.size()!=(int)x.size())return (int)v.size()*sign<(int)x.size()*x.sign;\n for(int i=v.size()-1;i>=0;i--)if(v[i]!=x.v[i])return v[i]*sign<x.v[i]*x.sign;\n return false;\n }\n bool operator>(const bigint& x)const{return x<*this;}\n bool operator<=(const bigint& x)const{return !(x>*this);}\n bool operator>=(const bigint& x)const{return !(x<*this);}\n};\ntypedef bigint<4> Bigint;\n\nint main(){\n Bigint x,y;\n cin>>x>>y;\n cout<<x*y<<endl;\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 19040, "score_of_the_acc": -0.2056, "final_rank": 10 }, { "submission_id": "aoj_NTL_2_C_4589996", "code_snippet": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\n\n//template\n#define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)\n#define ALL(v) (v).begin(),(v).end()\ntypedef long long int ll;\nconst int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12;\ntemplate<typename T>inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}\ntemplate<typename T>inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}\n//end\n\ntemplate<typename T>struct FFT{\n struct C{\n T x,y;\n C(T _x=0,T _y=0):x(_x),y(_y){}\n C operator~()const{return {x,-y};}\n C operator+(const C& c)const{return {x+c.x,y+c.y};}\n C operator-(const C& c)const{return {x-c.x,y-c.y};}\n C operator*(const C& c)const{return {x*c.x-y*c.y,x*c.y+y*c.x};}\n };\n vector<C> rt;\n FFT(int lg=20){\n rt.resize(1<<lg,1);\n rep(k,1,lg){\n int d=1<<k;\n rep(i,0,d){\n if(i&1)rt[d+i]=C(cos(2*M_PI*i/d),sin(2*M_PI*i/d));\n else rt[d+i]=rt[(d+i)>>1];\n }\n }\n }\n void fft(vector<C>& a,bool inv=0){\n int n=a.size(); assert((n&(n-1))==0);\n if(inv){\n for(int i=1;i<n;i<<=1)for(int j=0;j<n;j+=i*2)for(int k=0;k<i;k++){\n a[i+j+k]=a[i+j+k]*~rt[i*2+k]; C tmp=a[j+k]-a[i+j+k];\n a[j+k]=a[j+k]+a[i+j+k]; a[i+j+k]=tmp;\n } rep(i,0,n)a[i].x/=n,a[i].y/=n;\n }\n else{\n for(int i=n>>1;i;i>>=1)for(int j=0;j<n;j+=i*2)for(int k=0;k<i;k++){\n C tmp=a[j+k]-a[i+j+k];\n a[j+k]=a[j+k]+a[i+j+k]; a[i+j+k]=tmp*rt[i*2+k];\n }\n }\n for(int i=0,j=1;j<n-1;j++){\n for(int k=n>>1;k>(i^=k);k>>=1);\n if(j<i)swap(a[i],a[j]);\n }\n }\n vector<int> conv(vector<int> a,vector<int> b){\n if(a.empty() or b.empty())return vector<int>();\n int n=a.size()+b.size()-1,m=1; vector<int> res(n); while(m<n)m<<=1;\n vector<C> c(m); rep(i,0,a.size())c[i].x=a[i]; rep(i,0,b.size())c[i].y=b[i];\n fft(c); C rad(0,-0.25/m);\n for(int i=0,j=0;i<=m/2;i++,j=(m-i)&(m-1)){\n C z=(c[j]*c[j]-~(c[i]*c[i]))*rad;\n if(i!=j)c[j]=(c[i]*c[i]-~(c[j]*c[j]))*rad;\n c[i]=z;\n } fft(c); rep(i,0,n)res[i]=c[i].x+0.5; return res;\n }\n};\n\nFFT<double> fft;\ntemplate<int D=4>struct bigint{\n int B,sign; vector<int> v;\n bigint(ll x=0){\n B=1; rep(_,0,D)B*=10; sign=1;\n if(x<0)x*=-1,sign=0;\n do{v.push_back(x%B); x/=B;\n }while(x);\n }\n bigint(string s){\n B=1; rep(_,0,D)B*=10; sign=1;\n if(s[0]=='-')s.erase(s.begin()),sign=0;\n int add=0,cnt=0,base=1;\n while(s.size()){\n if(cnt==D){\n v.push_back(add);\n cnt=0; add=0; base=1;\n }\n add=(s.back()-'0')*base+add;\n cnt++; base*=10;\n s.pop_back();\n }\n if(add)v.push_back(add);\n }\n bigint operator-()const{\n bigint res=*this;\n res.sign^=1; return res;\n }\n bigint abs()const{\n bigint res=*this;\n res.sign=1; return res;\n }\n int& operator[](const int i){return v[i];}\n int size()const{return v.size();}\n void norm(){\n rep(i,0,v.size()-1){\n if(v[i]>=0){v[i+1]+=v[i]/B; v[i]%=B;}\n else{\n int c=(-v[i]+B-1)/B;\n v[i]+=c*B; v[i+1]-=c;\n }\n }\n if(!v.empty() and v.back()>=B){\n int c=v.back()/B;\n v.back()%=B; v.push_back(c);\n }\n while(v.size()>1 and v.back()==0)v.pop_back();\n }\n friend istream& operator>>(istream& is,bigint<D>& x){\n string tmp; is>>tmp;\n x=bigint(tmp); return is;\n }\n friend ostream& operator<<(ostream& os,bigint<D> x){\n if(x.v.empty() or ((int)x.size()==1 and x[0]==0))os<<\"0\";\n else{\n if(!x.sign)os<<\"-\";\n string res=to_string(x.v.back());\n for(int i=x.size()-2;i>=0;i--){\n string add; int w=x[i];\n rep(_,0,D){\n add+=('0'+(w%10)); w/=10;\n } reverse(ALL(add)); res+=add;\n } os<<res;\n }\n return os;\n }\n bigint& operator+=(const bigint& x){\n if(sign!=x.sign){*this-=(-x); return *this;}\n if((int)v.size()<(int)x.size())v.resize(x.size(),0);\n rep(i,0,x.size())v[i]+=x.v[i];\n norm(); return *this;\n }\n bigint& operator-=(const bigint& x){\n if(sign!=x.sign){*this+=(-x); return *this;}\n if(abs()<x.abs()){*this=x-(*this); sign^=1; return *this;}\n rep(i,0,x.size())v[i]-=x.v[i];\n norm(); return *this;\n }\n bigint& operator*=(const bigint& x){\n if(!x.sign)sign^=1; v=fft.conv(v,x.v);\n norm(); return *this;\n } /*\n bigint& operator/=(const bigint& x){\n \n } */\n bigint operator+(const bigint& x)const{return bigint(*this)+=x;}\n bigint operator-(const bigint& x)const{return bigint(*this)-=x;}\n bigint operator*(const bigint& x)const{return bigint(*this)*=x;}\n bigint operator/(const bigint& x)const{return bigint(*this)/=x;}\n bool operator<(const bigint& x)const{\n if(sign!=x.sign)return sign<x.sign;\n if((int)v.size()!=(int)x.size())return (int)v.size()*sign<(int)x.size()*x.sign;\n for(int i=v.size()-1;i>=0;i--)if(v[i]!=x.v[i])return v[i]*sign<x.v[i]*x.sign;\n return false;\n }\n bool operator>(const bigint& x)const{return x<*this;}\n bool operator<=(const bigint& x)const{return !(x>*this);}\n bool operator>=(const bigint& x)const{return !(x<*this);}\n};\ntypedef bigint<4> Bigint;\n\nint main(){\n Bigint x,y;\n cin>>x>>y;\n cout<<x*y<<endl;\n return 0;\n}", "accuracy": 0.64, "time_ms": 20, "memory_kb": 19040, "score_of_the_acc": -0.2056, "final_rank": 18 }, { "submission_id": "aoj_NTL_2_C_4589990", "code_snippet": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\n\n//template\n#define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)\n#define ALL(v) (v).begin(),(v).end()\ntypedef long long int ll;\nconst int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12;\ntemplate<typename T>inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}\ntemplate<typename T>inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}\n//end\n\ntemplate<typename T>struct FFT{\n struct C{\n T x,y;\n C(T _x=0,T _y=0):x(_x),y(_y){}\n C operator~()const{return {x,-y};}\n C operator+(const C& c)const{return {x+c.x,y+c.y};}\n C operator-(const C& c)const{return {x-c.x,y-c.y};}\n C operator*(const C& c)const{return {x*c.x-y*c.y,x*c.y+y*c.x};}\n };\n vector<C> rt;\n FFT(int lg=20){\n rt.resize(1<<lg,1);\n rep(k,1,lg){\n int d=1<<k;\n rep(i,0,d){\n if(i&1)rt[d+i]=C(cos(2*M_PI*i/d),sin(2*M_PI*i/d));\n else rt[d+i]=rt[(d+i)>>1];\n }\n }\n }\n void fft(vector<C>& a,bool inv=0){\n int n=a.size(); assert((n&(n-1))==0);\n if(inv){\n for(int i=1;i<n;i<<=1)for(int j=0;j<n;j+=i*2)for(int k=0;k<i;k++){\n a[i+j+k]=a[i+j+k]*~rt[i*2+k]; C tmp=a[j+k]-a[i+j+k];\n a[j+k]=a[j+k]+a[i+j+k]; a[i+j+k]=tmp;\n } rep(i,0,n)a[i].x/=n,a[i].y/=n;\n }\n else{\n for(int i=n>>1;i;i>>=1)for(int j=0;j<n;j+=i*2)for(int k=0;k<i;k++){\n C tmp=a[j+k]-a[i+j+k];\n a[j+k]=a[j+k]+a[i+j+k]; a[i+j+k]=tmp*rt[i*2+k];\n }\n }\n for(int i=0,j=1;j<n-1;j++){\n for(int k=n>>1;k>(i^=k);k>>=1);\n if(j<i)swap(a[i],a[j]);\n }\n }\n vector<int> conv(vector<int> a,vector<int> b){\n int n=a.size()+b.size()-1,m=1; vector<int> res(n); while(m<n)m<<=1;\n vector<C> c(m); rep(i,0,a.size())c[i].x=a[i]; rep(i,0,b.size())c[i].y=b[i];\n fft(c); C rad(0,-0.25/m);\n for(int i=0,j=0;i<=m/2;i++,j=(m-i)&(m-1)){\n C z=(c[j]*c[j]-~(c[i]*c[i]))*rad;\n if(i!=j)c[j]=(c[i]*c[i]-~(c[j]*c[j]))*rad;\n c[i]=z;\n } fft(c); rep(i,0,n)res[i]=c[i].x+0.5; return res;\n }\n};\n\nFFT<double> fft;\ntemplate<int D=4>struct bigint{\n int B,sign; vector<int> v;\n bigint(ll x=0){\n B=1; rep(_,0,D)B*=10; sign=1;\n if(x<0)x*=-1,sign=0;\n do{v.push_back(x%B); x/=B;\n }while(x);\n }\n bigint(string s){\n B=1; rep(_,0,D)B*=10; sign=1;\n if(s[0]=='-')s.erase(s.begin()),sign=0;\n int add=0,cnt=0,base=1;\n while(s.size()){\n if(cnt==D){\n v.push_back(add);\n cnt=0; add=0; base=1;\n }\n add=(s.back()-'0')*base+add;\n cnt++; base*=10;\n s.pop_back();\n }\n if(add)v.push_back(add);\n }\n bigint operator-()const{\n bigint res=*this;\n res.sign^=1; return res;\n }\n bigint abs()const{\n bigint res=*this;\n res.sign=1; return res;\n }\n int& operator[](const int i){return v[i];}\n int size()const{return v.size();}\n void norm(){\n rep(i,0,v.size()-1){\n if(v[i]>=0){v[i+1]+=v[i]/B; v[i]%=B;}\n else{\n int c=(-v[i]+B-1)/B;\n v[i]+=c*B; v[i+1]-=c;\n }\n }\n if(!v.empty() and v.back()>=B){\n int c=v.back()/B;\n v.back()%=B; v.push_back(c);\n }\n while(v.size()>1 and v.back()==0)v.pop_back();\n }\n friend istream& operator>>(istream& is,bigint<D>& x){\n string tmp; is>>tmp;\n x=bigint(tmp); return is;\n }\n friend ostream& operator<<(ostream& os,bigint<D> x){\n if(x.v.empty() or ((int)x.size()==1 and x[0]==0))os<<\"0\";\n else{\n if(!x.sign)os<<\"-\";\n string res=to_string(x.v.back());\n for(int i=x.size()-2;i>=0;i--){\n string add; int w=x[i];\n rep(_,0,D){\n add+=('0'+(w%10)); w/=10;\n } reverse(ALL(add)); res+=add;\n } os<<res;\n }\n return os;\n }\n bigint& operator+=(const bigint& x){\n if(sign!=x.sign){*this-=(-x); return *this;}\n if((int)v.size()<(int)x.size())v.resize(x.size(),0);\n rep(i,0,x.size())v[i]+=x.v[i];\n norm(); return *this;\n }\n bigint& operator-=(const bigint& x){\n if(sign!=x.sign){*this+=(-x); return *this;}\n if(abs()<x.abs()){*this=x-(*this); sign^=1; return *this;}\n rep(i,0,x.size())v[i]-=x.v[i];\n norm(); return *this;\n }\n bigint& operator*=(const bigint& x){\n if(!x.sign)sign^=1; v=fft.conv(v,x.v);\n norm(); return *this;\n } /*\n bigint& operator/=(const bigint& x){\n \n } */\n bigint operator+(const bigint& x)const{return bigint(*this)+=x;}\n bigint operator-(const bigint& x)const{return bigint(*this)-=x;}\n bigint operator*(const bigint& x)const{return bigint(*this)*=x;}\n bigint operator/(const bigint& x)const{return bigint(*this)/=x;}\n bool operator<(const bigint& x)const{\n if(sign!=x.sign)return sign<x.sign;\n if((int)v.size()!=(int)x.size())return (int)v.size()*sign<(int)x.size()*x.sign;\n for(int i=v.size()-1;i>=0;i--)if(v[i]!=x.v[i])return v[i]*sign<x.v[i]*x.sign;\n return false;\n }\n bool operator>(const bigint& x)const{return x<*this;}\n bool operator<=(const bigint& x)const{return !(x>*this);}\n bool operator>=(const bigint& x)const{return !(x<*this);}\n};\ntypedef bigint<4> Bigint;\n\nint main(){\n Bigint x,y;\n cin>>x>>y;\n cout<<x*y<<endl;\n return 0;\n}", "accuracy": 0.08, "time_ms": 20, "memory_kb": 19008, "score_of_the_acc": -0.2053, "final_rank": 19 }, { "submission_id": "aoj_NTL_2_C_4498645", "code_snippet": "#include<iostream>\n#include<vector>\n#include<string>\n#include<algorithm>\n\nusing namespace std;\n\nstruct fast_io {\n\tfast_io(){\n\t\tstd::cin.tie(nullptr);\n\t\tstd::ios::sync_with_stdio(false);\n\t};\n} fio;\n\nclass Karatsuba{\n\tint base = 10; // base > 1\n\tvector<int> num;\n\tbool sign; // true : + false : -\n\t\npublic:\n\t\n\tKaratsuba(){\n\t\tsign = false;\n\t\tnum.push_back(0);\n\t}\n\t\n\tKaratsuba(size_t size){\n\t\tsign = false;\n\t\tnum.resize(size);\n\t}\n\t\n\t~Karatsuba(){\n\t}\n\t\n\tKaratsuba operator+(const Karatsuba &k) const {\n\t\tKaratsuba res;\n\t\t\n\t\tif(k.sign^sign) {\n\t\t\tint maxs = max(k.num.size(), num.size());\n\t\t\tbool com = true; // num >= k.num\n\t\t\tint index = -1;\n\t\t\t\n\t\t\tfor(int i = maxs-1; i >= 0; i--){\n\t\t\t\tint a = 0, b = 0;\n\t\t\t\tif(i < num.size()) a = num[i];\n\t\t\t\tif(i < k.num.size()) b = k.num[i];\n\t\t\t\t\n\t\t\t\tif(a < b) {\n\t\t\t\t\tcom = false;\n\t\t\t\t\tindex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if(a > b) {\n\t\t\t\t\tcom = true;\n\t\t\t\t\tindex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(index == -1){\n\t\t\t\tres.sign = false;\n\t\t\t\tres.num.push_back(0);\n\t\t\t} else if(com) {\n\t\t\t\tres.num.resize(index+1);\n\t\t\t\t\n\t\t\t\tfor(int i = 0; i <= index; i++){\n\t\t\t\t\tif(i < num.size()) res.num[i] += num[i];\n\t\t\t\t\tif(i < k.num.size()) res.num[i] -= k.num[i];\n\t\t\t\t\t\n\t\t\t\t\tif(res.num[i] < 0) {\n\t\t\t\t\t\tres.num[i] += base;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor(int j = i+1; ; j++){\n\t\t\t\t\t\t\tif(num[j]) {\n\t\t\t\t\t\t\t\tres.num[j]--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tres.num[j] = base-1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(sign == true) res.sign = true;\n\t\t\t} else {\n\t\t\t\tres.num.resize(index+1);\n\t\t\t\t\n\t\t\t\tfor(int i = 0; i <= index; i++){\n\t\t\t\t\tif(i < num.size()) res.num[i] -= num[i];\n\t\t\t\t\tif(i < k.num.size()) res.num[i] += k.num[i];\n\t\t\t\t\t\n\t\t\t\t\tif(res.num[i] < 0) {\n\t\t\t\t\t\tres.num[i] += base;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor(int j = i+1; ; j++){\n\t\t\t\t\t\t\tif(k.num[j]) {\n\t\t\t\t\t\t\t\tres.num[j]--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tres.num[j] = base-1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(k.sign == true) res.sign = true;\n\t\t\t}\n\t\t\t\n\t\t\twhile(res.num.back() == 0 && res.num.size() >= 2){\n\t\t\t\tres.num.pop_back();\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\tres.num.resize(max(k.num.size(), num.size()));\n\t\t\tres.sign = sign;\n\t\t\t\n\t\t\tfor(int i = 0; i < res.num.size(); i++){\n\t\t\t\tif(i < k.num.size()) res.num[i] += k.num[i];\n\t\t\t\tif(i < num.size()) res.num[i] += num[i];\n\t\t\t\tif(res.num[i] >= base) {\n\t\t\t\t\tif(i + 1 == res.num.size()) {\n\t\t\t\t\t\tres.num.push_back(1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres.num[i+1] += 1;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tres.num[i] %= base;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn res;\n\t}\n\t\n\tKaratsuba operator-(const Karatsuba &k) const {\n\t\tKaratsuba res;\n\t\t\n\t\tif(k.sign^sign^1) {\n\t\t\tint maxs = max(k.num.size(), num.size());\n\t\t\tbool com = true; // num >= k.num\n\t\t\tint index = -1;\n\t\t\t\n\t\t\tfor(int i = maxs-1; i >= 0; i--){\n\t\t\t\tint a = 0, b = 0;\n\t\t\t\tif(i < num.size()) a = num[i];\n\t\t\t\tif(i < k.num.size()) b = k.num[i];\n\t\t\t\t\n\t\t\t\tif(a < b) {\n\t\t\t\t\tcom = false;\n\t\t\t\t\tindex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if(a > b) {\n\t\t\t\t\tcom = true;\n\t\t\t\t\tindex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(index == -1){\n\t\t\t\tres.sign = false;\n\t\t\t\tres.num.push_back(0);\n\t\t\t} else if(com) {\n\t\t\t\tres.num.resize(index+1);\n\t\t\t\t\n\t\t\t\tfor(int i = 0; i <= index; i++){\n\t\t\t\t\tif(i < num.size()) res.num[i] += num[i];\n\t\t\t\t\tif(i < k.num.size()) res.num[i] -= k.num[i];\n\t\t\t\t\t\n\t\t\t\t\tif(res.num[i] < 0) {\n\t\t\t\t\t\tres.num[i] += base;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor(int j = i+1; ; j++){\n\t\t\t\t\t\t\tif(num[j]) {\n\t\t\t\t\t\t\t\tres.num[j]--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tres.num[j] = base-1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(sign == true) res.sign = true;\n\t\t\t} else {\n\t\t\t\tres.num.resize(index+1);\n\t\t\t\t\n\t\t\t\tfor(int i = 0; i <= index; i++){\n\t\t\t\t\tif(i < num.size()) res.num[i] -= num[i];\n\t\t\t\t\tif(i < k.num.size()) res.num[i] += k.num[i];\n\t\t\t\t\t\n\t\t\t\t\tif(res.num[i] < 0) {\n\t\t\t\t\t\tres.num[i] += base;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor(int j = i+1; ; j++){\n\t\t\t\t\t\t\tif(k.num[j]) {\n\t\t\t\t\t\t\t\tres.num[j]--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tres.num[j] = base-1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(k.sign == false) res.sign = true;\n\t\t\t}\n\t\t\t\n\t\t\twhile(res.num.back() == 0 && res.num.size() >= 2){\n\t\t\t\tres.num.pop_back();\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\tres.num.resize(max(k.num.size(), num.size()));\n\t\t\tres.sign = sign;\n\t\t\t\n\t\t\tfor(int i = 0; i < res.num.size(); i++){\n\t\t\t\tif(i < k.num.size()) res.num[i] += k.num[i];\n\t\t\t\tif(i < num.size()) res.num[i] += num[i];\n\t\t\t\tif(res.num[i] >= base) {\n\t\t\t\t\tif(i + 1 == res.num.size()) {\n\t\t\t\t\t\tres.num.push_back(1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres.num[i+1] += 1;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tres.num[i] %= base;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn res;\n\t}\n\t\n\tKaratsuba operator*(const Karatsuba &k) const {\n\t\tKaratsuba res;\n\t\t\n\t\tint maxs = max(k.num.size(), num.size());\n\t\t\n\t\tres.sign = sign^k.sign;\n\t\t\n\t\tif(maxs <= 1) {\n\t\t\tint z0;\n\t\t\tres.num.resize(1,0);\n\t\t\tz0 = num[0] * k.num[0];\n\t\t\tres.num[0] = z0 % base;\n\t\t\tif(z0/base) res.num.push_back(z0/base);\n\t\t} else {\n\t\t\tint b = (maxs+1)/2;\n\t\t\tKaratsuba z0, z1, z2;\n\t\t\tKaratsuba x0(b), x1, y0(b), y1;\n\t\t\t\n\t\t\tif(num.size() <= b) x1.resize(1);\n\t\t\telse x1.resize(b);\n\t\t\t\n\t\t\tif(k.num.size() <= b) y1.resize(1);\n\t\t\telse y1.resize(b);\n\t\t\t\n\t\t\tfor(int i = 0; i < b; i++){\n\t\t\t\tif(i < num.size()) x0.num[i] = num[i];\n\t\t\t\tif(i < k.num.size()) y0.num[i] = k.num[i];\n\t\t\t}\n\t\t\t\n\t\t\tfor(int i = b; i < 2*b; i++){\n\t\t\t\tif(i < num.size()) x1.num[i-b] = num[i];\n\t\t\t\tif(i < k.num.size()) y1.num[i-b] = k.num[i];\n\t\t\t}\n\t\t\t\n\t\t\twhile(x0.num.back() == 0 && x0.num.size() >= 2){\n\t\t\t\tx0.num.pop_back();\n\t\t\t}\n\t\t\twhile(x1.num.back() == 0 && x1.num.size() >= 2){\n\t\t\t\tx1.num.pop_back();\n\t\t\t}\n\t\t\twhile(y0.num.back() == 0 && y0.num.size() >= 2){\n\t\t\t\ty0.num.pop_back();\n\t\t\t}\n\t\t\twhile(y1.num.back() == 0 && y1.num.size() >= 2){\n\t\t\t\ty1.num.pop_back();\n\t\t\t}\n\t\t\t\n\t\t\tz2 = x1 * y1;\n\t\t\tz0 = x0 * y0;\n\t\t\tz1 = z2 + z0 - (x1 - x0) * (y1 - y0);\n\t\t\t\n\t\t\tres.resize(max({z0.size(), z1.size()+b, z2.size()+b*2}));\n\t\t\t\n\t\t\tfor(int i = 0; i < res.size(); i++){\n\t\t\t\tif(i < z0.size()) res.num[i] += z0.num[i];\n\t\t\t\tif(i >= b && i-b < z1.size()) res.num[i] += z1.num[i-b];\n\t\t\t\tif(i >= 2*b && i-b*2 < z2.size()) res.num[i] += z2.num[i-b*2];\n\t\t\t\t\n\t\t\t\tif(res.num[i] >= base) {\n\t\t\t\t\tif(i + 1 < res.num.size()) {\n\t\t\t\t\t\tres.num[i+1] += res.num[i] / base;\n\t\t\t\t\t\tres.num[i] %= base;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres.num.push_back(res.num[i] / base);\n\t\t\t\t\t\tres.num[i] %= base;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\twhile(res.num.back() == 0 && res.num.size() >= 2){\n\t\t\t\tres.num.pop_back();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(res.num.size() == 1 && res.num[0] == 0) res.sign = false;\n\t\t\n\t\treturn res;\n\t}\n\t\n\t\n\tKaratsuba& operator=(const Karatsuba& k) & {\n\t\tthis->num = k.num;\n\t\tthis->sign = k.sign;\n\t\t\n\t\treturn *this;\n\t}\n\t\n\tbool operator<(const Karatsuba &k) const {\n\t\tif(k.sign^sign) {\n\t\t\tif(sign == false) return false;\n\t\t\tif(k.sign == false) return true;\n\t\t} else if(sign){\n\t\t\tif(num.size() > k.num.size()) return true;\n\t\t\tif(num.size() < k.num.size()) return false;\n\t\t\t\n\t\t\tfor(int i = (int)num.size()-1; i >= 0; i--){\n\t\t\t\tint a = num[i];\n\t\t\t\tint b = k.num[i];\n\t\t\t\t\n\t\t\t\tif(b < a) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else if(b > a) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif(num.size() > k.num.size()) return false;\n\t\t\tif(num.size() < k.num.size()) return true;\n\t\t\t\n\t\t\tfor(int i = (int)num.size()-1; i >= 0; i--){\n\t\t\t\tint a = num[i];\n\t\t\t\tint b = k.num[i];\n\t\t\t\t\n\t\t\t\tif(b < a) {\n\t\t\t\t\treturn false;\n\t\t\t\t} else if(b > a) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\tsize_t size() const {\n\t\treturn num.size();\n\t}\n\t\n\tvoid resize(size_t size) {\n\t\tnum.resize(size);\n\t}\n\t\n\t\n\tstring to_string() const {\n\t\tstring res;\n\t\t\n\t\tif(sign == true) res += \"-\";\n\t\t\n\t\tfor(int i = (int)num.size()-1; i >= 0; i--){\n\t\t\tres += '0' + num[i];\n\t\t}\n\t\t\n\t\treturn res;\n\t}\n\t\n\tvoid string_to(string s){\n\t\tint b = 0;\n\t\t\n\t\tsign = false;\n\t\t\n\t\tif(s[0] == '-') {\n\t\t\tsign = true;\n\t\t\tb++;\n\t\t}\n\t\t\n\t\tnum.clear();\n\t\t\n\t\tfor(int i = (int)s.size()-1; i >= b; i--){\n\t\t\tnum.push_back(s[i] - '0');\n\t\t}\n\t\t\n\t\twhile(num.back() == 0 && num.size() >= 1){\n\t\t\tnum.pop_back();\n\t\t}\n\t\n\t\tif(num.size() == 0) {\n\t\t\tsign = false;\n\t\t\tnum.push_back(0);\n\t\t}\n\t}\n};\n\nstd::ostream& operator<<(std::ostream& lhs, const Karatsuba& rhs) {\n\t\n\tlhs << rhs.to_string();\n\treturn lhs;\n}\n\nstd::istream& operator>>(std::istream& lhs, Karatsuba& rhs) {\n\tstring str;\n\t\n\tcin>>str;\n\t\n\trhs.string_to(str);\n\t\n\treturn lhs;\n}\n\nsigned main(){\n\t\n\tKaratsuba a, b;\n\t\n\tcin>>a>>b;\n\t\n\tcout<<a * b<<endl;\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3304, "score_of_the_acc": -0.0379, "final_rank": 5 }, { "submission_id": "aoj_NTL_2_C_4446987", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nvector<int> stoa(string const& s){\n vector<int> a(s.size());\n for(int i=(s[0]=='-'?1:0);i<s.size();++i){\n a[i] = s[i]-'0';\n }\n return a;\n}\nstring atos(vector<int> const& a){\n string s;\n for(auto ai:a)s+=(ai+'0');\n return s;\n}\n\nstring product(string const& lhs,string const& rhs){\n if(lhs==\"0\"||rhs==\"0\")return \"0\";\n string sign = (lhs[0]=='-'^rhs[0]=='-'?\"-\":\"\");\n auto a = stoa(lhs);\n reverse(a.begin(),a.end());\n auto b = stoa(rhs);\n reverse(b.begin(),b.end());\n int n = a.size();\n int m = b.size();\n vector<vector<int>> tmp(m,vector<int>(n+m));\n for(int i=0;i<n;++i){\n for(int j=0;j<m;++j){\n tmp[j][i+j] += a[i]*b[j]%10;\n tmp[j][i+j+1] += a[i]*b[j]/10;\n }\n }\n vector<int> res(n+m+1);\n for(int i=0;i<n+m;++i){\n for(int j=0;j<m;++j){\n res[i] += tmp[j][i];\n res[i+1] += res[i]/10;\n res[i] %= 10;\n }\n }\n while(res.size()>1&&res.back()==0)res.pop_back();\n reverse(res.begin(),res.end());\n return sign+atos(res);\n}\n\nsigned main(){\n\n string a,b;\n cin>>a>>b;\n\n cout<<product(a,b)<<endl;\n\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10796, "score_of_the_acc": -0.0807, "final_rank": 8 }, { "submission_id": "aoj_NTL_2_C_4375298", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define rep(i,n) for(long long i=0; i<(n); i++)\ntemplate<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }\ntemplate<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }\n\nbool compare(string a, string b) {\n if (a.size() > b.size()) return true;\n else if (a.size() < b.size()) return false;\n else {\n for (long long i = 0; i < a.size(); i++) {\n if (a[i] > b[i]) return true;\n else if (a[i] < b[i]) return false;\n }\n }\n return true;\n}\n\n\nstring add(string a, string b) {\n bool x = false, y = false;\n if (a[0] == '-') x = true;\n if (b[0] == '-') y = true;\n\n if (x && y) return '-' + add(a.substr(1, a.size()-1), b.substr(1, b.size()-1));\n else if (x) return add(b, a);\n // 'a - b' or 'a + b'\n\n if (y) b = b.substr(1, b.size()-1);\n if (y && !compare(a, b)) {\n return '-' + add(b, '-' + a);\n }\n\n reverse(a.begin(), a.end());\n reverse(b.begin(), b.end());\n\n string res = \"\";\n long long up = 0;\n\n for (long long i = 0; i < max(a.size(), b.size()); i++) {\n long long tmp = up;\n if (i < a.size()) {\n tmp += (a[i] - '0');\n }\n if (i < b.size() && b[i] != '-') {\n if (y) tmp -= (b[i] - '0');\n else tmp += (b[i] - '0');\n }\n\n if (tmp < 0) {\n res.push_back((10 + tmp) + '0');\n up = -1;\n }\n else if (tmp > 9) {\n res.push_back((tmp - 10) + '0');\n up = 1;\n }\n else {\n res.push_back(tmp + '0');\n up = 0;\n }\n }\n\n if (up > 0) res.push_back(up + '0');\n\n reverse(res.begin(), res.end());\n\n long long begin = 0;\n while (res[begin] == '0') begin++;\n \n if (res.size() == begin) return \"0\";\n else return res.substr(begin, res.size() - begin);\n}\n\nstring mult(string a, string b) {\n if (a == \"0\" || b == \"0\") return \"0\";\n string res = \"0\";\n bool ifminus = false;\n if (a[0] == '-' && b[0] == '-') return mult(a.substr(1, a.size()-1), b.substr(1, b.size()-1));\n else if (a[0] == '-') return '-' + mult(a.substr(1, a.size()-1), b);\n else if (b[0] == '-') return '-' + mult(a, b.substr(1, b.size()-1));\n\n reverse(b.begin(), b.end());\n\n for (long long i = 0; i < b.size(); i++) {\n string tmp = \"0\";\n for (long long j = 0; j < (b[i] - '0'); j++) {\n tmp = add(tmp, a);\n }\n for (long long j = 0; j < i; j++) {\n tmp = tmp + '0';\n }\n res = add(res, tmp);\n }\n\n return res;\n}\n\n\nint main(){\n string a, b;\n cin >> a >> b;\n cout << mult(a, b) << endl;\n return 0;\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 3220, "score_of_the_acc": -0.2593, "final_rank": 12 }, { "submission_id": "aoj_NTL_2_C_4289840", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\n\nstring fixedNum( string a )\n{\n if( a.size() == 1 )\n return a;\n for( int i = 0; i < a.size(); i++ )\n if( '1'<= a[i] && a[i] <= '9' )\n return a.substr( i, a.size() );\n return \"0\";\n}\n\nstring calcAddition( string a, string b )\n{\n a = fixedNum(a); b = fixedNum(b);\n int as = a.size(), bs = b.size(), d = as > bs ? as - bs : bs - as;\n string s = \"0\", t = \"0\";\n for( int i = 0; i < d; i++ )\n as > bs ? t += \"0\" : s += \"0\";\n s += a; t += b;\n\n for( int i = s.size() - 1; i >= 1; i-- )\n {\n s[i] += t[i] - '0';\n if( s[i] > '9' )\n {\n s[i] -= 10;\n s[i-1]++;\n }\n }\n\n return s[0] == '0' ? s.substr( 1, s.size() ) : s;\n}\n\nstring calcMultiplication( string a, string b )\n{\n a = fixedNum(a); b = fixedNum(b);\n int as = a.size(), bs = b.size(), d = as > bs ? as - bs : bs - as;\n string s = \"0\", t = \"0\", x = \"\", sum = \"\", zero = \"\", digit = \"\";\n for( int i = 0; i < d; i++ )\n as > bs ? t += \"0\" : s += \"0\";\n s += a; t += b;\n\n for( int i = 0; i < s.size(); i++ )\n zero += \"0\";\n \n x = zero;\n sum = zero;\n\n for( int i = s.size() - 1; i >= 1; i-- )\n {\n for( int j = s.size() - 1; j >= 1; j-- )\n x[j] = ( t[i] - '0' ) * ( s[j] - '0' );\n for( int j = s.size() - 1; j >= 1; j-- )\n {\n int f = x[j] / 10;\n x[j-1] += f;\n x[j] = x[j] - 10 * f + '0';\n }\n x += digit;\n sum = calcAddition( x, sum );\n digit += \"0\";\n x = zero;\n }\n return sum;\n}\n\nint main()\n{\n string a, b;\n\n cin >> a >> b;\n\n int as = a.size(), bs = b.size();\n string s = a.substr( 1, as ), t = b.substr( 1, bs );\n\n if( a[0] == '-' && b[0] == '-' )\n cout << calcMultiplication( s, t ) << endl;\n else if( a[0] >= '0' && b[0] >= '0' )\n cout << calcMultiplication( a, b ) << endl;\n else\n {\n if( a == \"0\" || b == \"0\" )\n cout << \"0\" << endl;\n else if( a[0] == '-' )\n cout << '-' << calcMultiplication( s, b ) << endl;\n else\n cout << '-' << calcMultiplication( a, t ) << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3228, "score_of_the_acc": -0.0001, "final_rank": 1 }, { "submission_id": "aoj_NTL_2_C_3619231", "code_snippet": "// includes\n#include <bits/stdc++.h>\n\n// macros\n#define ll long long int\n#define pb emplace_back\n#define mk make_pair\n#define pq priority_queue\n#define FOR(i, a, b) for(int i=(a);i<(b);++i)\n#define rep(i, n) FOR(i, 0, n)\n#define rrep(i, n) for(int i=((int)(n)-1);i>=0;i--)\n#define irep(itr, st) for(auto itr = (st).begin(); itr != (st).end(); ++itr)\n#define irrep(itr, st) for(auto itr = (st).rbegin(); itr != (st).rend(); ++itr)\n#define vrep(v, i) for(int i = 0; i < (v).size(); i++)\n#define all(x) (x).begin(),(x).end()\n#define sz(x) ((int)(x).size())\n#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end())\n#define FI first\n#define SE second\n#define dump(a, n) for(int i = 0; i < n; i++)cout << a[i] << \"\\n \"[i + 1 != n];\n#define dump2(a, n, m) for(int i = 0; i < n; i++)for(int j = 0; j < m; j++)cout << a[i][j] << \"\\n \"[j + 1 != m];\n#define bit(n) (1LL<<(n))\n#define INT(n) int n; cin >> n;\n#define LL(n) ll n; cin >> n;\n#define DOUBLE(n) double n; cin >> n;\nusing namespace std;\n\n// types\ntypedef pair<int, int> P;\ntypedef pair<ll, int> Pl;\ntypedef pair<ll, ll> Pll;\ntypedef pair<double, double> Pd;\ntypedef complex<double> cd;\n \n// constants\nconst int inf = 1e9;\nconst ll linf = 1LL << 50;\nconst double EPS = 1e-10;\nconst int mod = 1e9 + 7;\nconst int dx[4] = {-1, 0, 1, 0};\nconst int dy[4] = {0, -1, 0, 1};\n\n// solve\ntemplate <class T>bool chmax(T &a, const T &b){if(a < b){a = b; return 1;} return 0;}\ntemplate <class T>bool chmin(T &a, const T &b){if(a > b){a = b; return 1;} return 0;}\ntemplate <typename T> istream &operator>>(istream &is, vector<T> &vec){for(auto &v: vec)is >> v; return is;}\ntemplate <typename T> ostream &operator<<(ostream &os, const vector<T>& vec){for(int i = 0; i < vec.size(); i++){ os << vec[i]; if(i + 1 != vec.size())os << \" \";} return os;}\ntemplate <typename T> ostream &operator<<(ostream &os, const set<T>& st){for(auto itr = st.begin(); itr != st.end(); ++itr){ os << *itr; auto titr = itr; if(++titr != st.end())os << \" \";} return os;}\ntemplate <typename T> ostream &operator<<(ostream &os, const unordered_set<T>& st){for(auto itr = st.begin(); itr != st.end(); ++itr){ os << *itr; auto titr = itr; if(++titr != st.end())os << \" \";} return os;}\ntemplate <typename T> ostream &operator<<(ostream &os, const multiset<T>& st){for(auto itr = st.begin(); itr != st.end(); ++itr){ os << *itr; auto titr = itr; if(++titr != st.end())os << \" \";} return os;}\ntemplate <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T>& st){for(auto itr = st.begin(); itr != st.end(); ++itr){ os << *itr; auto titr = itr; if(++titr != st.end())os << \" \";} return os;}\ntemplate <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p){os << p.first << \" \" << p.second; return os;}\ntemplate <typename T1, typename T2> ostream &operator<<(ostream &os, const map<T1, T2> &mp){for(auto itr = mp.begin(); itr != mp.end(); ++itr){ os << itr->first << \":\" << itr->second; auto titr = itr; if(++titr != mp.end())os << \" \"; } return os;}\ntemplate <typename T1, typename T2> ostream &operator<<(ostream &os, const unordered_map<T1, T2> &mp){for(auto itr = mp.begin(); itr != mp.end(); ++itr){ os << itr->first << \":\" << itr->second; auto titr = itr; if(++titr != mp.end())os << \" \"; } return os;}\n\ntemplate <typename T>\nT power(T a, T n, T mod) {\n T res = 1;\n T tmp = n;\n T curr = a;\n while(tmp){\n if(tmp % 2 == 1){\n res = (T)((ll)res * curr % mod);\n }\n curr = (T)((ll)curr * curr % mod);\n tmp >>= 1;\n }\n return res;\n}\n\ntemplate<typename T>\nT extgcd(T a, T b, T &x, T &y){\n T d = a;\n if(b != 0){\n d = extgcd(b, a % b, y, x);\n y -= (a / b) * x;\n }else{\n x = 1, y = 0;\n }\n return d;\n}\n\ntemplate <typename T>\nT modinv(T a, T m){\n long long x = 0, y = 0;\n extgcd<long long>(a, m, x, y);\n x %= m;\n if(x < 0)x += m;\n return x;\n}\n\ntemplate <typename T>\nlong long garner(vector<T> b, vector<T> m, T MOD){\n m.emplace_back(MOD);\n vector<long long> coef(m.size(), 1);\n vector<long long> consts(m.size(), 0);\n for(int i = 0; i < b.size(); i++){\n long long t = ((b[i] - consts[i]) % m[i]) * modinv<long long>(coef[i], m[i]) % m[i];\n for(int j = i + 1; j < m.size(); j++){\n consts[j] = (consts[j] + t * coef[j] % m[j]) % m[j];\n coef[j] = coef[j] * m[i] % m[j];\n }\n }\n return consts.back();\n}\n\ntemplate <int MOD, int g>\nstruct NTT{\n int get_mod(){\n return MOD;\n }\n void _ntt(vector<long long> &f, bool inv=false){\n int n = f.size(), mask = n - 1;\n int h = power<long long>(g, (MOD - 1) / n, MOD);\n if(inv)h = modinv(h, MOD);\n vector<long long> tmp(n);\n for(int i = n >> 1; i >= 1; i >>= 1){\n long long zeta = power<long long>(h, i, MOD);\n long long w = 1;\n for(int j = 0; j < n; j += i){\n for(int k = 0; k < i; k++){\n tmp[j+k] = (f[((j<<1)&mask)+k] + w * f[(((j<<1)+i)&mask)+k] % MOD) % MOD;\n }\n w = w * zeta % MOD;\n }\n swap(f, tmp);\n }\n }\n void ntt(vector<long long> &f){\n _ntt(f, false);\n }\n void intt(vector<long long> &f){\n _ntt(f, true);\n int n = f.size();\n int ni = modinv(n, MOD);\n for(int i = 0; i < n; i++)f[i] = f[i] * ni % MOD;\n }\n vector<long long> convolution(vector<long long> f, vector<long long> h){\n int n = 1;\n while(n < int(f.size() + h.size()))n *= 2;\n f.resize(n, 0); h.resize(n, 0);\n ntt(f);\n ntt(h);\n for(int i = 0; i < n; i++)f[i] = f[i] * h[i] % MOD;\n intt(f);\n return f;\n }\n};\n\nusing NTT1 = NTT<167772161, 3>;\nusing NTT2 = NTT<469762049, 3>;\nusing NTT3 = NTT<1224736769, 3>;\n\nvector<long long> arbitrary_mod_convolution(vector<long long> f, vector<long long> g, long long MOD){\n for(size_t i = 0; i < f.size(); i++)f[i] %= MOD;\n for(size_t i = 0; i < g.size(); i++)g[i] %= MOD;\n NTT1 ntt1;\n NTT2 ntt2;\n NTT3 ntt3;\n auto x1 = ntt1.convolution(f, g);\n auto x2 = ntt2.convolution(f, g);\n auto x3 = ntt3.convolution(f, g);\n\n vector<long long> res(x1.size());\n vector<long long> b(3), m(3);\n m[0] = ntt1.get_mod();\n m[1] = ntt2.get_mod();\n m[2] = ntt3.get_mod();\n for(size_t i = 0; i < x1.size(); i++){\n b[0] = x1[i];\n b[1] = x2[i];\n b[2] = x3[i];\n res[i] = garner<long long>(b, m, MOD);\n }\n return res;\n}\n\nconst ll B = 10000;\nconst int BW = 4;\nstruct BigInt{\n vector<ll> digit;\n BigInt(ll a = 0){\n digit.emplace_back(a);\n normalize();\n }\n BigInt(const string &s){\n from_string(s);\n }\n void from_string(const string &s){\n digit.clear();\n int i;\n for(i = (int)s.size() - BW; i >= 0; i-=BW){\n digit.emplace_back(stol(s.substr(i, BW)));\n }\n i += BW;\n if(i > 0)digit.emplace_back(stol(s.substr(0, i)));\n }\n void normalize(){\n ll c = 0;\n for(int i = 0; i < digit.size(); i++){\n while(digit[i] < 0){\n if(i + 1 == digit.size())digit.emplace_back(0);\n digit[i+1]--;\n digit[i] += B;\n }\n ll a = digit[i] + c;\n digit[i] = a % B;\n c = a / B;\n }\n while(c){\n digit.emplace_back(c % B);\n c /= B;\n }\n for(int i = (int)digit.size() - 1; i >= 1; i--){\n if(digit[i] == 0){\n digit.pop_back();\n }else{\n break;\n }\n }\n }\n size_t size(){\n return digit.size();\n }\n BigInt& operator=(ll a){\n digit.resize(1, a);\n normalize();\n return *this;\n }\n BigInt& operator=(const string &s){\n from_string(s);\n return *this;\n }\n} ZERO(0), ONE(1);\n\nostream &operator<<(ostream &os, const BigInt &b){\n os << b.digit[b.digit.size() - 1];\n for(int i = (int)b.digit.size() - 2; i >= 0; i--){\n os << setw(BW) << setfill('0') << b.digit[i];\n }\n return os;\n}\n\nistream & operator>>(istream &is, BigInt &b){\n string s;\n is >> s;\n b.from_string(s);\n return is;\n}\n\nbool operator<(const BigInt &x, const BigInt &y){\n if(x.digit.size() != y.digit.size())return x.digit.size() < y.digit.size();\n for(int i = x.digit.size() - 1; i >= 0; i--){\n if(x.digit[i] != y.digit[i])return x.digit[i] < y.digit[i];\n }\n return false;\n}\n\nbool operator>(const BigInt &x, const BigInt y){\n return y < x;\n}\n\nbool operator<=(const BigInt &x, const BigInt &y){\n return !(y < x);\n}\n\nbool operator>=(const BigInt &x, const BigInt &y){\n return !(x < y);\n}\n\nbool operator!=(const BigInt &x, const BigInt &y){\n return x < y || y < x;\n}\n\nbool operator==(const BigInt &x, const BigInt &y){\n return !(x < y) && !(y < x);\n}\n\nBigInt operator+(const BigInt &x, ll a){\n BigInt res = x;\n res.digit[0] += a;\n res.normalize();\n return res;\n}\n\nBigInt operator+(const BigInt &x, const BigInt &y){\n BigInt res = x;\n while(res.digit.size() < y.digit.size())res.digit.emplace_back(0);\n for(int i = 0; i < y.digit.size(); i++)res.digit[i] += y.digit[i];\n res.normalize();\n return res;\n}\n\nBigInt operator-(const BigInt &x, const BigInt &y){\n BigInt res = x;\n assert(res.digit.size() >= y.digit.size());\n for(int i = 0; i < y.digit.size(); i++)res.digit[i] -= y.digit[i];\n res.normalize();\n return res;\n}\n\nBigInt operator*(const BigInt &x, const BigInt &y){\n BigInt z;\n //NTT3 ntt;\n vector<long long> xc = x.digit, yc = y.digit;\n /*z.digit.assign(x.digit.size() + y.digit.size(), 0);\n for(int i = 0; i < x.digit.size(); i++){\n for(int j = 0; j < y.digit.size(); j++){\n z.digit[i+j] += x.digit[i] * y.digit[j];\n }\n }*/\n //z.digit = ntt.convolution(xc, yc);\n z.digit = arbitrary_mod_convolution(xc, yc, (ll)mod * 10);\n z.normalize();\n return z;\n}\n\nBigInt operator*(const BigInt &x, ll a){\n BigInt res = x;\n for(int i = 0; i < res.digit.size(); i++)res.digit[i] *= a;\n res.normalize();\n return res;\n}\n\npair<BigInt, ll> divmod(const BigInt &x, ll a){\n ll c = 0;\n BigInt res = x;\n for(int i = (int)res.digit.size() - 1; i >= 0; i--){\n ll t = B * c + res.digit[i];\n res.digit[i] = t / a;\n c = t % a;\n }\n res.normalize();\n return make_pair(res, c);\n}\n\nBigInt operator/(const BigInt &x, ll a){\n return divmod(x, a).first;\n}\n\nBigInt operator%(const BigInt &x, ll a){\n return divmod(x, a).second;\n}\n\npair<BigInt, BigInt> divmod(const BigInt &x, const BigInt &y){\n BigInt rx = x, ry = y;\n if(x.digit.size() < y.digit.size())return make_pair(ZERO, x);\n int F = B / (y.digit[y.digit.size() - 1] + 1);\n rx = rx * F; ry = ry * F;\n BigInt z;\n z.digit.assign(rx.digit.size() - ry.digit.size() + 1, 0);\n for(int k = (int)z.digit.size() - 1, i = (int)rx.digit.size() - 1; k >= 0; k--, i--){\n z.digit[k] = (i + 1 < rx.digit.size() ? rx.digit[i+1]: 0) * B + rx.digit[i];\n z.digit[k] /= ry.digit[ry.digit.size() - 1];\n BigInt t;\n t.digit.assign(k + ry.digit.size(), 0);\n for(int m = 0; m < ry.digit.size(); m++){\n t.digit[k+m] = z.digit[k] * ry.digit[m];\n }\n t.normalize();\n while(rx < t){\n z.digit[k] -= 1;\n for(int m = 0; m < ry.digit.size(); m++){\n t.digit[k+m] -= ry.digit[m];\n }\n t.normalize();\n }\n rx = rx - t;\n }\n z.normalize();\n return make_pair(z, rx / F);\n}\n\nBigInt operator/(const BigInt &x, const BigInt &y){\n return divmod(x, y).first;\n}\n\nBigInt operator%(const BigInt &x, const BigInt &y){\n return divmod(x, y).second;\n}\n\nBigInt& operator+=(BigInt &x, ll a){\n x = x + a;\n return x;\n}\n\nBigInt &operator+=(BigInt &x, const BigInt &y){\n x = x + y;\n return x;\n}\n\nBigInt &operator-=(BigInt &x, const BigInt &y){\n x = x - y;\n return x;\n}\n\nBigInt& operator*=(BigInt &x, const BigInt &y){\n x = x * y;\n return x;\n}\n\nBigInt& operator/=(BigInt &x, const BigInt &y){\n x = x / y;\n return x;\n}\n\nBigInt& operator%=(BigInt &x, const BigInt &y){\n x = x % y;\n return x;\n}\n\nBigInt& operator/=(BigInt &x, ll a){\n x = x / a;\n return x;\n}\n\nBigInt& operator%=(BigInt &x, ll a){\n x = x % a;\n return x;\n}\n\nBigInt sqrt(const BigInt &x){\n BigInt l = 1;\n BigInt r = x;\n while(r - l > BigInt(1)){\n BigInt m = (r + l) / 2;\n if(m * m > x)r = m;\n else l = m;\n }\n return l;\n}\n\nstruct SBigInt{\n bool neg = false;\n BigInt b = 0;\n SBigInt(){}\n SBigInt(ll a): b(BigInt(abs(a))){\n if(a < 0)neg = true;\n }\n SBigInt(const string &s){\n string t = s;\n if(t[0] == '-'){\n neg = true;\n t = t.substr(1, t.size() - 1);\n }\n b = BigInt(t);\n }\n void check_zero(){\n if(b == ZERO)neg = false;\n }\n bool operator==(const SBigInt &r) const{\n return (neg == r.neg) && (b == r.b);\n }\n bool operator!=(const SBigInt &r) const{\n return (neg != r.neg) || (b != r.b);\n }\n SBigInt operator-() const{\n SBigInt res = *this;\n res.neg = !res.neg;\n res.check_zero();\n return res;\n }\n};\n\nSBigInt operator+(const SBigInt &x, const SBigInt &y){\n SBigInt res;\n if(x.neg == y.neg){\n res.b = x.b + y.b;\n res.neg = x.neg;\n }else{\n if(x.b > y.b){\n res.b = x.b - y.b;\n res.neg = x.neg;\n }else{\n res.b = y.b - x.b;\n res.neg = y.neg;\n }\n }\n res.check_zero();\n return res;\n}\n\nSBigInt operator-(const SBigInt &x, const SBigInt &y){\n SBigInt res = x + (- y);\n res.check_zero();\n return res;\n}\n\nSBigInt operator*(const SBigInt &x, const SBigInt &y){\n SBigInt res;\n res.neg = !(x.neg == y.neg);\n res.b = x.b * y.b;\n res.check_zero();\n return res;\n}\n\nSBigInt operator/(const SBigInt &x, const SBigInt &y){\n SBigInt res;\n res.neg = !(x.neg == y.neg);\n res.b = x.b / y.b;\n res.check_zero();\n return res;\n}\n\nostream &operator<<(ostream &os, const SBigInt &b){\n if(b.neg)os << \"-\";\n os << b.b;\n return os;\n}\n\nint main(int argc, char const* argv[])\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout << fixed << setprecision(20);\n string a, b;\n cin >> a >> b;\n SBigInt A(a), B(b);\n cout << A * B << endl;\n return 0;\n}", "accuracy": 0.64, "time_ms": 20, "memory_kb": 3308, "score_of_the_acc": -0.038, "final_rank": 17 } ]
aoj_0044_cpp
素数 II 素数というのは、1 よりも大きくそれ自身か 1 でしか割りきれない整数をいいます。例えば、2 は、2 と 1 でしか割り切れないので素数ですが、12 は、12 と 1 のほかに、2, 3, 4, 6 で割りきれる数なので素数ではありません。 整数 n を入力したとき、 n より小さい素数のうち最も大きいものと、 n より大きい素数のうち最も小さいものを出力するプログラムを作成してください。 Input 複数のデータセットが与えられます。各データセットに n (3 ≤ n ≤ 50,000) が1行に与えられます。 データセットの数は 50 を超えません。 Output 各データセットに対して、 n より小さい素数のうち最大のものと、 n より大きい素数のうち最小のものを1つのスペースで区切って1行に出力して下さい。 Sample Input 19 3517 Output for the Sample Input 17 23 3511 3527
[ { "submission_id": "aoj_0044_3570869", "code_snippet": "#include <cstdio>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <stdlib.h>\nusing namespace std;\n\n\n\nint main(){\n\tint d,arr[100000],count,ch;\n\tarr[0]=2;\n\tcount =0;\n\tfor(int i=3;i<=50100;i++){\n\t\tch=0;\n\t\tfor(int j=0;j<=count;j++){\n\t\t\tif(i%arr[j] == 0)ch=1;\n\t\t}\n\t\tif(ch == 0){\n\t\t\tcount++;\n\t\t\tarr[count]=i;\n\t\t}\n\t}\n\twhile(scanf(\"%d\",&d) != EOF){\n\t\tfor(int i=0;;i++){\n\t\t\tif(arr[i]==d){\n\t\t\t\tprintf(\"%d %d\\n\",arr[i-1],arr[i+1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(arr[i]>d){\n\t\t\t\tprintf(\"%d %d\\n\",arr[i-1],arr[i]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\t\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 300, "memory_kb": 3220, "score_of_the_acc": -0.4895, "final_rank": 2 }, { "submission_id": "aoj_0044_3202548", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nvector<int> prime;\n\nint main(void) {\n\tfor(int i = 2;i < 60000;i++) {\n\t\tbool isPrime = true;\n\t\tfor(auto e:prime) {\n\t\t\tif(i % e == 0) {\n\t\t\t\tisPrime = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(isPrime) prime.push_back(i);\n\t}\n\tint n;\n\twhile(cin >> n) {\n\t\tauto eq = equal_range(prime.begin(),prime.end(),n);\n\t\tcout << *(eq.first-1) << \" \" << *(eq.second) << endl;\n\t}\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3048, "score_of_the_acc": -0.0227, "final_rank": 1 }, { "submission_id": "aoj_0044_2811117", "code_snippet": "#include<iostream>\nusing namespace std;\n\nvoid prime(int a){\n int cnt1=a+1;\n int cnt2=a-1;\n bool is_prime[1000000];\n is_prime[0] = is_prime[1] = false;\n for(int i=2;i<1000000;i++){\n is_prime[i] = true;\n }\n for(int i=2;i*i<1000000;i++){\n if(is_prime[i]){\n for(int j=i*i;j<1000000;j+=i){\n is_prime[j] = false;\n }\n }\n }\n while(1){\n if(is_prime[cnt2]){\n cout << cnt2 << \" \";\n break;\n }\n cnt2--;\n }\n\n while(1){\n if(is_prime[cnt1]){\n cout << cnt1 << endl;\n break;\n }\n cnt1++;\n }\n\n}\n\nint main(){\n while(1){\n int num;\n cin >> num;\n if(cin.eof())\n break;\n\n prime(num);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 4052, "score_of_the_acc": -1, "final_rank": 3 }, { "submission_id": "aoj_0044_2290108", "code_snippet": "#include<iostream>\n#include<algorithm>\n#include<vector>\n#include<set>\n#include<string>\n\n\nint main() {\n\tint n;\n\tbool a;\n\tstd::vector<int> prime;\n\tprime.emplace_back(2);\n\tfor (int i = 3; i < 1000000; i += 2) {\n\t\ta = false;\n\t\tfor (int j = 3; j <= std::sqrt(i); j += 2) {\n\t\t\tif (i%j == 0) {\n\t\t\t\ta = true;\n\t\t\t}\n\t\t}\n\t\tif (a == false) {\n\t\t\tprime.emplace_back(i);\n\t\t}\n\t}\n\twhile (std::cin >> n) {\n\t\tint ans = 0;\n\t\tint low = 0, high = 0;\n\t\tfor (int i = 0; i < prime.size(); i++) {\n\t\t\tif (prime[i] < n) {\n\t\t\t\tlow = prime[i];\n\t\t\t}\n\t\t\tif (prime[i] > n) {\n\t\t\t\thigh = prime[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tstd::cout << low << \" \" << high << std::endl;\n\t}\n}", "accuracy": 1, "time_ms": 900, "memory_kb": 3264, "score_of_the_acc": -1.2151, "final_rank": 4 } ]
aoj_0040_cpp
アフィン暗号 簡単な暗号法の一つに、アフィン暗号というものがあります。まず、アルファベット a〜z を a = 0, b = 1, c = 2,..., x = 23, y = 24, z = 25 と 0〜25 の数字に置き換えます。そして、以下の式で、原文のアルファベットを置換します。 $F(\gamma) = (\alpha \cdot \gamma + \beta)$ mod $26$ ただし、mod 26 は 26 で割った余りを表します。例えば、$\alpha = 3, \beta = 2$ のとき、アルファベットの 'a' (=0) は、$F(0) = (3 \cdot 0 + 2)$ mod $26 = 2$ で 'c' に、アルファベットの 'n' (=13) は $F(13) = (3 \cdot 13 + 2)$ mod $26 = 15$ で 'p' に置換されます。 このとき、$\gamma$ に対する $F(\gamma)$ が必ず 1 対 1 で対応付けられるように、$\alpha$ と $\beta$ は慎重に選ばれているものとします($\alpha$ と 26 が互いに素であることが条件)。$\alpha = 4, \beta = 7$ のときのように、$F('a') = 7, F('n') = 7$ と、'a' も 'n' も同じ 'h' に置換されるようなことはありません。また、アルファベット以外の文字は置換されません。 暗号化された文字列を元の文章に復号したものを出力するプログラムを作成してください。元の文章には、キーワードとして that this のいずれかが必ず含まれているものとします。 Input 複数のデータセットが与えられます。1行目にデータセット数 $n$ ($n \leq 30$) が与えられます。続いて $n$ 行のデータが与えられます。各データセットに英小文字と空白からなる 256 文字以内の暗号化された文章が1行に与えられます。 Output 各データセットに対して、復号した元の文章を1行に出力して下さい。 Sample Input 1 y eazqyp pnop pngtg ye obmpngt xmybp mr lygw Output for the Sample Input i submit that there is another point of view
[ { "submission_id": "aoj_0040_2489714", "code_snippet": "#include<iostream>\n#include<string>\n#include<cmath>\n#include<queue>\n#include<map>\n#include<set>\n#include<list>\n#include<iomanip>\n#include<vector>\n#include<functional>\n#include<algorithm>\n#include<cstdio>\n#include<unordered_map>\nusing namespace std;\n//---------------------------------------------------\n//????????????????????????????????????\n#define int long long\n#define str string\nconst int inf = 999999999999999999;\nstruct P {\n\tint pos, cost;\n};\nbool operator<(P a, P b) { return a.cost < b.cost; }\nbool operator>(P a, P b) { return a.cost > b.cost; }\nstruct B {\n\tint to, cost;\n};\nint gcm(int i, int j) {//?????§??¬?´???°\n\tif (i > j) swap(i, j);\n\tif (i == 0) return j;\n\treturn gcm(j%i, i);\n}\nbool sfind(string s, string l) {//?????????1??????????????????2????????????\n\tfor (int i = 0; i <= s.size() - l.size(); i++) {\n\t\tstr t = \"\";\n\t\tfor (int j = 0; j < l.size(); j++)\n\t\t\tt += s[i + j];\n\t\tif (t == l)\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}\ntypedef long long ll;\ntypedef long double ld;\n//---------------------------------------------------\n//+++++++++++++++++++++++++++++++++++++++++++++++++++\n//---------------------------------------------------\nsigned main() {\n\tint n;\n\tcin >> n;\n\tgetchar();\n\tfor (int r = 0; r < n; r++) {\n\t\tstring s;\n\t\tgetline(cin, s);\n\t\tfor (int i = 0; i < 26; i++) {\n\t\t\tfor (int j = 0; j < 26; j++) {\n\t\t\t\tstring a = \"\";\n\t\t\t\tfor (int z = 0; z < s.size(); z++) {\n\t\t\t\t\tif (s[z] == ' ')\n\t\t\t\t\t\ta += \" \";\n\t\t\t\t\telse\n\t\t\t\t\t\ta += (char)((((s[z] - 'a')*i + j) % 26) + 'a');\n\t\t\t\t}\n\t\t\t\tif (sfind(a, \"that\") || sfind(a, \"this\")) {\n\t\t\t\t\tcout << a << endl;\n\t\t\t\t\tgoto stop;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tstop:;\n\t}\n\tgetchar(); getchar();\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 3156, "score_of_the_acc": -2, "final_rank": 8 }, { "submission_id": "aoj_0040_1954615", "code_snippet": "#include<iostream>\n#include<string.h>\n#include<vector>\n#include<list>\n#include<stdio.h>\n#include<math.h>\n#include<iomanip>\n#include<map>\n#include<stack>\n#include<queue>\n#include<algorithm>\n#define range(i,a,b) for(int i = (a); i < (b); i++)\n#define rep(i,b) range(i,0,b)\n#define debug(x) cout << \"debug \" << x << endl;\nusing namespace std;\n\nint main(){\n int n;\n char ans[257], str[257];\n while(cin >> n){\n cin.ignore();\n rep(i,n){\n cin.getline(str, sizeof(str));\n bool c = false;\n rep(i,26){\n rep(j,26){\n rep(k,strlen(str)){\n if(str[k] != ' ')\n ans[k] = (i * str[k] - 'a' + j) % 26 + 'a';\n else ans[k] = str[k];\n }\n if(strstr(ans, \"this\") != NULL || strstr(ans, \"that\") != NULL){\n c = true;\n }\n if(c) break;\n }\n if(c) break;\n }\n ans[strlen(str)] = '\\0';\n cout << ans << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1160, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_0040_1863770", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <string>\nusing namespace std;\n\n\nbool IsCoprime(int a, int b)\n{\n\twhile (a > 0 && b > 0)\n\t{\n\t\tif (a < b) swap(a, b);\n\t\ta %= b;\n\t}\n\tif (a == 1 || b == 1) return true;\n\treturn false;\n}\n\n\nchar get(int a, int b, char c)\n{\n\tfor (int i = 0; i < 26; i++)\n\t{\n\t\tif ((a * i + b) % 26 == c - 'a') return char(i + 'a');\n\t}\n}\n\n\nint main()\n{\n\tint n;\n\tstring cip;\n\tstring dec;\n\n\tcin >> n;\n\tcin.get();\n\n\twhile (n--)\n\t{\n\t\tgetline(cin, cip);\n\t\tdec = cip;\n\n\t\tfor (int a = 0; a < 26; a++)\n\t\t{\n\t\t\tif (!IsCoprime(a, 26)) continue;\n\t\t\tfor (int b = 0; b < 26; b++)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < cip.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tif (cip[i] == ' ') continue;\n\t\t\t\t\tdec[i] = get(a, b, cip[i]);\n\t\t\t\t}\n\t\t\t\tif (dec.find(\"that\") != -1 || dec.find(\"this\") != -1)\n\t\t\t\t{\n\t\t\t\t\tcout << dec << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1212, "score_of_the_acc": -0.0261, "final_rank": 3 }, { "submission_id": "aoj_0040_1853174", "code_snippet": "#define _USE_MATH_DEFINES\n#include <iostream>\n#include <sstream>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n#include <stack>\n#include <limits>\n#include <map>\n#include <string>\n#include <cstring>\n\ntypedef long long ll;\nusing namespace std;\n\nint F(int a, int b, int c){\n\treturn (a*c+b) % 26;\n}\n\nint main(){\n\tint n;\n\tstring str1;\n\tgetline(cin,str1);\n\n\tn = atoi(str1.c_str());\n\tfor(int i=0;i<n;i++){\n\t\tstring str2;\n\t\tgetline(cin,str2);\n\n\t\tfor(int a=0;a<100;a++){\n\t\t\tfor(int b=0;b<100;b++){\n\t\t\t\tstring tmp = str2;\n\t\t\t\tfor(int i=0;i<str2.size();i++){\n\t\t\t\t\tif(tmp[i]=='.') continue;\n\t\t\t\t\tif(tmp[i]==' ') continue;\n\t\t\t\t\tif(isdigit(tmp[i])) continue;\n\t\t\t\t\ttmp[i] = F(a,b,str2[i]-'a') + 'a';\n\t\t\t\t}\n\n\t\t\t\tif(tmp.find(\"that\") != string::npos\n\t\t\t\t\t|| tmp.find(\"this\") != string::npos){\n\t\t\t\t\t\tcout << tmp << endl;\n\t\t\t\t\t\tgoto found;\n\t\t\t\t}\n\t\t\t}\n\t\t}\nfound:;\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1200, "score_of_the_acc": -0.02, "final_rank": 2 }, { "submission_id": "aoj_0040_1841488", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std; \n \nmap<char, int> c2i;\nmap<int, char> i2c;\nstring str;\n \nvoid init()\n{\n for (char ch = 'a'; ch <= 'z'; ch++) {\n\tc2i[ch] = ch - 'a';\n\ti2c[ch - 'a'] = ch;\n }\n}\n \nbool serch(string s)\n{\n string str;\n stringstream ss(s);\n while (ss >> str) {\n if (str == \"this\" || str == \"that\") {\n return 1;\n }\n }\n return 0;\n}\n \nchar F(char ch, int a, int b)\n{\n int num = (a * c2i[ch] + b) % 26; \n return i2c[num];\n}\n \nint main()\n{\n int n;\n init(); \n cin >> n;\n cin.ignore();\n while (n--) {\n\tgetline(cin, str);\n \n\tfor (int i = 0; i < 26; i++) {\n\t for (int j = 0; j < 26; j++) {\n\t\tstring next;\n\t\tfor (int k = 0; k < (int)str.size(); k++) {\n\t\t if (islower(str[k])) {\n next += F(str[k], i, j);\n\t\t } else {\n next += str[k];\n }\n }\n\t\tif (serch(next)) {\n\t\t cout << next << endl;\n goto END;\n\t\t}\n\t }\n\t}\n END:;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3004, "score_of_the_acc": -0.9238, "final_rank": 6 }, { "submission_id": "aoj_0040_1772504", "code_snippet": "#include<cstdio>\n#include<cmath>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#include<map>\nusing namespace std;\nstring change(int a,int b,string str){\n for(int i=0;i<str.size();i++)str[i]=((str[i]-'a')*a+b)%26+'a';\n return str;\n}\nstring out(int a,int b,string str){\n for(int i=0;i<str.size();i++){\n if('a'<=str[i]&&str[i]<='z'){\n for(int j=0;j<26;j++){\n if((j*a+b)%26+'a'==str[i]){\n str[i]=j+'a';\n break;\n }\n }\n }\n }\n return str;\n}\nint main(){\n int N;\n cin>>N;\n for(int i=0;i<N;i++){\n string str;\n if(!i)getchar();\n getline(cin,str);\n for(int j=1;;j++){\n for(int k=0;k<26;k++){\n for(int l=0;l<str.size()-3;l++){\n if(change(j,k,\"that\")==str.substr(l,4)){\n cout<<out(j,k,str)<<endl;\n goto exit;\n }\n if(change(j,k,\"this\")==str.substr(l,4)){\n cout<<out(j,k,str)<<endl;\n goto exit;\n }\n }\n }\n }\n exit:;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 1220, "score_of_the_acc": -1.0301, "final_rank": 7 }, { "submission_id": "aoj_0040_1664994", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n#define rep(i,n) for(i=0;i<n;++i)\n#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); itr++)\n#define mp make_pair\n#define pb push_back\n#define fi first\n#define sc second\n\nint gcd(int p, int q){\n if(p<q) swap(p,q);\n while(q!=0){\n int tmp=p%q;\n p=q;\n q=tmp;\n }\n return p;\n}\n\nint main(int argc, char const *argv[]) {\n int i,j,k;\n\n string a=\"abcdefghijklmnopqrstuvwxyz\";\n\n int n;\n scanf(\"%d\\n\",&n);\n for(int times=0; times<n; ++times){\n string s;\n getline(cin,s);\n //cout << s << endl;\n\n string ans;\n bool end=false;\n\n for(i=1; i<=25; ++i){//??¢???????????????\n if(gcd(26,i)!=1) continue;\n\n rep(j,26){\n //????????£?????§????¨?\n set<int> ch;\n rep(k,a.size()) ch.insert((i*k+j)%26);\n //??????\n if(ch.size()!=a.size()) continue;\n\n //printf(\"(%d,%d)\\n\",i,j);\n\n //?????????\n ans=\"\";\n int p=0;\n rep(k,s.size()){\n if('a'<=s[k] && s[k]<='z'){\n ans+='a'+(i*(s[k]-'a')+j)%26;\n }\n else{\n ans+=s[k];\n string tmp=ans.substr(p,k-p);\n //cout << tmp << endl;\n\n if(tmp==\"this\"||tmp ==\"that\")\n end=true;\n\n p=k+1;\n }\n }\n\n string tmp=ans.substr(p,k-p);\n //cout << tmp << endl;\n\n if(tmp==\"this\"||tmp ==\"that\")\n end=true;\n\n\n if(end) break;\n }\n if(end) break;\n }\n\n std::cout << ans << std::endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1240, "score_of_the_acc": -0.0401, "final_rank": 5 }, { "submission_id": "aoj_0040_1662878", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\n\nchar T[27] = \"abcdefghijklmnopqrstuvwxyz\";\n\nstring S, V;\nint n;\nint x[26];\n\nint main() {\n\tcin >> n;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tS = \"\";\n\t\twhile (S == \"\") {\n\t\t\tgetline(cin, S);\n\t\t}\n\t\tfor (int j = 0; j < 26; j++)\n\t\t{\n\t\t\tfor (int k = 0; k < 26; k++)\n\t\t\t{\n\t\t\t\tfor (int l = 0; l < 26; l++)\n\t\t\t\t{\n\t\t\t\t\tx[l] = -1;\n\t\t\t\t}\n\t\t\t\tfor (int l = 0; l < 26; l++)\n\t\t\t\t{\n\t\t\t\t\tif (x[(j*l + k) % 26] == -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx[(j*l + k) % 26] = l;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tgoto E;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tV = \"\";\n\t\t\t\tfor (int l = 0; l < S.size(); l++)\n\t\t\t\t{\n\t\t\t\t\tfor (int m = 0; m < 26; m++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (T[m] == S[l])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tV += T[x[m]];\n\t\t\t\t\t\t\tgoto G;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tV += S[l];\n\t\t\t\tG:;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < S.size() - 3; i++)\n\t\t\t\t{\n\t\t\t\t\tif (V.substr(i, 4) == \"this\" || V.substr(i, 4) == \"that\")\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << V << endl;\n\t\t\t\t\t\tgoto H;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tE:;\n\t\t\t}\n\t\t}\n\tH:;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1220, "score_of_the_acc": -0.0301, "final_rank": 4 } ]
aoj_0042_cpp
泥棒 宝物がたくさん収蔵されている博物館に、泥棒が大きな風呂敷を一つだけ持って忍び込みました。盗み出したいものはたくさんありますが、風呂敷が耐えられる重さが限られており、これを超えると風呂敷が破れてしまいます。そこで泥棒は、用意した風呂敷を破らず且つ最も価値が高くなるようなお宝の組み合わせを考えなくてはなりません。 風呂敷が耐えられる重さ W 、および博物館にある個々のお宝の価値と重さを読み込んで、重さの総和が W を超えない範囲で価値の総和が最大になるときの、お宝の価値総和と重さの総和を出力するプログラムを作成してください。ただし、価値の総和が最大になる組み合わせが複数あるときは、重さの総和が小さいものを出力することとします。 Input 複数のデータセットが与えられます。各データセットは以下のような形式で与えられます。 W N v 1 , w 1 v 2 , w 2 : v N , w N 1行目に風呂敷の耐えられる重さを表す整数 W ( W ≤ 1,000)、2行目にお宝の数 N (1 ≤ N ≤ 1,000) が与えられます。続く N 行に i 番目のお宝の価値を表す整数 v i (0 ≤ v i ≤ 10,000) とその重さを表す整数 w i (0 ≤ w i ≤ W ) の組がそれぞれ1行に与えられます。 W が 0 のとき入力の最後とします。データセットの数は 50 を超えません。 Output 各データセットに対して以下のように出力して下さい。 Case データセットの番号: 風呂敷に入れたお宝の価値総和 そのときのお宝の重さの総和 Sample Input 50 5 60,10 100,20 120,30 210,45 10,4 50 5 60,10 100,20 120,30 210,45 10,4 0 Output for the Sample Input Case 1: 220 49 Case 2: 220 49
[ { "submission_id": "aoj_0042_7370385", "code_snippet": "#include <bits/stdc++.h>\n#include <stdint.h>\n\nusing namespace std;\n\n#define PI M_PI\n#define MOD 1000000007\n#define debug(x) cout << #x << \" = \" << x << endl\n#define MAP_HAS_KEY(m, key) (m.find(key) != m.end())\n\ntemplate<class T> std::vector<std::string> split(const std::string& s, const T& separator, bool ignore_empty = 0, bool split_empty = 0) {\n struct {\n auto len(const std::string& s) { return s.length(); }\n auto len(const std::string::value_type* p) { return p ? std::char_traits<std::string::value_type>::length(p) : 0; }\n auto len(const std::string::value_type c) { return c == std::string::value_type() ? 0 : 1; /*return 1;*/ }\n } util;\n \n if (s.empty()) { /// empty string ///\n if (!split_empty || util.len(separator)) return {\"\"};\n return {};\n }\n \n auto v = std::vector<std::string>();\n auto n = static_cast<std::string::size_type>(util.len(separator));\n if (n == 0) { /// empty separator ///\n if (!split_empty) return {s};\n for (auto&& c : s) v.emplace_back(1, c);\n return v;\n }\n \n auto p = std::string::size_type(0);\n while (1) { /// split with separator ///\n auto pos = s.find(separator, p);\n if (pos == std::string::npos) {\n if (ignore_empty && p - n + 1 == s.size()) break;\n v.emplace_back(s.begin() + p, s.end());\n break;\n }\n if (!ignore_empty || p != pos)\n v.emplace_back(s.begin() + p, s.begin() + pos);\n p = pos + n;\n }\n return v;\n}\n\nint64_t primeFactor(int64_t n) {\n for(int64_t i=2; i<=n; i++) {\n if(n%i == 0) return i;\n }\n return n;\n}\n\nint primeCount(int n) {\n int current = n;\n int count = 0;\n \n for(;;) {\n //cout << current << \" \";\n int prime = primeFactor(current);\n current = current / prime;\n count++;\n\n if(current == 1) break;\n }\n return count;\n}\n\ntypedef struct {\n int64_t value;\n int64_t weight;\n} ITEM;\n\nbool test(int caseCount) {\n int w, n;\n\n cin >> w;\n if(w == 0) return false;\n\n cin >> n;\n\n vector<ITEM> treasures(n);\n for(int i=0; i<n; i++) {\n string s;\n cin >> s;\n auto strs = split(s, ',');\n int a = stoi(strs[0]);\n int b = stoi(strs[1]);\n treasures[i] = ITEM{a, b};\n }\n\n map<pair<int, int>, ITEM> memo;\n\n function<ITEM(int, int)> rec = [&](int idx, int leastWeight) {\n if(idx == n) return ITEM{0, leastWeight};\n auto key = make_pair(idx, leastWeight);\n if(MAP_HAS_KEY(memo, key)) return memo[key];\n\n auto treasure = treasures[idx];\n\n ITEM a = rec(idx+1, leastWeight);\n if(leastWeight < treasure.weight) {\n memo[key] = a;\n return a;\n }\n ITEM b = rec(idx+1, leastWeight - treasure.weight);\n b.value += treasure.value;\n //b.weight -= treasure.weight;\n\n if(a.value == b.value) memo[key] = (a.weight > b.weight) ? a : b;\n else memo[key] = (a.value > b.value) ? a : b;\n \n return memo[key];\n };\n\n cout << \"Case \" << caseCount << \":\" << endl;\n ITEM result = rec(0, w);\n cout << result.value << endl;\n cout << w - result.weight << endl;\n\n return true;\n}\n\nint main() {\n\n int caseCount = 0;\n for(;;) {\n if(!test(++caseCount)) break;\n }\n\n}", "accuracy": 1, "time_ms": 450, "memory_kb": 65188, "score_of_the_acc": -1.1483, "final_rank": 4 }, { "submission_id": "aoj_0042_6259751", "code_snippet": "#include<stdio.h>\n#include<string.h>\n\nstruct Node\n{\n\tint w;\n\tint v;\n};\n\nNode g_dp[1001][1001];\nNode g_data[1001];\n\nNode slove(Node data[], int idx, int n, int sum)\n{\n\tNode tmp;\n\ttmp.w = 0;\n\ttmp.v = 0;\n\tif (idx >= n)\n\t{\n\t\ttmp.w = sum;\n\t\ttmp.v = 0;\n\t\treturn tmp;\n\t}\n\n\tif (sum <= 0)\n\t\treturn tmp;\n\n\tif (g_dp[idx][sum].v != 0)\n\t\treturn g_dp[idx][sum];\n\n\n\tNode ret, ret1, ret2;\n\tint s = sum - data[idx].w;\n\tif (s >= 0)\n\t{\n\t\tret1 = slove(data, idx + 1, n, s);\n\t\tret1.v += data[idx].v;\n\t}\n\telse\n\t{\n\t\tret1 = tmp;\n\t}\n\n\tret2 = slove(data, idx + 1, n, sum);\n\tif (ret1.v > ret2.v)\n\t\tret = ret1;\n\telse\n\t\tret = ret2;\n\tg_dp[idx][sum] = ret;\n\treturn g_dp[idx][sum];\n}\n\n\nint main()\n{\n\tint w, n, v1, w1;\n\tint mk = 0;\n\twhile (scanf(\"%d\", &w) != EOF)\n\t{\n\t\tif (w == 0)\n\t\t\tbreak;\n\t\tscanf(\"%d\", &n);\n\t\tmemset(g_data, 0, sizeof(g_data));\n\t\tmemset(g_dp, 0, sizeof(g_dp));\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tscanf(\"%d,%d\", &v1, &w1);\n\t\t\tg_data[i].w = w1;\n\t\t\tg_data[i].v = v1;\n\t\t}\n\t\tmk++;\n\t\tNode maxN = slove(g_data, 0, n, w);\n\t\tprintf(\"Case %d:\\n\",mk);\n\t\tprintf(\"%d\\n%d\\n\", maxN.v, w - maxN.w);\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10580, "score_of_the_acc": -0.004, "final_rank": 2 }, { "submission_id": "aoj_0042_3637488", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int\t\t\t\tlong long\n#define FOR( i, m, n ) for( int (i) = (m); (i) < (n); (i)++ )\n#define REP( i, n ) FOR( i, 0, n )\n#define REPR( i, m )\tfor( int (i) = (m); (i) >= 0; (i)-- )\n#define REPONE( i, n )\tFOR( i, 1, n + 1 )\n#define ALL( a ) (a).begin(), (a).end()\n#define MP\t\t\t\tmake_pair\n#define EB\t\t\t\templace_back\n\ntypedef pair<int, int> P;\n\ntemplate<class T>bool chmax( T& a, const T& b ) { if( a < b ) { a = b; return 1; } return 0; }\ntemplate<class T>bool chmin( T& a, const T& b ) { if( a > b ) { a = b; return 1; } return 0; }\n\nconst int INF = 1e9;\nconst int MOD = 1e9 + 7;\n\nint dp[1001][10001];\n\nsigned main() {\n\tint W, N, cnt = 1;\n\twhile( cin >> W, W ) {\n\t\tcin >> N;\n\t\tfill( dp[0], dp[1001], 0 );\n\n\t\tint w = 0, vmax = 0;\n\t\tvector<P> tre( N );\n\t\tREP( i, N ) {\n\t\t\tchar c;\n\t\t\tcin >> tre[i].first >> c >> tre[i].second;\n\t\t}\n\n\t\tREP( i, N ) {\n\t\t\tREP( j, W + 1 ) {\n\t\t\t\tif( j - tre[i].second >= 0 ) {\n\t\t\t\t\tdp[i + 1][j] = max( dp[i][j], dp[i][j - tre[i].second] + tre[i].first );\n\n\t\t\t\t\tif( vmax < dp[i + 1][j] ) {\n\t\t\t\t\t\tvmax = dp[i + 1][j];\n\t\t\t\t\t\tw = j;\n\t\t\t\t\t} else if( vmax == dp[i + 1][j] ) {\n\t\t\t\t\t\tchmin( w, j );\n\t\t\t\t\t}\n\n\n\t\t\t\t} else {\n\t\t\t\t\tdp[i + 1][j] = dp[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Case \" << ( cnt++ ) << \":\" << endl;\n\t\tcout << dp[N][W] << endl << w << endl;\n\n\t}\n}", "accuracy": 1, "time_ms": 80, "memory_kb": 81296, "score_of_the_acc": -0.8011, "final_rank": 3 }, { "submission_id": "aoj_0042_3224544", "code_snippet": "#include <cstdio>\n#include <utility>\n#include <vector>\nusing namespace std;\n\n#define gcu getchar_unlocked\nint in(int c){int n=0;bool m=false;if(c=='-')m=true,c=gcu();\n\tdo{n=10*n+(c-'0'),c=gcu();}while(c>='0');return m?-n:n;}\nint in() {return in(gcu());}\nbool scan(int &n){int c=gcu();return c==EOF?false:(n=in(c),true);}\nbool scan(char &c){c=gcu();gcu();return c!=EOF;}\n//bool scan(string &s){int c;s=\"\";\n//\tfor(;;){c=gcu();if(c=='\\n'||c==' ')return true;else if(c==EOF)return false;s+=c;}}\n#define pcu putchar_unlocked\n#define vo inline void out\ntemplate <typename T>\nvo(T n){static char buf[20];char *p=buf;\n\tif(n<0)pcu('-'),n*=-1;if(!n)*p++='0';else while(n)*p++=n%10+'0',n/=10;\n\twhile (p!=buf)pcu(*--p);}\nvo(const char *s){while(*s)pcu(*s++);}\nvo(char c){pcu(c);}\n//vo(string &s){for (char c: s) pcu(c);}\ntemplate <typename head, typename... tail> vo(head&& h, tail&&... t){out(h);out(move(t)...);}\n//template <typename T> vo(vector<T> &v){for(T &x:v)out(&x == &v[0]?\"\":\" \"),out(x);out('\\n');}\n#undef vo\n\nstruct T {int v, w;};\n\nT find(int n, int w, vector<T> &ts, vector<vector<T>> &m) {\n\tT r;\n\tif (n < 0)\n\t\treturn {0, w};\n\telse if (m[n][w].w != -1)\n\t\treturn m[n][w];\n\telse if (ts[n].w > w)\n\t\tr = find(n - 1, w, ts, m);\n\telse {\n\t\tT a = find(n - 1, w, ts, m),\n\t\t b = find(n - 1, w - ts[n].w, ts, m);\n\t\tb.v += ts[n].v;\n\t\tr = a.v > b.v ? a : b;\n\t}\n\tm[n][w] = r;\n\treturn r;\n}\n\nint main() {\n\tfor (int w, n, i = 1; (w = in()) && (n = in()); i++) {\n\t\tout(\"Case \", i, \":\\n\");\n\t\tvector<T> ts(n);\n\t\tvector<vector<T>> m(n, vector<T>(w + 1, {0, -1}));\n\t\tfor (auto &t: ts) {\n\t\t\tint v = in();\n\t\t\tt = {v, in()};\n\t\t}\n\t\tT r = find(n - 1, w, ts, m);\n\t\tout(r.v, '\\n', w - r.w, '\\n');\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 10172, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_0042_3224505", "code_snippet": "#include <cstdio>\n#include <utility>\n#include <vector>\n#include <map>\nusing namespace std;\n\n#define gcu getchar_unlocked\nint in(int c){int n=0;bool m=false;if(c=='-')m=true,c=gcu();\n\tdo{n=10*n+(c-'0'),c=gcu();}while(c>='0');return m?-n:n;}\nint in() {return in(gcu());}\nbool scan(int &n){int c=gcu();return c==EOF?false:(n=in(c),true);}\nbool scan(char &c){c=gcu();gcu();return c!=EOF;}\n//bool scan(string &s){int c;s=\"\";\n//\tfor(;;){c=gcu();if(c=='\\n'||c==' ')return true;else if(c==EOF)return false;s+=c;}}\n#define pcu putchar_unlocked\n#define vo inline void out\ntemplate <typename T>\nvo(T n){static char buf[20];char *p=buf;\n\tif(n<0)pcu('-'),n*=-1;if(!n)*p++='0';else while(n)*p++=n%10+'0',n/=10;\n\twhile (p!=buf)pcu(*--p);}\nvo(const char *s){while(*s)pcu(*s++);}\nvo(char c){pcu(c);}\n//vo(string &s){for (char c: s) pcu(c);}\ntemplate <typename head, typename... tail> vo(head&& h, tail&&... t){out(h);out(move(t)...);}\n//template <typename T> vo(vector<T> &v){for(T &x:v)out(&x == &v[0]?\"\":\" \"),out(x);out('\\n');}\n#undef vo\n\nstruct T {int v, w;};\nmap<vector<int>, T> m;\n\nT find(int n, int w, vector<T> &ts) {\n\tT r;\n\tvector<int> k = {n, w};\n\tif (m.count(k))\n\t\treturn m[k];\n\tif (n < 0)\n\t\tr = {0, w};\n\telse if (ts[n].w > w)\n\t\tr = find(n - 1, w, ts);\n\telse {\n\t\tT a = find(n - 1, w, ts),\n\t\t b = find(n - 1, w - ts[n].w, ts);\n\t\tb.v += ts[n].v;\n\t\tr = a.v > b.v ? a : b;\n\t}\n\tm[k] = r;\n\treturn r;\n}\n\nint main() {\n\tfor (int w, n, i = 1; (w = in()) && (n = in()); i++) {\n\t\tout(\"Case \", i, \":\\n\");\n\t\tvector<T> ts(n);\n\t\tm = {};\n\t\tfor (auto &t: ts) {\n\t\t\tint v = in();\n\t\t\tt = {v, in()};\n\t\t}\n\t\tT r = find(n - 1, w, ts);\n\t\tout(r.v, '\\n', w - r.w, '\\n');\n\t}\n}", "accuracy": 1, "time_ms": 740, "memory_kb": 111024, "score_of_the_acc": -2, "final_rank": 5 }, { "submission_id": "aoj_0042_3224496", "code_snippet": "#include <cstdio>\n#include <utility>\n#include <vector>\n#include <map>\nusing namespace std;\n\n#define gcu getchar_unlocked\nint in(int c){int n=0;bool m=false;if(c=='-')m=true,c=gcu();\n\tdo{n=10*n+(c-'0'),c=gcu();}while(c>='0');return m?-n:n;}\nint in() {return in(gcu());}\nbool scan(int &n){int c=gcu();return c==EOF?false:(n=in(c),true);}\nbool scan(char &c){c=gcu();gcu();return c!=EOF;}\n//bool scan(string &s){int c;s=\"\";\n//\tfor(;;){c=gcu();if(c=='\\n'||c==' ')return true;else if(c==EOF)return false;s+=c;}}\n#define pcu putchar_unlocked\n#define vo inline void out\ntemplate <typename T>\nvo(T n){static char buf[20];char *p=buf;\n\tif(n<0)pcu('-'),n*=-1;if(!n)*p++='0';else while(n)*p++=n%10+'0',n/=10;\n\twhile (p!=buf)pcu(*--p);}\nvo(const char *s){while(*s)pcu(*s++);}\nvo(char c){pcu(c);}\n//vo(string &s){for (char c: s) pcu(c);}\ntemplate <typename head, typename... tail> vo(head&& h, tail&&... t){out(h);out(move(t)...);}\n//template <typename T> vo(vector<T> &v){for(T &x:v)out(&x == &v[0]?\"\":\" \"),out(x);out('\\n');}\n#undef vo\n\nstruct T {int v, w;};\nmap<vector<int>, T> m;\n\nT find(int n, int w, vector<T> &ts) {\n\tT r;\n\tvector<int> k = {n, w};\n\tif (m.count(k))\n\t\treturn m[k];\n\tif (n < 0 || ts[n].w > w)\n\t\tr = {0, w};\n\telse {\n\t\tT a = find(n - 1, w, ts),\n\t\t b = find(n - 1, w - ts[n].w, ts);\n\t\tb.v += ts[n].v;\n\t\tr = a.v > b.v ? a : b;\n\t}\n\tm[k] = r;\n\treturn r;\n}\n\nint main() {\n\tfor (int w, n, i = 1; (w = in()) && (n = in()); i++) {\n\t\tout(\"Case \", i, \":\\n\");\n\t\tvector<T> ts(n);\n\t\tm = {};\n\t\tfor (auto &t: ts) {\n\t\t\tint v = in();\n\t\t\tt = {v, in()};\n\t\t}\n\t\tT r = find(n - 1, w, ts);\n\t\tout(r.v, '\\n', w - r.w, '\\n');\n\t}\n}", "accuracy": 0.5, "time_ms": 700, "memory_kb": 110940, "score_of_the_acc": -1.9444, "final_rank": 6 } ]
aoj_0041_cpp
式 与えられた 4 つの 1 から 9 の整数を使って、答えが 10 になる式をつくります。 4 つの整数 a, b, c, d を入力したとき、下記の条件に従い、答えが 10 になる式を出力するプログラムを作成してください。また、答えが複数ある時は、最初に見つかった答えだけを出力するものとします。答えがない時は、0 と出力してください。 演算子として、加算 (+)、減算 (-)、乗算 (*) だけを使います。除算 (/) は使いません。使用できる演算子は3個です。 数を4つとも使わなければいけません。 4つの数の順番は自由に入れ換えてかまいません。 カッコを使ってもかまいません。使用できるカッコは3組(6個)以下です。 Input 複数のデータセットが与えられます。各データセットの形式は以下のとおり: a b c d 入力は4つの 0 で終了します。データセットの数は 40 を超えません。 Output 各データセットについて、与えられた 4 つの整数と上記の演算記号およびカッコを組み合わせて値が 10 となる式または 0 を1行に出力してください。式の文字列が 1024 文字を超えてはいけません。 Sample Input 8 7 9 9 4 4 4 4 5 5 7 5 0 0 0 0 Output for the Sample Input ((9 * (9 - 7)) - 8) 0 ((7 * 5) - (5 * 5))
[ { "submission_id": "aoj_0041_8027424", "code_snippet": "#pragma region Macros\n\n// #pragma GCC optimize(\"O3,unroll-loops\")\n// #pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2\")\n\n#include <bits/extc++.h>\n// #include <atcoder/all>\n// using namespace atcoder;\nusing namespace std;\nusing namespace __gnu_pbds;\n\n// #include <boost/multiprecision/cpp_dec_float.hpp>\n// #include <boost/multiprecision/cpp_int.hpp>\n// namespace mp = boost::multiprecision;\n// using Bint = mp::cpp_int;\n// using Bdouble = mp::number<mp::cpp_dec_float<128>>;\n\n#define TO_STRING(var) # var\n#define pb emplace_back\n#define int ll\n#define endl '\\n'\n#define sqrt __builtin_sqrtl\n\nusing ll = long long;\nusing ld = long double;\nconst ld PI = acos(-1);\nconst int INF = 1 << 30;\nconst ll INFL = 1LL << 61;\nconst int MOD = 998244353;\n// const int MOD = 1000000007;\n\nconst ld EPS = 1e-10;\nconst bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }\n\nconst vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗\nconst vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};\n\nstruct Edge {\n int from, to;\n int cost;\n Edge(int to, int cost) : from(-1), to(to), cost(cost) {}\n Edge(int from, int to, int cost) : from(from), to(to), cost(cost) {}\n Edge &operator=(const int &x) {\n to = x;\n return *this;\n }\n};\n\n__attribute__((constructor))\nvoid constructor() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout << fixed << setprecision(12);\n}\n\nstruct custom_hash {\n static uint64_t splitmix64(uint64_t x) {\n x += 0x9e3779b97f4a7c15;\n x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n x = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n return x ^ (x >> 31);\n }\n\n size_t operator()(uint64_t x) const {\n static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n return splitmix64(x + FIXED_RANDOM);\n }\n};\n\nint POW(int x, int n) {\n __int128_t ret = 1;\n // if (ret >= INFL) return INFL;\n if (n < 0) { cout << \"error\" << endl; return 0; }\n else if (x == 1 or n == 0) ret = 1;\n else if (x == -1 && n % 2 == 0) ret = 1; \n else if (x == -1) ret = -1; \n else if (n % 2 == 0) ret = POW(x * x, n / 2);\n else ret = x * POW(x, n - 1);\n\n if (ret > 8e18) ret = 0;\n return ret;\n}\nint floor(int x, int y) { return (x > 0 ? x / y : (x - y + 1) / y); }\nint ceil(int x, int y) { return (x > 0 ? (x + y - 1) / y : x / y); }\nll per(int x, int y) {\n if (y == 0) {\n cout << \"error\" << endl;\n return INFL;\n }\n if (x >= 0 && y > 0) return x / y;\n if (x >= 0 && y < 0) return x / y - (x % y < 0);\n if (x < 0 && y < 0) return x / y + (x % y < 0);\n // if (x < 0 && y > 0) \n return x / y - (x % y < 0);\n}\nll mod(int x, int y) {\n if (y == 0) {\n cout << \"error\" << endl;\n return INFL;\n }\n if (x >= 0 && y > 0) return x % y;\n if (x >= 0 && y < 0) return x % y;\n if (x < 0 && y < 0) {\n __int128_t ret = x % y;\n ret += (__int128_t)abs(y) * INFL;\n ret %= abs(y);\n return ret;\n }\n // if (x < 0 && y > 0) {\n __int128_t ret = x % y;\n ret += (__int128_t)abs(y) * INFL;\n ret %= abs(y);\n return ret;\n // }\n}\nint modf(ld x) {\n if (equals(x, 0)) return 0;\n\telse if (x < 0) return ceill(x);\n\telse return floorl(x);\n}\n\ntemplate <class T> bool chmax(T &a, const T& b) {\n if (a < b) { a = b; return true; }\n return false;\n}\ntemplate <class T> bool chmin(T &a, const T& b) {\n if (a > b) { a = b; return true; }\n return false;\n}\n\nint countl_zero(int N) { return __builtin_clzll(N); }\nint countl_one(int N) {\n int ret = 0; while (N % 2) { N /= 2; ret++; }\n return ret;\n}\nint countr_zero(int N) { return __builtin_ctzll(N); }\nint countr_one(int N) {\n int ret = 0, k = 63 - __builtin_clzll(N);\n while (k != -1 && (N & (1LL << k))) { k--; ret++; }\n return ret;\n}\nint popcount(int N) { return __builtin_popcountll(N); }\nint unpopcount(int N) { return 64 - __builtin_clzll(N) - __builtin_popcountll(N); }\n\nint top_bit(int N) { return 63 - __builtin_clzll(N);} // 2^kの位\nint bot_bit(int N) { return __builtin_ctz(N);} // 2^kの位\nint MSB(int N) { return 1 << (63 - __builtin_clzll(N)); } // mask\n\nint bit_width(int N) { return 64 - __builtin_clzll(N); } // 桁数\nint ceil_log2(int N) { return 63 - __builtin_clzll(N); }\nint bit_floor(int N) { return 1 << (63 - __builtin_clzll(N)); }\nint floor_log2(int N) { return 64 - __builtin_clzll(N-1); }\nint bit_ceil(int N) { return 1 << (64 - __builtin_clzll(N-1)) - (N==1); }\n\nclass UnionFind {\npublic:\n\tUnionFind() = default;\n UnionFind(int N) : par(N), sz(N, 1) {\n iota(par.begin(), par.end(), 0);\n }\n\n\tint root(int x) {\n\t\tif (par[x] == x) return x;\n\t\treturn (par[x] = root(par[x]));\n\t}\n\n\tbool unite(int x, int y) {\n\t\tint rx = root(x);\n\t\tint ry = root(y);\n\n if (rx == ry) return false;\n\t\tif (sz[rx] < sz[ry]) swap(rx, ry);\n\n\t\tsz[rx] += sz[ry];\n\t\tpar[ry] = rx;\n\n return true;\n\t}\n\n\tbool issame(int x, int y) { return (root(x) == root(y)); }\n\tint size(int x) { return sz[root(x)]; }\n\n vector<vector<int>> groups(int N) {\n vector<vector<int>> G(N);\n for (int x = 0; x < N; x++) {\n G[root(x)].push_back(x);\n }\n\t\tG.erase(\n remove_if(G.begin(), G.end(),\n [&](const vector<int>& V) { return V.empty(); }),\n G.end());\n return G;\n }\n\nprivate:\n\tvector<int> par;\n\tvector<int> sz;\n};\n\ntemplate<int mod> class Modint{\npublic:\n int val = 0;\n Modint(int x = 0) { while (x < 0) x += mod; val = x % mod; }\n Modint(const Modint &r) { val = r.val; }\n\n Modint operator -() { return Modint(-val); } // 単項\n Modint operator +(const Modint &r) { return Modint(*this) += r; }\n Modint operator +(const int &q) { Modint r(q); return Modint(*this) += r; }\n Modint operator -(const Modint &r) { return Modint(*this) -= r; }\n Modint operator -(const int &q) { Modint r(q); return Modint(*this) -= r; }\n Modint operator *(const Modint &r) { return Modint(*this) *= r; }\n Modint operator *(const int &q) { Modint r(q); return Modint(*this) *= r; }\n Modint operator /(const Modint &r) { return Modint(*this) /= r; }\n Modint operator /(const int &q) { Modint r(q); return Modint(*this) /= r; }\n \n Modint& operator ++() { val++; if (val >= mod) val -= mod; return *this; } // 前置\n Modint operator ++(signed) { ++*this; return *this; } // 後置\n Modint& operator --() { val--; if (val < 0) val += mod; return *this; }\n Modint operator --(signed) { --*this; return *this; }\n Modint &operator +=(const Modint &r) { val += r.val; if (val >= mod) val -= mod; return *this; }\n Modint &operator +=(const int &q) { Modint r(q); val += r.val; if (val >= mod) val -= mod; return *this; }\n Modint &operator -=(const Modint &r) { if (val < r.val) val += mod; val -= r.val; return *this; }\n Modint &operator -=(const int &q) { Modint r(q); if (val < r.val) val += mod; val -= r.val; return *this; }\n Modint &operator *=(const Modint &r) { val = val * r.val % mod; return *this; }\n Modint &operator *=(const int &q) { Modint r(q); val = val * r.val % mod; return *this; }\n Modint &operator /=(const Modint &r) {\n int a = r.val, b = mod, u = 1, v = 0;\n while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}\n val = val * u % mod; if (val < 0) val += mod;\n return *this;\n }\n Modint &operator /=(const int &q) {\n Modint r(q); int a = r.val, b = mod, u = 1, v = 0;\n while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}\n val = val * u % mod; if (val < 0) val += mod;\n return *this;\n }\n\n bool operator ==(const Modint& r) { return this -> val == r.val; }\n bool operator <(const Modint& r) { return this -> val < r.val; }\n bool operator !=(const Modint& r) { return this -> val != r.val; }\n};\n\nusing mint = Modint<MOD>;\n\nistream &operator >>(istream &is, mint& x) {\n int t; is >> t;\n x = t;\n return (is);\n}\nostream &operator <<(ostream &os, const mint& x) {\n return os << x.val;\n}\nmint modpow(const mint &x, int n) {\n if (n == 0) return 1;\n mint t = modpow(x, n / 2);\n t = t * t;\n if (n & 1) t = t * x;\n return t;\n}\n\nint modpow(__int128_t x, int n, int mod) {\n __int128_t ret = 1;\n while (n > 0) {\n if (n % 2 == 1) ret = ret * x % mod;\n x = x * x % mod;\n n /= 2;\n }\n return ret;\n}\n\nint modinv(__int128_t x, int mod) {\n if (x == 1) return 1;\n return mod - modinv(mod % x, mod) * (mod / x) % mod;\n}\n\nistream &operator >>(istream &is, __int128_t& x) {\n string S; is >> S;\n __int128_t ret = 0;\n int f = 1;\n if (S[0] == '-') f = -1; \n for (int i = 0; i < S.length(); i++)\n if ('0' <= S[i] && S[i] <= '9')\n ret = 10 * ret + S[i] - '0';\n x = ret * f;\n return (is);\n}\nostream &operator <<(ostream &os, __int128_t x) {\n ostream::sentry s(os);\n if (s) {\n __uint128_t tmp = x < 0 ? -x : x;\n char buffer[128];\n char *d = end(buffer);\n\n do {\n --d;\n *d = \"0123456789\"[tmp % 10];\n tmp /= 10;\n } while (tmp != 0);\n\n if (x < 0) {\n --d;\n *d = '-';\n }\n int len = end(buffer) - d;\n\n if (os.rdbuf()->sputn(d, len) != len) {\n os.setstate(ios_base::badbit);\n }\n }\n return os;\n}\n\nstring to_string(char c) {\n string s = {c};\n return s;\n}\n\nvector<mint> _fac, _finv, _inv;\nvoid COMinit(int N) {\n _fac.resize(N + 1);\n _finv.resize(N + 1);\n _inv.resize(N + 1);\n _fac[0] = _fac[1] = 1;\n _finv[0] = _finv[1] = 1;\n _inv[1] = 1;\n for (int i = 2; i <= N; i++) {\n _fac[i] = _fac[i-1] * mint(i);\n _inv[i] = -_inv[MOD % i] * mint(MOD / i);\n _finv[i] = _finv[i - 1] * _inv[i];\n }\n}\n\nmint COM(int N, int K) {\n if (N < K) return 0;\n if (N < 0 or K < 0) return 0;\n return _fac[N] * _finv[K] * _finv[N - K];\n}\n\n#pragma endregion\n\nusing T = int;\nT calc_revpo(vector<string> &S) {\n int N = S.size();\n vector<T> st;\n for (int i = 0; i < N; i++) {\n if (S[i] == \"+\") {\n T b = st.back();\n st.pop_back();\n T a = st.back();\n st.pop_back();\n st.pb(a + b);\n } else if (S[i] == \"-\") {\n T b = st.back();\n st.pop_back();\n T a = st.back();\n st.pop_back();\n st.pb(a - b);\n } else if (S[i] == \"*\") {\n T b = st.back();\n st.pop_back();\n T a = st.back();\n st.pop_back();\n st.pb(a * b);\n } else st.pb(stoll(S[i]));\n }\n return st.back();\n}\n\nstring decode_revpo(vector<string> &S) {\n vector<string> st;\n int N = S.size();\n for (int i = 0; i < N; i++) {\n if (S[i][0] >= '0' && S[i][0] <= '9') st.push_back(S[i]);\n else {\n string B = st.back();\n st.pop_back();\n string A = st.back();\n st.pop_back();\n\n // 演算子が「*」「/」で、演算子の前の式が\n // 「宙ぶらりんの+ -」を含むとき括弧をつける\n if (S[i] == \"*\") {\n int depth = 0;\n int sz = A.size();\n for (int j = 0; j < sz; j++) {\n if (A[j] == '(') depth++;\n if (A[j] == ')') depth--;\n\n if (depth == 0 && (A[j] == '+' or A[j] == '-')) {\n A = \"(\" + A + \")\";\n break;\n }\n }\n }\n\n // 演算子が「-」「*」で、演算子の後の式が\n // 「宙ぶらりんの+ -」を含むとき括弧をつける\n if (S[i] == \"-\" or S[i] == \"*\") {\n int depth = 0;\n int sz = B.size();\n for (int j = 0; j < sz; j++) {\n if (B[j] == '(') depth++;\n if (B[j] == ')') depth--;\n\n if (depth == 0 && (B[j] == '+' or B[j] == '-')) {\n B = \"(\" + B + \")\";\n break;\n }\n }\n }\n\n if (S[i] == \"+\") st.push_back(A + \" + \" + B);\n if (S[i] == \"-\") st.push_back(A + \" - \" + B);\n if (S[i] == \"*\") st.push_back(A + \" * \" + B);\n }\n }\n return st.back();\n}\n\n// 数字を1, 演算子を0とした01列Bが逆ポーランド記法としてありえるか\n// 括弧列のような判定方法\nbool isvalid(vector<int> &B) {\n int N = B.size();\n\n int depth = B[0];\n for (int i = 1; i < N; i++) {\n if (depth == 0) return false;\n if (B[i]) depth++;\n else depth--;\n }\n return true;\n}\n\nsigned main() {\n while (true) {\n int N = 4, M = 10;\n vector<int> A(N);\n for (int i = 0; i < N; i++) cin >> A[i];\n sort(A.begin(), A.end());\n if (A[0] + A[1] + A[2] + A[3] == 0) break;\n\n vector<int> B(N + N - 1, 1); // 01列。1が数字、0が演算子\n for (int i = 0; i < N - 1; i++) B[i] = 0;\n\n int ans = 0;\n string S;\n do {\n if (isvalid(B)) { // 逆ポの記法としてありえるなら\n sort(A.begin(), A.end());\n do {\n int p = POW(3LL, N - 1);\n for (int j = 0; j < p; j++) {\n vector<string> T;\n int curA = 0, curC = 0;\n\n vector<string> C;\n int J = j;\n while (J) {\n int r = J % 3;\n J /= 3;\n\n if (r == 0) C.pb(\"+\");\n if (r == 1) C.pb(\"-\");\n if (r == 2) C.pb(\"*\");\n }\n while (C.size() < N - 1) C.pb(\"+\");\n\n for (int k = 0; k < N + N - 1; k++) {\n if (B[k]) T.pb(to_string(A[curA])), curA++;\n else T.pb(C[curC]), curC++;\n }\n if (abs(calc_revpo(T) - M) < EPS) {\n S = decode_revpo(T);\n ans++;\n }\n }\n } while (next_permutation(A.begin(), A.end()));\n }\n } while (next_permutation(B.begin(), B.end()));\n if (ans == 0) cout << ans << endl;\n else cout << S << endl;\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3432, "score_of_the_acc": -1.0312, "final_rank": 11 }, { "submission_id": "aoj_0041_4893128", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\n#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)\n#define FOR(i, a, b) for (int i = (a), i##_len = (b); i < i##_len; i++)\n#define ALL(x) (x).begin(), (x).end() // sortなどの引数を省略したい\n#ifdef _DEBUG\n#define PRE_COMMAND \\\n std::cin.rdbuf(in.rdbuf()); \\\n std::cout << fixed << setprecision(15);\n#else\n#define PRE_COMMAND cout << fixed << setprecision(15);\n#endif\nconst double EPS = 1e-10, PI = acos(-1.0);\ntemplate <class T> auto MAX(T& seq) {\n return *max_element(seq.begin(), seq.end());\n}\ntemplate <class T> auto MIN(T& seq) {\n return *min_element(seq.begin(), seq.end());\n}\ntemplate <class T> auto SUM(T& seq) {\n T temp{0};\n auto& temp2 = temp[0];\n return accumulate(seq.begin(), seq.end(), temp2);\n}\ntemplate <class T> void SORT(T& seq) { sort(seq.begin(), seq.end()); }\ntemplate <class T, class S> void SORT(T& seq, S& sort_order) {\n sort(seq.begin(), seq.end(), sort_order);\n}\ntemplate <class T> void SORTR(vector<T>& seq) {\n sort(seq.begin(), seq.end(), greater<T>());\n}\ntemplate <class T, class S, class R> long long pow(T n_0, S k_0, R mod_0) {\n long long n = n_0 % mod_0, k = k_0, mod = mod_0, now = 1;\n while (k) {\n if (k & 1) now = (now * n) % mod;\n n = (n * n) % mod;\n k >>= 1;\n }\n return now;\n}\ntemplate <typename T> istream& operator>>(istream& is, vector<T>& vec) {\n for (T& x : vec) is >> x;\n return is;\n}\ntemplate <typename T> ostream& operator<<(ostream& os, const vector<T>& v) {\n if (!v.size()) return os;\n typename vector<T>::const_iterator ii = v.begin();\n os << *ii++;\n for (; ii != v.end(); ++ii) os << \" \" << *ii;\n return os;\n}\n\n// カンマ区切りのデータをvector<int>に変換\nvector<int> comma_sep(string inp) {\n inp += ',';\n vector<int> v;\n string s = \"\";\n for (char c : inp) {\n if (c == ',') {\n v.push_back(stoi(s));\n s = \"\";\n } else {\n s += c;\n }\n }\n return v;\n}\n\ntemplate <class T>\nvector<vector<T>> permutations_parts(vector<T> p, int x, int s, int n) {\n vector<vector<T>> ret;\n if (x == s) {\n for (int i = x; i < n; i++) ret.push_back({p[i]});\n return ret;\n }\n for (int i = x; i < n; i++) {\n vector<T> v = p;\n swap(v[x], v[i]);\n vector<vector<T>> v2 = permutations_parts(v, x + 1, s, n);\n T q = v[x];\n int size = (int)v2.size();\n for (int i = 0; i < size; i++) { v2[i].push_back(q); }\n copy(v2.begin(), v2.end(), back_inserter(ret));\n }\n return ret;\n}\ntemplate <class T> vector<vector<T>> permutations(vector<T> v, int size = -1) {\n int n = (int)v.size();\n if (size == -1) size = n;\n if (size == n) {\n vector<vector<T>> ret;\n int ret_size = 1;\n for (int i = size; i > 1; i--) ret_size *= i;\n ret.reserve(ret_size);\n do { ret.push_back(v); } while (next_permutation(v.begin(), v.end()));\n return ret;\n }\n return permutations_parts(v, 0, size - 1, n);\n}\n\ntemplate <class T> vector<vector<T>> permutations2(vector<T> v, int size = -1) {\n int n = (int)v.size();\n if (size == -1) size = n;\n if (size == n) {\n vector<vector<T>> ret;\n int ret_size = 1;\n for (int i = size; i > 1; i--) ret_size *= i;\n ret.reserve(ret_size);\n do { ret.push_back(v); } while (next_permutation(v.begin(), v.end()));\n }\n return permutations_parts(v, 0, size - 1, n);\n}\n\nint main() {\n PRE_COMMAND\n int a, b, c, d;\n string a_s, b_s, c_s, d_s, s;\n while (cin >> a_s >> b_s >> c_s >> d_s) {\n if (a_s == \"0\") break;\n s = \"0\";\n int ans, ans2;\n vector<string> v2 = {a_s, b_s, c_s, d_s};\n vector<vector<string>> v3 = permutations(v2);\n vector<vector<string>> v4 = permutations2(v2);\n SORT(v4);\n for (string c1 : {\" + \", \" - \", \" * \"}) {\n for (string c2 : {\" + \", \" - \", \" * \"}) {\n for (string c3 : {\" + \", \" - \", \" * \"}) {\n for (auto v : v4) {\n a_s = v[0], b_s = v[1], c_s = v[2], d_s = v[3];\n a = stoi(a_s), b = stoi(b_s), c = stoi(c_s),\n d = stoi(d_s);\n // ((a+b)+c)+d\n ans = 0;\n if (c1 == \" + \") ans = a + b;\n if (c1 == \" - \") ans = a - b;\n if (c1 == \" * \") ans = a * b;\n if (c2 == \" + \") ans = ans + c;\n if (c2 == \" - \") ans = ans - c;\n if (c2 == \" * \") ans = ans * c;\n if (c3 == \" + \") ans = ans + d;\n if (c3 == \" - \") ans = ans - d;\n if (c3 == \" * \") ans = ans * d;\n if (ans == 10)\n s = \"(((\" + a_s + c1 + b_s + \")\" + c2 + c_s + \")\" +\n c3 + d_s + \")\";\n // (a+b)+(c+d)\n ans = 0, ans2 = 0;\n if (c1 == \" + \") ans = a + b;\n if (c1 == \" - \") ans = a - b;\n if (c1 == \" * \") ans = a * b;\n if (c3 == \" + \") ans2 = c + d;\n if (c3 == \" - \") ans2 = c - d;\n if (c3 == \" * \") ans2 = c * d;\n if (c2 == \" + \") ans = ans + ans2;\n if (c2 == \" - \") ans = ans - ans2;\n if (c2 == \" * \") ans = ans * ans2;\n if (ans == 10)\n s = \"((\" + a_s + c1 + b_s + \")\" + c2 + \"(\" + c_s +\n c3 + d_s + \"))\";\n // (a+(b+c))+d\n ans = 0;\n if (c2 == \" + \") ans = b + c;\n if (c2 == \" - \") ans = b - c;\n if (c2 == \" * \") ans = b * c;\n if (c1 == \" + \") ans = a + ans;\n if (c1 == \" - \") ans = a - ans;\n if (c1 == \" * \") ans = a * ans;\n if (c3 == \" + \") ans = ans + d;\n if (c3 == \" - \") ans = ans - d;\n if (c3 == \" * \") ans = ans * d;\n if (ans == 10)\n s = \"((\" + a_s + c1 + \"(\" + b_s + c2 + c_s + \"))\" +\n c3 + d_s + \")\";\n // a+((b+c)+d)\n ans = 0;\n if (c2 == \" + \") ans = b + c;\n if (c2 == \" - \") ans = b - c;\n if (c2 == \" * \") ans = b * c;\n if (c3 == \" + \") ans = ans + d;\n if (c3 == \" - \") ans = ans - d;\n if (c3 == \" * \") ans = ans * d;\n if (c1 == \" + \") ans = a + ans;\n if (c1 == \" - \") ans = a - ans;\n if (c1 == \" * \") ans = a * ans;\n if (ans == 10)\n s = \"(\" + a_s + c1 + \"((\" + b_s + c2 + c_s + \")\" +\n c3 + d_s + \"))\";\n // a+(b+(c+d))\n ans = 0;\n if (c3 == \" + \") ans = c + d;\n if (c3 == \" - \") ans = c - d;\n if (c3 == \" * \") ans = c * d;\n if (c2 == \" + \") ans = b + ans;\n if (c2 == \" - \") ans = b - ans;\n if (c2 == \" * \") ans = b * ans;\n if (c1 == \" + \") ans = a + ans;\n if (c1 == \" - \") ans = a - ans;\n if (c1 == \" * \") ans = a * ans;\n if (ans == 10)\n s = \"(\" + a_s + c1 + \"(\" + b_s + c2 + \"(\" + c_s +\n c3 + d_s + \")))\";\n }\n }\n }\n }\n cout << s << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3200, "score_of_the_acc": -0.8942, "final_rank": 7 }, { "submission_id": "aoj_0041_4893122", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\n#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)\n#define FOR(i, a, b) for (int i = (a), i##_len = (b); i < i##_len; i++)\n#define ALL(x) (x).begin(), (x).end() // sortなどの引数を省略したい\n#ifdef _DEBUG\n#define PRE_COMMAND \\\n std::cin.rdbuf(in.rdbuf()); \\\n std::cout << fixed << setprecision(15);\n#else\n#define PRE_COMMAND cout << fixed << setprecision(15);\n#endif\nconst double EPS = 1e-10, PI = acos(-1.0);\ntemplate <class T> auto MAX(T& seq) {\n return *max_element(seq.begin(), seq.end());\n}\ntemplate <class T> auto MIN(T& seq) {\n return *min_element(seq.begin(), seq.end());\n}\ntemplate <class T> auto SUM(T& seq) {\n T temp{0};\n auto& temp2 = temp[0];\n return accumulate(seq.begin(), seq.end(), temp2);\n}\ntemplate <class T> void SORT(T& seq) { sort(seq.begin(), seq.end()); }\ntemplate <class T, class S> void SORT(T& seq, S& sort_order) {\n sort(seq.begin(), seq.end(), sort_order);\n}\ntemplate <class T> void SORTR(vector<T>& seq) {\n sort(seq.begin(), seq.end(), greater<T>());\n}\ntemplate <class T, class S, class R> long long pow(T n_0, S k_0, R mod_0) {\n long long n = n_0 % mod_0, k = k_0, mod = mod_0, now = 1;\n while (k) {\n if (k & 1) now = (now * n) % mod;\n n = (n * n) % mod;\n k >>= 1;\n }\n return now;\n}\ntemplate <typename T> istream& operator>>(istream& is, vector<T>& vec) {\n for (T& x : vec) is >> x;\n return is;\n}\ntemplate <typename T> ostream& operator<<(ostream& os, const vector<T>& v) {\n if (!v.size()) return os;\n typename vector<T>::const_iterator ii = v.begin();\n os << *ii++;\n for (; ii != v.end(); ++ii) os << \" \" << *ii;\n return os;\n}\n\n// カンマ区切りのデータをvector<int>に変換\nvector<int> comma_sep(string inp) {\n inp += ',';\n vector<int> v;\n string s = \"\";\n for (char c : inp) {\n if (c == ',') {\n v.push_back(stoi(s));\n s = \"\";\n } else {\n s += c;\n }\n }\n return v;\n}\n\ntemplate <class T>\nvector<vector<T>> permutations_parts(vector<T> p, int x, int s, int n) {\n vector<vector<T>> ret;\n if (x == s) {\n for (int i = x; i < n; i++) ret.push_back({p[i]});\n return ret;\n }\n for (int i = x; i < n; i++) {\n vector<T> v = p;\n swap(v[x], v[i]);\n vector<vector<T>> v2 = permutations_parts(v, x + 1, s, n);\n T q = v[x];\n int size = (int)v2.size();\n for (int i = 0; i < size; i++) { v2[i].push_back(q); }\n copy(v2.begin(), v2.end(), back_inserter(ret));\n }\n return ret;\n}\ntemplate <class T> vector<vector<T>> permutations(vector<T> v, int size = -1) {\n int n = (int)v.size();\n if (size == -1) size = n;\n if (size == n) {\n vector<vector<T>> ret;\n int ret_size = 1;\n for (int i = size; i > 1; i--) ret_size *= i;\n ret.reserve(ret_size);\n do { ret.push_back(v); } while (next_permutation(v.begin(), v.end()));\n //return ret;\n }\n return permutations_parts(v, 0, size - 1, n);\n}\n\nint main() {\n PRE_COMMAND\n int a, b, c, d;\n string a_s, b_s, c_s, d_s, s;\n while (cin >> a_s >> b_s >> c_s >> d_s) {\n if (a_s == \"0\") break;\n s = \"0\";\n int ans, ans2;\n vector<string> v2 = {a_s, b_s, c_s, d_s};\n vector<vector<string>> v3 = permutations(v2);\n for (string c1 : {\" + \", \" - \", \" * \"}) {\n for (string c2 : {\" + \", \" - \", \" * \"}) {\n for (string c3 : {\" + \", \" - \", \" * \"}) {\n for (auto v : v3) {\n a_s = v[0], b_s = v[1], c_s = v[2], d_s = v[3];\n a = stoi(a_s), b = stoi(b_s), c = stoi(c_s),\n d = stoi(d_s);\n // ((a+b)+c)+d\n ans = 0;\n if (c1 == \" + \") ans = a + b;\n if (c1 == \" - \") ans = a - b;\n if (c1 == \" * \") ans = a * b;\n if (c2 == \" + \") ans = ans + c;\n if (c2 == \" - \") ans = ans - c;\n if (c2 == \" * \") ans = ans * c;\n if (c3 == \" + \") ans = ans + d;\n if (c3 == \" - \") ans = ans - d;\n if (c3 == \" * \") ans = ans * d;\n if (ans == 10)\n s = \"(((\" + a_s + c1 + b_s + \")\" + c2 + c_s + \")\" +\n c3 + d_s + \")\";\n // (a+b)+(c+d)\n ans = 0, ans2 = 0;\n if (c1 == \" + \") ans = a + b;\n if (c1 == \" - \") ans = a - b;\n if (c1 == \" * \") ans = a * b;\n if (c3 == \" + \") ans2 = c + d;\n if (c3 == \" - \") ans2 = c - d;\n if (c3 == \" * \") ans2 = c * d;\n if (c2 == \" + \") ans = ans + ans2;\n if (c2 == \" - \") ans = ans - ans2;\n if (c2 == \" * \") ans = ans * ans2;\n if (ans == 10)\n s = \"((\" + a_s + c1 + b_s + \")\" + c2 + \"(\" + c_s +\n c3 + d_s + \"))\";\n // (a+(b+c))+d\n ans = 0;\n if (c2 == \" + \") ans = b + c;\n if (c2 == \" - \") ans = b - c;\n if (c2 == \" * \") ans = b * c;\n if (c1 == \" + \") ans = a + ans;\n if (c1 == \" - \") ans = a - ans;\n if (c1 == \" * \") ans = a * ans;\n if (c3 == \" + \") ans = ans + d;\n if (c3 == \" - \") ans = ans - d;\n if (c3 == \" * \") ans = ans * d;\n if (ans == 10)\n s = \"((\" + a_s + c1 + \"(\" + b_s + c2 + c_s + \"))\" +\n c3 + d_s + \")\";\n // a+((b+c)+d)\n ans = 0;\n if (c2 == \" + \") ans = b + c;\n if (c2 == \" - \") ans = b - c;\n if (c2 == \" * \") ans = b * c;\n if (c3 == \" + \") ans = ans + d;\n if (c3 == \" - \") ans = ans - d;\n if (c3 == \" * \") ans = ans * d;\n if (c1 == \" + \") ans = a + ans;\n if (c1 == \" - \") ans = a - ans;\n if (c1 == \" * \") ans = a * ans;\n if (ans == 10)\n s = \"(\" + a_s + c1 + \"((\" + b_s + c2 + c_s + \")\" +\n c3 + d_s + \"))\";\n // a+(b+(c+d))\n ans = 0;\n if (c3 == \" + \") ans = c + d;\n if (c3 == \" - \") ans = c - d;\n if (c3 == \" * \") ans = c * d;\n if (c2 == \" + \") ans = b + ans;\n if (c2 == \" - \") ans = b - ans;\n if (c2 == \" * \") ans = b * ans;\n if (c1 == \" + \") ans = a + ans;\n if (c1 == \" - \") ans = a - ans;\n if (c1 == \" * \") ans = a * ans;\n if (ans == 10)\n s = \"(\" + a_s + c1 + \"(\" + b_s + c2 + \"(\" + c_s +\n c3 + d_s + \")))\";\n }\n }\n }\n }\n cout << s << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3176, "score_of_the_acc": -0.8832, "final_rank": 6 }, { "submission_id": "aoj_0041_4357268", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <iomanip>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <numeric>\n#include <bitset>\n#include <cmath>\n\nstatic const int MOD = 1000000007;\nusing ll = long long;\nusing u32 = unsigned;\nusing u64 = unsigned long long;\nusing namespace std;\n\ntemplate<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;\n\nint main() {\n vector<char> v(4);\n string A = \"+-*\";\n while(true){\n for (auto &&i : v) scanf(\" %c\", &i);\n if(v[0] == '0') break;\n auto solve = [&](string &s) -> string {\n stack<pair<string, int>> S;\n for (auto &&i : s) {\n if(isdigit(i)) S.emplace(string(1, i), i-'0');\n else if(i == '+'){\n if(S.size() < 2) return {};\n auto a = S.top(); S.pop();\n auto b = S.top(); S.pop();\n S.emplace(\"(\" + a.first + \"+\" + b.first + \")\", a.second+b.second);\n }else if(i == '*'){\n if(S.size() < 2) return {};\n auto a = S.top(); S.pop();\n auto b = S.top(); S.pop();\n S.emplace(\"(\" + a.first + \"*\" + b.first + \")\", a.second*b.second);\n }else if(i == '-'){\n if(S.size() < 2) return {};\n auto a = S.top(); S.pop();\n auto b = S.top(); S.pop();\n S.emplace(\"(\" + a.first + \"-\" + b.first + \")\", a.second-b.second);\n }\n }\n if(S.top().second != 10) return {};\n else return S.top().first;\n };\n int ok = 0;\n for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) for (int k = 0; k < 3; ++k) {\n string s = string(1, v[0])+v[1]+v[2]+v[3]+A[i]+A[j]+A[k];\n sort(s.begin(),s.end());\n do {\n auto ret = solve(s);\n if(!ret.empty()){\n cout << ret << \"\\n\";\n i = j = k = 3;\n ok = 1;\n break;\n }\n }while(next_permutation(s.begin(),s.end()));\n }\n if(!ok) puts(\"0\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 60, "memory_kb": 3100, "score_of_the_acc": -1.0048, "final_rank": 10 }, { "submission_id": "aoj_0041_4310788", "code_snippet": "#include <bits/stdc++.h>\n//typedef\n//-------------------------#include <bits/stdc++.h>\n\nconst double pi = 3.141592653589793238462643383279;\n\nusing namespace std;\n\n//conversion\n//------------------------------------------\ninline int toInt(string s)\n{\n int v;\n istringstream sin(s);\n sin >> v;\n return v;\n}\ntemplate <class T>\ninline string toString(T x)\n{\n ostringstream sout;\n sout << x;\n return sout.str();\n}\ninline int readInt()\n{\n int x;\n scanf(\"%d\", &x);\n return x;\n}\n\n//typedef\n//------------------------------------------\ntypedef vector<int> VI;\ntypedef vector<VI> VVI;\ntypedef vector<string> VS;\ntypedef pair<int, int> PII;\ntypedef pair<long long, long long> PLL;\ntypedef pair<int, PII> TIII;\ntypedef long long LL;\ntypedef unsigned long long ULL;\ntypedef vector<LL> VLL;\ntypedef vector<VLL> VVLL;\n\n//container util\n\n//------------------------------------------\n#define ALL(a) (a).begin(), (a).end()\n#define RALL(a) (a).rbegin(), (a).rend()\n#define PB push_back\n#define MP make_pair\n#define SZ(a) int((a).size())\n#define SQ(a) ((a) * (a))\n#define EACH(i, c) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define EXIST(s, e) ((s).find(e) != (s).end())\n#define SORT(c) sort((c).begin(), (c).end())\n\n//repetition\n//------------------------------------------\n#define FOR(i, s, n) for (int i = s; i < (int)n; ++i)\n#define REP(i, n) FOR(i, 0, n)\n#define MOD 1000000007\n\n#define rep(i, a, b) for (int i = a; i < (b); ++i)\n#define trav(a, x) for (auto &a : x)\n#define all(x) x.begin(), x.end()\n#define sz(x) (int)(x).size()\n\ntypedef long long ll;\ntypedef pair<int, int> P;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\nconst double EPS = 1E-8;\n\n#define chmin(x, y) x = min(x, y)\n#define chmax(x, y) x = max(x, y)\n\nclass UnionFind\n{\npublic:\n vector<int> par;\n vector<int> siz;\n\n UnionFind(int sz_) : par(sz_), siz(sz_, 1)\n {\n for (ll i = 0; i < sz_; ++i)\n par[i] = i;\n }\n void init(int sz_)\n {\n par.resize(sz_);\n siz.assign(sz_, 1LL);\n for (ll i = 0; i < sz_; ++i)\n par[i] = i;\n }\n\n int root(int x)\n {\n while (par[x] != x)\n {\n x = par[x] = par[par[x]];\n }\n return x;\n }\n\n bool merge(int x, int y)\n {\n x = root(x);\n y = root(y);\n if (x == y)\n return false;\n if (siz[x] < siz[y])\n swap(x, y);\n siz[x] += siz[y];\n par[y] = x;\n return true;\n }\n\n bool issame(int x, int y)\n {\n return root(x) == root(y);\n }\n\n int size(int x)\n {\n return siz[root(x)];\n }\n};\n\nll modPow(ll x, ll n, ll mod = MOD)\n{\n ll res = 1;\n while (n)\n {\n if (n & 1)\n res = (res * x) % mod;\n\n res %= mod;\n x = x * x % mod;\n n >>= 1;\n }\n return res;\n}\n\n#define SIEVE_SIZE 5000000 + 10\nbool sieve[SIEVE_SIZE];\nvoid makeSieve()\n{\n for (int i = 0; i < SIEVE_SIZE; ++i)\n sieve[i] = true;\n sieve[0] = sieve[1] = false;\n for (int i = 2; i * i < SIEVE_SIZE; ++i)\n if (sieve[i])\n for (int j = 2; i * j < SIEVE_SIZE; ++j)\n sieve[i * j] = false;\n}\n\nbool isprime(ll n)\n{\n if (n == 0 || n == 1)\n return false;\n for (ll i = 2; i * i <= n; ++i)\n if (n % i == 0)\n return false;\n return true;\n}\n\nconst int MAX = 2000010;\nlong long fac[MAX], finv[MAX], inv[MAX];\n\n// テーブルを作る前処理\nvoid COMinit()\n{\n fac[0] = fac[1] = 1;\n finv[0] = finv[1] = 1;\n inv[1] = 1;\n for (int i = 2; i < MAX; i++)\n {\n fac[i] = fac[i - 1] * i % MOD;\n inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;\n finv[i] = finv[i - 1] * inv[i] % MOD;\n }\n}\n\n// 二項係数計算\nlong long COM(int n, int k)\n{\n if (n < k)\n return 0;\n if (n < 0 || k < 0)\n return 0;\n return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;\n}\n\nlong long extGCD(long long a, long long b, long long &x, long long &y)\n{\n if (b == 0)\n {\n x = 1;\n y = 0;\n return a;\n }\n long long d = extGCD(b, a % b, y, x);\n y -= a / b * x;\n return d;\n}\n// 負の数にも対応した mod (a = -11 とかでも OK)\ninline long long mod(long long a, long long m)\n{\n return (a % m + m) % m;\n}\n\n// 逆元計算 (ここでは a と m が互いに素であることが必要)\nlong long modinv(long long a, long long m)\n{\n long long x, y;\n extGCD(a, m, x, y);\n return mod(x, m); // 気持ち的には x % m だが、x が負かもしれないので\n}\nll GCD(ll a, ll b)\n{\n\n if (b == 0)\n return a;\n return GCD(b, a % b);\n}\n\ntypedef vector<ll> vec;\ntypedef vector<vec> mat;\n\nmat mul(mat &A, mat &B)\n{\n mat C(A.size(), vec((int)B[0].size()));\n for (int i = 0; i < A.size(); ++i)\n {\n for (int k = 0; k < B.size(); ++k)\n {\n for (int j = 0; j < B[0].size(); ++j)\n {\n C[i][j] = (C[i][j] + A[i][k] % MOD * B[k][j] % MOD) % MOD;\n }\n }\n }\n return C;\n}\nmat matPow(mat A, ll n)\n{\n mat B(A.size(), vec((int)A.size()));\n\n for (int i = 0; i < A.size(); ++i)\n {\n B[i][i] = 1;\n }\n\n while (n > 0)\n {\n if (n & 1)\n B = mul(B, A);\n A = mul(A, A);\n n >>= 1;\n }\n return B;\n}\n\nconst int INF = 1e9 + 7;\n#define repi(i, m, n) for (int i = m; i < n; i++)\n#define fi first\n#define se second\nclass Arithmetic\n{\npublic:\n string str;\n int n, flag = 1;\n void init(string s)\n {\n str = s;\n n = str.size();\n }\n int add(int a, int b) { return a + b; }\n int mul(int a, int b) { return a * b; }\n int div(int a, int b) { return a / b; }\n int sur(int a, int b) { return a % b; }\n\n P get_num(int p)\n {\n int ans = 0, q = -1, f = 0;\n if (str[p] == '(')\n return calc(p + 1, 0);\n if (str[p] == '-')\n {\n f = 1;\n p++;\n }\n if (str[p] == '(')\n {\n P pi = calc(p + 1, 0);\n return P(-pi.fi, pi.se);\n }\n repi(i, p, n)\n {\n if (!isdigit(str[i]))\n break;\n ans = ans * 10 + (str[i] - '0');\n q = i;\n }\n if (f)\n return P(-ans, q);\n return P(ans, q);\n }\n\n P calc(int pp = 0, int f = 0)\n {\n P pi = get_num(pp);\n int ans = pi.fi, p = pi.se + 1;\n repi(i, p, n)\n {\n if (f and str[i] == ')')\n return P(ans, i - 1);\n if (str[i] == ')')\n return P(ans, i);\n if (str[i] == '*' or str[i] == '/' or str[i] == '%')\n {\n pi = get_num(i + 1);\n if (str[i] == '*')\n ans = mul(ans, pi.fi);\n if (str[i] == '/')\n ans = div(ans, pi.fi);\n if (str[i] == '%')\n ans = sur(ans, pi.fi);\n }\n if (str[i] == '+' or str[i] == '-')\n {\n if (f)\n return P(ans, i - 1);\n if (str[i] == '+')\n pi = calc(i + 1, 1);\n if (str[i] == '-')\n pi = calc(i, 1);\n ans = add(ans, pi.fi);\n }\n i = pi.se;\n }\n return P(ans, n - 1);\n }\n int solve(int ret = -INF)\n { //0除算のとき返す値\n flag = 1;\n P ans = calc();\n if (!flag)\n return ret;\n return ans.fi;\n }\n};\n\nstring ans = \"\";\n\nvoid rec(int idx, string s, vector<string> &v, bool p)\n{\n if (idx == 3)\n {\n s += v[idx];\n if (p)\n {\n s += ')';\n }\n Arithmetic solver;\n solver.init(s);\n if (solver.solve() == 10)\n {\n ans = s;\n }\n return;\n }\n if (!p)\n {\n s += v[idx];\n rec(idx + 1, s + '+', v, false);\n rec(idx + 1, s + '*', v, false);\n rec(idx + 1, s + '-', v, false);\n s.pop_back();\n s += '(';\n s += v[idx];\n rec(idx + 1, s + '+', v, true);\n rec(idx + 1, s + '*', v, true);\n rec(idx + 1, s + '-', v, true);\n }\n else\n {\n s += v[idx];\n rec(idx + 1, s + '+', v, true);\n rec(idx + 1, s + '*', v, true);\n rec(idx + 1, s + '-', v, true);\n\n s.pop_back();\n s += v[idx];\n s += ')';\n rec(idx + 1, s + '+', v, false);\n rec(idx + 1, s + '*', v, false);\n rec(idx + 1, s + '-', v, false);\n }\n}\nint main()\n{\n cin.tie(0);\n ios::sync_with_stdio(false);\n cout << fixed << setprecision(20);\n\n vector<string> v(4);\n while (cin >> v[0] >> v[1] >> v[2] >> v[3])\n {\n if (v[0] == \"0\" && v[1] == \"0\" && v[2] == \"0\" && v[3] == \"0\")\n break;\n\n ans = \"\";\n sort(all(v));\n do\n {\n string t = \"\";\n rec(0, \"\", v, false);\n\n } while (next_permutation(all(v)));\n if (ans == \"\")\n cout << 0 << endl;\n else\n {\n string tmp = \"\";\n for (int i = 0; i < ans.size(); i++)\n {\n if (ans[i] == '*' || ans[i] == '+' || ans[i] == '-')\n {\n tmp += \" \";\n tmp += ans[i];\n tmp += \" \";\n }\n else\n {\n tmp += ans[i];\n }\n }\n cout << tmp << endl;\n }\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3128, "score_of_the_acc": -0.8613, "final_rank": 5 }, { "submission_id": "aoj_0041_2292293", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing db = double;\nusing ll = long long;\nusing vi = vector <int>;\n#define op operator\n#define pb push_back\n\nstring ans;\nvoid dfs(vector <pair <int, string>> v) {\n\tif(v.size() == 1) {\n\t\tif(v[0].first == 10)\n\t\t\tans = v[0].second;\n\t\telse\n\t\t\treturn;\n\t}\n\tint n = v.size();\n\tfor(int i = 0; i < n; i ++)\n\t\tfor(int j = 0; j < n; j ++) if(i != j) {\n\t\t\tvector <pair <int, string>> nxt;\n\t\t\tfor(int k = 0; k < n; k ++) if(i != k && j != k)\n\t\t\t\tnxt.pb({v[k]});\n\t\t\tnxt.pb({v[i].first + v[j].first, \"(\" + v[i].second + \"+\" + v[j].second + \")\"});\n\t\t\tdfs(nxt); nxt.pop_back();\n\t\t\tnxt.pb({v[i].first - v[j].first, \"(\" + v[i].second + \"-\" + v[j].second + \")\"});\n\t\t\tdfs(nxt); nxt.pop_back();\n\t\t\tnxt.pb({v[i].first * v[j].first, \"(\" + v[i].second + \"*\" + v[j].second + \")\"});\n\t\t\tdfs(nxt); nxt.pop_back();\n\t\t}\n}\n\nint a[4];\n\nint main() {\n\tios :: sync_with_stdio(0);\n\n\tfor(;;) {\n\t\tfor(int i = 0; i < 4; i ++)\n\t\t\tcin >> a[i];\n\t\tif(*max_element(a, a + 4) == 0)\n\t\t\tbreak;\n\t\tvector <pair <int, string>> v;\n\t\tfor(int i = 0; i < 4; i ++)\n\t\t\tv.pb({a[i], to_string(a[i])});\n\t\tans = \"\";\n\t\tdfs(v);\n\t\tif(ans.size())\n\t\t\tcout << ans << '\\n';\n\t\telse\n\t\t\tcout << \"0\\n\";\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3276, "score_of_the_acc": -0.9601, "final_rank": 9 }, { "submission_id": "aoj_0041_2149302", "code_snippet": "#include \"bits/stdc++.h\"\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,int> pii;\n#define rep(i,n) for(ll i=0;i<(ll)(n);i++)\n#define all(a) (a).begin(),(a).end()\n#define pb push_back\n#define INF (1e9+1)\n//#define INF (1LL<<59)\n\n\nint RPN(vector<char> v){\n\tstack<int> num;\n\trep(i,v.size()){\n\t\tif(isdigit(v[i])){\n\t\t\tnum.push(v[i]-'0');\n\t\t}else{\n\t\t\tif(num.size()<2) throw -1;\n\t\t\tint a,b;\n\t\t\ta = num.top(),num.pop();\n\t\t\tb = num.top();num.pop();\n\t\t\tif(v[i]=='+')num.push(a+b);\n\t\t\tif(v[i]=='-')num.push(a-b);\n\t\t\tif(v[i]=='*')num.push(a*b);\n\t\t}\n\t}\n\tif(num.size()!=1)throw -1;\n\t\n\treturn num.top();\n}\n\nvoid printRPN(vector<char> v){\n\tstack<string> num;\n\trep(i,v.size()){\n\t\tif(isdigit(v[i])){\n\t\t\tnum.push(string(1,v[i]));\n\t\t}else{\n\t\t\tstring a,b;\n\t\t\ta = num.top(),num.pop();\n\t\t\tb = num.top();num.pop();\n\t\t\tif(v[i]=='+')num.push(\"(\"+a+\"+\"+b+\")\");\n\t\t\tif(v[i]=='-')num.push(\"(\"+a+\"-\"+b+\")\");\n\t\t\tif(v[i]=='*')num.push(\"(\"+a+\"*\"+b+\")\");\n\t\t}\n\t}\n\tcout<<num.top()<<endl;\n}\n\nint main(){\n\tvector<char> v(4);\n\twhile(cin>>v[0]>>v[1]>>v[2]>>v[3]){\n\t\tif(v[0]=='0'&&v[1]=='0'&&v[2]=='0'&&v[3]=='0')break;\n\t\trep(plus,4){\n\t\t\trep(minus,4){\n\t\t\t\trep(mul,4){\n\t\t\t\t\tvector<char> tmp=v;\n\t\t\t\t\tif(plus+minus+mul!=3)continue;\n\t\t\t\t\trep(i,plus)tmp.pb('+');\n\t\t\t\t\trep(i,minus)tmp.pb('-');\n\t\t\t\t\trep(i,mul)tmp.pb('*');\n\t\t\t\t\t\n\t\t\t\t\tsort(all(tmp));\n\t\t\t\t\tdo{\n\t\t\t\t\t\tint res;\n\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\tres = RPN(tmp);\n\t\t\t\t\t\t}catch(int e){continue;}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(res==10){\n\t\t\t\t\t\t\tprintRPN(tmp);\n\t\t\t\t\t\t\tgoto next;\n\t\t\t\t\t\t}\n\t\t\t\t\t}while(next_permutation(all(tmp)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout<<0<<endl;\n\tnext:;\n\t}\n}", "accuracy": 1, "time_ms": 330, "memory_kb": 3144, "score_of_the_acc": -1.8686, "final_rank": 14 }, { "submission_id": "aoj_0041_2109508", "code_snippet": "#include <stdio.h>\n#include <cmath>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <vector>\n\nusing namespace std;\n\nbool Found;\nchar ans[30];\n\nint calc(char arg[30]){\n\n\tint tmp,op1,work,count,work2;\n\tchar line[30],calc;\n\tstack<int> NUM,work_num;\n\tstack<char> OP,work_op;\n\n\tint loop;\n\tfor(loop = 0; arg[loop] != '\\0';loop++)line[loop] = arg[loop];\n\n\tline[loop++] = '=';\n\tline[loop] = '\\0';\n\n\n\tbool numFLG,negFLG;\n\n\ttmp = 0;\n\tnumFLG = false;\n\tnegFLG = false;\n\n\tfor(int k = 0; line[k] != '\\0'; k++){\n\t\tif(line[k] >= '0' && line[k] <= '9'){\n\t\t\tnumFLG = true;\n\t\t\ttmp = 10*tmp + (line[k] - '0');\n\n\t\t}else{\n\n\t\t\tif(numFLG == true){\n\n\t\t\t\tif(negFLG){\n\t\t\t\t\ttmp = -1*tmp;\n\t\t\t\t\tnegFLG = false;\n\t\t\t\t}\n\n\t\t\t\tif(OP.empty() == false && (OP.top() == '*' || OP.top() == '/')){\n\t\t\t\t\tcalc = OP.top();\n\t\t\t\t\tOP.pop();\n\t\t\t\t\top1 = NUM.top();\n\t\t\t\t\tNUM.pop();\n\n\t\t\t\t\tif(calc == '*'){\n\t\t\t\t\t\tNUM.push(tmp*op1);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tNUM.push(op1/tmp);\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tNUM.push(tmp);\n\t\t\t\t}\n\n\t\t\t\tnumFLG = false;\n\t\t\t\ttmp = 0;\n\t\t\t}\n\n\t\t\tif(line[k] == '+' ||line[k] == '*' || line[k] == '/' || line[k] == '(' || line[k] == '-'){\n\t\t\t\tOP.push(line[k]);\n\t\t\t}else if(line[k] == ')'){\n\t\t\t\twork = NUM.top();\n\t\t\t\tNUM.pop();\n\t\t\t\twork_num.push(work);\n\n\t\t\t\tcount = 0;\n\n\t\t\t\twhile(true){\n\t\t\t\t\tcalc = OP.top();\n\t\t\t\t\tOP.pop();\n\t\t\t\t\tif(calc == '(')break;\n\n\t\t\t\t\tcount++;\n\n\t\t\t\t\twork_op.push(calc);\n\n\t\t\t\t\twork = NUM.top();\n\t\t\t\t\tNUM.pop();\n\t\t\t\t\twork_num.push(work);\n\t\t\t\t}\n\n\t\t\t\tif(count == 0){\n\t\t\t\t\twork = work_num.top();\n\t\t\t\t\twork_num.pop();\n\t\t\t\t}else{\n\n\t\t\t\t\twork = work_num.top();\n\t\t\t\t\twork_num.pop();\n\n\t\t\t\t\twhile(!work_num.empty()){\n\t\t\t\t\t\tcalc = work_op.top();\n\t\t\t\t\t\twork_op.pop();\n\n\t\t\t\t\t\tif(calc == '+'){\n\t\t\t\t\t\t\twork += work_num.top();\n\t\t\t\t\t\t}else if(calc == '-'){\n\t\t\t\t\t\t\twork -= work_num.top();\n\t\t\t\t\t\t}else if(calc == '*'){\n\t\t\t\t\t\t\twork *= work_num.top();\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\twork /= work_num.top();\n\t\t\t\t\t\t}\n\t\t\t\t\t\twork_num.pop();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(OP.empty() == false && OP.top() == '*'){\n\t\t\t\t\tOP.pop();\n\t\t\t\t\twork2 = NUM.top();\n\t\t\t\t\tNUM.pop();\n\t\t\t\t\twork *= work2;\n\t\t\t\t}else if(OP.empty() == false &&OP.top() == '/'){\n\t\t\t\t\tOP.pop();\n\t\t\t\t\twork2 = NUM.top();\n\t\t\t\t\tNUM.pop();\n\t\t\t\t\twork = work2/work;\n\t\t\t\t}\n\n\t\t\t\tNUM.push(work);\n\n\t\t\t}else{\n\t\t\t\twork = NUM.top();\n\t\t\t\tNUM.pop();\n\t\t\t\twork_num.push(work);\n\n\t\t\t\twhile(!NUM.empty()){\n\t\t\t\t\tcalc = OP.top();\n\t\t\t\t\tOP.pop();\n\n\t\t\t\t\twork_op.push(calc);\n\n\t\t\t\t\twork = NUM.top();\n\t\t\t\t\tNUM.pop();\n\t\t\t\t\twork_num.push(work);\n\t\t\t\t}\n\n\t\t\t\twork = work_num.top();\n\t\t\t\twork_num.pop();\n\n\t\t\t\twhile(!work_num.empty()){\n\t\t\t\t\tcalc = work_op.top();\n\t\t\t\t\twork_op.pop();\n\n\t\t\t\t\tif(calc == '+'){\n\t\t\t\t\t\twork += work_num.top();\n\t\t\t\t\t}else if(calc == '-'){\n\t\t\t\t\t\twork -= work_num.top();\n\t\t\t\t\t}else if(calc == '*'){\n\t\t\t\t\t\twork *= work_num.top();\n\t\t\t\t\t}else{\n\t\t\t\t\t\twork /= work_num.top();\n\t\t\t\t\t}\n\t\t\t\t\twork_num.pop();\n\t\t\t\t}\n\n\t\t\t\treturn work;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\t//must not reach here\n}\n\n\nvoid func(int a,int b, int c,int d){\n\n\tchar eq1[30],eq2[30],eq3[30],eq4[30],eq5[30],eq6[30],eq7[30],eq8[30];\n\teq1[0] = '(',eq1[1] = '0' + a,eq1[2] = '?',eq1[3] = '0' + b,eq1[4] = ')',eq1[5] = '?',eq1[6] = '(',eq1[7] = '0' + c,eq1[8] = '?',eq1[9] = '0' + d,eq1[10] = ')',eq1[11] = '\\0';\n\n\teq2[0] = '0' + a,eq2[1] = '?',eq2[2] = '(',eq2[3] = '0' + b,eq2[4] = '?',eq2[5] = '0' + c,eq2[6] = ')',eq2[7] = '?',eq2[8] = '0' + d,eq2[9] = '\\0';\n\n\teq3[0] = '0' + a,eq3[1] = '?',eq3[2] = '0' + b,eq3[3] = '?',eq3[4] = '(',eq3[5] = '0' + c,eq3[6] = '?',eq3[7] = '0' + d,eq3[8] = ')',eq3[9] = '\\0';\n\n\teq4[0] = '0' + a,eq4[1] = '?',eq4[2] = '(',eq4[3] = '0' + b,eq4[4] = '?',eq4[5] = '(',eq4[6] = '0' + c,eq4[7] = '?',eq4[8] = '0' + d,eq4[9] = ')',eq4[10] = ')',eq4[11] = '\\0';\n\n\teq5[0] = '(',eq5[1] = '0' + a,eq5[2] = '?',eq5[3] = '(',eq5[4] = '0' + b,eq5[5] = '?',eq5[6] = '0' + c,eq5[7] = ')',eq5[8] = ')',eq5[9] = '?',eq5[10] = '0' + d,eq5[11] = '\\0';\n\n\teq6[0] = '(',eq6[1] = '0' + a,eq6[2] = '?',eq6[3] = '0' + b,eq6[4] = ')',eq6[5] = '?',eq6[6] = '0' + c,eq6[7] = '?',eq6[8] = '0' + d,eq6[9] = '\\0';\n\n\teq7[0] = '(',eq7[1] = '(',eq7[2] = '0' + a,eq7[3] = '?',eq7[4] = '0' + b,eq7[5] = ')',eq7[6] = '?',eq7[7] = '0' + c,eq7[8] = ')',eq7[9] = '?',eq7[10] = '0' + d,eq7[11] = '\\0';\n\n\teq8[0] = '0' + a,eq8[1] = '?',eq8[2] = '(',eq8[3] = '(',eq8[4] = '0' + b,eq8[5] = '?',eq8[6] = '0' + c,eq8[7] = ')',eq8[8] = '?',eq8[9] = '0' + d,eq8[10] = ')',eq8[11] = '\\0';\n\n\n\tfor(int x = 0; x < 3; x++){\n\t\tfor(int y = 0; y < 3; y++){\n\t\t\tfor(int z = 0; z < 3; z++){\n\t\t\t\tswitch(x){\n\t\t\t\tcase 0:\n\t\t\t\t\teq1[2] = '+',eq2[1] = '+',eq3[1] = '+',eq4[1] = '+',eq5[2] = '+',eq6[2] = '+',eq7[3] = '+',eq8[1] = '+';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\teq1[2] = '-',eq2[1] = '-',eq3[1] = '-',eq4[1] = '-',eq5[2] = '-',eq6[2] = '-',eq7[3] = '-',eq8[1] = '-';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\teq1[2] = '*',eq2[1] = '*',eq3[1] = '*',eq4[1] = '*',eq5[2] = '*',eq6[2] = '*',eq7[3] = '*',eq8[1] = '*';\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tswitch(y){\n\t\t\t\tcase 0:\n\t\t\t\t\teq1[5] = '+',eq2[4] = '+',eq3[3] = '+',eq4[4] = '+',eq5[5] = '+',eq6[5] = '+',eq7[6] = '+',eq8[5] = '+';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\teq1[5] = '-',eq2[4] = '-',eq3[3] = '-',eq4[4] = '-',eq5[5] = '-',eq6[5] = '-',eq7[6] = '-',eq8[5] = '-';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\teq1[5] = '*',eq2[4] = '*',eq3[3] = '*',eq4[4] = '*',eq5[5] = '*',eq6[5] = '*',eq7[6] = '*',eq8[5] = '*';\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tswitch(z){\n\t\t\t\tcase 0:\n\t\t\t\t\teq1[8] = '+',eq2[7] = '+',eq3[6] = '+',eq4[7] = '+',eq5[9] = '+',eq6[7] = '+',eq7[9] = '+',eq8[8] = '+';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\teq1[8] = '-',eq2[7] = '-',eq3[6] = '-',eq4[7] = '-',eq5[9] = '-',eq6[7] = '-',eq7[9] = '-',eq8[8] = '-';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\teq1[8] = '*',eq2[7] = '*',eq3[6] = '*',eq4[7] = '*',eq5[9] = '*',eq6[7] = '*',eq7[9] = '*',eq8[8] = '*';\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(calc(eq1) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq1[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t\tif(calc(eq2) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq2[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t\tif(calc(eq3) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq3[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t\tif(calc(eq4) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq4[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t\tif(calc(eq5) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq5[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t\tif(calc(eq6) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq6[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t\tif(calc(eq7) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq7[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t\tif(calc(eq8) == 10){\n\t\t\t\t\tfor(int i = 0; i < 30; i++)ans[i] = eq8[i];\n\t\t\t\t\tFound = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nint main(){\n\n\tint a,b,c,d,num[4];\n\n\twhile(true){\n\t\tscanf(\"%d %d %d %d\",&a,&b,&c,&d);\n\t\tif(a == 0 && b == 0 && c == 0 && d == 0)break;\n\n\t\tFound = false;\n\n\t\tnum[0] = a,num[1] = b,num[2] = c,num[3] =d;\n\n\t\tfor(int e = 0; e < 4; e++){\n\t\t\tfor(int f = 0; f < 4; f++){\n\t\t\t\tfor(int g = 0; g < 4; g++){\n\t\t\t\t\tfor(int h = 0; h < 4; h++){\n\t\t\t\t\t\tif(e != f && e != g && e != h && f != g && f != h && g != h)func(num[e],num[f],num[g],num[h]);\n\t\t\t\t\t\tif(Found)break;\n\t\t\t\t\t}\n\t\t\t\t\tif(Found)break;\n\t\t\t\t}\n\t\t\t\tif(Found)break;\n\t\t\t}\n\t\t\tif(Found)break;\n\t\t}\n\n\t\tif(Found)printf(\"%s\\n\",ans);\n\t\telse{\n\t\t\tprintf(\"0\\n\");\n\t\t}\n\t}\n\n\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 2556, "score_of_the_acc": -0.6629, "final_rank": 3 }, { "submission_id": "aoj_0041_1963921", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <string>\n#include <map>\n#include <algorithm>\n#include <cmath>\n#include <random>\nusing namespace std;\n\n#define REP(i,n) for(int (i)=0; (i)<(n); (i)++)\n#define FOR(i,a,b) for(int (i)=(a); (i)<(b); (i)++)\n#define ALL(v) v.begin(), v.end()\n\n// every calculation can be written\n// ((a ? b) ? c) ? d or (a ? b) ? (c ? d)\n\nint calc(int a, int b, char ope) {\n if (ope == '+') return a + b;\n if (ope == '-') return a - b;\n if (ope == '*') return a * b;\n return -1;\n}\n\nbool isten(string s) {\n int ans;\n if (s[1] == '(') {\n int a, b, c, d;\n a = s[2] - '0';\n b = s[6] - '0';\n c = s[11] - '0';\n d = s[16] - '0';\n ans = calc(calc(calc(a,b,s[4]), c, s[9]), d, s[14]);\n }else {\n int a, b, c, d;\n a = s[1] - '0';\n b = s[5] - '0';\n c = s[11] - '0';\n d = s[15] - '0';\n ans = calc(calc(a, b, s[3]), calc(c, d, s[13]), s[8]);\n }\n return ans == 10;\n}\n\n// every calculation can be written\n// ((a ? b) ? c) ? d or (a ? b) ? (c ? d)\n\n\nvector<char> operands = {'+', '-', '*'};\nrandom_device rd;\n\nchar getRandomOperand() {\n return operands[rd() % 3];\n}\n\nvoid solve41(int a, int b, int c, int d) {\n vector<int> nums;\n nums.push_back(a), nums.push_back(b), nums.push_back(c), nums.push_back(d);\n sort(ALL(nums));\n do {\n REP(i,100) {\n string eq1, eq2;\n eq1 = \"((\" + to_string(nums[0]) + \" \" + getRandomOperand() + \" \" +\n to_string(nums[1]) + \") \" + getRandomOperand() + \" \" + to_string(nums[2]) +\n \") \" + getRandomOperand() + \" \" + to_string(nums[3]);\n eq2 = \"(\" + to_string(nums[0]) + \" \" + getRandomOperand() + \" \" +\n to_string(nums[1]) + \") \" + getRandomOperand() + \" (\" + to_string(nums[2]) +\n \" \" + getRandomOperand() + \" \" + to_string(nums[3]) + \")\";\n if (isten(eq1)) {\n cout << eq1 << endl;\n return;\n }else if (isten(eq2)) {\n cout << eq2 << endl;\n return;\n }\n }\n }while (next_permutation(nums.begin(), nums.end()));\n cout << 0 << endl;\n}\n\nint main() {\n int a, b, c, d;\n while(cin >> a >> b >> c >> d, a + b + c + d) {\n solve41(a,b,c,d);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3124, "score_of_the_acc": -0.8595, "final_rank": 4 }, { "submission_id": "aoj_0041_1963920", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <string>\n#include <map>\n#include <algorithm>\n#include <cmath>\n#include <random>\nusing namespace std;\n\n#define REP(i,n) for(int (i)=0; (i)<(n); (i)++)\n#define FOR(i,a,b) for(int (i)=(a); (i)<(b); (i)++)\n#define ALL(v) v.begin(), v.end()\n\n// every calculation can be written\n// ((a ? b) ? c) ? d or (a ? b) ? (c ? d)\n\nint calc(int a, int b, char ope) {\n if (ope == '+') return a + b;\n if (ope == '-') return a - b;\n if (ope == '*') return a * b;\n return -1;\n}\n\nbool isten(string s) {\n int ans;\n if (s[1] == '(') {\n int a, b, c, d;\n a = s[2] - '0';\n b = s[6] - '0';\n c = s[11] - '0';\n d = s[16] - '0';\n ans = calc(calc(calc(a,b,s[4]), c, s[9]), d, s[14]);\n }else {\n int a, b, c, d;\n a = s[1] - '0';\n b = s[5] - '0';\n c = s[11] - '0';\n d = s[15] - '0';\n ans = calc(calc(a, b, s[3]), calc(c, d, s[13]), s[8]);\n }\n return ans == 10;\n}\n\n// every calculation can be written\n// ((a ? b) ? c) ? d or (a ? b) ? (c ? d)\n\n\nvector<char> operands = {'+', '-', '*'};\nrandom_device rd;\n\nchar getRandomOperand() {\n return operands[rd() % 3];\n}\n\nvoid solve41(int a, int b, int c, int d) {\n vector<int> nums;\n nums.push_back(a), nums.push_back(b), nums.push_back(c), nums.push_back(d);\n sort(ALL(nums));\n do {\n REP(i,500) {\n string eq1, eq2;\n eq1 = \"((\" + to_string(nums[0]) + \" \" + getRandomOperand() + \" \" +\n to_string(nums[1]) + \") \" + getRandomOperand() + \" \" + to_string(nums[2]) +\n \") \" + getRandomOperand() + \" \" + to_string(nums[3]);\n eq2 = \"(\" + to_string(nums[0]) + \" \" + getRandomOperand() + \" \" +\n to_string(nums[1]) + \") \" + getRandomOperand() + \" (\" + to_string(nums[2]) +\n \" \" + getRandomOperand() + \" \" + to_string(nums[3]) + \")\";\n if (isten(eq1)) {\n cout << eq1 << endl;\n return;\n }else if (isten(eq2)) {\n cout << eq2 << endl;\n return;\n }\n }\n }while (next_permutation(nums.begin(), nums.end()));\n cout << 0 << endl;\n}\n\nint main() {\n int a, b, c, d;\n while(cin >> a >> b >> c >> d, a + b + c + d) {\n solve41(a,b,c,d);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 100, "memory_kb": 3144, "score_of_the_acc": -1.1499, "final_rank": 12 }, { "submission_id": "aoj_0041_1829312", "code_snippet": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <string>\n#include <sstream>\n#include <cmath>\nusing namespace std;\n\ntypedef pair<int,string> pis;\n#define fi first\n#define se second\n\nvector<pis> solve(vector<int> nums) {\n\tvector<pis> res;\n\tif(nums.size() == 1) {\n\t\tstring s;\n\t\tstringstream sstr;\n\t\tsstr << nums[0];\n\t\tsstr >> s;\n\t\tres.push_back(pis(nums[0],s));\n\t\treturn res;\n\t}\n\tfor(int i = 1; i < nums.size(); i++) {\n\t\tvector<int> a(nums.begin(), nums.begin()+i);\n\t\tvector<int> b(nums.begin()+i, nums.end());\n\t\tvector<pis> aa, bb;\n\t\taa = solve(a);\n\t\tbb = solve(b);\n\t\tfor(int i = 0; i < aa.size(); i++) {\n\t\t\tfor(int j = 0; j < bb.size(); j++) {\n\t\t\t\tres.push_back(pis(aa[i].fi + bb[j].fi, \"(\" + aa[i].se + \"+\" + bb[j].se + \")\"));\n\t\t\t\tres.push_back(pis(aa[i].fi - bb[j].fi, \"(\" + aa[i].se + \"-\" + bb[j].se + \")\"));\n\t\t\t\tres.push_back(pis(aa[i].fi * bb[j].fi, \"(\" + aa[i].se + \"*\" + bb[j].se + \")\"));\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n\nint main() {\n\twhile(1) {\n\t\tvector<int> a;\n\t\ta.resize(4);\n\t\tbool brk = true;\n\t\tfor(int i = 0; i < 4; i++) {\n\t\t\tcin >> a[i];\n\t\t\tif(a[i] != 0) brk = false;\n\t\t}\n\t\tif(brk) break;\n\n\t\tsort(a.begin(), a.end());\n\t\tstring res = \"0\";\n\t\tdo {\n\t\t\tvector<pis> tmp;\n\t\t\ttmp = solve(a);\n\t\t\tfor(int i = 0; i < tmp.size(); i++) {\n\t\t\t\tif(tmp[i].fi == 10)\n\t\t\t\t\tres = tmp[i].se;\n\t\t\t}\n\t\t} while(next_permutation(a.begin(), a.end()));\n\t\tcout << res << endl;\n\t}\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 1284, "score_of_the_acc": -0.0826, "final_rank": 2 }, { "submission_id": "aoj_0041_1829298", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std ;\n\n#define pb(n) push_back(n)\n#define fi first\n#define se second\n#define all(r) (r).begin(),(r).end()\n#define gsort(st,en) sort((st),(en),greater<int>())\n#define vmax(ary) *max_element(all(ary))\n#define vmin(ary) *min_element(all(ary))\n#define debug(x) cout<<#x<<\": \"<<x<<endl\n#define fcout(n) cout<<fixed<<setprecision((n))\n#define scout(n) cout<<setw(n)\n#define vary(type,name,size,init) vector< type> name(size,init)\n#define vvl(v,w,h,init) vector<vector<ll>> v(w,vector<ll>(h,init));\n\n#define rep(i,n) for(int i = 0; i < (int)(n);++i)\n#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)\n#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)\n#define repa(n,array) for(auto &n :(array))\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vl = vector<ll>;\nusing dict = map<string,int>;\nusing pii = pair<int,int> ;\nusing pll = pair<ll,ll> ;\n\ntemplate<typename T>\nT ston(string& str, T n){\n istringstream sin(str) ;\n T num ;\n sin >> num ;\n return num ;\n}\n\nconst string op[4] = {\"+\",\"-\",\"*\",\"/\"};\nconst string pare[] = {\"(.!.)!.!.\",\".!.!(.!.)\",\".!(.!.)!.\",\"(.!.)!(.!.)\",\"(.!.!.)!.\",\".!(.!.!.)\",\"(.!(.!.))!.\",\"((.!.)!.)!.\",\".!((.!.)!.)\",\".!(.!(.!.))\",\".!.!.!.\"};\n\ndouble RPN(string str){\n string s,s2;\n double ans;\n stack<double> n;\n s = str;\n ans = 0;\n s += \" \" ;\n rep(i,s.size()){\n if(s[i] != ' '){\n s2 += s[i];\n }\n else{\n double a,b;\n if(s2 == \"+\"){\n b = n.top(),n.pop();\n a = n.top(),n.pop();\n ans = a + b;\n n.push(ans);\n }\n else if(s2 == \"-\"){\n b = n.top(),n.pop();\n a = n.top(),n.pop();\n ans = a - b;\n n.push(ans);\n }\n else if(s2 == \"*\"){\n b = n.top(),n.pop();\n a = n.top(),n.pop();\n ans = a * b;\n n.push(ans);\n }\n else if(s2 == \"/\"){\n b = n.top(),n.pop();\n a = n.top(),n.pop();\n ans = a / b;\n n.push(ans);\n }\n else{\n n.push(ston(s2,1.0));\n }\n s2.clear();\n }\n }\n return n.top();\n}\n\nvector<string> Split(char c,string s){\n vector<string> res(0);\n string str = \"\";\n rep(i,s.size()){\n if(s[i] == c){\n if(str.size()){\n res.push_back(str);\n }\n str.clear();\n }\n else{\n str += s[i];\n }\n }\n res.push_back(str);\n return res;\n}\nbool check(string s1,string s2){\n if(((s1 == \"+\" || s1 == \"-\" ) && s2 != \"(\")|| s1 == s2) return true;\n if((s1 == \"*\" || s1 == \"/\")&& (s2 == \"+\" || s2 == \"-\")) return false;\n if(s2 == \"(\") return false;\n}\nstring ConvertRPN(string s){\n const string notnumber = \"+-*/() \";\n stack<string> fom;\n auto str = Split(' ',s);\n string res = \"\";\n rep(i,str.size()){\n if(notnumber.find(str[i]) == string::npos){\n res += str[i];\n res += \" \";\n }\n else if(str[i] == \")\"){\n while(fom.top() != \"(\"){\n if(fom.top() != \" \"){\n res += fom.top();\n res += \" \";\n }\n fom.pop();\n }\n fom.pop();\n }\n else if(str[i] == \"(\" || fom.empty()){\n fom.push(str[i]);\n }\n else if(check(str[i],fom.top())){\n while(!fom.empty() && check(str[i],fom.top())){\n if(fom.top() != \" \"){\n res += fom.top();\n res += \" \";\n }\n fom.pop();\n }\n fom.push(str[i]);\n }\n else{\n fom.push(str[i]);\n }\n }\n bool f = true;\n while(fom.size()){\n if(fom.top() != \" \"){\n res += fom.top();\n res += \" \";\n }\n fom.pop();\n }\n res.resize(res.size()-1);\n return res;\n}\n\nint main(){\n cin.tie(0);\n ios::sync_with_stdio(false);\n vary(ll,v,4,0);\n while(cin >> v[0] >> v[1] >> v[2] >> v[3] && v[0] && v[1] && v[2] && v[3]){\n sort(all(v));\n bool f = false;\n do{\n rep(i,3){\n rep(j,3){\n rep(k,3){\n string formula = op[i]+op[j] + op[k];\n rep(m,10){\n ll c = 0,d = 0;\n string res =\"\";\n rep(l,pare[m].size()){\n if(pare[m][l] == '.'){\n res += to_string(v[c])+ \" \";\n ++c;\n }\n else if(pare[m][l] == '!'){\n res += formula[d];\n res += \" \";\n ++d;\n }\n else{\n res += pare[m][l];\n res += \" \";\n }\n }\n res.resize(res.size()-1);\n string tmp = res;\n res = ConvertRPN(res);\n if(RPN(res) == 10){\n cout << tmp<<endl;\n f = true;\n i = j = k = 4;\n v.clear();\n break;\n }\n }\n }\n }\n }\n }while(next_permutation(all(v)));\n if(!f){\n cout << 0 << endl;\n }\n v.resize(4);\n }\n return 0;\n}", "accuracy": 1, "time_ms": 90, "memory_kb": 3220, "score_of_the_acc": -1.1533, "final_rank": 13 }, { "submission_id": "aoj_0041_1658385", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef complex<double> P;\ntypedef pair<int,int> pii;\n#define REP(i,n) for(ll i=0;i<n;++i)\n#define REPR(i,n) for(ll i=1;i<n;++i)\n#define FOR(i,a,b) for(ll i=a;i<b;++i)\n\n#define DEBUG(x) cout<<#x<<\": \"<<x<<endl\n#define DEBUG_VEC(v) cout<<#v<<\":\";REP(i,v.size())cout<<\" \"<<v[i];cout<<endl\n#define ALL(a) (a).begin(),(a).end()\n\n#define MOD (ll)(1e9+7)\n#define ADD(a,b) a=((a)+(b))%MOD\n#define FIX(a) ((a)%MOD+MOD)%MOD\n\nint calc(string s){\n assert(s.size()==7);\n stack<int> st;\n REP(i,s.size()){\n char c = s[i];\n if(c=='+'){\n if(st.size()<2) return -1;\n int a = st.top(); st.pop();\n a += st.top(); st.pop();\n st.push(a);\n }else if(c=='-'){\n if(st.size()<2) return -1;\n int a = st.top(); st.pop();\n a -= st.top(); st.pop();\n st.push(a);\n }else if(c=='*'){\n if(st.size()<2) return -1;\n int a = st.top(); st.pop();\n a *= st.top(); st.pop();\n st.push(a);\n }else{\n st.push((int)(c-'0'));\n }\n }\n assert(st.size()==1);\n return st.top();\n}\n\nvoid output(string s){\n stack<string> st;\n REP(i,s.size()){\n char c = s[i];\n if(c=='+' || c=='-' || c=='*'){\n if(st.size()<2) assert(false&&\"NO STACK\");\n string a = \"(\";\n a += st.top(); st.pop();\n a += c;\n a += st.top(); st.pop();\n a += \")\";\n st.push(a);\n }else{\n st.push(string(1,c));\n }\n }\n assert(st.size()==1);\n cout<<st.top()<<endl;\n}\n\nint main(){\n int a[4];\n while(~scanf(\"%d%d%d%d\",a,a+1,a+2,a+3)){\n if(a[0]==0 && a[1]==0 && a[2]==0 && a[3]==0)break;\n // ???????????????????¨????\n vi expr(7,0);\n FOR(i,4,7)expr[i]=1;\n vi numlst(4);\n REP(i,4)numlst[i]=i;\n bool flag = false;\n do{\n if(flag)break;\n if(expr[0]==1 || expr[1]==1) continue;\n if(expr[6]==0) continue;\n REP(exmsk,3*3*3){\n if(flag)break;\n do{\n if(flag)break;\n string s = \"\";\n int i1=0;\n int tmp = exmsk;\n REP(i,7){\n if(expr[i]==0){\n s += (char)(a[numlst[i1]]+'0');\n ++i1;\n }else{\n s += \"+-*\"[tmp%3];\n tmp /= 3;\n }\n }\n int res = calc(s);\n if(res==10){\n flag = true;\n output(s);\n break;\n }\n }while(next_permutation(ALL(numlst)));\n }\n }while(next_permutation(ALL(expr)));\n if(!flag)cout<<0<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 1240, "score_of_the_acc": -0.0625, "final_rank": 1 }, { "submission_id": "aoj_0041_1589855", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,x,y) for(int i=(x);i<(y);++i)\n#define debug(x) #x << \"=\" << (x)\n\n#ifdef DEBUG\n#define _GLIBCXX_DEBUG\n#define dump(x) std::cerr << debug(x) << \" (L:\" << __LINE__ << \")\" << std::endl\n#else\n#define dump(x)\n#endif\n\ntypedef long long int ll;\ntypedef pair<int,int> pii;\n//template<typename T> using vec=std::vector<T>;\n\nconst int inf=1<<30;\nconst long long int infll=1LL<<58;\nconst double eps=1e-9;\nconst int dx[]={1,0,-1,0},dy[]={0,1,0,-1};\n\ntemplate <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){\n\tos << \"[\";\n\tfor (const auto &v : vec) {\n\t\tos << v << \",\";\n\t}\n\tos << \"]\";\n\treturn os;\n}\n\nstring int_to_string(int x){\n stringstream ss;\n ss << x;\n return ss.str();\n}\n\nvector<pair<int,string>> nv(const vector<pair<int,string>>& v,const vector<pair<int,string>>& tmp,const vector<int>& idxs,char op){\n auto x=v[idxs[0]],y=v[idxs[1]];\n pair<int,string> p;\n if(op=='+') p=make_pair(x.first+y.first,\"(\"+x.second+\" + \"+y.second+\")\");\n else if(op=='-') p=make_pair(x.first-y.first,\"(\"+x.second+\" - \"+y.second+\")\");\n else if(op=='*') p=make_pair(x.first*y.first,\"(\"+x.second+\" * \"+y.second+\")\");\n auto res=tmp; res.emplace_back(p);\n return move(res);\n}\n\nstring dfs(vector<pair<int,string>> v){\n if(v.size()==1){\n if(v[0].first==10) return v[0].second;\n else return \"\";\n }\n\n string res=\"\";\n rep(b,0,1<<v.size()){\n if(__builtin_popcount(b)!=2) continue;\n vector<pair<int,string>> tmp;\n vector<int> idxs;\n rep(i,0,v.size()){\n if((1&(b>>i))==0) tmp.emplace_back(v[i]);\n else idxs.emplace_back(i);\n }\n\n res=max(res,dfs(nv(v,tmp,idxs,'+')));\n res=max(res,dfs(nv(v,tmp,idxs,'*')));\n res=max(res,dfs(nv(v,tmp,idxs,'-')));\n swap(idxs[0],idxs[1]);\n res=max(res,dfs(nv(v,tmp,idxs,'-')));\n }\n return res;\n}\n\nvoid solve(){\n int a,b,c,d;\n while(cin >> a >> b >> c >> d){\n if(a==0 and b==0 and c==0 and d==0) break;\n vector<pair<int,string>> v;\n v.emplace_back(make_pair(a,int_to_string(a)));\n v.emplace_back(make_pair(b,int_to_string(b)));\n v.emplace_back(make_pair(c,int_to_string(c)));\n v.emplace_back(make_pair(d,int_to_string(d)));\n string ans=dfs(v);\n\n if(ans.empty()) cout << 0 << endl;\n else cout << ans << endl;\n }\n}\n\nint main(){\n\tstd::ios::sync_with_stdio(false);\n\tstd::cin.tie(0);\n\tsolve();\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3224, "score_of_the_acc": -0.9051, "final_rank": 8 } ]
aoj_0067_cpp
島の数 地勢を示す縦 12, 横 12 のマスからなる平面図があります。おのおののマスは白か黒に塗られています。白は海を、黒は陸地を表します。二つの黒いマスが上下、あるいは左右に接しているとき、これらは地続きであるといいます。この平面図では、黒いマス一つのみ、あるいは地続きの黒いマスが作る領域を「島」といいます。例えば下図には、5 つの島があります。 ■■■■□□□□■■■■ ■■■□□□□□■■■■ ■■□□□□□□■■■■ ■□□□□□□□■■■■ □□□■□□□■□□□□ □□□□□□■■■□□□ □□□□□■■■■■□□ ■□□□■■■■■■■□ ■■□□□■■■■■□□ ■■■□□□■■■□□□ ■■■■□□□■□□□□ □□□□□□□□□□□□ マスのデータを読み込んで、島の数を出力するプログラムを作成してください。 Input 入力は複数のデータセットからなります。各データセットに1つの平面図が与えられます。黒いマスを 1、白いマスを 0 で表現した 12 個の数字の列 12 行でひとつの平面図を表します。データセットの間は1つの空行で区切られています。 データセットの数は 20 を超えません。 Output データセットごとに、島の数を1行に出力します。 Sample Input 111100001111 111000001111 110000001111 100000001111 000100010000 000000111000 000001111100 100011111110 110001111100 111000111000 111100010000 000000000000 010001111100 110010000010 010010000001 010000000001 010000000110 010000111000 010000000100 010000000010 010000000001 010010000001 010010000010 111001111100 000000000000 111111111111 100010100001 100010100001 100010100001 100010100001 100100100101 101000011101 100000000001 100000000001 111111111111 100000000001 Output for the Sample Input 5 13 4 Hint 以下はサンプルインプットを■と□で表したものです。 ■■■■□□□□■■■■  □■□□□■■■■■□□  □□□□□□□□□□□□ ■■■□□□□□■■■■  ■■□□■□□□□□■□  ■■■■■■■■■■■■ ■■□□□□□□■■■■  □■□□■□□□□□□■  ■□□□■□■□□□□■ ■□□□□□□□■■■■  □■□□□□□□□□□■  ■□□□■□■□□□□■ □□□■□□□■□□□□  □■□□□□□□□■■□  ■□□□■□■□□□□■ □□□□□□■■■□□□  □■□□□□■■■□□□  ■□□□■□■□□□□■ □□□□□■■■■■□□  □■□□□□□□□■□□  ■□□■□□■□□■□■ ■□□□■■■■■■■□  □■□□□□□□□□■□  ■□■□□□□■■■□■ ■■□□□■■■■■□□  □■□□□□□□□□□■  ■□□□□□□□□□□■ ■■■□□□■■■□□□  □■□□■□□□□□□■  ■□□□□□□□□□□■ ■■■■□□□■□□□□  □■□□■□□□□□■□  ■■■■■■■■■■■■ □□□□□□□□□□□□  ■■■□□■■■■■□□  ■□□□□□□□□□□■
[ { "submission_id": "aoj_0067_5246731", "code_snippet": "#include <bits/stdc++.h>\n#define NIL (-1)\n#define LL long long\nusing namespace std;\nconst int64_t MOD = 1e9 + 7;\nconst int INF = INT_MAX;\nconst double PI = acos(-1.0);\n\nvector<string> island(12);\nvector<vector<bool>> seen(12, vector<bool>(12));\n\nvoid bfs(int h, int w) {\n\tqueue<pair<int, int>> q;\n\tq.push(make_pair(h, w));\n\n\tvector<int> X, Y;\n\tX = { 0,-1,1,0 };\n\tY = { -1,0,0,1 };\n\n\tint x, y;\n\twhile (!q.empty()) {\n\t\ty = q.front().first;\n\t\tx = q.front().second;\n\t\tseen[y][x] = 1;\n\t\tq.pop();\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint H, W;\n\t\t\tH = y + Y[i];\n\t\t\tW = x + X[i];\n\t\t\tif (H < 0 || H>11) continue;\n\t\t\tif (W < 0 || W>11) continue;\n\t\t\tif ((!seen[H][W])&& (island[H][W]=='1')) q.push(make_pair(H, W));\n\t\t}\n\t}\n\treturn;\n}\n\nint main() {\n\tfor (int i = 0; i < 12; i++) island[i].assign(\"\");\n\n\twhile (cin >> island[0]) {\n\t\t//cout << island[0] << endl;\n\t\tfor (int i = 1; i < 12; i++) cin >> island[i];\n\t\t//for (int i = 0; i < 12; i++) cout << island[i] << endl;\n\t\tfor (int i = 0; i < 12; i++) {\n\t\t\tfor (int j = 0; j < 12; j++) {\n\t\t\t\tseen[i][j] = 0;\n\t\t\t}\n\t\t}\n\n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < 12; i++) {\n\t\t\tfor (int j = 0; j < 12; j++) {\n\t\t\t\tif ((island[i][j] == '1') && (!seen[i][j])) {\n\t\t\t\t\tcnt++;\n\t\t\t\t\tbfs(i, j);\n\t\t\t\t\t/*for (int i = 0; i < 12; i++) {\n\t\t\t\t\t\tfor (int j = 0; j < 12; j++) {\n\t\t\t\t\t\t\tcout << seen[i][j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t}\n\t\t\t\t\tcout << endl;*/\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << cnt << endl;\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8800, "score_of_the_acc": -2, "final_rank": 4 }, { "submission_id": "aoj_0067_3324152", "code_snippet": "#include <iostream>\n#include <queue>\n#include <string>\n#include <vector>\n\n#define N 12\n\nusing namespace std;\n\nint main() {\n // 隣接行列\n // int adjacent[N][N];\n string s;\n while(cin >> s) {\n vector<string> numStr(N);\n // 到達したかどうかを判断\n bool reached[N][N];\n\n numStr[0] = s;\n for(int i = 1; i < N; i++) {\n cin >> numStr[i];\n }\n\n for(int i = 0; i < N; i++) {\n for(int j = 0; j < N; j++) {\n // cout << numStr[i].at(j);\n reached[i][j] = false;\n }\n // cout << endl;\n }\n // cout << numStr[N+1];\n\n // 始点の選択\n queue<pair<int, int> > que;\n // 島の数\n int cnt = 0;\n for(int i = 0; i < N; i++) {\n for(int j = 0; j < N; j++) {\n if(reached[i][j] == false && numStr[i].at(j) == '1') {\n que.push(pair<int, int>(i, j));\n // その島のカウントをつける。\n cnt++;\n while(!que.empty()) {\n // popする値を保存する。\n int f = que.front().first;\n int s = que.front().second;\n // cout << \"front = (\" << f << \",\" << s << \")\" << endl;\n // popする値をtrueに変更する。\n reached[f][s] = true;\n que.pop();\n\n // 右\n if(!(s == N-1)) {\n // cout << \"log右\" << endl;\n if(reached[f][s+1] == false && numStr[f].at(s+1) == '1') que.push(pair<int, int>(f, s+1));\n }\n // 左\n if(!(s == 0)) {\n // cout << \"log左\" << endl;\n if(reached[f][s-1] == false && numStr[f].at(s-1) == '1') que.push(pair<int, int>(f, s-1));\n }\n // 上\n if(!(f == 0)) {\n // cout << \"log上\" << endl;\n if(reached[f-1][s] == false && numStr[f-1].at(s) == '1') que.push(pair<int, int>(f+1, s));\n }\n // 下\n if(!(f == N-1)) {\n // cout << \"log下\" << endl;\n if(reached[f+1][s] == false && numStr[f+1].at(s) == '1') que.push(pair<int, int>(f+1, s));\n }\n\n }\n }\n }\n }\n cout << cnt << endl;\n // 終了判定\n // if(cin.eof()) break;\n }\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 8740, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_0067_2313551", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef pair<int,int> PA;\nint dx[4] = {1,-1,0,0};\nint dy[4] = {0,0,1,-1};\nqueue<PA> que;\nint main(){\n int n,ans;\n char m[13][13];\n \n while(cin >> m[0]){\n \n for(int j = 0;j < 12;j++){\n if(j==0) continue;\n cin >> m[j];\n }\n ans = 0;\n for(int j = 0;j < 12;j++){\n for(int k = 0;k < 12;k++){\n\tif(m[j][k] == '1'){\n\t que.push(PA(j,k));\n\t while(!que.empty()){\n\t PA p=que.front();que.pop();\n\t m[p.first][p.second] = '0';\n\t for(int l = 0;l < 4;l++){\n\t int y = p.first+dy[l];\n\t int x = p.second+dx[l];\n\t if(x<0||y<0||x>=12||y>=12||m[y][x]=='0') continue;\n\t que.push( PA(y,x) );\n\t }\n\t }\n\t ans++;\n\t}\n }\n }\n cout << ans << endl;\n }\n return (0);\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8768, "score_of_the_acc": -1.4667, "final_rank": 3 }, { "submission_id": "aoj_0067_2204416", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint vecx[4]={0,1,0,-1},vecy[4]={1,0,-1,0};\n\nvoid explore(string atlas[12],int vstd[12][12],int i,int j){\n queue<pair<int,int> > bfs;\n bfs.push(make_pair(i,j));\n while(!bfs.empty()){\n int x=bfs.front().first,y=bfs.front().second;\n vstd[x][y]=1;\n for(int k=0; k<4; k++){\n int nextx=x+vecx[k],nexty=y+vecy[k];\n if(nextx<0||nextx>11||nexty<0||nexty>11)continue;\n if(atlas[x+vecx[k]][y+vecy[k]]=='1'&&vstd[x+vecx[k]][y+vecy[k]]==0){\n bfs.push(make_pair(x+vecx[k],y+vecy[k]));\n }\n }\n bfs.pop();\n //cout<<x<<' '<<y<<endl;\n }\n}\n\nint main(){\n string atlas[12];\n int vstd[12][12],cnt;\n while(cin>>atlas[0],!cin.eof()){\n cnt=0;\n for(int i=1; i<12; i++){\n cin>>atlas[i];\n }\n fill(vstd[0],vstd[12],0);\n for(int i=0; i<12; i++){\n for(int j=0; j<12; j++){\n if(vstd[i][j]==0&&atlas[i][j]=='1'){\n explore(atlas,vstd,i,j);\n cnt++;\n }\n }\n }\n cout<<cnt<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 30, "memory_kb": 8764, "score_of_the_acc": -1.4, "final_rank": 2 } ]
aoj_0043_cpp
パズル 1 〜 9 の数字を 14 個組み合わせて完成させるパズルがあります。与えられた 13 個の数字にもうひとつ数字を付け加えて完成させます。 パズルの完成条件は 同じ数字を2つ組み合わせたものが必ずひとつ必要です。 残りの12 個の数字は、3個の数字の組み合わせ4つです。 3個の数字の組み合わせ方は、同じ数字を3つ組み合わせたものか、または3つの連続する数字を組み合わせたものです。ただし、9 1 2 のような並びは連続する数字とは認められません。 同じ数字は4 回まで使えます。 13 個の数字からなる文字列を読み込んで、パズルを完成することができる数字を昇順に全て出力するプログラムを作成してください。なお、1〜9 のどの数字を付け加えてもパズルを完成させることができないときは 0 を出力してください。 例えば与えられた文字列が 3456666777999 の場合 「2」があれば、 234 567 666 77 999 「3」があれば、 33 456 666 777 999 「5」があれば、 345 567 666 77 999 「8」があれば、 345 666 678 77 999 というふうに、2 3 5 8 のいずれかの数字が付け加えられるとパズルは完成します。「6」でも整いますが、5 回目の使用になるので、この例では使えないことに注意してください。 Input 入力は複数のデータセットからなります。各データセットとして、13 個の数字が1行に与えられます。データセットの数は 50 を超えません。 Output データセットごとに、パズルを完成させることができる数字を昇順に空白区切りで1行に出力します。 Sample Input 3649596966777 6358665788577 9118992346175 9643871425498 7755542764533 1133557799246 Output for the Sample Input 2 3 5 8 3 4 1 2 3 4 5 6 7 8 9 7 8 9 1 2 3 4 6 7 8 0
[ { "submission_id": "aoj_0043_4893249", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\n#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)\n#define FOR(i, a, b) for (int i = (a), i##_len = (b); i < i##_len; i++)\n#define ALL(x) (x).begin(), (x).end() // sortなどの引数を省略したい\n#ifdef _DEBUG\n#define PRE_COMMAND \\\n std::cin.rdbuf(in.rdbuf()); \\\n std::cout << fixed << setprecision(15);\n#else\n#define PRE_COMMAND cout << fixed << setprecision(15);\n#endif\nconst double EPS = 1e-10, PI = acos(-1.0);\ntemplate <class T> auto MAX(T& seq) {\n return *max_element(seq.begin(), seq.end());\n}\ntemplate <class T> auto MIN(T& seq) {\n return *min_element(seq.begin(), seq.end());\n}\ntemplate <class T> auto SUM(T& seq) {\n T temp{0};\n auto& temp2 = temp[0];\n return accumulate(seq.begin(), seq.end(), temp2);\n}\ntemplate <class T> void SORT(T& seq) { sort(seq.begin(), seq.end()); }\ntemplate <class T, class S> void SORT(T& seq, S& sort_order) {\n sort(seq.begin(), seq.end(), sort_order);\n}\ntemplate <class T> void SORTR(vector<T>& seq) {\n sort(seq.begin(), seq.end(), greater<T>());\n}\ntemplate <class T, class S, class R> long long pow(T n_0, S k_0, R mod_0) {\n long long n = n_0 % mod_0, k = k_0, mod = mod_0, now = 1;\n while (k) {\n if (k & 1) now = (now * n) % mod;\n n = (n * n) % mod;\n k >>= 1;\n }\n return now;\n}\ntemplate <typename T> istream& operator>>(istream& is, vector<T>& vec) {\n for (T& x : vec) is >> x;\n return is;\n}\ntemplate <typename T> ostream& operator<<(ostream& os, const vector<T>& v) {\n if (!v.size()) return os;\n typename vector<T>::const_iterator ii = v.begin();\n os << *ii++;\n for (; ii != v.end(); ++ii) os << \" \" << *ii;\n return os;\n}\n\n// カンマ区切りのデータをvector<int>に変換\nvector<int> comma_sep(string inp) {\n inp += ',';\n vector<int> v;\n string s = \"\";\n for (char c : inp) {\n if (c == ',') {\n v.push_back(stoi(s));\n s = \"\";\n } else {\n s += c;\n }\n }\n return v;\n}\n\ntemplate <class S> map<S, int> Counter(vector<S>& v) {\n map<S, int> ret;\n for (auto i : v) { ret[i]++; }\n return ret;\n}\n\nint main() {\n PRE_COMMAND\n set<vector<int>> ok_list;\n vector<vector<int>> three_pair = {\n {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}, {6, 7, 8},\n {7, 8, 9}, {1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4}, {5, 5, 5},\n {6, 6, 6}, {7, 7, 7}, {8, 8, 8}, {9, 9, 9}};\n vector<vector<int>> two_pair = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5},\n {6, 6}, {7, 7}, {8, 8}, {9, 9}};\n vector<int> deck;\n for (auto t1 : three_pair) {\n for (auto t2 : three_pair) {\n for (auto t3 : three_pair) {\n for (auto t4 : three_pair) {\n for (auto t5 : two_pair) {\n deck = {};\n for (int i : t1) deck.push_back(i);\n for (int i : t2) deck.push_back(i);\n for (int i : t3) deck.push_back(i);\n for (int i : t4) deck.push_back(i);\n for (int i : t5) deck.push_back(i);\n map<int, int> c = Counter(deck);\n bool flag = false;\n for (auto temp : c) {\n if (get<1>(temp) > 4) flag = true;\n }\n if (flag) continue;\n SORT(deck);\n ok_list.insert(deck);\n }\n }\n }\n }\n }\n string s;\n while (cin >> s) {\n vector<int> now, ans;\n for (int i = 0; i < 13; i++) now.push_back((int)(s[i] - '0'));\n for (int i = 1; i < 10; i++) {\n vector<int> now2 = now;\n now2.push_back(i);\n SORT(now2);\n if (ok_list.count(now2)) ans.push_back(i);\n }\n if (ans.size()) {\n cout << ans << endl;\n } else {\n cout << 0 << endl;\n }\n }\n}", "accuracy": 1, "time_ms": 230, "memory_kb": 4816, "score_of_the_acc": -0.8331, "final_rank": 14 }, { "submission_id": "aoj_0043_4357252", "code_snippet": "#include <iostream>\n#include <algorithm>\n#include <iomanip>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <numeric>\n#include <bitset>\n#include <cmath>\n\nstatic const int MOD = 1000000007;\nusing ll = long long;\nusing u32 = uint32_t;\nusing namespace std;\n\ntemplate<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;\n\nbool solve(string s){\n map<int, int> m;\n for (auto &&i : s) {\n m[i]++;\n }\n sort(s.begin(),s.end());\n vector<string> v, u;\n for (int i = 1; i <= 9; ++i) {\n v.emplace_back(3, (char)(i+'0'));\n u.emplace_back(2, (char)(i+'0'));\n }\n for (int i = 1; i < 8; ++i) {\n string t;\n for (int j = 0; j < 3; ++j) {\n t += (char)(i+j+'0');\n }\n v.emplace_back(t);\n }\n int n = v.size();\n\n for (int i = 0; i < n; ++i) {\n for (int j = i; j < n; ++j) {\n for (int k = j; k < n; ++k) {\n for (int l = k; l < n; ++l) {\n for (int o = 0; o < 9; ++o) {\n string t = v[i]+v[j]+v[k]+v[l]+u[o];\n sort(t.begin(),t.end());\n if(s == t) return true;\n }\n }\n }\n }\n }\n return false;\n}\n\nint main() {\n string s;\n while(getline(cin, s)){\n sort(s.begin(),s.end());\n map<int, int> cnt;\n for (auto &&i : s) {\n cnt[i-'0']++;\n }\n int b = 0;\n for (int i = 1; i <= 9; ++i) {\n if(cnt[i] < 4){\n string t = s;\n t += char(i + '0');\n if(solve(t)) {\n if(b++) cout << \" \";\n cout << i;\n }\n }\n }\n if(!b) printf(\"0\");\n puts(\"\");\n }\n return 0;\n}", "accuracy": 1, "time_ms": 630, "memory_kb": 3164, "score_of_the_acc": -1.1895, "final_rank": 18 }, { "submission_id": "aoj_0043_2896038", "code_snippet": "#include<iostream>\n#include<string>\n#include<vector>\n#include<algorithm>\nbool serch(std::vector<int>&nums)\n{\n\tconst int length = nums.size();\n\tstatic int found_hand = 0;\n\tswitch (found_hand)\n\t{\n\tcase 0:\n\t\tint pair[2];\n\t\tfor (int i = 0; i < length - 1; i++)\n\t\t{\n\t\t\tfor (int j = i + 1; j < length; j++)\n\t\t\t{\n\t\t\t\tif (nums[i] == nums[j])\n\t\t\t\t{\n\t\t\t\t\tpair[0] = nums[i];\n\t\t\t\t\tpair[1] = nums[j];\n\t\t\t\t\tnums.erase(nums.begin() + j);\n\t\t\t\t\tnums.erase(nums.begin() + i);\n\t\t\t\t\tfound_hand++;\n\t\t\t\t\tif (serch(nums))\n\t\t\t\t\t{\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tnums.push_back(pair[0]);\n\t\t\t\t\t\tnums.push_back(pair[1]);\n\t\t\t\t\t\tstd::sort(nums.begin(), nums.end());\n\t\t\t\t\t\tfound_hand--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tint trio[3];\n\t\tfor (int i = 0; i < length - 2; i++)\n\t\t{\n\t\t\tfor (int j = i + 1; j < length - 1; j++)\n\t\t\t{\n\t\t\t\tfor (int k = j + 1; k < length; k++)\n\t\t\t\t{\n\t\t\t\t\tif (nums[i] == nums[j] && nums[j] == nums[k] || nums[j] == nums[i] + 1 && nums[k] == nums[j] + 1)\n\t\t\t\t\t{\n\t\t\t\t\t\ttrio[0] = nums[i];\n\t\t\t\t\t\ttrio[1] = nums[j];\n\t\t\t\t\t\ttrio[2] = nums[k];\n\t\t\t\t\t\tnums.erase(nums.begin() + k);\n\t\t\t\t\t\tnums.erase(nums.begin() + j);\n\t\t\t\t\t\tnums.erase(nums.begin() + i);\n\t\t\t\t\t\tfound_hand++;\n\t\t\t\t\t\tif (found_hand == 5 || serch(nums))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfound_hand = 0;\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnums.push_back(trio[0]);\n\t\t\t\t\t\t\tnums.push_back(trio[1]);\n\t\t\t\t\t\t\tnums.push_back(trio[2]);\n\t\t\t\t\t\t\tstd::sort(nums.begin(), nums.end());\n\t\t\t\t\t\t\tfound_hand--;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\treturn false;\n}\nint main()\n{\n\tfor (std::string str; std::cin >> str;)\n\t{\n\t\tstd::vector<int>ans;\n\t\tans.reserve(9);\n\t\tstd::vector<int>nums;\n\t\tnums.reserve(14);\n\t\tstd::vector<int>appearance_count(9, 0);\n\t\tfor (auto i : str)\n\t\t{\n\t\t\tconst int foo = static_cast<int>(i - '0');\n\t\t\tnums.push_back(foo);\n\t\t\tappearance_count[foo]++;\n\t\t}\n\t\tfor (int i = 1; i <= 9; i++)\n\t\t{\n\t\t\tif (appearance_count[i] == 4)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tauto nums_copy = nums;\n\t\t\tnums_copy.push_back(i);\n\t\t\tstd::sort(nums_copy.begin(), nums_copy.end());\n\t\t\tif (serch(nums_copy))\n\t\t\t{\n\t\t\t\tans.push_back(i);\n\t\t\t}\n\t\t}\n\t\tif (ans.size() == 0)\n\t\t{\n\t\t\tstd::cout << '0';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < ans.size(); i++)\n\t\t\t{\n\t\t\t\tif (i != 0)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << ' ';\n\t\t\t\t}\n\t\t\t\tstd::cout << ans[i];\n\t\t\t}\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3180, "score_of_the_acc": -0.2947, "final_rank": 12 }, { "submission_id": "aoj_0043_2140762", "code_snippet": "#include<bits/stdc++.h>\n#define rep(i,n)for(int i=0;i<n;i++)\nusing namespace std;\n\nint d[14];\nint memo[10][4][2][1 << 14];\nbool solve(int p, int cnt, bool r,int u) {\n\tif (memo[p][cnt][r][u] != -1)return memo[p][cnt][r][u];\n\tbool ok = false;\n\tif (cnt == 3) {\n\t\tint f = -1, s = -1;\n\t\trep(i, 14) {\n\t\t\tif (!(u>>i&1)) {\n\t\t\t\tif (f == -1)f = d[i];\n\t\t\t\telse if (s == -1)s = d[i];\n\t\t\t\telse ok = true;\n\t\t\t}\n\t\t}\n\t\tif (!ok) {\n\t\t\tif (f == s)return memo[p][cnt][r][u]=true;\n\t\t\treturn memo[p][cnt][r][u]=false;\n\t\t}\n\t\tok = true; cnt = 0;\n\t}\n\trep(i, 14) {\n\t\tif (!(u>>i&1) && (ok || (r&&d[i] == p + 1) || (!r&&d[i] == p))) {\n\t\t\tu |= 1 << i;\n\t\t\tif (solve(d[i], cnt + 1, r,u))return memo[p][cnt][r][u]=true;\n\t\t\tif (ok) {\n\t\t\t\tif (solve(d[i], cnt + 1, !r,u))return memo[p][cnt][r][u]=true;\n\t\t\t}\n\t\t\tu ^= 1 << i;\n\t\t}\n\t}\n\treturn memo[p][cnt][r][u]=false;\n}\nint main() {\n\twhile (1) {\n\t\tint cnt[10]{};\n\t\trep(i, 13) {\n\t\t\tif (!~scanf(\"%1d\", &d[i]))return 0;\n\t\t\tcnt[d[i]]++;\n\t\t}\n\t\tbool flag = false;\n\t\tfor (int i = 1; i <= 9; i++) {\n\t\t\tif (cnt[i] >= 4)continue;\n\t\t\td[13] = i;\n\t\t\tmemset(memo, -1, sizeof(memo));\n\t\t\tif (solve(0, 3, 0, 0)) {\n\t\t\t\tif (flag)printf(\" \");\n\t\t\t\tprintf(\"%d\", i);\n\t\t\t\tflag = true;\n\t\t\t}\n\t\t}\n\t\tif (!flag)printf(\"0\");\n\t\tprintf(\"\\n\");\n\t}\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 8312, "score_of_the_acc": -1.0441, "final_rank": 17 }, { "submission_id": "aoj_0043_2140759", "code_snippet": "#include<bits/stdc++.h>\n#define rep(i,n)for(int i=0;i<n;i++)\nusing namespace std;\n\nint d[14];\nbool used[14];\nbool solve(int p, int cnt, bool r) {\n\tbool ok = false;\n\tif (cnt == 3) {\n\t\tint f = -1, s = -1;\n\t\trep(i, 14) {\n\t\t\tif (!used[i]) {\n\t\t\t\tif (f == -1)f = d[i];\n\t\t\t\telse if (s == -1)s = d[i];\n\t\t\t\telse ok = true;\n\t\t\t}\n\t\t}\n\t\tif (!ok) {\n\t\t\tif (f == s)return true;\n\t\t\treturn false;\n\t\t}\n\t\tok = true; cnt = 0;\n\t}\n\trep(i, 14) {\n\t\tif (!used[i] && (ok || (r&&d[i] == p + 1) || (!r&&d[i] == p))) {\n\t\t\tused[i] = true;\n\t\t\tif (solve(d[i], cnt + 1, r))return true;\n\t\t\tif (ok) {\n\t\t\t\tif (solve(d[i], cnt + 1, !r))return true;\n\t\t\t}\n\t\t\tused[i] = false;\n\t\t}\n\t}\n\treturn false;\n}\nint main(){\n\twhile (1) {\n\t\tint cnt[10]{};\n\t\trep(i, 13) {\n\t\t\tif (!~scanf(\"%1d\", &d[i]))return 0;\n\t\t\tcnt[d[i]]++;\n\t\t}\n\t\tbool flag = false;\n\t\tfor (int i = 1; i <= 9; i++) {\n\t\t\tif (cnt[i] >= 4)continue;\n\t\t\td[13] = i;\n\t\t\tmemset(used, 0, sizeof(used));\n\t\t\tif (solve(0, 3, 0)) {\n\t\t\t\tif (flag)printf(\" \");\n\t\t\t\tprintf(\"%d\", i);\n\t\t\t\tflag = true;\n\t\t\t}\n\t\t}\n\t\tif (!flag)printf(\"0\");\n\t\tprintf(\"\\n\");\n\t}\n}", "accuracy": 1, "time_ms": 520, "memory_kb": 3072, "score_of_the_acc": -1.0149, "final_rank": 16 }, { "submission_id": "aoj_0043_1979953", "code_snippet": "#define\t_USE_MATH_DEFINES\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <functional>\n#include <vector>\n#include <cstdio>\n#include <cstring>\n#include <cmath>\n#include <cfloat>\n#include <map>\n#include <queue>\n#include <stack>\n#include <list>\n#include <string>\n#include <set>\n#include <complex>\n#include <utility>\n#include <numeric>\n#define rep(i,n) for(int i=0;i<(n);i++)\n#define REP(i,a,n) for(int i=a;i<(n);i++)\n#define rrep(i,n) for(int i=(n)-1;i>=0;i--)\n#define VI\tvector<int>\n#define\t VS vector<string>\n#define all(a) (a).begin(),(a).end()\n#define debug(x) cout<<#x<<\": \"<<x<<endl\nusing namespace std;\ntypedef long long ll;\n\nconst int INF=1e9;\nchar fi[101][101];\nint day[12]={31,28,31,30,31,30,31,31,30,31,30,31};\ndouble EPS = 1e-10;\nint N,M;\nint sx,sy;\nint gx,gy;\nint w,h;\nint ans;\nint dx[4]={0,0,-1,1};\nint dy[4]={-1,1,0,0};\nconst int MAX_V=100;\nconst int MAX_N=100;\nchar o[3]={'+','-','*'};\n#define md 1000003\n\n\nint dp[353][353]={0};\nint bow[353][353]={0};\ndouble add(double a,double b){\n\tif(abs(a+b)<EPS*(abs(a)+abs(b)))\n\treturn 0;\n\treturn a+b;\n}\n\nstruct P{\n\tdouble x,y;\n\tP(){}\n\t\tP(double x,double y):x(x),y(y){\n\t\t}\n\t\tP operator + (P p){\n\t\t\treturn P(add(x,p.x),add(y,p.y));\n\t\t}\n\t\tP operator - (P p){\n\t\t\treturn P(add(x,-p.x),add(y,-p.y));\n\t\t}\n\t\tP operator *(double d){\n\t\t\treturn P(x*d,y*d);\n\t\t}\n\t\tdouble dot(P p){\n\t\t\treturn add(x*p.x,y*p.y);\n\t\t}\n\t\tdouble det(P p){\n\t\t\treturn add(x*p.y,-y*p.x);\n\t\t}\n};\n\nbool cmp_x(const P& p,const P& q){\n\tif(p.x!=q.x) return p.x<q.x;\n\treturn p.y<q.y;\n}\n\nvector<P> convex_hull(P* ps, int n){\n\tsort(ps,ps+n,cmp_x);\n\tint k=0;\n\tvector<P> \tqs(n*2);\n\t\n\trep(i,n){\n\t\twhile(k>1&&(qs[k-1]-qs[k-2]).det(ps[i]-qs[k-1])<=0)\n\t\t\tk--;\n\t\tqs[k++]=ps[i];\n\t}\n\tfor(int i=n-2,t=k;i>=0;i--){\n\t\twhile(k>t&&(qs[k-1]-qs[k-2]).det(ps[i]-qs[k-1])<=0)\n\t\tk--;\n\t\tqs[k++]=ps[i];\n\t}\n\tqs.resize(k-1);\n\treturn qs;\n}\n\nint n,m;\nvector<double> p;\nP ps[101];\nchar c[520][520];\nlong long mod=1000000007;\nlong long pow(ll i,ll j){\n\tll tmp=1;\n\twhile(j){\n\t\tif(j%2) tmp=tmp*i%mod;\n\t\ti=i*i%mod;\n\t\tj/=2;\n\t}\n\treturn tmp;\n}\nint cards[10];\nbool ok;\nvoid saiki(int deep){\n\tif(deep==4){\n\t\tok=true;\n\t\treturn;\n\t}\n\tfor(int i=1;i<=7;i++){\n\t\tif(cards[i]>0&&cards[i+1]>0&&cards[i+2]>0){\n\t\t\tcards[i]--;\n\t\t\tcards[i+1]--;\n\t\t\tcards[i+2]--;\n\t\t\tsaiki(deep+1);\n\t\t\tcards[i]++;\n\t\t\tcards[i+1]++;\n\t\t\tcards[i+2]++;\n\t\t}\n\t\tfor(int i=1;i<=9;i++){\n\t\t\tif(cards[i]>2){\n\t\t\t\tcards[i]-=3;\n\t\t\t\tsaiki(deep+1);\n\t\t\t\tcards[i]+=3;\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n\nint main(){\n\t\n\tstring s;\n\twhile(cin>>s){\n\t\tfor(int i=0;i<=9;i++){\n\t\t\tcards[i]=0;\n\t\t}\n\t\tqueue<int> a;\n\t\tbool f=false;\n\t\t\n\trep(i,s.size()){\n\t\tcards[s[i]-'0']++;\n\t\tif(cards[s[i]-'0']>4){\n\t\t\tf=true;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\tif(!f){\n\tfor(int i=1;i<=9;i++){\n\t\tif(cards[i]<4){\n\t\t\tok=false;\n\t\t\tcards[i]++;\n\t\t\tfor(int j=1;j<=9;j++){\n\t\t\t\tif(cards[j]>1){\n\t\t\t\t\tcards[j]-=2;\n\t\t\t\t\tsaiki(0);\n\t\t\t\t\tif(ok){\n\t\t\t\t\t\ta.push(i);\n\t\t\t\t\t\tcards[j]+=2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcards[j]+=2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcards[i]--;\n\t\t}\n\t\t\t\n\t}\n\t}\n\t\tif(f||a.empty())\n\t\t\tcout<<0<<endl;\n\telse{\n\t\tcout<<a.front();\n\t\ta.pop();\n\t\twhile(!a.empty()){\n\t\t\tcout<<\" \"<<a.front();\n\t\t\ta.pop();\n\t\t}\n\t\tcout<<endl;\n\t\t\n\t}\n\t}\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 1196, "score_of_the_acc": -0.0164, "final_rank": 4 }, { "submission_id": "aoj_0043_1841027", "code_snippet": "#include<iostream>\n#include<vector>\n#include<queue>\n#include<string>\nusing namespace std;\nqueue<vector<int> >Q;\nstring S; int p[14];\nint main() {\n\twhile (cin >> S) {\n\t\tvector<int>s; int g[10] = { 0,0,0,0,0,0,0,0,0,0 };\n\t\tfor (int i = 0; i < 13; i++) {\n\t\t\tp[i] = S[i] - '0'; g[p[i]]++;\n\t\t}\n\t\tfor (int i = 0; i < 10; i++)s.push_back(g[i]);\n\t\ts.push_back(1); int f[10] = { 0,0,0,0,0,0,0,0,0,0 };\n\t\tfor (int h = 1; h < 10; h++) {\n\t\t\ts[h]++; Q.push(s); int OK = 0;\n\t\t\twhile (!Q.empty()) {\n\t\t\t\tvector<int>t = Q.front(), u; Q.pop(); int sum = 0;\n\t\t\t\tfor (int i = 0; i < 10; i++) sum += t[i];\n\t\t\t\tif (sum == 0)OK = 1;\n\t\t\t\tfor (int i = 0; i < 10; i++) {\n\t\t\t\t\tif (t[i] >= 2 && t[10] >= 1) { u = t; u[i] -= 2; u[10] = 0; Q.push(u); }\n\t\t\t\t\tif (t[i] >= 3) { u = t; u[i] -= 3; Q.push(u); }\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\t\tif (t[i] >= 1 && t[i + 1] >= 1 && t[i + 2] >= 1) {\n\t\t\t\t\t\tu = t; u[i] -= 1; u[i + 1] -= 1; u[i + 2] -= 1; Q.push(u);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < 10; i++) {\n\t\t\t\tif (s[h] >= 5)OK = 0;\n\t\t\t}\n\t\t\tf[h] = OK; s[h]--;\n\t\t}\n\t\tint V = 0;\n\t\tfor (int i = 1; i < 10; i++) {\n\t\t\tif (f[i] == 1) {\n\t\t\t\tif (V >= 1) { cout << ' '; }\n\t\t\t\tcout << i; V++;\n\t\t\t}\n\t\t}\n\t\tif (V == 0)cout << '0';\n\t\tcout << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1268, "score_of_the_acc": -0.0118, "final_rank": 2 }, { "submission_id": "aoj_0043_1590651", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nint mentu[16][3] = {\n\t{1,1,1},{2,2,2},{3,3,3},{4,4,4},{5,5,5},{6,6,6},{7,7,7},{8,8,8},{9,9,9},\n\t{1,2,3},{2,3,4},{3,4,5},{4,5,6},{5,6,7},{6,7,8},{7,8,9}\n};\n\nint main(){\n\t\n\tstring str;\n\t\n\twhile(true){\n\t\t\n\t\tint num[10], num_1[10], dummy[10];\n\t\t\n\t\tbool ans[10];\n\t\t\n\t\tcin >> str;\n\t\tif(cin.eof()){\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tnum[i] = 0;\n\t\t\tans[i] = false;\n\t\t}\n\t\t\n\t\tfor(int i = 0; i < str.size(); i++){\n\t\t\tnum[str[i] - '0']++;\n\t\t}\n\t\t\n\t\tfor(int rest = 1; rest <= 9; rest++){\n\t\t\tfor(int i = 0; i < 10; i++){\n\t\t\t\tnum_1[i] = num[i];\n\t\t\t}\n\t\t\t\n\t\t\tif(num_1[rest] >= 4){\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tnum_1[rest]++;\n\t\t\t}\n\t\t\t\n\t\t\tfor(int i = 0; i < 16; i++){\n\t\t\t\tfor(int j = i; j < 16; j++){\n\t\t\t\t\tfor(int k = j; k < 16; k++){\n\t\t\t\t\t\tfor(int l = k; l < 16; l++){\n\t\t\t\t\t\t\tfor(int m = 1; m <= 9; m++){\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor(int b = 1; b <= 9; b++){\n\t\t\t\t\t\t\t\t\tdummy[b] = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor(int a = 0; a < 3; a++){\n\t\t\t\t\t\t\t\t\tdummy[mentu[i][a]]++;\n\t\t\t\t\t\t\t\t\tdummy[mentu[j][a]]++;\n\t\t\t\t\t\t\t\t\tdummy[mentu[k][a]]++;\n\t\t\t\t\t\t\t\t\tdummy[mentu[l][a]]++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tdummy[m] += 2;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor(int b = 1; b <= 9; b++){\n\t\t\t\t\t\t\t\t\tif(num_1[b] != dummy[b]){\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(b == 9){\n\t\t\t\t\t\t\t\t\t\tans[rest] = true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\tcout << \" \";\n\t\t\t\n\t\t\tfor(int i = 1; i <= 9; i++){\n\t\t\t\tcout << dummy[i];\n\t\t\t}\n\t\t\t*/\n\t\t\t\n\t\t}\n\t\t\n\t\tint loop;\n\t\t\n\t\tbool found;\n\t\t\n\t\tfound = false;\n\t\t\n\t\tfor(loop = 1; loop <= 9; loop++){\n\t\t\tif(ans[loop]){\n\t\t\t\tcout << loop;\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(loop = loop + 1; loop <= 9; loop++){\n\t\t\tif(ans[loop]){\n\t\t\t\tcout << \" \" << loop;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!found){\n\t\t\tcout << \"0\";\n\t\t}\n\t\tcout << endl;\n\t\t\n\t}\n\t\n\treturn 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 1184, "score_of_the_acc": -0.0441, "final_rank": 7 }, { "submission_id": "aoj_0043_1360445", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\ntypedef unsigned long long ull;\n#define loop(i,a,b) for(int i=(a);i<ull(b);++i)\n#define rep(i,n) loop(i,0,n)\n#define all(a) (a).begin(), (a).end()\n\nbool ok(int i, int j){\n\treturn i == j && i < 9;\n}\n\nint main(){\n\tstring s;\n\tvector<vector<int> > a, b;\n\tfor(int i=1; i < 10; i++){\n\t\tvector<int> v;\n\t\tfor(int j=0; j< 2; j++) v.push_back(i);\n\t\tb.push_back(v);\n\t\tv.push_back(i);\n\t\ta.push_back(v);\n\t}\n\tfor(int i=1; i <= 7; i++){\n\t\tvector<int> v;\n\t\tfor(int j=0; j < 3; j++) v.push_back(i+j);\n\t\ta.push_back(v);\n\t}\n\n\twhile(cin >> s){\n\t\tint c[10] = {0};\n\t\tfor(int i=0; i < s.size(); i++) c[s[i]-'0']++;\n\t\tstring t = \"123456789\";\n\n\t\tvector<int> ret;\n\t\trep(q, t.size()){\n\t\t\tc[t[q]-'0']++;\n\t\t\tbool p = true;\n\t\t\trep(i, 10) if(4 < c[i]){c[t[q]-'0']--; p = false; break;}\n\t\t\tif(!p) continue;\n\t\t\tloop(i, 0, a.size())loop(j, 0, a.size()){\n\t\t\t\tif(ok(i, j)) continue;\n\t\t\t\tloop(k, 0, a.size()){\n\t\t\t\t\tif(ok(j, k) || ok(i, k)) continue;\n\t\t\t\t\tloop(l, 0, a.size()){\n\t\t\t\t\t\tif(ok(i, l) || ok(j, l) || ok(k, l)) continue;\n\t\t\t\t\t\trep(m, b.size()){\n\t\t\t\t\t\t\tif(i == m || j == m || k == m || l == m) continue;\n\t\t\t\t\t\t\tint d[10] = {0};\n\t\t\t\t\t\t\trep(n, 3){d[a[i][n]]++; d[a[j][n]]++; d[a[k][n]]++; d[a[l][n]]++;}\n\t\t\t\t\t\t\trep(n, 2) d[b[m][n]]++;\n\t\t\t\t\t\t\tbool possible = true;\n\t\t\t\t\t\t\trep(n, 10) if(c[n] != d[n]){possible = false; break;}\n\t\t\t\t\t\t\tif(possible) ret.push_back(q+1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tc[t[q]-'0']--;\n\t\t}\n\t\tint n = -1;\n\t\trep(i, ret.size()){\n\t\t\tif(n != ret[i]){cout << (i == 0 ? \"\" : \" \") << ret[i]; n = ret[i];}\n\t\t}\n\t\tif(n == -1) cout << 0;\n\t\tcout << endl;\n\t}\n}", "accuracy": 1, "time_ms": 690, "memory_kb": 1228, "score_of_the_acc": -1.0062, "final_rank": 15 }, { "submission_id": "aoj_0043_1242837", "code_snippet": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <bitset>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\ntypedef map<int, int> Num;\n\nint check2(Num a) {\n\tint sum = 0;\n\tfor (int i = 1; i <= 9; i++)\n\t\tsum += a[i];\n\treturn sum;\n}\n\nvoid check1(Num a, int n, int *ans) {\n\tif (check2(a) == 0) {\n\t\t*ans |= (0x01 << n);\n\t\treturn;\n\t}\n\n\tfor (int i = 1; i <= 9; i++) {\n\t\tif (a[i] >= 3) {\n\t\t\ta[i] -= 3;\n\t\t\tcheck1(a, n, ans);\n\t\t\ta[i] += 3;\n\t\t}\n\t}\n\n\tfor (int i = 3; i <= 9; i++) {\n\t\tif (a[i-2] && a[i-1] && a[i]) {\n\t\t\ta[i-2] -= 1;\n\t\t\ta[i-1] -= 1;\n\t\t\ta[i] -= 1;\n\t\t\tcheck1(a, n, ans);\n\t\t\ta[i-2] += 1;\n\t\t\ta[i-1] += 1;\n\t\t\ta[i] += 1;\n\t\t}\n\t}\n}\n\nint solve(Num a) {\n\tint ans = 0;\n\tfor (int i = 1; i <= 9; i++) {\n\t\tif (a[i] == 4) continue;\n\n\t\ta[i]++;\n\t\tfor (int j = 1; j <= 9; j++)\n\t\t\tif (a[j] > 1) {\n\t\t\t\ta[j] -= 2;\n\t\t\t\tcheck1(a, i, &ans);\n\t\t\t\ta[j] += 2;\n\t\t\t}\n\t\ta[i]--;\n\t}\n\treturn ans;\n}\n\nint main() {\n\tstring str;\n\twhile (cin >> str) {\n\t\tNum a;\n\t\tfor (int i = 1; i <= 9; i++)\n\t\t\ta[i] = 0;\n\t\tfor (int i = 0; i < str.size(); i++) {\n\t\t\tint s = str[i] - '0';\n\t\t\ta[s]++;\n\t\t}\n\t\tint ans = solve(a);\n\t\tif (ans == 0)\n\t\t\tcout << 0 << endl;\n\t\telse {\n\t\t\tint ifs = 0;\n\t\t\tfor (int i = 1; i <= 9; i++) {\n\t\t\t\tif (ans & (0x01 << i))\n\t\t\t\t\tcout << ((ifs++) ? \" \" : \"\") << i;\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 1188, "score_of_the_acc": -0.0153, "final_rank": 3 }, { "submission_id": "aoj_0043_1091760", "code_snippet": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <map>\n#include <vector>\nusing namespace std;\n\nstring str;\n\nbool c (map<char,int> m) {\n for (auto i = m.begin(); i != m.end(); i++) {\n if (i->second != 0) return false;\n }\n return true;\n}\n\nbool dfs(map<char,int> m) {\n if (c(m)) return true;\n for (char i = '1'; i <= '9'; i++) {\n if (m[i] >= 3) {\n m[i] -= 3;\n if (dfs (m)) return true;;\n m[i] += 3;\n }\n if (i + 2 <= '9' && m[i] > 0 && m[i+1] > 0 && m[i+2] > 0) {\n m[i]--; m[i + 1]--; m[i + 2]--;\n if (dfs(m)) return true;\n m[i]++; m[i + 1]++; m[i + 2]++;\n }\n }\n return false;\n}\n\nint main ()\n{\n while (cin >> str) {\n map<char,int> m;\n for (char i = '1' ; i <= '9'; i++) m[i] = 0;\n for (int i = 0; i < str.size(); i++) {\n m[str[i]]++;\n }\n\n vector<char> res;\n for (char i = '1'; i <= '9'; i++) {\n if (m[i] >= 4) continue;\n m[i]++;\n for (char j = '1'; j <= '9'; j++) {\n if (m[j] >= 2) {\n m[j] -= 2;\n if (dfs(m)) {\n res.push_back(i);\n m[j] += 2;\n break;\n }\n m[j] += 2;\n }\n }\n m[i]--;\n }\n if (res.size()) {\n cout << res[0];\n for (int i = 1; i < res.size(); i++) cout << \" \" << res[i];\n } else cout << 0;\n cout << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1204, "score_of_the_acc": -0.0028, "final_rank": 1 }, { "submission_id": "aoj_0043_1053767", "code_snippet": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <cstring>\n#include <string>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <map>\n#include <set>\n#include <bitset>\n#include <numeric>\n#include <utility>\n#include <iomanip>\n#include <algorithm>\n#include <functional>\nusing namespace std;\n\ntypedef long long ll;\ntypedef vector<int> vint;\ntypedef vector<long long> vll;\ntypedef pair<int,int> pint;\ntypedef pair<long long, long long> pll;\n\n#define MP make_pair\n#define PB push_back\n#define ALL(s) (s).begin(),(s).end()\n#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)\n#define COUT(x) cout << #x << \" = \" << (x) << \" (L\" << __LINE__ << \")\" << endl\n\ntemplate<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }\ntemplate<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }\ntemplate<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P) \n{ return s << '<' << P.first << \", \" << P.second << '>'; }\ntemplate<class T> ostream& operator << (ostream &s, vector<T> P) \n{ for (int i = 0; i < P.size(); ++i) { if (i > 0) { s << \" \"; } s << P[i]; } return s << endl; }\ntemplate<class T1, class T2> ostream& operator << (ostream &s, map<T1,T2> P) \n{ EACH(it, P) { s << \"<\" << it->first << \"->\" << it->second << \"> \"; } return s << endl; }\n\n\nstring str;\nset<vint> se;\n\nint main() {\n se.clear();\n \n int j[4];\n for (int i = 1; i <= 9; ++i) {\n for (j[0] = 1; j[0] <= 16; ++j[0]) {\n for (j[1] = 1; j[1] <= 16; ++j[1]) {\n for (j[2] = 1; j[2] <= 16; ++j[2]) {\n for (j[3] = 1; j[3] <= 16; ++j[3]) {\n vint tmp(9, 0);\n tmp[i-1] = 2;\n for (int k = 0; k < 4; ++k) {\n if (j[k] <= 9) tmp[j[k]-1] += 3;\n else {\n tmp[j[k]-10]++;\n tmp[j[k]-9]++;\n tmp[j[k]-8]++;\n }\n }\n bool check = true;\n for (int l = 0; l < 9; ++l) if (tmp[l] > 4) check = false;\n if (check) se.insert(tmp);\n }\n }\n }\n }\n }\n \n while (cin >> str) {\n vint vec(9, 0);\n for (int i = 0; i < str.size(); ++i) vec[ str[i]-'1' ]++;\n vint res;\n for (int add = 1; add <= 9; ++add) {\n vint tmp = vec;\n tmp[add-1]++;\n if (se.count(tmp)) res.PB(add);\n }\n \n if (res.size() == 0) cout << \"0\";\n else {\n for (int i = 0; i < res.size(); ++i) {\n cout << res[i];\n if (i != res.size()-1) cout << \" \";\n }\n }\n cout << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 70, "memory_kb": 2660, "score_of_the_acc": -0.2953, "final_rank": 13 }, { "submission_id": "aoj_0043_948775", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef map<char, int> State;\n\nbool finished(State &m){\n for(char c = '1' ; c <= '9' ; c++){\n if(m[c]) return false;\n }\n return true;\n}\n\nbool bfs(string s){\n State start;\n for(int i = 0 ; i < (int)s.size() ; i++){\n start[s[i]]++;\n if(start[s[i]] > 4) return false;\n }\n queue<State> que;\n for(char c = '1' ; c <= '9' ; c++){\n if(start[c] >= 2){\n State nex = start;\n nex[c] -= 2;\n que.push(nex); \n }\n }\n \n while(!que.empty()){\n State q = que.front(); que.pop();\n \n if(finished(q)) return true;\n \n for(char c = '1' ; c <= '9' ; c++){\n if(q[c] >= 3){\n\tState nex = q;\n\tnex[c] -= 3;\n\tque.push(nex);\n }\n }\n for(char c = '1' ; c <= '7' ; c++){\n if(q[c] >= 1 && q[c+1] >= 1 && q[c+2] >= 1){\n\tState nex = q;\n\tnex[c] -= 1, nex[c+1] -= 1, nex[c+2] -= 1;\n\tque.push(nex);\n }\n }\n }\n return false;\n}\n\nint main(){\n string s;\n while(cin >> s){\n vector<char> ans;\n for(char c = '1' ; c <= '9' ; c++){\n if(bfs(s + c)) ans.push_back(c);\n }\n if(ans.size() == 0) cout << 0 << endl;\n else{\n for(int i = 0 ; i < (int)ans.size() ; i++){\n\tcout << ans[i];\n\tif(i == (int)ans.size()-1) cout << endl;\n\telse cout << ' ';\n }\n }\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 1288, "score_of_the_acc": -0.0293, "final_rank": 6 }, { "submission_id": "aoj_0043_899145", "code_snippet": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nvector<int> a(14);\nbool solve(int x, int y);\nint main(){\n string s;\n while(cin >>s){\n vector<int> ans;\n for(int i=1; i<10; i++){\n int n[10]={};\n bool f = true;\n for(int j=0; j<s.size(); j++) a[j] = s[j]-'0';\n a[13] = i;\n sort(a.begin(),a.end());\n for(int j=0; j<a.size(); j++) n[a[j]]++;\n for(int j=1; j<10; j++) if(n[j]>4) f = false;\n if(f) if(solve(1,4)) ans.push_back(i);\n }\n if(ans.size() == 0) cout <<\"0\"<<endl;\n else{\n for(int i=0; i<ans.size(); i++){\n\tif(i != 0) cout <<\" \";\n\tcout <<ans[i];\n }\n cout <<endl;\n }\n }\n}\nbool solve(int x, int y){\n int ans = false;\n if(x == 0 && y == 0) return true;\n if(x == 1){\n for(int i=0; i<13; i++){\n if(a[i] == -1) continue;\n if(a[i] == a[i+1]){\n\tint sc = a[i];\n\ta[i] = a[i+1] = -1;\n\tans = ans|solve(0,y);\n\ta[i] = a[i+1] = sc;\n }\n }\n }\n if(y != 0){\n for(int i=0; i<12; i++){\n if(a[i] == -1) continue;\n if(a[i] == a[i+1] && a[i+1] == a[i+2]){\n\tint sc = a[i];\n\ta[i] = a[i+1] = a[i+2] = -1;\n\tans = ans|solve(x,y-1);\n\ta[i] = a[i+1] = a[i+2] = sc;\n }\n for(int j=i+1; j<13; j++){\n\tif(a[j]!=a[i]+1) continue;\n\tfor(int k=j+1; k<14; k++){\n\t if(a[k]!=a[j]+1) continue;\n\t int sc = a[i];\n\t a[i] = a[j] = a[k] = -1;\n\t ans = ans|solve(x,y-1);\n\t a[i] = sc; a[j] = sc+1; a[k] = sc+2;\n\t}\n }\n }\n }\n return ans;\n}", "accuracy": 1, "time_ms": 170, "memory_kb": 1204, "score_of_the_acc": -0.2381, "final_rank": 11 }, { "submission_id": "aoj_0043_860578", "code_snippet": "#include<stdio.h>\n#include<string.h>\n#include<set>\n#include<vector>\n\nstd::set<std::vector<int> > all;\n\nvoid search(std::vector<int> count,int p,int cPerm[2]){\n\tif(p==10&&(cPerm[0]+cPerm[1]==0)){\n\t\tall.insert(count);\t\t\n\t}else{\n\t\tif(count[p]<=2&&cPerm[0]>0){\n\t\t\tcPerm[0]=0;\n\t\t\tcount[p]+=2;\n\t\t\tsearch(count,p,cPerm);\n\t\t\tcount[p]-=2;\n\t\t\tcPerm[0]=1;\n\t\t}\n\t\tif(count[p]<=1&&cPerm[1]>0){\n\t\t\tcPerm[1]--;\n\t\t\tcount[p]+=3;\n\t\t\tsearch(count,p,cPerm);\n\t\t\tcount[p]-=3;\n\t\t\tcPerm[1]++;\n\t\t}\n\t\tif(p<=7&&count[p]<4&&cPerm[1]>0){\n\t\t\tcPerm[1]--;\n\t\t\tcount[p]++;\n\t\t\tcount[p+1]++;\n\t\t\tcount[p+2]++;\n\t\t\tsearch(count,p,cPerm);\n\t\t\tcount[p]--;\n\t\t\tcount[p+1]--;\n\t\t\tcount[p+2]--;\n\t\t\tcPerm[1]++;\n\t\t}\n\t\tif(count[p]<=4)search(count,p+1,cPerm);\n\t}\n}\n\nint main(){\n\tchar text[15];\n\tstd::vector<int> count;\n\tint cPerm[2]={1,4};\n\tfor(int i=0;i<=9;i++)count.push_back(0);\n\tsearch(count,1,cPerm);\n\twhile(scanf(\"%s\",text)!=EOF){\n\t\tfor(int i=0;i<=9;i++)count[i]=0;\n\t\tfor(int i=0;text[i]!='\\0';i++)count[text[i]-'0']++;\n\t\tbool isFirst=true;\n\t\t\n\t\tfor(int i=1;i<=9;i++){\n\t\t\tcount[i]++;\n\t\t\tif(all.find(count)!=all.end()){\n\t\t\t\tif(isFirst==true){\n\t\t\t\t\tisFirst=false;\n\t\t\t\t}else{\n\t\t\t\t\tprintf(\" \");\n\t\t\t\t}\n\t\t\t\tprintf(\"%d\",i);\n\t\t\t}\n\t\t\tcount[i]--;\n\t\t}\n\t\tprintf(\"%s\",isFirst?\"0\\n\":\"\\n\");\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 2480, "score_of_the_acc": -0.1818, "final_rank": 10 }, { "submission_id": "aoj_0043_764761", "code_snippet": "#include<iostream>\n#include<cstdio>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nvector<int> a(14),b(14);\nbool five();\nbool tempy(int x, int y);\nint main(){\n for(;;){\n vector<int> ans;\n if(scanf(\"%1d\",&a[0]) == EOF) break;\n for(int i=1; i<13; i++) scanf(\"%1d\",&a[i]);\n for(int i=1; i<=9; i++){\n a[13] = i;\n for(int j=0; j<14; j++) b[j] = a[j];\n sort(b.begin(),b.end());\n if(five()) continue;\n if(tempy(1,4)) ans.push_back(i); \n }\n if(ans.empty()) ans.push_back(0);\n for(int i=0; i<ans.size(); i++){\n if(i != 0) cout <<\" \";\n cout <<ans[i];\n }\n cout <<endl;\n }\n return 0;\n}\nbool five(){\n for(int i=0,j=0,k=0; i<14; i++){\n if(b[i] != j){j=b[i];k = 1;}\n else k++;\n if(k == 5) return true;\n }\n return false;\n}\nbool tempy(int x, int y){\n if(x == 0 && y == 0) return true;\n for(int i=0; i<14; i++){\n if(b[i] == 0) continue;\n if(x != 0){\n for(int j=i+1; j<14; j++){\n\tif(b[i] != b[j]) continue;\n\tint q = b[i];\n\tb[i] = b[j] = 0;\n\tif(tempy(0,y)) return true;\n\tb[i] = b[j] = q;\n\tbreak;\n }\n }\n if(y != 0){\n for(int j=i+1; j<14; j++){\n\tif(b[i] != b[j]) continue;\n\tfor(int k=j+1; k<14; k++){\n\t if(b[i] != b[k]) continue;\n\t int q = b[i];\n\t b[i] = b[j] = b[k] = 0;\n\t if(tempy(x,y-1)) return true;\n\t b[i] = b[j] = b[k] = q;\n\t goto flag_pon;\n\t}\n }\n flag_pon:;\n for(int j=i+1; j<14; j++){\n\tif(b[i]+1 != b[j]) continue;\n\tfor(int k=j+1; k<14; k++){\n\t if(b[i]+2 != b[k]) continue;\n\t int q = b[i];\n\t b[i] = b[j] = b[k] = 0;\n\t if(tempy(x,y-1)) return true;\n\t b[i] = q;b[j] = q+1;b[k] = q+2;\n\t goto flag_chi;\n\t}\n }\n flag_chi:;\n }\n }\n return false;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 1232, "score_of_the_acc": -0.0214, "final_rank": 5 }, { "submission_id": "aoj_0043_582316", "code_snippet": "#include<iostream>\n#include<string>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nvector<int> h(14),a(13);\nvector<bool> hf(14);\nbool ten(int x, int y);\nint main(){\n string s;\n while(cin >>s){\n bool f = false;\n for(int i=0; i<13; i++) a[i] = s[i]-'0';\n for(int i=1; i<=9; i++){\n int lot[10]={0};\n bool ax = true;\n for(int j=0; j<13; j++) h[j] = a[j];\n h[13] = i;\n for(int j=0; j<14; j++){hf[j] = true;lot[h[j]]++;}\n for(int j=1; j<10; j++) if(lot[j]>4) ax = false;\n if(ax){\n\tsort(h.begin(),h.end());\n\tif(ten(4,1)){\n\t if(f) cout <<\" \";\n\t cout <<i;\n\t f = true;\n\t}\n }\n }\n if(!f) cout <<\"0\";\n cout <<endl;\n }\n return 0;\n}\nbool ten(int x, int y){\n bool f=false;\n if(x == 0 && y == 0) return true;\n for(int i=0; i<14; i++){\n if(hf[i]){\n if(y!=0){\n\tfor(int j=i+1; j<14; j++){\n\t if(hf[j] && h[i] == h[j]){\n\t hf[i] = hf[j] = false;\n\t f|=ten(x,0);\n\t if(f) return f;\n\t hf[i] = hf[j] = true;\n\t break;\n\t }\n\t else if(h[i]!=h[j]) break;\n\t}\n }\n if(x!=0){\n\tfor(int j=i+1; j<14; j++){\n\t if(hf[j] && h[i] == h[j]){\n\t for(int k=j+1; k<14; k++){\n\t if(hf[k] && h[i] == h[k]){\n\t\thf[i] =\thf[j] = hf[k] = false;\n\t\tf|=ten(x-1,y);\n\t\tif(f) return f;\n\t\thf[i] = hf[j] = hf[k] = true;\n\t\tbreak;\n\t }\n\t else if(h[i]!=h[k]) break;\n\t }\n\t }\n\t else if(h[i]!=h[j]) break;\n\t}\n\tfor(int j=i+1; j<14; j++){\n\t if(hf[j] && h[i]+1 == h[j]){\n\t for(int k=j+1; k<14; k++){\n\t if(hf[k] && h[i]+2 == h[k]){\n\t\thf[i] =\thf[j] = hf[k] = false;\n\t\tf|=ten(x-1,y);\n\t\tif(f) return f;\n\t\thf[i] = hf[j] = hf[k] = true;\n\t\tbreak;\n\t }\n\t else if(h[i]+2<h[k]) break;\n\t }\n\t }\n\t else if(h[i]+1<h[j]) break;\n\t}\n }\n }\n }\n return f;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 1200, "score_of_the_acc": -0.0464, "final_rank": 8 }, { "submission_id": "aoj_0043_582313", "code_snippet": "#include<iostream>\n#include<string>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nvector<int> h(14);\nvector<bool> hf(14);\nbool ten(int x, int y);\nint main(){\n string s;\n while(cin >>s){\n bool f = false;\n vector<int> a(13);\n for(int i=0; i<13; i++) a[i] = s[i]-'0';\n for(int i=1; i<=9; i++){\n int lot[10]={0};\n bool ax = true;\n for(int j=0; j<13; j++) h[j] = a[j];\n h[13] = i;\n for(int j=0; j<14; j++){\n\thf[j] = true;\n\tlot[h[j]]++;\n }\n for(int j=1; j<10; j++) if(lot[j]>4) ax = false;\n if(ax){\n\tsort(h.begin(),h.end());\n\tif(ten(4,1)){\n\t if(f) cout <<\" \";\n\t cout <<i;\n\t f = true;\n\t}\n }\n }\n if(!f) cout <<\"0\";\n cout <<endl;\n }\n return 0;\n}\nbool ten(int x, int y){\n bool f=false;\n if(x == 0 && y == 0) return true;\n for(int i=0; i<14; i++){\n if(hf[i]){\n if(y!=0){\n\tfor(int j=i+1; j<14; j++){\n\t if(hf[j] && h[i] == h[j]){\n\t hf[i] = false;\n\t hf[j] = false;\n\t f|=ten(x,0);\n\t if(f) return f;\n\t hf[i] = true;\n\t hf[j] = true;\n\t break;\n\t }\n\t else if(h[i]!=h[j]) break;\n\t}\n }\n if(x!=0){\n\tfor(int j=i+1; j<14; j++){\n\t if(hf[j] && h[i] == h[j]){\n\t for(int k=j+1; k<14; k++){\n\t if(hf[k] && h[i] == h[k]){\n\t\thf[i] = false;\n\t\thf[j] = false;\n\t\thf[k] = false;\n\t\tf|=ten(x-1,y);\n\t\tif(f) return f;\n\t\thf[i] = true;\n\t\thf[j] = true;\n\t\thf[k] = true;\n\t\tbreak;\n\t }\n\t else if(h[i]!=h[k]) break;\n\t }\n\t }\n\t else if(h[i]!=h[j]) break;\n\t}\n\tfor(int j=i+1; j<14; j++){\n\t if(hf[j] && h[i]+1 == h[j]){\n\t for(int k=j+1; k<14; k++){\n\t if(hf[k] && h[i]+2 == h[k]){\n\t\thf[i] = false;\n\t\thf[j] = false;\n\t\thf[k] = false;\n\t\tf|=ten(x-1,y);\n\t\tif(f) return f;\n\t\thf[i] = true;\n\t\thf[j] = true;\n\t\thf[k] = true;\n\t\tbreak;\n\t }\n\t else if(h[i]+2<h[k]) break;\n\t }\n\t }\n\t else if(h[i]+1<h[j]) break;\n\t}\n }\n }\n }\n return f;\n}", "accuracy": 1, "time_ms": 50, "memory_kb": 1200, "score_of_the_acc": -0.0611, "final_rank": 9 } ]
aoj_0072_cpp
灯篭 会津若松市は「歴史の町」として知られています。今から約 400 年前、蒲生氏郷により城下町の骨格が作られましたが、その後、徳川三代将軍家光公の異母弟「保科正之」公を藩祖とする会津藩 23 万石の中心都市として発展しました。今でも市内のいたるところに史跡や昔日の面影が残っているため、毎年、全国から多くの観光客が訪れています。 今年は、NHK大河ドラマで「新選組!」が放送されているため、新選組ゆかりの地(*1)として、大幅に観光客が増加しています。そこで市では、市内に点在する史跡を結ぶ通り沿いに 100 m 間隔で灯篭を設置して飾りたてることにしました。灯篭を飾ってある通りを辿れば市内の全ての史跡に到達できるように設置することが条件ですが、一筆書きでたどれる必要はありません。しかし、予算が限られているので設置する灯篭の数を最小限にする必要があります。 史跡と史跡を結ぶ通りのデータを読み込んで、必要最小限の灯篭の数を出力するプログラムを作成して下さい。ただし、史跡と史跡の間の距離は 200 m 以上で、100 の倍数で与えられます。おのおのの史跡から一番近い灯篭までの距離は 100 m で、市内の史跡は 100 箇所以内です。史跡自身には灯篭を設置する必要はありません。 (*1) 新選組は会津藩御預という形で発足、白虎隊の悲劇で知られる会津戊辰戦争に参戦、市内天寧寺に土方歳三が近藤勇の墓を建立 Input 複数のデータセットが与えられます。各データセットは以下の形式で与えられます。 n m a 1 , b 1 , d 1 a 2 , b 2 , d 2 : a m , b m , d m 各データセットの最初の 1 行には史跡の箇所数 n が与えられます。続いて史跡と史跡を結ぶ通りの数 m が与えられます。続く m 行に カンマで区切られてた3 つの数数 a i , b i , d i が与えられます。 a i , b i は史跡の番号です。史跡の番号は 0 番から n - 1 番まで振られています。 a i b i はそれらを結ぶ通りがあることを示し、 d i は a i b i 間の道路の距離を表します。 n が 0 のとき入力の最後とします。データセットの数は 20 を超えません。 Output 各データセットに対して、必要最小限の灯篭の数を1行に出力して下さい。 Sample Input 4 4 0,1,1500 0,2,2000 1,2,600 1,3,500 0 Output for the Sample Input 23
[ { "submission_id": "aoj_0072_1759212", "code_snippet": "// 0072\n#include <iostream>\n#include <vector>\n#include <stdio.h>\n#include <stdlib.h>\nusing namespace std;\n\nstruct road{\n\tint dis;\n\tint v1;\n\tint v2;\n};\n\n\nint findSet(int x, vector<int> &p){\n\tif(x != p[x])\n\t\tp[x] = findSet(p[x], p);\n\treturn p[x];\n}\n\nbool isSameSet(int x, int y, vector<int> &p){\n\treturn findSet(x, p) == findSet(y, p);\n}\n\nvoid link(int x, int y, vector<int> &p, vector<int> &rank){\n\tif(rank[x] > rank[y]){\n\t\tp[y] = x;\n\t}else{\n\t\tp[x] = y;\n\t\tif(rank[x] == rank[y])\n\t\t\trank[y]++;\n\t}\n}\n\nvoid unite(int x, int y, vector<int> &p, vector<int> &rank){\n\tlink(findSet(x, p), findSet(y, p), p, rank);\n}\n\nvoid Sort(vector<road> &ver){\n\troad r;\n\tfor(int i=0;i<ver.size();i++){\n\t\tfor(int j=1;j<ver.size()-i;j++){\n\t\t\tif(ver[j-1].dis > ver[j].dis){\n\t\t\t\tr = ver[j-1];\n\t\t\t\tver[j-1] = ver[j];\n\t\t\t\tver[j] = r;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint lantern(vector<road> ver){\n\tvector<int> rank, p;\n\tfor(int i=0;i<ver.size();i++){\n\t\tp.push_back(i);\n\t\trank.push_back(0);\n\t}\n\n\tint lan = 0;\n\tfor(int i=0;i<ver.size();i++){\n\t\tif(!isSameSet(ver[i].v1, ver[i].v2, p)){\n\t\t\tlan += ver[i].dis/100-1;\n\t\t\tunite(ver[i].v1, ver[i].v2, p, rank);\n\t\t}\n\t}\n\n\treturn lan;\n}\n\nint main(){\n\twhile(1){\n\t\tint n, m, a, b, d;\n\t\tvector<road> ver;\n\t\troad v;\n\n\t\tcin>>n;\n\t\tif(n == 0)\n\t\t\tbreak;\n\n\t\tcin>>m;\n\t\tfor(int i=0;i<m;i++){\n\t\t\tscanf(\"%d,%d,%d\", &a, &b, &d);\n\t\t\tv.v1 = a;\n\t\t\tv.v2 = b;\n\t\t\tv.dis = d;\n\t\t\tver.push_back(v);\n\t\t}\n\n\t\tSort(ver);\n\t\t\n\t\tcout<<lantern(ver)<<endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 1396, "score_of_the_acc": -2, "final_rank": 4 }, { "submission_id": "aoj_0072_1731423", "code_snippet": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\nusing namespace std;\n\nint n, m;\n\nconst int INF = 1e+9;\nconst int MAX_V = 100;\nint cost[MAX_V][MAX_V];\nint mincost[MAX_V];\nbool used[MAX_V];\n\nint prim(){\n\tfor(int i=0 ; i < n ; i++ ){\n\t\tmincost[i] = INF;\n\t\tused[i] = false;\n\t}\n\tmincost[0] = 0;\n\tint res = 0;\n\t\n\twhile( true ){\n\t\tint v = -1;\n\t\tfor(int u=0 ; u < n ; u++ ){\n\t\t\tif( !used[u] && (v == -1 || mincost[u] < mincost[v]) ){\n\t\t\t\tv = u;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(v == -1) break;\n\t\tused[v] = true;\n\t\tres += mincost[v];\n\t\t\n\t\tfor(int u=0 ; u < n ; u++ ){\n\t\t\tmincost[u] = min( mincost[u] , cost[v][u] );\n\t\t}\n\t}\n\treturn res;\n}\n\n// ?????????s?????????c???????????§??????????????????\nvector<string> split_string(string s, char c){\n\tstring str;\n\tvector<string> vs;\n\ts.push_back( c );\n\t\n\tfor(int i=0 ; i < s.size() ; i++ ){\n\t\tif( s[i] == c ){\n\t\t\tif( !str.empty() ){\n\t\t\t\tvs.push_back( str );\n\t\t\t\tstr.clear();\n\t\t\t}\n\t\t}else{\n\t\t\tstr.push_back( s[i] );\n\t\t}\n\t}\n\treturn vs;\n}\n\n// string???int?????????\nint s_to_i(string s){\n\tint n=0;\n\tfor(int i=0 ; i < s.size() ; i++ ){\n\t\tn *= 10;\n\t\tn += s[i] - '0';\n\t}\n\treturn n;\n}\n\nint main(){\n\twhile( cin >> n , n ){\n\t\tfor(int u=0 ; u < n ; u++ ){\n\t\t\tfor(int v=0 ; v < n ; v++ ){\n\t\t\t\tcost[u][v] = cost[v][u] = INF;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcin >> m;\n\t\tcin.ignore();\n\t\tfor(int i=0 ; i < m ; i++ ){\n\t\t\tstring s;\n\t\t\tgetline(cin,s);\n\t\t\tvector<string> vs = split_string( s , ',' );\n\t\t\tint u = s_to_i( vs[0] );\n\t\t\tint v = s_to_i( vs[1] );\n\t\t\tint c = (s_to_i( vs[2] ) - 100) / 100;\n\t\t\tcost[u][v] = cost[v][u] = c;\n\t\t}\n\t\tint ans = prim();\n\t\tcout << ans << endl;\n\t}\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1252, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_0072_1294687", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nstruct LINE {\n\tint a;\n\tint b;\n\tint d;\n\tbool use;\n};\n\nvector<int> getconnect(vector<LINE> &lines,int n)\n{\n\tvector<int>\tr;\n\tfor(int i=0;i<lines.size();i++){\n\t\tif( lines[i].a != lines[i].b && (lines[i].a==n || lines[i].b==n) ){\n\t\t\tr.push_back(i);\n\t\t}\n\t}\n\treturn r;\n}\n\nint main() {\n\n\twhile(true){\n\n\tint n,m;\n\tcin >> n >> m;\n\tif( n==0) break;\n\t\n\tvector<LINE> lines;\n\t\n\tfor(int i=0;i<m;i++){\n\t\tLINE l;\n\t\tchar c;\n\t\tcin >> l.a >> c >> l.b >> c >> l.d;\n\t\tl.use=false;\n\t\tlines.push_back(l);\n\t}\n\n\twhile( true ){\n\n\t\tint count=0;\n\t\tfor(int i=0;i<n;i++){\n\t\t\tauto idxs=getconnect(lines,i);\n\t\t\tif( idxs.empty() ) continue;\n\n\t\t\tcount++;\n\t\t\t\n\t\t\tint mini = idxs[0];\n\t\t\tint mind = lines[mini].d;\n\t\t\tfor(int idx : idxs){\n\t\t\t\tif( lines[idx].d < mind ){\n\t\t\t\t\tmini = idx;\n\t\t\t\t\tmind = lines[idx].d;\n\t\t\t\t}\n\t\t\t}\n\t\t\tint t = lines[mini].a!=i?lines[mini].a:lines[mini].b;\n\t\t\t\n\t\t\tauto idxs2=getconnect(lines,t);\n\t\t\tfor(int idx : idxs2){\n\t\t\t\tif( lines[idx].a==t){\n\t\t\t\t\tlines[idx].a = i;\n\t\t\t\t}\n\t\t\t\tif( lines[idx].b==t){\n\t\t\t\t\tlines[idx].b = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlines[mini].use=true;\n\t\t}\n\t\tif( count==0) break;\n\t\tcount=0;\n\t}\n\n\tint ans=0;\n\tfor( auto l : lines){\n\t\tif( l.use){\n\t\t\tans += l.d/100-1;\n\t\t}\n\t}\n\tcout << ans << endl;\n\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1348, "score_of_the_acc": -0.6667, "final_rank": 2 }, { "submission_id": "aoj_0072_1078062", "code_snippet": "// 2014/09/22 Tazoe\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <algorithm>\nusing namespace std;\n\nconst int INF = 1000000000;\n\nint main()\n{\n\twhile(true){\n\t\tint n;\n\t\tcin >> n;\n\n\t\tif(n==0)\n\t\t\tbreak;\n\n\t\tint W[100][100];\n\t\tfor(int i=0; i<n; i++){\n\t\t\tfor(int j=0; j<n; j++){\n\t\t\t\tW[i][j] = INF;\n\t\t\t}\n\t\t}\n\n\t\tint m;\n\t\tcin >> m;\n\n\t\tfor(int i=0; i<m; i++){\n\t\t\tstring s;\n\t\t\tcin >> s;\n\n\t\t\tfor(int j=0; j<s.size(); j++){\n\t\t\t\tif(s[j]==','){\n\t\t\t\t\ts[j] = ' ';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tistringstream is(s);\n\t\t\tint a, b, d;\n\t\t\tis >> a >> b >> d;\n\n\t\t\tW[a][b] = W[b][a] = d;\n\t\t}\n/*\n\t\tfor(int i=0; i<n; i++){\n\t\t\tfor(int j=0; j<n; j++){\n\t\t\t\tif(W[i][j]==INF){\n\t\t\t\t\tcout << \"INF\" << ' ';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcout << W[i][j] << ' ';\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n*/\n\n\t\tint mincost[100];\n\t\tbool used[100];\n\n\t\tfor(int i=0; i<n; i++){\n\t\t\tmincost[i] = INF;\n\t\t\tused[i] = false;\n\t\t}\n\n\t\tmincost[0] = 0;\n\t\tint res = 0;\n\n\t\twhile(true){\n\t\t\tint v = -1;\n\t\t\tfor(int u=0; u<n; u++){\n\t\t\t\tif(!used[u] && (v==-1 || mincost[u]<mincost[v])){\n\t\t\t\t\tv = u;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(v==-1)\n\t\t\t\tbreak;\n\n\t\t\tused[v] = true;\n\t\t\tif(v!=0){\n\t\t\t\tres += (mincost[v]/100-1);\n\t\t\t}\n\n\t\t\tfor(int u=0; u<n; u++){\n\t\t\t\tmincost[u] = min(mincost[u], W[v][u]);\n\t\t\t}\n\t\t}\n\n\t\tcout << res << endl;\n\t}\n\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 1256, "score_of_the_acc": -1.0278, "final_rank": 3 } ]
aoj_0056_cpp
ゴールドバッハの予想 4 以上の偶数は 2 つの素数の和で表すことができるということが知られています。これはゴールドバッハ予想といい、コンピュータの計算によりかなり大きな数まで正しいことが確かめられています。例えば、10 は、7 + 3、5 + 5 の 2 通りの素数の和で表すことができます。 整数 n を入力し、 n を 2 つの素数の和で表す組み合わせ数が何通りあるかを出力するプログラムを作成してください。ただし、 n は 4 以上、50,000 以下とします。また、入力される n は偶数であるとはかぎりません。 Input 複数のデータセットが与えられます。各データセットに n が1行に与えられます。 n が 0 のとき入力の最後とします。データセットの数は 10,000 を超えません。 Output 各データセットに対して、 n を 2 つの素数の和で表す組み合わせ数を1行に出力して下さい。 Sample Input 10 11 0 Output for the Sample Input 2 0
[ { "submission_id": "aoj_0056_9629737", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(void){\n vector<int> yakusu(50001, -1);\n for(int i=2; i<=50000; i++){\n if(yakusu[i]!=-1) continue;\n int copy=i;\n while(copy<=50000){\n if(yakusu[copy]==-1) yakusu[copy]=i;\n copy+=i;\n }\n }\n vector<int> prime;\n for(int i=2; i<=50000; i++){\n if(yakusu[i]==i) prime.push_back(i);\n }\n int m=prime.size();\n map<int, int> ans;\n for(int i=0; i<m-1; i++){\n for(int j=i; j<m; j++){\n ans[prime[i]+prime[j]]++;\n }\n }\n\n int n;\n while(cin >> n){\n if(n==0) break;\n cout << ans[n] << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 710, "memory_kb": 6100, "score_of_the_acc": -2, "final_rank": 20 }, { "submission_id": "aoj_0056_9147754", "code_snippet": "#pragma region Macros\n\n#pragma GCC optimize(\"O3,unroll-loops\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2\")\n\n#include <bits/extc++.h>\n// #include <atcoder/all>\n// using namespace atcoder;\nusing namespace std;\nusing namespace __gnu_pbds;\n\n// #include <boost/multiprecision/cpp_dec_float.hpp>\n// #include <boost/multiprecision/cpp_int.hpp>\n// namespace mp = boost::multiprecision;\n// using Bint = mp::cpp_int;\n// using Bdouble = mp::number<mp::cpp_dec_float<256>>;\n// Bdouble Beps = 0.00000000000000000000000000000001; // 1e-32\n// const bool equals(Bdouble a, Bdouble b) { return mp::fabs(a - b) < Beps; }\n\n#define pb emplace_back\n#define int ll\n#define endl '\\n'\n// #define unordered_map<int, int> gp_hash_table<int, int, custom_hash> \n\n#define sqrt __builtin_sqrtl\n#define cbrt __builtin_cbrtl\n#define hypot __builtin_hypotl\n\n#define next asdnext\n#define prev asdprev\n\nusing ll = long long;\nusing ld = long double;\nconst ld PI = acosl(-1);\nconst int INF = 1 << 30;\nconst ll INFL = 1LL << 61;\n// const int MOD = 998244353;\nconst int MOD = 1000000007;\n\nconst ld EPS = 1e-10;\nconst bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }\n\nconst vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗\nconst vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};\n\nstruct Edge {\n int from, to, cost;\n Edge() : from(-1), to(-1), cost(-1) {}\n Edge(int to, int cost) : to(to), cost(cost) {}\n Edge(int from, int to, int cost) : from(from), to(to), cost(cost) {}\n bool operator ==(const Edge& e) {\n return this->from == e.from && this->to == e.to && this->cost == e.cost;\n }\n bool operator !=(const Edge& e) {\n return this->from != e.from or this->to != e.to or this->cost != e.cost;\n }\n};\n\nchrono::system_clock::time_point start;\n__attribute__((constructor))\nvoid constructor() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout << fixed << setprecision(10);\n start = chrono::system_clock::now();\n}\n\nrandom_device seed_gen;\nmt19937_64 rng(seed_gen());\nuniform_int_distribution<int> dist_x(0, 1e9);\nstruct RNG {\n unsigned Int(unsigned l, unsigned r) {\n return dist_x(rng) % (r - l + 1) + l;\n }\n ld Double() {\n return ld(dist_x(rng)) / 1e9;\n }\n} rnd;\n\nusing i64 = ll;\n// using i64 = uint64_t;\n// bit演算, x==0の場合は例外処理した方がよさそう. 区間は [l, r)\ni64 lrmask(i64 l, i64 r) { return (1LL << r) - (1LL << l); }\ni64 sub_bit(i64 x, i64 l, i64 r) { i64 b = x & ((1LL << r) - (1LL << l)); return b >> l; } // r溢れ可\ni64 bit_width(i64 x) { return 64 - __builtin_clzll(x) + (x == 0); }\n\ni64 popcount(i64 x) { return __builtin_popcountll(x); }\ni64 popcount(i64 x, i64 l, i64 r) { return __builtin_popcountll(sub_bit(x, l, r)); }\ni64 unpopcount(i64 x) { return bit_width(x) - __builtin_popcountll(x); }\ni64 unpopcount(i64 x, i64 l, i64 r) { return r - l - __builtin_popcountll(sub_bit(x, l, r)); }\nbool is_pow2(i64 x) { return __builtin_popcountll(x) == 1; }\n\ni64 top_bit(i64 x) { return 63 - __builtin_clzll(x);} // 2^kの位 (x > 0)\ni64 bot_bit(i64 x) { return __builtin_ctz(x);} // 2^kの位 (x > 0)\n// i64 next_bit(i64 x, i64 k) { return 0; }\n// i64 prev_bit(i64 x, i64 k) { return 0; }\n// i64 kth_bit(i64 x, i64 k) { return 0; }\ni64 MSB(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // mask\ni64 LSB(i64 x) { return (x & -x); } // mask\n\ni64 countl_zero(i64 x) { return __builtin_clzll(x); }\ni64 countl_one(i64 x) {\n i64 ret = 0, k = 63 - __builtin_clzll(x);\n while (k != -1 && (x & (1LL << k))) { k--; ret++; }\n return ret;\n}\ni64 countr_zero(i64 x) { return __builtin_ctzll(x); } // x==0のとき64が返ることに注意\ni64 countr_one(i64 x) { i64 ret = 0; while (x & 1) { x >>= 1; ret++; } return ret; }\n\ni64 floor_log2(i64 x) { if (x == 0) return 0; return 63 - __builtin_clzll(x); }\ni64 bit_floor(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // MSBと同じ\ni64 ceil_log2(i64 x) { if (x == 0) return 0; return 64 - __builtin_clzll(x - 1); }\ni64 bit_ceil(i64 x) { if (x == 0) return 0; return 1LL << (64 - __builtin_clzll(x - 1)); }\n\ni64 rotl(i64 x, i64 k) { // 有効bit内でrotate. オーバーフロー注意\n i64 w = bit_width(x); k %= w;\n return ((x << k) | (x >> (w - k))) & ((1LL << w) - 1);\n}\n// i64 rotl(i64 x, i64 l, i64 m, i64 r) {}\ni64 rotr(i64 x, i64 k) {\n i64 w = bit_width(x); k %= w;\n return ((x >> k) | (x << (w - k))) & ((1LL << w) - 1);\n}\n// i64 rotr(i64 x, i64 l, i64 m, i64 r) {}\ni64 bit_reverse(i64 x) { // 有効bit内で左右反転\n i64 r = 0, w = bit_width(x);\n for (i64 i = 0; i < w; i++) r |= ((x >> i) & 1) << (w - i - 1);\n return r;\n}\n// i64 bit_reverse(i64 x, i64 l, i64 r) { return 0; }\n\nbool is_palindrome(i64 x) { return x == bit_reverse(x); }\nbool is_palindrome(i64 x, i64 l, i64 r) { i64 b = sub_bit(x, l, r); return b == bit_reverse(b); }\ni64 concat(i64 a, i64 b) { return (a << bit_width(b)) | b; } // オーバーフロー注意\ni64 erase(i64 x, i64 l, i64 r) { return x>>r<<l | x&(1LL<<l - 1); } // [l, r) をカット\n\ni64 hamming(i64 a, i64 b) { return __builtin_popcountll(a ^ b); }\ni64 hamming(i64 a, i64 b, i64 l, i64 r) { return __builtin_popcountll(sub_bit(a, l, r) ^ sub_bit(b, l, r)); }\ni64 compcount(i64 x) { return (__builtin_popcountll(x ^ (x >> 1)) + (x & 1)) / 2; }\ni64 compcount2(i64 x) { return compcount(x & (x >> 1)); } // 長さ2以上の連結成分の個数\ni64 adjacount(i64 x) { return __builtin_popcountll(x & (x >> 1)); } // 隣接する1のペアの個数\n\ni64 next_combination(i64 x) {\n i64 t = x | (x - 1); return (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(x) + 1));\n}\n\n\n__int128_t POW(__int128_t x, int n) {\n __int128_t ret = 1;\n assert(n >= 0);\n if (x == 1 or n == 0) ret = 1;\n else if (x == -1 && n % 2 == 0) ret = 1; \n else if (x == -1) ret = -1; \n else if (n % 2 == 0) {\n assert(x < INFL);\n ret = POW(x * x, n / 2);\n } else {\n assert(x < INFL);\n ret = x * POW(x, n - 1);\n }\n return ret;\n}\nint per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq\n assert(y != 0);\n if (x >= 0 && y > 0) return x / y;\n if (x >= 0 && y < 0) return x / y - (x % y < 0);\n if (x < 0 && y < 0) return x / y + (x % y < 0);\n return x / y - (x % y < 0); // (x < 0 && y > 0) \n}\nint mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr\n assert(y != 0);\n if (x >= 0) return x % y;\n __int128_t ret = x % y; // (x < 0)\n ret += (__int128_t)abs(y) * INFL;\n ret %= abs(y);\n return ret;\n}\nint floor(int x, int y) { // (ld)x / y 以下の最大の整数\n assert(y != 0);\n if (y < 0) x = -x, y = -y;\n return x >= 0 ? x / y : (x + 1) / y - 1;\n}\nint ceil(int x, int y) { // (ld)x / y 以上の最小の整数\n assert(y != 0);\n if (y < 0) x = -x, y = -y;\n return x > 0 ? (x - 1) / y + 1 : x / y;\n}\nint round(int x, int y) {\n assert(y != 0);\n return (x * 2 + y) / (y * 2);\n}\nint round(int x, int y, int k) { // (ld)(x/y)を10^kの位に関して四捨五入\n assert(y != 0); // TODO\n return INF;\n}\nint round2(int x, int y) { // 五捨五超入 // 未verify\n assert(y != 0);\n if (y < 0) y = -y, x = -x;\n int z = z / y;\n if ((z * 2 + 1) * y <= y * 2) z++;\n return z;\n}\n// int round(ld x, int k) { // xを10^kの位に関して四捨五入\n// }\n// int floor(ld x, int k) { // xを10^kの位に関してflooring\n// }\n// int ceil(ld x, int k) { // xを10^kの位に関してceiling\n// }\n// int kth(int x, int y, int k) { // x / yの10^kの位の桁\n// }\nint floor(ld x, ld y) { // 誤差対策TODO\n assert(!equals(y, 0));\n return floor(x / y);\n // floor(x) = ceil(x - 1) という話も\n}\nint ceil(ld x, ld y) { // 誤差対策TODO // ceil(p/q) = -floor(-(p/q))らしい\n assert(!equals(y, 0));\n return ceil(x / y);\n // ceil(x) = floor(x + 1)\n}\nint perl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす q\n // 未verify. 誤差対策TODO. EPS外してもいいかも。\n assert(!equals(y, 0));\n if (x >= 0 && y > 0) return floor(x / y)+EPS;\n if (x >= 0 && y < 0) return -floor(x / fabs(y));\n if (x < 0 && y < 0) return floor(x / y) + (x - floor(x/y)*y < -EPS);\n return floor(x / y) - (x - floor(x/y)*y < -EPS); // (x < 0 && y > 0) \n}\nld modl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす r\n // 未verify. 誤差対策TODO. -0.0が返りうる。\n assert(!equals(y, 0));\n if (x >= 0) return x - fabs(y)*fabs(per(x, y));\n return x - fabs(y)*floor(x, fabs(y));\n}\nint seisuu(ld x) { return (int)x; } // 整数部分. 誤差対策TODO\n// 正なら+EPS, 負なら-EPSしてから、文字列に直して小数点以下を捨てる?\nint seisuu(int x, int y) {\n assert(y != 0);\n return x / y;\n}\nint seisuu(ld x, ld y) { // 誤差対策TODO\n assert(!equals(y, 0));\n return (int)(x / y);\n}\n\ntemplate <class T> pair<T, T> max(const pair<T, T> &a, const pair<T, T> &b) {\n if (a.first > b.first or a.first == b.first && a.second > b.second) return a;\n return b;\n}\ntemplate <class T> pair<T, T> min(const pair<T, T> &a, const pair<T, T> &b) {\n if (a.first < b.first or a.first == b.first && a.second < b.second) return a;\n return b;\n}\n\ntemplate <class T> bool chmax(T &a, const T& b) {\n if (a < b) { a = b; return true; } return false;\n}\ntemplate <class T> bool chmin(T &a, const T& b) {\n if (a > b) { a = b; return true; } return false;\n}\ntemplate <class T> T mid(T a, T b, T c) { // 誤差対策TODO\n return a + b + c - max({a, b, c}) - min({a, b, c});\n}\ntemplate <class T> void Sort(T &a, T &b, bool rev = false) { \n if (rev == false) { // TODO テンプレート引数\n if (a > b) swap(a, b);\n } else {\n if (b > a) swap(b, a);\n }\n}\ntemplate <class T> void sort(T &a, T &b, T &c, bool rev = false) {\n if (rev == false) { \n if (a > b) swap(a, b); if (a > c) swap(a, c); if (b > c) swap(b, c);\n } else {\n if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);\n }\n}\ntemplate <class T> void sort(T &a, T &b, T &c, T &d, bool rev = false) {\n if (rev == false) { \n if (a > b) swap(a, b); if (a > c) swap(a, c); if (a > d) swap(a, d);\n if (b > c) swap(b, c); if (b > d) swap(b, d); if (c > d) swap(c, d);\n } else {\n if (d > c) swap(d, c); if (d > b) swap(d, b); if (d > a) swap(d, a);\n if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);\n }\n}\n\nstruct custom_hash {\n static uint64_t splitmix64(uint64_t x) {\n x += 0x9e3779b97f4a7c15;\n x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n x = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n return x ^ (x >> 31);\n }\n\n size_t operator()(uint64_t x) const {\n static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n return splitmix64(x + FIXED_RANDOM);\n }\n};\n\nclass Compress {\npublic:\n int sz = 0;\n // gp_hash_table<int, int, custom_hash> Z, UZ;\n unordered_map<int, int> Z; // 元の値 -> 圧縮した値\n unordered_map<int, int> UZ; // 圧縮した値 -> 元の値\n\n Compress(const vector<int> &V, int base = 0) {\n this->sz = base;\n set<int> s(V.begin(), V.end());\n\n for (int x : s) {\n this->Z[x] = this->sz;\n this->UZ[this->sz] = x;\n this->sz++;\n }\n }\n \n Compress(const vector<int> &V1, const vector<int> &V2, int base = 0) {\n this->sz = base;\n vector<int> V3 = V2;\n V3.insert(V3.end(), V1.begin(), V1.end());\n set<int> s(V3.begin(), V3.end());\n\n for (int x : s) {\n this->Z[x] = this->sz;\n this->UZ[this->sz] = x;\n this->sz++;\n }\n }\n\n Compress(const vector<int> &V1, const vector<int> &V2, const vector<int> &V3, int base = 0) {\n this->sz = base;\n vector<int> V4 = V1;\n V4.insert(V4.end(), V2.begin(), V2.end());\n V4.insert(V4.end(), V3.begin(), V3.end());\n set<int> s(V4.begin(), V4.end());\n\n for (int x : s) {\n this->Z[x] = this->sz;\n this->UZ[this->sz] = x;\n this->sz++;\n }\n }\n\n Compress(const vector<int> &V1, const vector<int> &V2,\n const vector<int> &V3, const vector<int> &V4, int base = 0) {\n this->sz = base;\n vector<int> V5 = V1;\n V5.insert(V5.end(), V2.begin(), V2.end());\n V5.insert(V5.end(), V3.begin(), V3.end());\n V5.insert(V5.end(), V4.begin(), V4.end());\n set<int> s(V5.begin(), V5.end());\n\n for (int x : s) {\n this->Z[x] = this->sz;\n this->UZ[this->sz] = x;\n this->sz++;\n }\n }\n\n vector<int> zip(const vector<int> &V) {\n vector<int> ret = V;\n for (int i = 0; i < (int)V.size(); i++) {\n ret[i] = Z[ret[i]];\n }\n return ret;\n }\n\n vector<int> unzip(const vector<int> &V) {\n vector<int> ret = V;\n for (int i = 0; i < (int)V.size(); i++) {\n ret[i] = UZ[ret[i]];\n }\n return ret;\n }\n\n int size() { return sz; }\n\n int encode(int x) { return Z[x]; }\n int decode(int x) {\n if (UZ.find(x) == UZ.end()) return -1; // xが元の配列に存在しないとき\n return UZ[x];\n }\n};\n\nclass UnionFind {\npublic:\n\tUnionFind() = default;\n UnionFind(int N) : par(N), sz(N, 1) {\n iota(par.begin(), par.end(), 0);\n }\n\tint root(int x) {\n\t\tif (par[x] == x) return x;\n\t\treturn (par[x] = root(par[x]));\n\t}\n\tbool unite(int x, int y) {\n\t\tint rx = root(x);\n\t\tint ry = root(y);\n if (rx == ry) return false;\n\t\tif (sz[rx] < sz[ry]) swap(rx, ry);\n\t\tsz[rx] += sz[ry];\n\t\tpar[ry] = rx;\n return true;\n\t}\n\tbool issame(int x, int y) { return (root(x) == root(y)); }\n\tint size(int x) { return sz[root(x)]; }\n vector<vector<int>> groups(int N) {\n vector<vector<int>> G(N);\n for (int x = 0; x < N; x++) {\n G[root(x)].push_back(x);\n }\n\t\tG.erase( remove_if(G.begin(), G.end(),\n [&](const vector<int>& V) { return V.empty(); }), G.end());\n return G;\n }\nprivate:\n\tvector<int> par, sz;\n};\n\ntemplate<typename T>\nstruct BIT {\n int N; // 要素数\n vector<T> bit[2]; // データの格納先\n BIT(int N_, int x = 0) {\n N = N_ + 1;\n bit[0].assign(N, 0); bit[1].assign(N, 0);\n if (x != 0) {\n for (int i = 0; i < N; i++) add(i, x);\n }\n }\n BIT(const vector<int> &A) {\n N = A.size() + 1;\n bit[0].assign(N, 0); bit[1].assign(N, 0);\n for (int i = 0; i < (int)A.size(); i++) add(i, A[i]);\n }\n void add_sub(int p, int i, T x) {\n while (i < N) { bit[p][i] += x; i += (i & -i); }\n }\n void add(int l, int r, T x) {\n add_sub(0, l + 1, -x * l); add_sub(0, r + 1, x * r);\n add_sub(1, l + 1, x); add_sub(1, r + 1, -x);\n }\n void add(int i, T x) { add(i, i + 1, x); }\n T sum_sub(int p, int i) {\n T ret = 0;\n while (i > 0) { ret += bit[p][i]; i -= (i & -i); }\n return ret;\n }\n T sum(int i) { return sum_sub(0, i) + sum_sub(1, i) * i; }\n T sum(int l, int r) { return sum(r) - sum(l); }\n T get(int i) { return sum(i, i + 1); }\n void set(int i, T x) { T s = get(i); add(i, -s + x); }\n};\n\ntemplate<int mod> class Modint {\npublic:\n int val = 0;\n Modint(int x = 0) { while (x < 0) x += mod; val = x % mod; }\n Modint(const Modint &r) { val = r.val; }\n\n Modint operator -() { return Modint(-val); } // 単項\n Modint operator +(const Modint &r) { return Modint(*this) += r; }\n Modint operator +(const int &q) { Modint r(q); return Modint(*this) += r; }\n Modint operator -(const Modint &r) { return Modint(*this) -= r; }\n Modint operator -(const int &q) { Modint r(q); return Modint(*this) -= r; }\n Modint operator *(const Modint &r) { return Modint(*this) *= r; }\n Modint operator *(const int &q) { Modint r(q); return Modint(*this) *= r; }\n Modint operator /(const Modint &r) { return Modint(*this) /= r; }\n Modint operator /(const int &q) { Modint r(q); return Modint(*this) /= r; }\n \n Modint& operator ++() { val++; if (val >= mod) val -= mod; return *this; } // 前置\n Modint operator ++(signed) { ++*this; return *this; } // 後置\n Modint& operator --() { val--; if (val < 0) val += mod; return *this; }\n Modint operator --(signed) { --*this; return *this; }\n Modint &operator +=(const Modint &r) { val += r.val; if (val >= mod) val -= mod; return *this; }\n Modint &operator +=(const int &q) { Modint r(q); val += r.val; if (val >= mod) val -= mod; return *this; }\n Modint &operator -=(const Modint &r) { if (val < r.val) val += mod; val -= r.val; return *this; }\n Modint &operator -=(const int &q) { Modint r(q); if (val < r.val) val += mod; val -= r.val; return *this; }\n Modint &operator *=(const Modint &r) { val = val * r.val % mod; return *this; }\n Modint &operator *=(const int &q) { Modint r(q); val = val * r.val % mod; return *this; }\n Modint &operator /=(const Modint &r) {\n int a = r.val, b = mod, u = 1, v = 0;\n while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}\n val = val * u % mod; if (val < 0) val += mod;\n return *this;\n }\n Modint &operator /=(const int &q) {\n Modint r(q); int a = r.val, b = mod, u = 1, v = 0;\n while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}\n val = val * u % mod; if (val < 0) val += mod;\n return *this;\n }\n bool operator ==(const Modint& r) { return this -> val == r.val; }\n bool operator <(const Modint& r) { return this -> val < r.val; }\n bool operator >(const Modint& r) { return this -> val > r.val; }\n bool operator !=(const Modint& r) { return this -> val != r.val; }\n};\n\nusing mint = Modint<MOD>;\n\nistream &operator >>(istream &is, mint& x) {\n int t; is >> t; x = t; return (is);\n}\nostream &operator <<(ostream &os, const mint& x) {\n return os << x.val;\n}\nmint modpow(const mint &x, int n) {\n if (n < 0) return (mint)1 / modpow(x, -n); // 未verify\n assert(n >= 0);\n if (n == 0) return 1;\n mint t = modpow(x, n / 2);\n t = t * t;\n if (n & 1) t = t * x;\n return t;\n}\n\nint modpow(__int128_t x, int n, int mod) {\n assert(n >= 0 && mod > 0); // TODO: n <= -1\n __int128_t ret = 1;\n while (n > 0) {\n if (n % 2 == 1) ret = ret * x % mod;\n x = x * x % mod;\n n /= 2;\n }\n return ret;\n}\nint modinv(__int128_t x, int mod) {\n assert(mod > 0);\n // assert(x > 0);\n if (x == 1 or x == 0) return 1;\n return mod - modinv(mod % x, mod) * (mod / x) % mod;\n}\n\nistream &operator >>(istream &is, __int128_t& x) {\n string S; is >> S;\n __int128_t ret = 0;\n int f = 1;\n if (S[0] == '-') f = -1; \n for (int i = 0; i < S.length(); i++)\n if ('0' <= S[i] && S[i] <= '9')\n ret = ret * 10 + S[i] - '0';\n x = ret * f;\n return (is);\n}\nostream &operator <<(ostream &os, __int128_t x) {\n ostream::sentry s(os);\n if (s) {\n __uint128_t tmp = x < 0 ? -x : x;\n char buffer[128]; char *d = end(buffer);\n do {\n --d; *d = \"0123456789\"[tmp % 10]; tmp /= 10;\n } while (tmp != 0);\n if (x < 0) { --d; *d = '-'; }\n int len = end(buffer) - d;\n if (os.rdbuf()->sputn(d, len) != len) os.setstate(ios_base::badbit);\n }\n return os;\n}\n\n__int128_t stoll(string &S) {\n __int128_t ret = 0; int f = 1;\n if (S[0] == '-') f = -1; \n for (int i = 0; i < S.length(); i++)\n if ('0' <= S[i] && S[i] <= '9') ret = ret * 10 + S[i] - '0';\n return ret * f;\n}\n__int128_t gcd(__int128_t a, __int128_t b) { return b ? gcd(b, a % b) : a; }\n__int128_t lcm(__int128_t a, __int128_t b) {\n return a / gcd(a, b) * b;\n // lcmが__int128_tに収まる必要あり\n}\n\nstring to_string(ld x, int k) { // xの小数第k位までをstring化する\n assert(k >= 0);\n stringstream ss;\n ss << setprecision(k + 2) << x;\n string s = ss.str();\n if (s.find('.') == string::npos) s += '.';\n int pos = s.find('.');\n for (int i = 0; k >= (int)s.size() - 1 - pos; i++) s += '0';\n s.pop_back();\n if (s.back() == '.') s.pop_back();\n return s;\n\n // stringstream ss; // 第k+1位を四捨五入して第k位まで返す\n // ss << setprecision(k + 1) << x;\n // string s = ss.str();\n // if (s.find('.') == string::npos) s += '.';\n // int pos = s.find('.');\n // for (int i = 0; k > (int)s.size() - 1 - pos; i++) s += '0';\n // if (s.back() == '.') s.pop_back();\n // return s;\n}\nstring to_string(__int128_t x) {\n string ret = \"\";\n if (x < 0) { ret += \"-\"; x *= -1; }\n while (x) { ret += (char)('0' + x % 10); x /= 10; }\n reverse(ret.begin(), ret.end());\n return ret;\n}\nstring to_string(char c) { string s = \"\"; s += c; return s; }\n\ntemplate<class T> size_t HashCombine(const size_t seed,const T &v) {\n return seed^(hash<T>()(v)+0x9e3779b9+(seed<<6)+(seed>>2));\n}\ntemplate<class T,class S> struct hash<pair<T,S>>{\n size_t operator()(const pair<T,S> &keyval) const noexcept {\n return HashCombine(hash<T>()(keyval.first), keyval.second);\n }\n};\ntemplate<class T> struct hash<vector<T>>{\n size_t operator()(const vector<T> &keyval) const noexcept {\n size_t s=0;\n for (auto&& v: keyval) s=HashCombine(s,v);\n return s;\n }\n};\ntemplate<int N> struct HashTupleCore{\n template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{\n size_t s=HashTupleCore<N-1>()(keyval);\n return HashCombine(s,get<N-1>(keyval));\n }\n};\ntemplate <> struct HashTupleCore<0>{\n template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{ return 0; }\n};\ntemplate<class... Args> struct hash<tuple<Args...>>{\n size_t operator()(const tuple<Args...> &keyval) const noexcept {\n return HashTupleCore<tuple_size<tuple<Args...>>::value>()(keyval);\n }\n};\n\nvector<mint> _fac, _finv, _inv;\nvoid COMinit(int N) {\n _fac.resize(N + 1); _finv.resize(N + 1); _inv.resize(N + 1);\n _fac[0] = _fac[1] = 1; _finv[0] = _finv[1] = 1; _inv[1] = 1;\n for (int i = 2; i <= N; i++) {\n _fac[i] = _fac[i-1] * mint(i);\n _inv[i] = -_inv[MOD % i] * mint(MOD / i);\n _finv[i] = _finv[i - 1] * _inv[i];\n }\n}\n\nmint FAC(int N) {\n if (N < 0) return 0; return _fac[N];\n}\nmint COM(int N, int K) {\n if (N < K) return 0; if (N < 0 or K < 0) return 0;\n return _fac[N] * _finv[K] * _finv[N - K];\n}\nmint PERM(int N, int K) {\n if (N < K) return 0; if (N < 0 or K < 0) return 0;\n return _fac[N] * _finv[N - K];\n}\nmint NHK(int N, int K) { // initのサイズに注意\n if (N == 0 && K == 0) return 1;\n return COM(N + K - 1, K);\n}\n\n#pragma endregion\n\nvector<string> split_str(string S, char c) {\n vector<string> ret;\n stringstream ss;\n for (int i = 0; i < S.size(); i++) {\n if (S[i] == c) {\n ret.pb(ss.str());\n ss.str(\"\");\n ss.clear();\n } else {\n ss << S[i];\n }\n }\n ret.pb(ss.str());\n return ret;\n}\n\nvector<int> erat(int N) {\n vector<bool> prime(N + 1, true);\n prime[0] = false;\n if (N >= 1) prime[1] = false;\n\n for (int i = 2; i * i <= N; i++) {\n if (prime[i]) {\n for (int j = i + i; j <= N; j += i) {\n prime[j] = false;\n }\n }\n }\n\n vector<int> ret;\n for (int i = 2; i <= N; i++) {\n if (prime[i]) ret.pb(i);\n }\n return ret;\n}\nsigned main() {\n // string S;\n // unordered_map<string, int> mp;\n // while (cin >> S) {\n // vector<string> V = split_str(S, ',');\n // mp[V[1]]++;\n // }\n vector<int> P = erat(5e4);\n int sz = P.size();\n vector<int> dp(1e5 + 1);\n for (int i = 0; i < sz; i++) {\n for (int j = i; j < sz; j++) {\n dp[P[i] + P[j]]++;\n }\n }\n\n int x;\n while (cin >> x, x) {\n cout << dp[x] << endl;\n }\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 4116, "score_of_the_acc": -0.3616, "final_rank": 19 }, { "submission_id": "aoj_0056_8861368", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main(void) {\n vector<int> isPrime(51000 + 1, false);\n isPrime[2] = true;\n for (int i = 3; i < 51000; i += 2) {\n isPrime[i] = true;\n }\n for (int i = 3; i*i < 51000; i += 2) {\n if (isPrime[i]) {\n for (int j = i * i; j < 51000; j += i) {\n isPrime[j] = false;\n }\n }\n }\n vector<int> primes;\n primes.reserve(51000/2); // Assuming half of the numbers are prime for upper limit\n primes.push_back(2);\n for (int i = 3; i < 51000; i += 2) {\n if (isPrime[i])\n primes.push_back(i);\n }\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n int i = 0, j = primes.size() - 1;\n while (i <= j) {\n if (primes[i] + primes[j] > n) {\n j--;\n } else if (primes[i] + primes[j] < n) {\n i++;\n } else {\n kotae++;\n i++;\n j--;\n }\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 3096, "score_of_the_acc": -0.1763, "final_rank": 11 }, { "submission_id": "aoj_0056_8861367", "code_snippet": "#include <iostream>\n#include <bitset>\n#include <vector>\nusing namespace std;\n\n#define MAX 51000\n\nbitset<MAX + 1> isPrime;\nvector<int> primes;\n\nvoid generatePrimes() {\n isPrime.set(); // set all bits to 1\n isPrime[0] = isPrime[1] = false;\n primes.push_back(2);\n for (int i = 4; i <= MAX; i += 2)\n isPrime[i] = false;\n \n for (int i = 3; i * i <= MAX; i += 2) {\n if (isPrime[i]) {\n primes.push_back(i);\n for (int j = i * i; j <= MAX; j += i) {\n isPrime[j] = false;\n }\n }\n }\n for(int i = primes.back() + 2; i <= MAX; i += 2) {\n if(isPrime[i]) primes.push_back(i);\n }\n}\n\nint main(void) {\n generatePrimes();\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 0; i < primes.size() && primes[i] <= n / 2; i++) {\n if (isPrime[n - primes[i]])\n kotae++;\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3196, "score_of_the_acc": -0.0799, "final_rank": 7 }, { "submission_id": "aoj_0056_8861366", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main(void) {\n vector<int> isPrime(51000 + 1, 0);\n isPrime[2] = 1;\n for (int i = 3; i < 51000; i += 2) {\n isPrime[i] = 1;\n }\n\n // Start checking multiples from the square of each prime number\n for (int i = 3; i * i < 51000; i += 2) {\n if (isPrime[i]) {\n for (int j = i * i; j < 51000; j += i) {\n isPrime[j] = 0;\n }\n }\n }\n\n vector<int> primes;\n primes.push_back(2);\n for (int i = 3; i < 51000; i += 2) {\n if (isPrime[i])\n primes.push_back(i);\n }\n\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n // Limit prime number iteration\n for (int i = 0; primes[i] <= n / 2; i++) {\n if (isPrime[n - primes[i]])\n kotae++;\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3188, "score_of_the_acc": -0.0631, "final_rank": 3 }, { "submission_id": "aoj_0056_8861364", "code_snippet": "#include <iostream>\n#include <vector>\n#include <bitset>\nusing namespace std;\n\nint main(void) {\n const int limit = 51000;\n bitset<limit + 1> isPrime;\n isPrime[2] = true;\n for (int i = 3; i <= limit; i += 2) {\n isPrime[i] = true;\n }\n for (int i = 3; i * i <= limit; i += 2) {\n if (isPrime[i]) {\n for (int j = i * i; j <= limit; j += i) {\n isPrime[j] = false;\n }\n }\n }\n vector<int> primes;\n primes.push_back(2);\n for (int i = 3; i <= limit; i += 2) {\n if (isPrime[i])\n primes.push_back(i);\n }\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 0; i < primes.size() && primes[i] <= n / 2; i++) {\n if (isPrime[n - primes[i]])\n kotae++;\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3128, "score_of_the_acc": -0.058, "final_rank": 2 }, { "submission_id": "aoj_0056_8861363", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main(void) {\n int MAX = 51000;\n vector<bool> isPrime(MAX + 1, true); // Initialize all to true\n vector<int> primes;\n\n isPrime[0] = isPrime[1] = false; // 0 and 1 are not prime numbers\n primes.push_back(2); // Add 2 to the list of prime numbers\n\n // Sieve of Eratosthenes algorithm\n for (int i = 2; i * i <= MAX; i++) {\n if (isPrime[i]) {\n for (int j = i * i; j <= MAX; j += i) {\n isPrime[j] = false;\n }\n }\n }\n \n // Add prime numbers to the list\n for (int i = 3; i <= MAX; i += 2) {\n if (isPrime[i])\n primes.push_back(i);\n }\n\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 0; i < primes.size(); i++) {\n if (primes[i] <= n / 2) {\n if (isPrime[n - primes[i]]) // Use [] instead of at\n kotae++;\n }\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3180, "score_of_the_acc": -0.1033, "final_rank": 9 }, { "submission_id": "aoj_0056_8861361", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main(void) {\n const int limit = 51000;\n vector<bool> isPrime(limit + 1, true);\n isPrime[0] = isPrime[1] = false;\n\n for (int i = 2; i * i <= limit; i++) {\n if (isPrime[i]) {\n for (int j = i * i; j <= limit; j += i) {\n isPrime[j] = false;\n }\n }\n }\n \n vector<int> primes;\n for (int i = 2; i <= limit; i++) {\n if (isPrime[i])\n primes.push_back(i);\n }\n \n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 0; i < primes.size() && primes[i] <= n/2; i++) {\n if (isPrime[n - primes[i]])\n kotae++;\n }\n cout << kotae << endl;\n }\n \n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3216, "score_of_the_acc": -0.0864, "final_rank": 8 }, { "submission_id": "aoj_0056_8861360", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\nusing namespace std;\nint main(void) {\n int limit = 51000;\n vector<char> isPrime(limit + 1, true);\n isPrime[0] = isPrime[1] = false;\n int sqrt_limit = sqrt(limit);\n \n for (int i = 2; i <= sqrt_limit; i++) {\n if (isPrime[i]) {\n for (int j = i * i; j <= limit; j += i) {\n isPrime[j] = false;\n }\n }\n }\n \n vector<int> primes;\n if(limit >= 2) primes.push_back(2);\n for (int i = 3; i <= limit; i += 2) {\n if (isPrime[i])\n primes.push_back(i);\n }\n\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 0; i < primes.size() && primes[i] <= n / 2; i++) {\n if (isPrime[n - primes[i]])\n kotae++;\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 3220, "score_of_the_acc": -0.0734, "final_rank": 5 }, { "submission_id": "aoj_0056_8861359", "code_snippet": "#include <iostream>\n#include <bitset>\nusing namespace std;\nint main(void) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n \n bitset<51000 + 1> isPrime;\n isPrime[2] = true;\n for (int i = 3; i <= 51000; i += 2) {\n isPrime[i] = true;\n }\n for (int i = 3; i * i <= 51000; i += 2) {\n if (isPrime[i]) {\n for (int j = i * i; j <= 51000; j += i) {\n isPrime[j] = false;\n }\n }\n }\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 2; i <= n / 2; i++) {\n if (isPrime[i] && isPrime[n - i])\n kotae++;\n }\n cout << kotae << '\\n';\n }\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 3176, "score_of_the_acc": -0.3021, "final_rank": 16 }, { "submission_id": "aoj_0056_8836537", "code_snippet": "#include <iostream>\n#include <vector>\n#include <bitset>\n#include <cmath>\nusing namespace std;\n\nint main() {\n const int limit = 51000;\n bitset<limit + 1> isPrime;\n isPrime.set();\n isPrime[0] = isPrime[1] = false;\n\n for (int i = 2; i * i <= limit; i++) {\n if (isPrime[i]) {\n for (int j = i * i; j <= limit; j += i) {\n isPrime[j] = false;\n }\n }\n }\n\n vector<int> primes;\n for (int i = 2; i <= limit; i++) {\n if (isPrime[i]) {\n primes.push_back(i);\n }\n }\n\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n int left = 0, right = primes.size() - 1;\n while (left <= right) {\n int sum = primes[left] + primes[right];\n if (sum == n) {\n kotae++;\n left++;\n right--;\n } else if (sum < n) {\n left++;\n } else {\n right--;\n }\n }\n cout << kotae << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 110, "memory_kb": 3136, "score_of_the_acc": -0.1892, "final_rank": 12 }, { "submission_id": "aoj_0056_8818956", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\nusing namespace std;\n\nint main(void) {\n vector<bool> isPrime(51000 + 1, false);\n isPrime[2] = true;\n for (int i = 3; i < 51000; i += 2) {\n isPrime[i] = true;\n }\n\n int limit = sqrt(51000);\n for (int i = 3; i <= limit; i += 2) {\n if (isPrime[i]) {\n for (int j = i*i; j < 51000; j += i) {\n isPrime[j] = false;\n }\n }\n }\n\n int n;\n while (cin >> n && n != 0) {\n int count = 0;\n for (int i = 2; i <= n / 2; ++i) {\n if (isPrime[i] && isPrime[n - i]) {\n count++;\n }\n }\n cout << count << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 190, "memory_kb": 3084, "score_of_the_acc": -0.2867, "final_rank": 15 }, { "submission_id": "aoj_0056_8818955", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main(void) {\n const int maxNum = 51000;\n vector<bool> isPrime(maxNum + 1, false);\n isPrime[2] = true;\n for (int i = 3; i <= maxNum; i += 2) {\n isPrime[i] = true;\n }\n for (int i = 3; i <= maxNum; i += 2) {\n if (isPrime[i]) { // Only check for prime numbers\n for (int j = i + i; j <= maxNum; j += i) {\n isPrime[j] = false;\n }\n }\n }\n vector<int> primes;\n primes.reserve(maxNum/2); // Preallocate memory\n primes.push_back(2);\n for (int i = 3; i <= maxNum; i += 2) {\n if (isPrime[i]) {\n primes.push_back(i);\n }\n }\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 0; i < primes.size() && primes[i] <= n / 2; i++) {\n if (isPrime[n - primes[i]]) {\n kotae++;\n }\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3108, "score_of_the_acc": -0.0516, "final_rank": 1 }, { "submission_id": "aoj_0056_8818954", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\nusing namespace std;\nint main(void) {\n vector<bool> isPrime(51000 + 1, true);\n vector<int> primes;\n primes.reserve(51000); // Reserve memory in advance\n isPrime[0] = isPrime[1] = false;\n for (int i = 2; i*i <= 51000; i++) {\n if (isPrime[i]) {\n for (int j = i*i; j <= 51000; j += i) {\n isPrime[j] = false;\n }\n }\n }\n for (int i = 2; i <= 51000; i++) {\n if (isPrime[i])\n primes.push_back(i);\n }\n int n;\n int size = primes.size(); // Store size in a variable\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 0; i < size; i++) {\n if (primes[i] <= n / 2) {\n if (isPrime[n - primes[i]]) // Use operator [] instead of at()\n kotae++;\n }\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3060, "score_of_the_acc": -0.0647, "final_rank": 4 }, { "submission_id": "aoj_0056_8818953", "code_snippet": "#include <iostream>\n#include <vector>\n#include <cmath>\nusing namespace std;\n\nint main(void) {\n vector<bool> isPrime(51000 + 1, true);\n isPrime[0] = isPrime[1] = false;\n for (int i = 2; i <= sqrt(51000); i++) {\n if (isPrime[i]) {\n for (int j = i * i; j <= 51000; j += i) {\n isPrime[j] = false;\n }\n }\n }\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 2; i <= n / 2; i++) {\n if (isPrime[i] && isPrime[n - i])\n kotae++;\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 200, "memory_kb": 2992, "score_of_the_acc": -0.2714, "final_rank": 14 }, { "submission_id": "aoj_0056_8818952", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n const int limit = 51000;\n vector<bool> isPrime(limit + 1, true);\n isPrime[0] = isPrime[1] = false;\n \n for (int i = 2; i*i <= limit; i++) {\n if (isPrime[i]) {\n for (int j = i*i; j <= limit; j += i) {\n isPrime[j] = false;\n }\n }\n }\n\n int n;\n while (cin >> n && n != 0) {\n int count = 0;\n for (int i = 2; i <= n / 2; i++) {\n if (isPrime[i] && isPrime[n - i]) {\n count++;\n }\n }\n cout << count << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 3092, "score_of_the_acc": -0.3179, "final_rank": 18 }, { "submission_id": "aoj_0056_8818950", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\nint main(void) {\n vector<bool> isPrime(51000 + 1, true);\n isPrime[0] = isPrime[1] = false;\n for (int i = 2; i * i <= 51000; i++) {\n if (isPrime[i]) {\n for (int j = i * i; j <= 51000; j += i) {\n isPrime[j] = false;\n }\n }\n }\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 2; i <= n / 2; i++) {\n if (isPrime[i] && isPrime[n - i])\n kotae++;\n }\n cout << kotae << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 210, "memory_kb": 3056, "score_of_the_acc": -0.3063, "final_rank": 17 }, { "submission_id": "aoj_0056_8818949", "code_snippet": "#include <iostream>\n#include <bitset>\nusing namespace std;\nint main(void) {\n ios::sync_with_stdio(false);\n bitset<51001> isPrime;\n isPrime.set();\n isPrime[0] = isPrime[1] = 0;\n for (int i = 4; i <= 51000; i += 2) {\n isPrime[i] = 0;\n }\n for (int i = 3; i * i <= 51000; i += 2) {\n if (isPrime[i]) {\n for (int j = i * i; j <= 51000; j += i) {\n isPrime[j] = 0;\n }\n }\n }\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n for (int i = 2; i <= n / 2; ++i) {\n if (isPrime[i] && isPrime[n - i])\n kotae++;\n }\n cout << kotae << \"\\n\";\n }\n return 0;\n}", "accuracy": 1, "time_ms": 180, "memory_kb": 3024, "score_of_the_acc": -0.2532, "final_rank": 13 }, { "submission_id": "aoj_0056_8810068", "code_snippet": "#include <iostream>\n#include <bitset>\n#include <vector>\n#include <cmath>\nusing namespace std;\n\nint main(void) {\n const int limit = 51000;\n const int sqrtLimit = sqrt(limit);\n\n bitset<limit + 1> isPrime;\n isPrime[2] = true;\n for (int i = 3; i <= limit; i += 2) {\n isPrime[i] = true;\n }\n for (int i = 3; i <= sqrtLimit; i += 2) {\n if (isPrime[i]) {\n for (int j = i * i; j <= limit; j += i * 2) {\n isPrime[j] = false;\n }\n }\n }\n\n vector<int> primes;\n primes.push_back(2);\n for (int i = 3; i <= limit; i += 2) {\n if (isPrime[i])\n primes.push_back(i);\n }\n\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n int primesSize = primes.size();\n for (int i = 0; i < primesSize; i++) {\n if (primes[i] <= n / 2) {\n if (isPrime[n - primes[i]])\n kotae++;\n }\n }\n cout << kotae << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 40, "memory_kb": 3192, "score_of_the_acc": -0.1072, "final_rank": 10 }, { "submission_id": "aoj_0056_8810064", "code_snippet": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main(void) {\n vector<char> isPrime(51000 + 1, false);\n isPrime[2] = true;\n\n for (int i = 3; i < 51000; i += 2) {\n isPrime[i] = true;\n }\n\n for (int i = 3; i < 51000; i += 2) {\n if (isPrime[i]) {\n for (int j = i + i; j < 51000; j += i) {\n isPrime[j] = false;\n }\n }\n }\n\n vector<int> primes;\n primes.push_back(2);\n\n for (int i = 3; i < 51000; i += 2) {\n if (isPrime[i]) {\n primes.push_back(i);\n }\n }\n\n int n;\n while (cin >> n && n != 0) {\n int kotae = 0;\n int maxSize = n / 2;\n int left = 0;\n int right = primes.size() - 1;\n int lastIndex = -1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n\n if (primes[mid] <= maxSize) {\n lastIndex = mid;\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n for (int i = 0; i <= lastIndex; i++) {\n if (isPrime[n - primes[i]]) {\n kotae++;\n }\n }\n\n cout << kotae << endl;\n }\n\n return 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 3188, "score_of_the_acc": -0.0773, "final_rank": 6 } ]
aoj_0088_cpp
博士が愛した符号 博士 : ピーター君、ついにやったよ。 ピーター : どうしました、デビッド博士?またくだらない発明ですか? 博士 : この表だよ、この表。 文字 符号 (空白) 101 ' 000000 , 000011 - 10010001 . 010001 ? 000001 A 100101 B 10011010 文字 符号 C 0101 D 0001 E 110 F 01001 G 10011011 H 010000 I 0111 J 10011000 文字 符号 K 0110 L 00100 M 10011001 N 10011110 O 00101 P 111 Q 10011111 R 1000 文字 符号 S 00110 T 00111 U 10011100 V 10011101 W 000010 X 10010010 Y 10010011 Z 10010000 ピーター : なんですか? この表は。 博士 : いいから、言う通りにしてみなさい。まず、お前の名前を紙に書いてごらん。 ピーター : はい"PETER POTTER" っと。 博士 : そうしたら、1文字ずつ、この表の「符号」に置き換えるのだよ。 ピーター : えーと"P" を「111」にして"E" を「110」して…結構面倒ですね。 111 110 00111 110 1000 101 111 00101 00111 00111 110 1000 になりました。なんだか、バーコードみたいですね。 博士 : よろしい。そうしたら、置き換えた文字列を全部つなげて、5文字ごとに区切ってみなさい。 ピーター : はいはい、つなげて区切ると。 11111 00011 11101 00010 11110 01010 01110 01111 10100 0 こんな感じになりました。けど、最後の「0」だけのやつはどうしますか? 博士 : 0を付け加えて5文字にしておいてくれ。 ピーター : えーと最後が0が1個だけだから0をあと4つ加えてやればいいんですね。できました。 11111 00011 11101 00010 11110 01010 01110 01111 10100 00000 博士 : 次はこの表を使うのだ。 符号 文字 00000 A 00001 B 00010 C 00011 D 00100 E 00101 F 00110 G 00111 H 符号 文字 01000 I 01001 J 01010 K 01011 L 01100 M 01101 N 01110 O 01111 P 符号 文字 10000 Q 10001 R 10010 S 10011 T 10100 U 10101 V 10110 W 10111 X 符号 文字 11000 Y 11001 Z 11010 (空白) 11011 . 11100 , 11101 - 11110 ' 11111 ? ピーター : これをどう使うんですか…そうか!今度は符号から文字に置き換えるのか! 博士 : そうそう。「11111」だったら「?」に、「00011」だったら「D」にとやってゆけばいいんだよ。 ピーター : これは単純ですね……えーと「?D-C'KOPUA」になりました。でも意味不明ですよ。 博士 : 文字数を数えてごらん。 ピーター : 10文字ですよ。あっ、「PETER POTTER」は12文字だったのに2文字減っています。 博士 : そう、この表を使えば文字を減らすことができるのだよ。じゃあ今度はこの文章で同じことをやっ てごらん。 PETER PIPER PICKED A PECK OF PICKLED PEPPERS. A PECK OF PICKLED PEPPERS PETER PIPER PICKED. IF PETER PIPER PICKED A PECK OF PICKLED PEPPERS, WHERE'S THE PECK OF PICKLED PEPPERS PETER PIPER PICKED? ピーター : ぎょぎょ、行が分かれていますが、どうするんですか? 博士 : 紙の都合で3行になってしまったが、改行文字のかわりに空白がある長い1行だと思っておくれ。 ピーター : はいはい。行と行の間にあるのは空白だと。しかし面倒だな……。 博士 : だったらプログラムにやらせればいいではないか。 ということで、ピーターの代わりに、読み込んだ文字列を符号に変換し出力するプログラムを作成してください。 入力 複数のデータセットが与えられます。各データセットに文字列1行(表に含まれる文字からなる)が与えられます。文字列に含まれる文字の数は 1 文字以上 100 文字以下です。 データセットの数は 200 を超えません。 出力 各データセットごとに、変換後の文字列を1行に出力してください。 Sample Input PETER POTTER Output for the Sample Input ?D-C'KOPUA
[ { "submission_id": "aoj_0088_1907220", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\nstring c2s(char c){\n if(c==' ') return \"101\";\n if(c=='\\'') return \"000000\";\n if(c==',') return \"000011\";\n if(c=='-') return \"10010001\";\n if(c=='.') return \"010001\";\n if(c=='?') return \"000001\";\n if(c=='A') return \"100101\";\n if(c=='B') return \"10011010\";\n if(c=='C') return \"0101\";\n if(c=='D') return \"0001\";\n if(c=='E') return \"110\";\n if(c=='F') return \"01001\";\n if(c=='G') return \"10011011\";\n if(c=='H') return \"010000\";\n if(c=='I') return \"0111\";\n if(c=='J') return \"10011000\";\n if(c=='K') return \"0110\";\n if(c=='L') return \"00100\";\n if(c=='M') return \"10011001\";\n if(c=='N') return \"10011110\";\n if(c=='O') return \"00101\";\n if(c=='P') return \"111\";\n if(c=='Q') return \"10011111\";\n if(c=='R') return \"1000\";\n if(c=='S') return \"00110\";\n if(c=='T') return \"00111\";\n if(c=='U') return \"10011100\";\n if(c=='V') return \"10011101\";\n if(c=='W') return \"000010\";\n if(c=='X') return \"10010010\";\n if(c=='Y') return \"10010011\";\n if(c=='Z') return \"10010000\"; \n}\nchar s2c(string x){\n if(x==\"00000\") return 'A';\n if(x==\"00001\") return 'B';\n if(x==\"00010\") return 'C';\n if(x==\"00011\") return 'D';\n if(x==\"00100\") return 'E';\n if(x==\"00101\") return 'F';\n if(x==\"00110\") return 'G';\n if(x==\"00111\") return 'H';\n if(x==\"01000\") return 'I';\n if(x==\"01001\") return 'J';\n if(x==\"01010\") return 'K';\n if(x==\"01011\") return 'L';\n if(x==\"01100\") return 'M';\n if(x==\"01101\") return 'N';\n if(x==\"01110\") return 'O';\n if(x==\"01111\") return 'P';\n if(x==\"10000\") return 'Q';\n if(x==\"10001\") return 'R';\n if(x==\"10010\") return 'S';\n if(x==\"10011\") return 'T';\n if(x==\"10100\") return 'U';\n if(x==\"10101\") return 'V';\n if(x==\"10110\") return 'W';\n if(x==\"10111\") return 'X';\n if(x==\"11000\") return 'Y';\n if(x==\"11001\") return 'Z';\n if(x==\"11010\") return ' ';\n if(x==\"11011\") return '.';\n if(x==\"11100\") return ',';\n if(x==\"11101\") return '-';\n if(x==\"11110\") return '\\'';\n if(x==\"11111\") return '?';\n}\nint main(){\n string s;\n while(getline(cin,s)){\n int i;\n string m;\n for(i=0;i<s.size();i++) m+=c2s(s[i]);\n if(m.size()%5!=0){\n m+=\"0000\";\n }\n string o;\n for(i=0;i+5<=m.size();i+=5){\n o+=s2c(m.substr(i,5));\n }\n cout << o << endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1196, "score_of_the_acc": 0, "final_rank": 1 }, { "submission_id": "aoj_0088_1665075", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n#define rep(i,n) for(i=0;i<n;++i)\n#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); itr++)\n#define mp make_pair\n#define pb push_back\n#define fi first\n#define sc second\n\nint main(int argc, char const *argv[]) {\n map<char,string> m;\n m[' '] =\"101\";\n m['\\'']=\"000000\";\n m[','] =\"000011\";\n m['-'] =\"10010001\";\n m['.'] =\"010001\";\n m['?'] =\"000001\";\n m['A'] =\"100101\";\n m['B'] =\"10011010\";\n m['C'] =\"0101\";\n m['D'] =\"0001\";\n m['E'] =\"110\";\n m['F'] =\"01001\";\n m['G'] =\"10011011\";\n m['H'] =\"010000\";\n m['I'] =\"0111\";\n m['J'] =\"10011000\";\n m['K'] =\"0110\";\n m['L'] =\"00100\";\n m['M'] =\"10011001\";\n m['N'] =\"10011110\";\n m['O'] =\"00101\";\n m['P'] =\"111\";\n m['Q'] =\"10011111\";\n m['R'] =\"1000\";\n m['S'] =\"00110\";\n m['T'] =\"00111\";\n m['U'] =\"10011100\";\n m['V'] =\"10011101\";\n m['W'] =\"000010\";\n m['X'] =\"10010010\";\n m['Y'] =\"10010011\";\n m['Z'] =\"10010000\";\n\n int i;\n string s;\n string al=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n while (getline(cin,s)){\n string ans=\"\";\n\n string a=\"\";\n rep(i,s.size()) a+=m[s[i]];\n\n int tmp=a.size()%5;\n if(tmp!=0){\n rep(i,5-tmp) a+=\"0\";\n }\n\n //cout << a << endl;\n\n for(int j=0; j<a.size(); j+=5){\n //5???????????¨????????????\n string b=a.substr(j,5);\n if(b==\"11010\") ans+=\" \";\n else if(b==\"11011\") ans+=\".\";\n else if(b==\"11100\") ans+=\",\";\n else if(b==\"11101\") ans+=\"-\";\n else if(b==\"11110\") ans+=\"'\";\n else if(b==\"11111\") ans+=\"?\";\n else{\n int val=0;\n for(int k=0; k<5; ++k){\n val+=(b[k]-'0')*pow(2,4-k);\n }\n ans+=al[val];\n }\n\n }\n\n std::cout << ans << std::endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1240, "score_of_the_acc": -1, "final_rank": 3 }, { "submission_id": "aoj_0088_1662841", "code_snippet": "#include<iostream>\n#include<string>\nusing namespace std;\n\nchar A1[33] = \" ',-.?ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nchar B1[33] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ .,-'?\";\n\nstring A2[32] = {\n\t\"101\",\n\t\"000000\",\n\t\"000011\",\n\t\"10010001\",\n\t\"010001\",\n\t\"000001\",\n\t\"100101\",\n\t\"10011010\",\n\t\"0101\",\n\t\"0001\",\n\t\"110\",\n\t\"01001\",\n\t\"10011011\",\n\t\"010000\",\n\t\"0111\",\n\t\"10011000\",\n\t\"0110\",\n\t\"00100\",\n\t\"10011001\",\n\t\"10011110\",\n\t\"00101\",\n\t\"111\",\n\t\"10011111\",\n\t\"1000\",\n\t\"00110\",\n\t\"00111\",\n\t\"10011100\",\n\t\"10011101\",\n\t\"000010\",\n\t\"10010010\",\n\t\"10010011\",\n\t\"10010000\"\n};\n\nstring B2[32] = {\n\t\"00000\",\n\t\"00001\",\n\t\"00010\",\n\t\"00011\",\n\t\"00100\",\n\t\"00101\",\n\t\"00110\",\n\t\"00111\",\n\t\"01000\",\n\t\"01001\",\n\t\"01010\",\n\t\"01011\",\n\t\"01100\",\n\t\"01101\",\n\t\"01110\",\n\t\"01111\",\n\t\"10000\",\n\t\"10001\",\n\t\"10010\",\n\t\"10011\",\n\t\"10100\",\n\t\"10101\",\n\t\"10110\",\n\t\"10111\",\n\t\"11000\",\n\t\"11001\",\n\t\"11010\",\n\t\"11011\",\n\t\"11100\",\n\t\"11101\",\n\t\"11110\",\n\t\"11111\"\n};\n\nstring U;\nstring V;\n\nint main() {\n\twhile (getline(cin, U)) {\n\t\tV = \"\";\n\t\tfor (int i = 0; i < U.size(); i++) {\n\t\t\tfor (int j = 0; j < 32; j++) {\n\t\t\t\tif (A1[j] == U[i]) {\n\t\t\t\t\tV += A2[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twhile (V.size() % 5 != 0) {\n\t\t\tV += '0';\n\t\t}\n\t\tU = \"\";\n\t\tfor (int i = 0; i < V.size(); i += 5) {\n\t\t\tfor (int j = 0; j < 32; j++) {\n\t\t\t\tif (B2[j] == V.substr(i, 5)) {\n\t\t\t\t\tU += B1[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << U << endl;\n\t}\n\treturn 0;\n}", "accuracy": 1, "time_ms": 20, "memory_kb": 1196, "score_of_the_acc": -1, "final_rank": 3 }, { "submission_id": "aoj_0088_1310781", "code_snippet": "//The Code A Doctor Loved\n#include<bits/stdc++.h>\nusing namespace std;\n\nstring p(string s, string t){\n for(int i=0; i<t.length(); i++){\n if(s.length()%6==5)s+=' ';\n s+=t[i];\n }\n return s;\n}\n\nstring into(string s){\n string t=\"\";\n for(int i=0; i<s.length(); i++){\n if(s[i]==' ')t=p(t, \"101\");\n if(s[i]=='\\'')t=p(t, \"000000\");\n if(s[i]==',')t=p(t,\"000011\");\n if(s[i]=='-')t=p(t,\"10010001\");\n if(s[i]=='.')t=p(t,\"010001\");\n if(s[i]=='?')t=p(t,\"000001\");\n if(s[i]=='A')t=p(t,\"100101\");\n if(s[i]=='B')t=p(t,\"10011010\");\n if(s[i]=='C')t=p(t,\"0101\");\n if(s[i]=='D')t=p(t,\"0001\");\n if(s[i]=='E')t=p(t,\"110\");\n if(s[i]=='F')t=p(t,\"01001\");\n if(s[i]=='G')t=p(t,\"10011011\");\n if(s[i]=='H')t=p(t,\"010000\");\n if(s[i]=='I')t=p(t,\"0111\");\n if(s[i]=='J')t=p(t,\"10011000\");\n if(s[i]=='K')t=p(t,\"0110\");\n if(s[i]=='L')t=p(t,\"00100\");\n if(s[i]=='M')t=p(t,\"10011001\");\n if(s[i]=='N')t=p(t,\"10011110\");\n if(s[i]=='O')t=p(t,\"00101\");\n if(s[i]=='P')t=p(t,\"111\");\n if(s[i]=='Q')t=p(t,\"10011111\");\n if(s[i]=='R')t=p(t,\"1000\");\n if(s[i]=='S')t=p(t,\"00110\");\n if(s[i]=='T')t=p(t,\"00111\");\n if(s[i]=='U')t=p(t,\"10011100\");\n if(s[i]=='V')t=p(t,\"10011101\");\n if(s[i]=='W')t=p(t,\"000010\");\n if(s[i]=='X')t=p(t,\"10010010\");\n if(s[i]=='Y')t=p(t,\"10010011\");\n if(s[i]=='Z')t=p(t,\"10010000\");\n }\n while(t.length()%6!=5)t+='0';\n stringstream ss(t);\n string ret=\"\", tmp;\n while(getline(ss, tmp, ' ')){\n if(tmp==\"00000\")ret+='A';\n if(tmp==\"00001\")ret+='B';\n if(tmp==\"00010\")ret+='C';\n if(tmp==\"00011\")ret+='D';\n if(tmp==\"00100\")ret+='E';\n if(tmp==\"00101\")ret+='F';\n if(tmp==\"00110\")ret+='G';\n if(tmp==\"00111\")ret+='H';\n if(tmp==\"01000\")ret+='I';\n if(tmp==\"01001\")ret+='J';\n if(tmp==\"01010\")ret+='K';\n if(tmp==\"01011\")ret+='L';\n if(tmp==\"01100\")ret+='M';\n if(tmp==\"01101\")ret+='N';\n if(tmp==\"01110\")ret+='O';\n if(tmp==\"01111\")ret+='P';\n if(tmp==\"10000\")ret+='Q';\n if(tmp==\"10001\")ret+='R';\n if(tmp==\"10010\")ret+='S';\n if(tmp==\"10011\")ret+='T';\n if(tmp==\"10100\")ret+='U';\n if(tmp==\"10101\")ret+='V';\n if(tmp==\"10110\")ret+='W';\n if(tmp==\"10111\")ret+='X';\n if(tmp==\"11000\")ret+='Y';\n if(tmp==\"11001\")ret+='Z';\n if(tmp==\"11010\")ret+=' ';\n if(tmp==\"11011\")ret+='.';\n if(tmp==\"11100\")ret+=',';\n if(tmp==\"11101\")ret+='-';\n if(tmp==\"11110\")ret+='\\'';\n if(tmp==\"11111\")ret+='?';\n }\n return ret;\n}\n\nint main(){\n string s;\n while(getline(cin, s)){\n cout<<into(s)<<endl;\n }\n return 0;\n}", "accuracy": 1, "time_ms": 10, "memory_kb": 1220, "score_of_the_acc": -0.5455, "final_rank": 2 } ]