File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ * Verified
3+ * https://atcoder.jp/contests/abc054/submissions/16977824
4+ */
5+ class Permutation implements java .util .Iterator <int []>, Iterable <int []> {
6+ private int [] next ;
7+
8+ public Permutation (int n ) {
9+ next = java .util .stream .IntStream .range (0 , n ).toArray ();
10+ }
11+
12+ @ Override
13+ public boolean hasNext () {
14+ return next != null ;
15+ }
16+
17+ @ Override
18+ public int [] next () {
19+ int [] r = next .clone ();
20+ next = nextPermutation (next );
21+ return r ;
22+ }
23+
24+ @ Override
25+ public java .util .Iterator <int []> iterator () {
26+ return this ;
27+ }
28+
29+ public static int [] nextPermutation (int [] a ) {
30+ if (a == null || a .length < 2 )
31+ return null ;
32+ int p = 0 ;
33+ for (int i = a .length - 2 ; i >= 0 ; i --) {
34+ if (a [i ] >= a [i + 1 ])
35+ continue ;
36+ p = i ;
37+ break ;
38+ }
39+ int q = 0 ;
40+ for (int i = a .length - 1 ; i > p ; i --) {
41+ if (a [i ] <= a [p ])
42+ continue ;
43+ q = i ;
44+ break ;
45+ }
46+ if (p == 0 && q == 0 )
47+ return null ;
48+ int temp = a [p ];
49+ a [p ] = a [q ];
50+ a [q ] = temp ;
51+ int l = p , r = a .length ;
52+ while (++l < --r ) {
53+ temp = a [l ];
54+ a [l ] = a [r ];
55+ a [r ] = temp ;
56+ }
57+ return a ;
58+ }
59+ }
Original file line number Diff line number Diff line change 1+ # クラス Permutation
2+
3+ 本機能は AtCoderLibrary ではなく C++標準ライブラリ ` std::next_permutation ` の移植です.
4+
5+ $N$が与えられたとき,長さ$N$の順列を辞書順に列挙することができます.
6+
7+ また,拡張 for 文によるイテレーションをサポートしています.
8+ 以下のイテレーションは,時間計算量 $O(N * N!)$で動作します.
9+
10+ ```
11+ Permutation perm = new Permutation(n);
12+ for (int[] p : perm) {
13+ // code here
14+ }
15+ ```
16+
17+ ## コンストラクタ
18+
19+ ### Permutation
20+
21+ ``` java
22+ public Permutation(int n)
23+ ```
24+
25+ 長さ$N$の順列を列挙するイテレータを作ります. 計算量 $O(N)$
26+
27+ ## メソッド
28+
29+ ### hasNext
30+
31+ ``` java
32+ public boolean hasNext()
33+ ```
34+
35+ イテレータが後続の要素を保持する場合に真を返します.計算量 $O(1)$
36+
37+ ### next
38+
39+ ``` java
40+ public int [] next()
41+ ```
42+
43+ イテレータの後続の要素を取得します.計算量 $O(N)$
44+
45+ ### iterator
46+
47+ ``` java
48+ public Iterator<int[]> iterator()
49+ ```
50+
51+ 順列を列挙するイテレータを取得します.
52+
53+ ### nextPermutation
54+
55+ ``` java
56+ public static int [] nextPermutation(int [] a)
57+ ```
58+
59+ 与えられた順列に対して,辞書順でその直後となるような順列を返却します.
60+ 但し,入力の配列が辞書順最大の場合は` null ` を返却します.
61+ 入力配列中の任意の 2 要素が相異なることを仮定しています.
62+ また,入力で与えられた順列を破壊的に変更することに注意してください.
63+ 計算量 $O(N)$
You can’t perform that action at this time.
0 commit comments