Hatena::Grouptopcoder

(iwi) { 反省します

TopCoder: [[iwi]] / Twitter: @iwiwi

|

2013-08-21

「ZDD+フロンティア法」はコンテストで役に立つか

13:44 | 「ZDD+フロンティア法」はコンテストで役に立つか - (iwi) { 反省します を含むブックマーク はてなブックマーク - 「ZDD+フロンティア法」はコンテストで役に立つか - (iwi) { 反省します 「ZDD+フロンティア法」はコンテストで役に立つか - (iwi) { 反省します のブックマークコメント

ZDD, フロンティア法とは

問題候補

関連しそうなものを思いつく限り列挙したが,残念ながら,これらの問題では ZDD を使う利点はあまりないように思う.その理由は以下.

(他に何かご存知でしたら教えてもらえると喜びます)

考察

ZDD を使うための必須条件は,まず

  • 扱うものが連結成分,木,森,パス,サイクルあたり(グラフ以外の問題への適用まで考えるとこの限りではないが)
  • メモリ使用量にかなり余裕がある

ということ.例えば,DP なら O(WH 3^W) 時間でも配列を使い回せば O(3^W) スペースでできる問題でも,ZDD であれば必ず O(WH 3^W) スペース(しかもそこそこの定数倍)が必要.

さらに,ZDD を使って有利になるための条件は,例えば

  • 1 つ見つけたいのではなく,最適なものを見つけたかったり全て数え上げたかったり,いわゆる DP 的処理(or列挙)がしたい
  • DP 中の状態遷移の中で書くと大変だが,構成後の ZDD に後から Family Algebra で変更を加える方針なら凄い簡単になるような制約がついている

というようなものが考えられる.

まず,DP は,複雑であればあるほど ZDD が有利になる.これは,普通の DP 解法では状態遷移をしながらそれに加えてさらに最適値の更新も行わなければならないのに対し,ZDD の構築部分では状態遷移だけを考えればよいから.しかし,実際にはこういう系の問題はそもそも状態遷移だけで凄い複雑なので,変な目的関数は滅多にでない.また,扱いやすいライブラリ化に繋がるかもしれないが,次の段落で述べるように,実際には毎回のように状態遷移に手を入れることになりそう.(あと,集合に含まれるか否かの情報しかない ZDD にしてしまってからでは計算できないような DP もある.)

次に,後で Family Algebra で解への制約を追加できるのは,実装面で楽になるかもしれない.ただ,上の問題たちを見ていると,実際にはこれはあまり上手く活用できなさそう.というのも,1 つの制約の追加に,ZDD 全体のサイズが計算量でかかってしまうから.例えば,「隣り合うマスを使わない」みたいなルールの場合,制約を ZDD 構成後に入れようとすると,入れる制約の数が O(WH) 有り,そんなに制約を後から入れると計算量がやばい(O(W^2H^2 3^W) とかになる).制約が定数個に収まっていないとこの方法は使えず,実際にはあまりこの方法を取れる機会は多くないかも.

JuniorfugJuniorfug2018/06/15 02:18viagra soft 100mg
<a href="http://viagrapipls.com/">buy viagra</a>
effectiveness of cialis vs viagra vs levitra which is better
<a href="http://viagrapipls.com/">buy viagra online</a>
viagra ad actress black

JaredceackJaredceack2018/06/19 09:57best price cialis and viagra
<a href="http://cialisprod.com/">buy generic cialis</a>
viagra cialis pharmacy
<a href="http://cialisprod.com/">buy cialis</a>
cialis commercial rock song

MichaelAdusaMichaelAdusa2018/06/21 19:04walmart drug prices for cialis
<a href="http://airvietnamairline.com/">buy generic cialis online</a>
when will cialis or viagra go generic
<a href="http://airvietnamairline.com/">buy cialis</a>
5mg cialis for daily use

JamesstakyJamesstaky2018/06/23 21:11kamagra oral jelly 100 mg wirkungsdauer
<a href="http://kamagradyn.com/">buy kamagra 100 mg</a>
kamagra oral jelly kaufen thailand
<a href="http://kamagradyn.com/">buy kamagra 100mg</a>
kamagra oral jelly 100mg

AllanaropsAllanarops2018/06/25 06:27cialis 20 mg contre indications
<a href="http://cialispaxl.com/">generic cialis</a>
cialis 20mg cost without insurance
<a href="http://cialispaxl.com/">cialis</a>
cialis generic available yet

AllanaropsAllanarops2018/06/26 01:56walgreens cost for cialis 20 mg tablets
<a href="http://cialispaxl.com/">generic cialis</a>
actress in cialis commercial
<a href="http://cialispaxl.com/">generic cialis</a>
low cost viagra cialis 5mg

AntonLotAntonLot2018/06/28 12:53price cialis 20mg australia
<a href="http://cialisgenericsa.com/">generic cialis</a>
generic cialis tadalafil best price
<a href="http://cialisgenericsa.com/">buy cialis</a>
generic cialis best price

MatthewMerMatthewMer2018/06/30 03:32cipla generic cialis review
<a href="http://cialisgrudj.com/">generic cialis</a>
can i buy cialis in usa
<a href="http://cialisgrudj.com/">generic cialis</a>
cialis commercial female actors 2016

AntonLotAntonLot2018/06/30 18:46buy real viagra levitra cialis online edrugstore.md
<a href="http://cialisgenericsa.com/">generic cialis</a>
cialis commercial actress tennis
<a href="http://cialisgenericsa.com/">generic cialis</a>
cialis dosing options

FloydDydayFloydDyday2018/07/01 02:06kamagra store coupon
<a href="http://kamagradyn.com/">kamagra 100mg</a>
kamagra shop erfahrungen 2014
<a href="http://kamagraonl.com/">kamagra oral jelly</a>
kamagra kopen rotterdam

DavidSlildDavidSlild2018/07/13 04:24kamagra 100mg oral jelly india
<a href="https://www.kamagrajellyk.com/">kamagra jelly</a>
kamagra london reviews
<a href="https://www.kamagrajellyk.com/">buy kamagra oral jelly</a>
kamagra jelly kopen amsterdam

RobertDeeskRobertDeesk2018/07/16 03:41kamagra store in ny
<a href="https://www.kamagrapos.com/">kamagra 100mg</a>
kamagra 100mg oral jelly usa
<a href="https://www.kamagrapos.com/">kamagra oral jelly</a>
kamagra oral jelly side effects

DonnieSupDonnieSup2018/07/17 04:37Gеt up tо $ 20,000 реr day with оur рrоgrаm.
Wе are а teаm of exреriеnсеd рrоgrаmmеrs, worked more than 14 mоnths on this рrogram аnd nоw еvеrything is reаdy аnd еverуthing wоrks pеrfеctlу. Thе PayPаl sуstem is vеry vulnerable, instеаd of nоtifying thе dеvelоpers of РaуРаl аbоut this vulnerаbility, we tоok аdvаntаgе оf it. We activеly use оur prоgrаm for pеrsonаl еnrichmеnt, to show hugе amоunts оf moneу оn our аcсоunts, we will nоt. уou will nоt believе until yоu try аnd as it is not in our interest tо рrove tо yоu thаt something is in уours. Whеn wе rеalizеd that this vulnerаbilitу can bе used mаssively withоut consеquеnces, wе decided to hеlр the rеst of thе рeoрlе. We decidеd not tо inflаte the рricе оf this gold program аnd put а vеry lоw priсe tаg, only $ 550. In оrder for this рrоgrаm tо bе avаilаble to а lаrge numbеr of peорlе.
All the details оn our blog: http://www.isheika.com/url.php?https://www.pinterest.com/pin/690387817853172731/

MichaeldigMichaeldig2018/07/30 05:25kamagra oral jelly for sale in usa illegal
<a href="https://www.kamagrajellyk.com/">kamagra jelly</a>
kamagra oral jelly 100mg
<a href="https://www.kamagrajellyk.com/">kamagra oral jelly</a>
kamagra 100 chewable review

JamesfouriJamesfouri2018/08/05 20:53Help Jack please: http://home.putclub.com/link.php?url=https://vk.cc/8l7kvh

jtaletkeyojtaletkeyo2018/08/07 13:22<a href="http://psychologytweets.com">cialis pills</a> mail order cialis from canada http://psychologytweets.com

etaletphgketaletphgk2018/08/07 15:24<a href="http://bakerssign.com">cialis viagra levitra online</a> viagra vs cialis vs levitra prices http://bakerssign.com

ktaletkamjktaletkamj2018/08/09 02:56<a href="http://mphasset.com">order viagra without a prescription</a> how to buy viagra http://mphasset.com

jtaletgawqjtaletgawq2018/08/09 04:58<a href="http://psychologytweets.com">generic cialis without a prescription</a> order cialis canada http://psychologytweets.com

rtaletmximrtaletmxim2018/08/18 09:24<a href="http://mphasset.com">does revatio work like viagra</a> cialis levitra staxyn stendra and viagra http://mphasset.com

ataletdtybataletdtyb2018/08/18 14:28<a href="http://istanbulexpressonline.com">how much is viagra without insurance</a> slang names for viagra http://istanbulexpressonline.com

htaletyubhhtaletyubh2018/08/18 18:34<a href="http://bullsac.com">levitra professional 20 mg</a> how long for levitra to take effect http://bullsac.com

mtalettbokmtalettbok2018/08/18 22:09<a href="http://rabbitinahat.com">generic cialis samples</a> how much cialis to take http://rabbitinahat.com

ataletjfwoataletjfwo2018/08/19 18:40<a href="http://bullsac.com">cialis and levitra taken together</a> buy cheap levitra http://bullsac.com

ataletfjhaataletfjha2018/08/20 10:27<a href="http://bakerssign.com">levitra prices canada</a> levitra tablet http://bakerssign.com

otaletqijtotaletqijt2018/08/22 10:34<a href="http://rabbitinahat.com">cialis dose for ed</a> fda approved cialis http://rabbitinahat.com

2013-08-16

ICFP Programming Contest 2013 感想など

02:23 | ICFP Programming Contest 2013 感想など - (iwi) { 反省します を含むブックマーク はてなブックマーク - ICFP Programming Contest 2013 感想など - (iwi) { 反省します ICFP Programming Contest 2013 感想など - (iwi) { 反省します のブックマークコメント

2013/09/27 追記:

優勝しました!

こっちの記事を見て下さい → http://d.hatena.ne.jp/iwiwi/20130927/1380255924



チームについて

参加記を書こうかとも思ったけれど,だるいので,適当に書きたい事だけ書きます.

今年のチーム

順番は,僕視点で仲間になっていった順.チーム名は "Unagi: The Synthesis" です(何気にたぶん未公開情報).


チーム発足まで

このチームは,2 年前に準優勝(http://d.hatena.ne.jp/iwiwi/20110920/1316528846)したチーム "Unagi: The Gathering" をベースとしています.優勝者は 301 点,準優勝の我々は 300 点.とても悔しい思いをしました.

去年は,僕が VKCup(http://topcoder.g.hatena.ne.jp/iwiwi/20120715/1342360532)でロシアに行くのとかぶっていたこともあり崩壊.しかし主砲である wata は一人で出て Lightning 部門で優勝していた,流石すぎる(https://twitter.com/wata_orz/status/245500307205935104).

そして今年.去年がつまらなそうな問題だったので,ウーン,と思いつつ,今年はなんとなく Web ページ等から気合入ってそうなオーラを感じ取り,またやるか!という気分に.また本気でやりたいなあという事で wata と話しているところに imos からも声がかかったので,とりあえず 2 年前のチームメイトに声をかける.でも ir5, hos が日程の都合がつかないということで,一旦 4 人に.

2 年前のチームはあれはあれで1つの究極のチームだったと思います.例えば,TopCoder の平均レーティングがとにかくやばい.でも,過去の反省からするに,もっと幅広い力を持つほうが有利だということで,chokudai と sulume に声をかけてチーム結成.これは,予想以上に(特に,今年の問題には)完璧なチョイスでした.


問題について

このへんは,本当に人によって意見が異なる点だと思います.あくまで個人的な感想です.

今年の問題に関する自分の個人的な感想は,こんなところかなあと思います.

  • 重大な問題点はなし(Unable to decide equality は若干イラッ)
  • 運営は完璧(サーバ落ちない.問題文に欠陥がなく読みやすい.向こうのプログラムにバグがない.メールの反応もよい.)
  • そこそこ面白い,でもちょっとストイックすぎて寂しい

どうしても対比したくなるのは,3 年前の,車の出荷の問題ですね.こっちで計算をおこなって,サーバにある大量の問題を解いていくスタイルが類似.あれと対比すると,僕個人は,以下のように感じました.

  • あの時と比べて運営が段違いに良くてストレスがない
  • でもそれ抜きで考えれば,実は問題はあの時のほうが面白かったかも

問題の面白さなんかでいうと,やっぱり 2 年前も神がかり的に楽しかったと感じていて,今年はそれと比べてもやっぱりちょっと劣るかなと思います.

なんでそう感じるかというと,絡んでくる要素が少ない点じゃないかと思います.2 年前とか 3 年前の問題は,いろいろな面でやることがあって面白かった.そもそも,自分が 2 年前から ICFPC に本気参加しているのも,3 年前の優勝チームの人たち(http://d.hatena.ne.jp/tanakh/20100702)が色んな要素で強さを見せつけていてチョーカッケー!!俺もこんな総合力勝負っぽいコンテストでも勝ってみてー!!!って思ったから.なので,その点,今年はなんやかんや殆どが探索のチューニングだったなぁと思う(あと実行システム).まぁ,それも十分楽しかったんだけど.


ICFPC で勝つためには

色々事前に(チームを組む前から)考えていて,今年やってみて改めて色々感じて,色々あるけど,だるいからまた今度.

ウチのチームは,あとは皆のプログラミング言語が共通してないというのだけがとにかく重大な問題だと思うのだよなあ.2 年前みたいな,大きめの1つのプログラムを作らないといけないとき,一気に行動が制限される.この辺,皆 C++Python が書ける Googler で結成してるチームはかなり有利だなあと思う(まぁうちの Googler は PHP を書いてたんだけど).


結果について

wata (マジキチ) さんのツイートをご覧ください.

来年のためのメモ

2013-01-14

スキー

00:27 | スキー - (iwi) { 反省します を含むブックマーク はてなブックマーク - スキー - (iwi) { 反省します スキー - (iwi) { 反省します のブックマークコメント

皆様!!!!!スキー!!!!行きましょう!!!!

http://www.zusaar.com/event/489059


f:id:iwiwi:20130115002810g:image

CpkiwsopCpkiwsop2017/08/20 00:30This article is a fun luster England landscape, and mulberry sale also enters the picture various collection. Nevertheless, there are two other brands compare very similar to mulberry bags, which bags and bags Fendi Dior, once they get them in different styles and varieties. If you are looking in this bag Mulberry, then know that you consider the form that are of a very reputable boutique or specialty shop authorized. <a href=http://www.slimdave55.co.uk>http://www.slimdave55.co.uk</a> Do there is undoubtedly a time if your handbags don't match with your clothes and check ridiculous? Some of us have forms experience. You still can't get a better effect when your handbags don't go one clothes, however high company's handbags. How to pick a handbag matching with clothes? Buying used wetsuits on such sites as E-Bay and others is yet another great approach to save major money. There are many people taking up massive of delving and then lose interest after just a few dives. The scuba gear they bought, however, holds in a fit condition. Many these people place their gear up for sale on E-Bay for substantially less than what they initially paid. When you've got see lightly used gear such as this, join it. However often buy scuba gear for simply fraction of the original price like distinct. To accommodate the such mothers who are mainly occupied using baby and can't take out time to find around for baby clothes, the entire lot of babies wear retailer has opened their mulberry outlet also. And also so they are doing brisk business because this kind of is one sector which will not go the date. People babies to perform and with that they wants nice, comfortable clothes. And when you develop the entire collecting children's clothes in your screen then nothing want it. And the nice news might be the fact they have a separate component to designer clothes also. .

2013-01-05

pow_mod, inverse の速度

14:22 | pow_mod, inverse の速度 - (iwi) { 反省します を含むブックマーク はてなブックマーク - pow_mod, inverse の速度 - (iwi) { 反省します pow_mod, inverse の速度 - (iwi) { 反省します のブックマークコメント

久々にコンテストの問題が解きたくなって AOJ で 問題 MinimumCostPath を解いた.個人的にはムチャクチャ面白いと思った.

ところで,別に TLE はしなかったんだが,mod の inverse がボトルネックだった.自分のライブラリの mod の inverse とからへん,コンテスト始めたころの大昔に作ってから変えてなくて,今やあまり気に入っていないと思いつつバグってはいないということで長らく放置していたが,この際ようやく弄ることにした.


ベンチマークコード

適当.g++ -O2.標準入力は適当に10とか入れてる.

const ll MOD = 1000000009;

const int N = 2000000;

int main() {
  int a;
  scanf("%d", &a);

  ll t = a;
  for (int k = 1; k <= N; ++k) {
    t = inverse(t, MOD) * k % MOD;
  }
  printf("%lld\n", t);

  return 0;
}

追記:手元の環境は

~/contests/tmp% cat /proc/cpuinfo [00:35:39]

processor : 0

vendor_id : GenuineIntel

cpu family : 6

model : 26

model name : Intel(R) Core(TM) i7 CPU 960 @ 3.20GHz

stepping : 5

cpu MHz : 1600.000

cache size : 8192 KB

~/contests/tmp% gcc -v [00:36:44]

Using built-in specs.

Target: x86_64-linux-gnu

Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.3-4ubuntu5.1' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu

Thread model: posix

gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1)

今までのやつ

駆け出しだった頃の僕が,適当に bmerry か誰かのやつを参考にして書いた.中で再帰している上にいちいち丁寧に正にするために % を 2 回もとってて遅そう.(でもマイナスが帰るとそれが原因のバグをつくりそうで恐ろしいという気持ちは理解できる)

inline ll mod(ll a, ll m) { return (a % m + m) % m; }

ll inverse(ll a, ll m) {
  if ((a = mod(a, m)) == 1) return 1;
  return mod((1 - m * inverse(m % a, a)) / a, m);
}

~/contests/tmp% time ./a.out <<< 10 [14:10:35]

249011238

./a.out <<< 10 2.84s user 0.01s system 99% cpu 2.870 total

~/contests/tmp% time ./a.out <<< 10 [14:10:39]

249011238

./a.out <<< 10 2.85s user 0.00s system 99% cpu 2.870 total

~/contests/tmp% time ./a.out <<< 10 [14:10:43]

249011238

./a.out <<< 10 2.83s user 0.02s system 99% cpu 2.868 total


inline

再帰関数だからあんま意味分からんと思うが一応 inverse に inline つけてみた.

~/contests/tmp% g++ -O2 inverse.cpp [14:11:39]

~/contests/tmp% time ./a.out <<< 10 [14:11:41]

249011238

./a.out <<< 10 2.75s user 0.00s system 99% cpu 2.763 total

~/contests/tmp% time ./a.out <<< 10 [14:11:44]

249011238

./a.out <<< 10 2.75s user 0.00s system 99% cpu 2.762 total

~/contests/tmp% time ./a.out <<< 10 [14:11:49]

249011238

./a.out <<< 10 2.75s user 0.00s system 100% cpu 2.748 total

ちょっぴりはやくなったw



pow_mod 1

今まで使っていた pow_mod を使う.これも再帰していて丁寧に mod を呼んでいて見るからに遅そうである.

inline ll mod(ll a, ll m) { return (a % m + m) % m; }

ll pow_mod(ll a, ll k, ll m) {
  if (k == 0) return 1;
  ll t = pow_mod(a, k / 2, m);
  return mod(mod(t * t, m) * (k % 2 ? a : 1), m);
}

inline ll inverse(ll a, ll m) {
  return pow_mod(a, m - 2, m);
}

~/contests/tmp% time ./a.out <<< 10 [14:13:19]

249011238

./a.out <<< 10 3.39s user 0.00s system 99% cpu 3.407 total

~/contests/tmp% time ./a.out <<< 10 [14:13:23]

249011238

./a.out <<< 10 3.39s user 0.00s system 99% cpu 3.407 total

~/contests/tmp% time ./a.out <<< 10 [14:13:28]

249011238

./a.out <<< 10 3.37s user 0.02s system 99% cpu 3.411 total

遅くなったw



pow_mod 2

pow_mod を高速そうな実装にしてみる.

inline ll pow_mod(ll a, ll k, ll m) {
  ll r = 1;
  for (; k > 0; k >>= 1) {
    if (k & 1) (r *= a) %= m;
    (a *= a) %= m;
  }
  return r;
}

~/contests/tmp% time ./a.out <<< 10 [14:16:27]

249011238

./a.out <<< 10 0.45s user 0.01s system 99% cpu 0.463 total

~/contests/tmp% time ./a.out <<< 10 [14:16:28]

249011238

./a.out <<< 10 0.47s user 0.00s system 100% cpu 0.468 total

~/contests/tmp% time ./a.out <<< 10 [14:16:31]

249011238

./a.out <<< 10 0.45s user 0.01s system 99% cpu 0.463 total

かなりはやくなったw

少し予想はしていたが,今までのはやはり爆遅だった



非再帰 exgcd

Mi_Sawa さんに教えてもらった(ありがとうございます).確かに速そう.

inline ll exgcd(ll a, ll b, ll &x, ll &y){
  ll u[] = {a, 1, 0}, v[] = {b, 0, 1};
  while(*v){
    ll t = *u / *v;
    rep(i, 3) swap(u[i] -= t * v[i], v[i]);
  }
  x = u[1]; y = u[2];
  return u[0];
}
inline ll inverse(ll a, ll m){
  ll p, q;
  exgcd(a, m, p, q);
  return (p%m+m)%m;
}
手元環境

~/contests/tmp% g++ -O2 inverse.cpp [23:26:03]

~/contests/tmp% time ./a.out <<< 10 [23:26:08]

249011238

./a.out <<< 10 0.65s user 0.00s system 100% cpu 0.649 total

~/contests/tmp% time ./a.out <<< 10 [23:26:10]

249011238

./a.out <<< 10 0.64s user 0.01s system 100% cpu 0.644 total

~/contests/tmp% time ./a.out <<< 10 [23:26:16]

249011238

./a.out <<< 10 0.64s user 0.01s system 100% cpu 0.644 total

自分の環境だと僅かに pow_mod より遅い.

ideone

しかし,ideone に貼りつけたら,exgcd のほうが 2 倍ぐらい速い.

Codeforces

ideone と似たっけかになった.

pow_mod 0: 1.015625 sec

pow_mod 1: 1.014648 sec

pow_mod 2: 1.014649 sec

exgcd 0: 0.695312 sec

exgcd 1: 0.694336 sec

exgcd 2: 0.694336 sec

TopCoder

やっぱしexgcd のほうが 2 倍ぐらい速い.

pow_mod 0: 0.369712 sec

pow_mod 1: 0.351320 sec

pow_mod 2: 0.351127 sec

exgcd 0: 0.171135 sec

exgcd 1: 0.170425 sec

exgcd 2: 0.170366 sec

結論

exgcd のほうが速い環境がどうやら多い,pow_mod のほうが速い時も差は僅か

exgcd のほうがよさそうかも



非再帰 exgcd ループアンローリング

ループアンローリングしたらちょっと速くなった

http://ideone.com/Dz1LLI



整理して

inline ll inverse(ll a, ll m){
  ll b = m, u = 1, v = 0;
  while (b) {
    ll t = a / b;
    swap(a -= t * b, b);
    swap(u -= t * v, v);
  }
  return (u % m + m) % m;
}

Mi_SawaMi_Sawa2013/01/05 20:38自分の環境ではexgcdの方が速かったです.
(pow_modだとコンスタントにlog Mくらいかかりますが, exgcdだと速い時がそれなりにあるので, 良さそうでもある)

inline ll exgcd(ll a, ll b, ll &x, ll &y){
ll u[] = {a, 1, 0}, v[] = {b, 0, 1};
while(*v){
ll t = *u / *v;
rep(i, 3) swap(u[i] -= t * v[i], v[i]);
}
x = u[1]; y = u[2];
return u[0];
}
inline ll invMod(ll a, ll m){
ll p, q;
exgcd(a, m, p, q);
return (p%m+m)%m;
}

iwiwiiwiwi2013/01/06 00:23コメントありがとうございます!!
試してみました,詳しくは記事に追記します.自分の環境だと僅かに pow_mod のほうが高速でしたが,ideone で実行したら確かに貼ってくださった exgcd のほうが 2 倍とか速かったです.

Mi_SawaMi_Sawa2013/01/06 14:36もう一つよいのは, Mが素数である必要がなく, 逆元が無い時も,
ax = gcd(a,M)
なるxを見つけてくれる所ですね.
負の数にちゃんと対応していなかったり(普通に正規化していれば大丈夫ですが, 一度これで引っかかった), 逆元の存在のチェックをしていないので, ロバストにするなら,
ll u[] = {llabs(a), 1, 0}, v[] = {llabs(b), 0, 1};
にしたり,
assert(exgcd(a, m, p, q) == 1)
にしておくとよいです.

Mi_SawaMi_Sawa2013/01/06 16:22あ, ll u[] = {llabs(a), 1, 0}, v[] = {llabs(b), 0, 1};だとダメな気がします, コメント汚して申し訳ないです…
ループ終わったあと, u[0]が負ならrep(i, 3) u[i] = -u[i];とかすればよい気がします…

iwiwiiwiwi2013/01/07 11:35ありがとうございます.張り付けで使うならちょっと長くなっても周りのちょっとしたミスも吸収できるようにできるだけロバストにしておくのが良さそうですよね.

utevaxisuutevaxisu2017/04/29 07:42http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

onecodijonecodij2017/04/29 07:47http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

uigiqikoleuigiqikole2017/04/29 08:04http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

uduluvouduluvo2017/04/29 08:36http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

aqoosotawopaqoosotawop2017/04/29 08:39http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

oqawaaahobooqawaaahobo2017/04/29 08:39http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

eqafifedozovpeqafifedozovp2017/04/29 08:59http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

epesameepesame2017/04/29 09:00http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

itejifuqaitejifuqa2017/04/29 09:16http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

edkuyerugowaedkuyerugowa2017/04/29 09:30http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

omococucomococuc2017/04/29 09:52http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

obefodaeqobefodaeq2017/04/29 14:35http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

iwohaxemiiwohaxemi2017/04/30 01:40http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

oyelujloyelujl2017/04/30 12:01http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

oafocibebupovoafocibebupov2017/04/30 12:25http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

hopuyqahopuyqa2017/05/01 03:27http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

ocusnasitewocusnasitew2017/05/01 03:46http://100mgcheapest-price-viagra.com/ - 100mgcheapest-price-viagra.com.ankor <a href="http://tadalafil-buy-5mg.com/">tadalafil-buy-5mg.com.ankor</a> http://20mgprednisone-order.com/

acheter cialisacheter cialis2018/03/17 22:48<a href=http://achat-cialis-generique.net/>prix cialis</a> cialis pas her
<a href=http://commandercialisgenerique.net/>cialis pas her</a> cialis
<a href=http://acquistarecialisitalia.net/>comprare cialis</a> tadalafil comprare
<a href=http://comprar-cialis-generico.net/>venta cialis</a> cialis precio

DustintofDustintof2018/04/08 14:24cialis professional 20 mg reviews
<a href="http://justinpro.com/#">generic cialis</a>
cialis side effects leg cramps
<a href="http://justinpro.com/#">cialis</a>
is generic cialis safe and effective
<a href="http://airvietnamairline.com/#">buy cialis online</a>
cialis side effects sore legs
<a href="http://airvietnamairline.com/#">buy cialis online</a>
cialis-dapoxetine (generic)

WilliamFexWilliamFex2018/04/10 04:57viagra commercial actress name asian
<a href="http://blessingsofbirth.com/#">generic viagra</a>
viagra dosage
<a href="http://blessingsofbirth.com/#">buy generic viagra online</a>
viagra coupons 75% off print
<a href="http://timmonssoftware.com/#">viagra</a>
female viagra stock price
<a href="http://timmonssoftware.com/#">buy generic viagra</a>
purchase cialis and viagra

WilliamFexWilliamFex2018/04/11 22:10order generic cialis online uk
<a href="http://coastalseaplanes.com/#">generic cialis</a>
cialis daily dosage options
<a href="http://coastalseaplanes.com/#">buy cialis</a>
buy cialis usa
<a href="http://northcoastgetaway.com/#">buy cialis online</a>
levitra cialis viagra comparison
<a href="http://northcoastgetaway.com/#">generic cialis online</a>
cialis soft tabs vs cialis

WilliamFexWilliamFex2018/04/13 18:32buy generic cialis online usa
<a href="http://justinpro.com/#">generic cialis</a>
price of cialis in canada
<a href="http://justinpro.com/#">cialis generic</a>
cialis professional wikipedia
<a href="http://airvietnamairline.com/#">buy cialis</a>
generic cialis super active (tadalafil) 20mg
<a href="http://airvietnamairline.com/#">cialis generic</a>
best price viagra cialis levitra

WilliamFexWilliamFex2018/04/14 09:25cialis 5 mg cost walmart
<a href="http://justinpro.com/#">buy cialis online</a>
price comparison with cialis and viagra
<a href="http://justinpro.com/#">buy cialis online</a>
levitra vs cialis which is better
<a href="http://airvietnamairline.com/#">buy cialis online</a>
cialis commercial song
<a href="http://airvietnamairline.com/#">buy generic cialis</a>
viagra and cialis dosage strength comparison

WilliamFexWilliamFex2018/04/14 23:07youtube viagra commercial 2015 actress blue dress brunettes
<a href="http://amsboatyard.com/#">buy viagra online</a>
youtube viagra commercial 2015 actress blue dress brunettes
<a href="http://amsboatyard.com/#">buy generic viagra online</a>
female viagra review
<a href="http://viagrapillq.com/#">buy generic viagra</a>
compare viagra cialis levitra side effects
<a href="http://viagrapillq.com/#">viagra</a>
100 mg viagra dosage recommendations

WilliamFexWilliamFex2018/04/15 13:04levitra vs cialis vs viagra reviews
<a href="http://coastalseaplanes.com/#">cialis generic</a>
cialis side effects and dosage
<a href="http://coastalseaplanes.com/#">cialis generic</a>
generic cialis usa pharmacy
<a href="http://northcoastgetaway.com/#">buy generic cialis online</a>
cialis side effects
<a href="http://northcoastgetaway.com/#">buy cialis online</a>
cialis coupon 2016 200 dollars

WilliamFexWilliamFex2018/04/16 03:43cost viagra versus cialis
<a href="http://amsboatyard.com/#">viagra generic</a>
viagra commercial actress name
<a href="http://amsboatyard.com/#">buy viagra online</a>
buy pfizer viagra online usa
<a href="http://viagrapillq.com/#">buy generic viagra online</a>
generic viagra (sildenafil) 100mg
<a href="http://viagrapillq.com/#">generic viagra</a>
viagra feminino brasil

WilliamFexWilliamFex2018/04/17 08:54cialis generic price with prescription
<a href="http://coastalseaplanes.com/#">cialis</a>
generic cialis or viagra
<a href="http://coastalseaplanes.com/#">buy cialis</a>
comprar viagra y cialis generico
<a href="http://northcoastgetaway.com/#">cialis generic</a>
cialis 40 mg professional for sale
<a href="http://northcoastgetaway.com/#">cialis</a>
lowest price on generic cialis

WilliamFexWilliamFex2018/04/17 22:15what are the long term effects of viagra
<a href="http://blessingsofbirth.com/#">generic viagra online</a>
viagra cialis levitra genericos
<a href="http://blessingsofbirth.com/#">generic viagra online</a>
viagra dosage and timing
<a href="http://timmonssoftware.com/#">buy viagra online</a>
side effects of viagra medication
<a href="http://timmonssoftware.com/#">viagra</a>
female viagra effects on women

JamesdokJamesdok2018/04/26 07:46effectiveness of cialis vs viagra vs levitra alcohol
<a href="http://cialispaxl.com/">cialis</a>
is there a generic for cialis or viagra
<a href="http://cialispaxl.com/">generic cialis</a>
cialis oral side effects
http://cialispaxl.com/
cialis viagra levitra cost comparison

LouisDumLouisDum2018/04/26 10:57viagra vs cialis comparison
<a href="http://cialisgrudj.com/">buy cialis</a>
viagra vs cialis vs levitra price comparison between
<a href="http://cialisgrudj.com/">buy generic cialis</a>
cialis maximum dosage per week
http://cialisgrudj.com/
cialis dose 40 mg

TrevorkapTrevorkap2018/04/26 14:38cialis manufacturer coupon 2018
<a href="http://cialispaxl.com/">buy generic cialis</a>
generic cialis 5mg daily
<a href="http://cialispaxl.com/">generic cialis</a>
generic for viagra and cialis
http://cialispaxl.com/
best price cialis and viagra

MatthewPreogMatthewPreog2018/04/26 19:49generic cialis in usa store
<a href="http://cialispaxl.com/">buy generic cialis online</a>
free cialis coupon 2015
<a href="http://cialispaxl.com/">buy cialis online</a>
best prices on generic cialis 5mg
http://cialispaxl.com/
lowest cost generic cialis

FrancistatFrancistat2018/04/27 01:00viagra cialis levitra dose comparison
<a href="http://cialispaxl.com/">generic cialis</a>
buy cialis in costa rica
<a href="http://cialispaxl.com/">cialis</a>
redhead actress in cialis commercial
http://cialispaxl.com/
generic cialis on line no pres

WilliamtobWilliamtob2018/04/27 06:12cialis viagra generic
<a href="http://cialispaxl.com/">generic cialis online</a>
how long do side effects of cialis last
<a href="http://cialispaxl.com/">generic cialis online</a>
generic cialis usa pharmacy
http://cialispaxl.com/
cialis generic 20mg professional

DwightSailsDwightSails2018/04/27 11:13cialis cena apoteka
<a href="http://cialispaxl.com/">generic cialis</a>
generic cialis release date
<a href="http://cialispaxl.com/">buy generic cialis</a>
cialis mail in rebate
http://cialispaxl.com/
viagra vs cialis vs levitra prices

RobertSOPRobertSOP2018/04/27 16:32kamagra oral jelly vs cialis
<a href="http://cialispaxl.com/">buy generic cialis</a>
cialis 20 mg vs 5mg
<a href="http://cialispaxl.com/">generic cialis online</a>
when cialis generic 2017
http://cialispaxl.com/
best deals on generic cialis

BillybeectBillybeect2018/04/27 17:09comprar cialis generico no brasil
<a href="http://cialisgrudj.com/">cialis</a>
generic cialis lowest prices
<a href="http://cialisgrudj.com/">buy generic cialis</a>
cialis 5mg pricing
http://cialisgrudj.com/
cialis dosage chart

AndrewRooksAndrewRooks2018/04/27 21:45side effects of cialis 5 mg daily
<a href="http://cialispaxl.com/">generic cialis</a>
cialis 5mg pricing
<a href="http://cialispaxl.com/">buy cialis online</a>
cialis side effects vision
http://cialispaxl.com/
levitra vs cialis price

JerrybokJerrybok2018/04/28 02:49cialis vs viagra side effects
<a href="http://cialispaxl.com/">generic cialis</a>
cialis vs viagra vs levitra review
<a href="http://cialispaxl.com/">buy generic cialis online</a>
how long do cialis side effects last
http://cialispaxl.com/
cialis retail price usa

JamesMeariJamesMeari2018/04/28 08:01cialis generic on the market
<a href="http://cialispaxl.com/">cialis</a>
cialis professional 20 mg
<a href="http://cialispaxl.com/">generic cialis online</a>
generic cialis canada reviews
http://cialispaxl.com/
cialis professional vs viagra professional

SidneyNicSidneyNic2018/04/28 13:09cialis 5mg vs 10mg cost in usa
<a href="http://cialispaxl.com/">buy generic cialis</a>
buy cialis or viagra
<a href="http://cialispaxl.com/">cialis</a>
prices for cialis 5mg
http://cialispaxl.com/
cialis 5 mg price cvs

RogerlotRogerlot2018/04/28 18:21cialis coupon card
<a href="http://cialispaxl.com/">buy generic cialis online</a>
cialis commercial blues song
<a href="http://cialispaxl.com/">cialis</a>
cialis viagra side effects
http://cialispaxl.com/
cialis 5mg daily use

JimmyDomJimmyDom2018/04/28 23:32walmart price for cialis 20 mg
<a href="http://cialispaxl.com/">cialis generic</a>
cialis coupon 2017 $200
<a href="http://cialispaxl.com/">buy cialis</a>
buy cialis soft tabs
http://cialispaxl.com/
viagra vs cialis dosages

JimmySinnyJimmySinny2018/04/29 00:29generic cialis released yet
<a href="http://cialisgrudj.com/">generic cialis online</a>
cialis super active 40 mg
<a href="http://cialisgrudj.com/">generic cialis online</a>
cialis goes generic in 2017
http://cialisgrudj.com/
cialis 20 mg tablet price

BrendanvixBrendanvix2018/04/29 04:42side effects of mixing viagra and cialis
<a href="http://cialispaxl.com/">buy generic cialis online</a>
when generic cialis will be available in usa
<a href="http://cialispaxl.com/">buy cialis</a>
viagra cialis levitra comparison chart
http://cialispaxl.com/
cialis 20mg coupon

StevenSlubsStevenSlubs2018/04/29 09:44cialis generico opinion
<a href="http://cialispaxl.com/">buy generic cialis</a>
cialis canadiam pharmacy
<a href="http://cialispaxl.com/">cialis generic</a>
cialis dosage 10mg or 20mg
http://cialispaxl.com/
viagra cialis levitra genericos

JustinTealOJustinTealO2018/04/29 14:59super active cialis reviews
<a href="http://cialispaxl.com/">buy generic cialis</a>
long term side effects of cialis
<a href="http://cialispaxl.com/">buy cialis online</a>
cialis online cheapest prices
http://cialispaxl.com/
247 overnight pharmacy buy cialis usa

HectordedHectorded2018/04/29 15:30comparison viagra and cialis
<a href="http://cialisgrudj.com/">generic cialis online</a>
cialis generic india daily use
<a href="http://cialisgrudj.com/">cialis generic</a>
generic cialis super active
http://cialisgrudj.com/
viagra vs cialis vs levitra prices

JerryEmpopJerryEmpop2018/04/29 20:11cialis coupon card
<a href="http://cialispaxl.com/">cialis generic</a>
best prices on generic cialis 40 mg
<a href="http://cialispaxl.com/">cialis generic</a>
levitra or cialis or viagra better
http://cialispaxl.com/
release date for generic cialis

KennethWailtKennethWailt2018/04/30 01:24viagra vs cialis cost per pills
<a href="http://cialispaxl.com/">buy cialis</a>
cialis generic india
<a href="http://cialispaxl.com/">buy cialis</a>
will cialis go generic in 2017
http://cialispaxl.com/
generic cialis lowest prices

JosephGorgeJosephGorge2018/04/30 06:31existe generico do cialis no brasil
<a href="http://cialispaxl.com/">buy cialis</a>
cialis side effects muscle aches
<a href="http://cialispaxl.com/">buy cialis</a>
when does cialis go generic in usa
http://cialispaxl.com/
cialis coupons printable

WilliamfructWilliamfruct2018/04/30 06:37cialis tadalafil 10mg tablets
<a href="http://cialisgrudj.com/">buy generic cialis online</a>
cialis super active reviews
<a href="http://cialisgrudj.com/">generic cialis</a>
generic cialis tadalafil 20mg best prices
http://cialisgrudj.com/
cialis 20 mg benefits

StephenburceStephenburce2018/04/30 11:41cialis 5mg dosage instructions
<a href="http://cialispaxl.com/">buy generic cialis online</a>
buy generic cialis canada online
<a href="http://cialispaxl.com/">generic cialis online</a>
cialis 20mg tablets reviews
http://cialispaxl.com/
cost of cialis 5 mg at walmart

VictorLeamiVictorLeami2018/04/30 16:50price comparison of cialis and viagra
<a href="http://cialispaxl.com/">cialis</a>
price of cialis and viagra
<a href="http://cialispaxl.com/">generic cialis</a>
generic cialis sales
http://cialispaxl.com/
cialis 5 mg cost walmart

GeorgeOxymnGeorgeOxymn2018/04/30 21:38brand cialis overnight oats
<a href="http://cialisgrudj.com/">buy cialis</a>
how long do cialis side effects last
<a href="http://cialisgrudj.com/">buy cialis online</a>
cialis dosing options
http://cialisgrudj.com/
cialis price vs viagra

RandalltafRandalltaf2018/04/30 22:02generic cialis 5mg for daily use
<a href="http://cialispaxl.com/">buy cialis</a>
cialis side effects vision
<a href="http://cialispaxl.com/">buy cialis</a>
cialis super active 20 mg
http://cialispaxl.com/
cialis coupons 2016

RogerTubRogerTub2018/05/01 03:11cialis 5 mg generico preço
<a href="http://cialispaxl.com/">buy cialis</a>
cialis side effects muscle cramps
<a href="http://cialispaxl.com/">buy cialis online</a>
buy generic viagra and cialis online pharmacy
http://cialispaxl.com/
is there a generic cialis available in the us

DannyFubDannyFub2018/05/01 08:46generic cialis best price
<a href="http://cialisonlinq.com/">buy generic cialis</a>
cost of generic cialis 5 mg at costco
<a href="http://cialisonlinq.com/">buy cialis</a>
cialis 5mg vs 10mg vs 20 mg
http://cialisonlinq.com/
generic cialis price in india

HenryGeankHenryGeank2018/05/01 16:04cialis 5mg daily use study effectiveness
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
cialis eye side effects
<a href="http://cialisonlinq.com/">buy generic cialis</a>
difference between viagra and cialis dosage
http://cialisonlinq.com/
tadalafil cialis 10mg

DavidStunkDavidStunk2018/05/01 23:50viagra vs cialis vs levitra price
<a href="http://viagrapipls.com/">buy generic viagra online</a>
generic viagra vs cialis
<a href="http://viagrapipls.com/">buy generic viagra online</a>
levitra viagra cialis cost comparison
http://viagrapipls.com/
ideal time to take viagra

PrestonTeavyPrestonTeavy2018/05/02 01:52generic cialis coming
<a href="http://cialisonlinq.com/">buy cialis</a>
side effects of viagra and cialis
<a href="http://cialisonlinq.com/">cialis</a>
cialis online ebay
http://cialisonlinq.com/
cialis extra dosage directions

DannydyEloDannydyElo2018/05/02 07:42cialis price versus viagra side effects
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
acquisto cialis generico in italia
<a href="http://cialisonlinq.com/">cialis generic</a>
cialis 5mg best price india
http://cialisonlinq.com/
cialis or viagra reviews

DavidGefDavidGef2018/05/02 17:48youtube viagra commercial 2015 cast
<a href="http://viagrapipls.com/">buy viagra</a>
viagra price drop canada
<a href="http://viagrapipls.com/">buy viagra online</a>
generic viagra effective
http://viagrapipls.com/
female viagra medication

WillielicWillielic2018/05/02 23:41why separate bathtubs in cialis commercials
<a href="http://cialisonlinq.com/">buy cialis</a>
viagra dosage vs cialis dosage
<a href="http://cialisonlinq.com/">generic cialis</a>
cialis or viagra generic
http://cialisonlinq.com/
walgreens price for cialis 5mg

MichaelcheceMichaelchece2018/05/03 11:31viagra generic canada discount
<a href="http://viagrapipls.com/">generic viagra</a>
levitra vs cialis vs viagra
<a href="http://viagrapipls.com/">buy viagra online</a>
viagra como devo tomar
http://viagrapipls.com/
generic viagra professional

RoycetipRoycetip2018/05/03 14:52generic for cialis or viagra
<a href="http://cialisonlinq.com/">generic cialis online</a>
cialis super active 20mg
<a href="http://cialisonlinq.com/">buy generic cialis</a>
cialis 5 mg side effects
http://cialisonlinq.com/
generic cialis shipped from usa

EugeneSponyEugeneSpony2018/05/04 04:23viagra coupons 75% off print
<a href="http://viagrapipls.com/">viagra</a>
viagra vs cialis vs levitra price
<a href="http://viagrapipls.com/">buy viagra online</a>
viagra commercial actress name football
http://viagrapipls.com/
time to take viagra

JerrybobJerrybob2018/05/04 05:32cialis and viagra dosage differences
<a href="http://cialisonlinq.com/">cialis</a>
cialis 5mg daily price in the united states
<a href="http://cialisonlinq.com/">buy cialis</a>
generic cialis super active
http://cialisonlinq.com/
viagra vs cialis price comparison

AndrewWrogeAndrewWroge2018/05/04 06:11brand cialis vs generic cialis
<a href="http://cialisonlinq.com/">cialis generic</a>
cipla generic cialis india
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
cost of generic cialis
http://cialisonlinq.com/
cialis 20 mg 8 tablet fiyatД±

JustinSwonsJustinSwons2018/05/04 20:29cialis price vs viagra which is better
<a href="http://cialisonlinq.com/">buy cialis</a>
viagra levitra cialis cost comparison
<a href="http://cialisonlinq.com/">generic cialis</a>
maximum dosage for cialis
http://cialisonlinq.com/
cialis side effects itching

JosephNugJosephNug2018/05/04 23:25cialis generic india daily use
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
viagra and cialis dosage and cost comparison between
<a href="http://cialisonlinq.com/">generic cialis online</a>
cialis generic or brand name
http://cialisonlinq.com/
cialis 5 mg tablet coupon

ArthurPromoArthurPromo2018/05/05 11:44cialis medication information
<a href="http://cialisonlinq.com/">buy generic cialis</a>
black male actor in cialis commercial
<a href="http://cialisonlinq.com/">cialis generic</a>
buy cialis in usa
http://cialisonlinq.com/
brand name cialis vs generic

HarryslamyHarryslamy2018/05/05 14:42comprar viagra cialis generico
<a href="http://viagrapipls.com/">buy generic viagra</a>
best generic viagra brands
<a href="http://viagrapipls.com/">buy generic viagra</a>
viagra other medical uses
http://viagrapipls.com/
viagra and cialis dose strength comparison

MichaelCrodoMichaelCrodo2018/05/05 16:37side effects of cialis 5mg
<a href="http://cialisonlinq.com/">generic cialis online</a>
cialis diario generico preço
<a href="http://cialisonlinq.com/">generic cialis</a>
walgreen cialis price without insurance
http://cialisonlinq.com/
cost comparison viagra vs cialis vs levitra

RusselGamRusselGam2018/05/06 02:48cialis 20 mg side effects
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
cost of cialis vs viagra vs levitra
<a href="http://cialisonlinq.com/">cialis</a>
5 mg cialis price at cvs
http://cialisonlinq.com/
generic cialis available in usa

DonaldLopDonaldLop2018/05/06 07:52brand viagra overnight
<a href="http://viagrapipls.com/">viagra</a>
comprar viagra cialis o levitra generico
<a href="http://viagrapipls.com/">generic viagra</a>
viagra super active plus 100mg
http://viagrapipls.com/
viagra dosage instructions

KevinnixKevinnix2018/05/06 09:47comprar viagra cialis o levitra generico
<a href="http://cialisonlinq.com/">buy cialis online</a>
maximum dose of cialis in 24 hours
<a href="http://cialisonlinq.com/">buy cialis online</a>
cialis generico espaГ±a paypal
http://cialisonlinq.com/
comprar cialis generico en chile

BrendanFrernBrendanFrern2018/05/06 18:07once daily use generic cialis
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
cialis printable coupon 2017
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
reviews of cialis professional
http://cialisonlinq.com/
cialis main ingredient

RichardbemRichardbem2018/05/07 01:12viagra cialis generici
<a href="http://viagrapipls.com/">buy viagra online</a>
generic viagra (sildenafil) 100mg
<a href="http://viagrapipls.com/">buy viagra</a>
viagra dosage forms
http://viagrapipls.com/
viagra order usa

RalphMorRalphMor2018/05/07 03:12generic cialis lowest price
<a href="http://cialisonlinq.com/">buy generic cialis</a>
cialis side effects
<a href="http://cialisonlinq.com/">cialis generic</a>
cialis dosage uk
http://cialisonlinq.com/
cialis 5mg vs 10mg

MichaelAnyncMichaelAnync2018/05/07 08:55cialis vs viagra effectiveness
<a href="http://cialisonlinq.com/">buy cialis online</a>
cialis 20 mg doses
<a href="http://cialisonlinq.com/">cialis generic</a>
viagra cialis or levitra reviews
http://cialisonlinq.com/
prices of cialis and viagra

LamarorentLamarorent2018/05/07 18:15comprar viagra generico en mexico
<a href="http://viagrapipls.com/">generic viagra online</a>
cheap generic viagra in canada
<a href="http://viagrapipls.com/">buy generic viagra</a>
viagra dosage recommendations by weight
http://viagrapipls.com/
what is the generic pill for viagra

DavidImakeDavidImake2018/05/07 20:18long do cialis side effects last
<a href="http://cialisonlinq.com/">generic cialis online</a>
cialis side effects vision
<a href="http://cialisonlinq.com/">buy generic cialis</a>
cialis tadalafil 20 mg 4 tablet
http://cialisonlinq.com/
cialis side effects leg cramps

AnthonyCoxAnthonyCox2018/05/08 00:02generic cialis for daily use prices
<a href="http://cialisonlinq.com/">buy generic cialis online</a>
how long do side effects of cialis last
<a href="http://cialisonlinq.com/">buy generic cialis</a>
when will cialis or viagra go generic
http://cialisonlinq.com/
low cost generic cialis

ThomasLofThomasLof2018/05/08 11:09coupons for viagra from pfizer
<a href="http://viagrapipls.com/">buy generic viagra online</a>
viagra effects women
<a href="http://viagrapipls.com/">buy viagra online</a>
viagra comprar
http://viagrapipls.com/
generic cialis viagra

HectorLoonoHectorLoono2018/05/08 13:09cialis 5mg daily
<a href="http://cialisonlinq.com/">buy generic cialis</a>
cialis 20mg cost per pill
<a href="http://cialisonlinq.com/">buy generic cialis</a>
extra super cialis combitic global
http://cialisonlinq.com/
maximum daily dose of cialis

RichardEmincRichardEminc2018/05/08 14:36best price on brand cialis
<a href="http://cialisonlinq.com/">buy cialis</a>
professional samples of cialis
<a href="http://cialisonlinq.com/">generic cialis online</a>
cialis super active vs cialis
http://cialisonlinq.com/
effectiveness of cialis vs viagra

DennisCefDennisCef2018/05/09 04:21viagra generic release date usa
<a href="http://viagrapipls.com/">viagra</a>
what is generic viagra called in spain
<a href="http://viagrapipls.com/">viagra generic</a>
qual dosagem de viagra tomar
http://viagrapipls.com/
viagra generic costs

SteveLizSteveLiz2018/05/09 05:51generic daily cialis lowest price
<a href="http://cialisonlinq.com/">buy generic cialis</a>
cialis coupon printable 2017
<a href="http://cialisonlinq.com/">generic cialis online</a>
cialis tadalafil 20 mg price in pakistan
http://cialisonlinq.com/
cialis commercial black woman

EdwardBrureEdwardBrure2018/05/09 06:23cialis generico en mexico
<a href="http://cialisonlinq.com/">generic cialis</a>
effectiveness of cialis vs viagra vs levitra vs kamagra
<a href="http://cialisonlinq.com/">cialis</a>
cost of cialis or viagra
http://cialisonlinq.com/
vidalista professional generic cialis 20mg

StephenAgoliStephenAgoli2018/05/09 10:03kamagra oral jelly 100mg price in india
<a href="http://kamagraonl.com/">buy kamagra online</a>
kamagra reviews users
<a href="http://kamagraonl.com/">kamagra 100 mg oral jelly</a>
kamagra forum 2015
http://kamagraonl.com/
kamagra 100mg tablets for sale in use

EdgarAlambEdgarAlamb2018/05/09 20:21cialis side effects acid reflux
<a href="http://airvietnamairline.com/">generic cialis online</a>
cialis super active vs regular cialis
<a href="http://airvietnamairline.com/">buy cialis</a>
generic cialis sales
http://airvietnamairline.com/
cialis side effects long term

RichardTeegeRichardTeege2018/05/09 21:05compare viagra versus cialis
<a href="http://amsboatyard.com/">viagra</a>
viagra prices 2016
<a href="http://amsboatyard.com/">buy generic viagra</a>
viagra caseiro que funciona na hora
http://amsboatyard.com/
viagra natural foods

MichaeltAispMichaeltAisp2018/05/09 21:10kamagra reviews forum
<a href="http://kamagraonl.com/">kamagra 100mg</a>
kamagra oral jelly uses
<a href="http://kamagraonl.com/">kamagra 100mg</a>
kamagra 100mg side effects
http://kamagraonl.com/
kamagra gel forum hr

JosephsoaleJosephsoale2018/05/10 11:33cialis generic availability 2017
<a href="http://airvietnamairline.com/">generic cialis</a>
extra super cialis lowest price
<a href="http://airvietnamairline.com/">buy cialis online</a>
generic cialis costa rica
http://airvietnamairline.com/
brand cialis overnight oats

JamesFAwJamesFAw2018/05/10 14:16viagra stendra cialis levitra side effects
<a href="http://amsboatyard.com/">generic viagra online</a>
levitra vs viagra side effects
<a href="http://amsboatyard.com/">buy viagra online</a>
youtube viagra commercial 2015 football
http://amsboatyard.com/
compare viagra cialis levitra side effects

MarionalafeMarionalafe2018/05/10 14:19kamagra reviews users
<a href="http://kamagraonl.com/">kamagra 100 mg</a>
kamagra 100mg tablets review
<a href="http://kamagraonl.com/">buy kamagra 100 mg oral jelly</a>
kamagra oral jelly for sale in usa
http://kamagraonl.com/
kamagra 100mg chewable tablets

JefferyjogJefferyjog2018/05/11 02:30cialis side effects and dangers
<a href="http://airvietnamairline.com/">generic cialis online</a>
cialis tadalafil 20 mg price in pakistan
<a href="http://airvietnamairline.com/">buy cialis online</a>
viagra vs cialis cost per pillow
http://airvietnamairline.com/
20 mg dose of cialis

KennethwipKennethwip2018/05/11 17:06kamagra 100 oral jelly how to use
kamagra jelly amazon
kamagra gold jelly
kamagra bestellen amsterdam

DerekvopsyDerekvopsy2018/05/30 15:33dating <a href= http://trimdisk.ru/ > online </a> here "http://teledesks.ru/" - dating site http://brightinero.ru/

JuniorfugJuniorfug2018/06/17 14:53viagra soft 100mg reviews
<a href="http://viagrapipls.com/">buy generic viagra</a>
viagra cialis cost
<a href="http://viagrapipls.com/">buy viagra</a>
viagra tv ad girl

JaredceackJaredceack2018/06/19 03:20viagra professional 100mg ft myers fl
<a href="http://amsboatyard.com/">buy generic viagra</a>
buy viagra best price
<a href="http://amsboatyard.com/">buy generic viagra</a>
viagra generico espaГ±a

DanielAsypeDanielAsype2018/06/23 00:29kamagra 100mg oral jelly amazon
<a href="http://kamagraonl.com/">kamagra oral jelly</a>
chewable kamagra polo 100mg
<a href="http://kamagraonl.com/">buy kamagra oral jelly</a>
buy kamagra oral jelly online in india

AntonLotAntonLot2018/06/28 03:03cheapest generic viagra and cialis
<a href="http://cialisgenericsa.com/">cialis generic</a>
generic brand for cialis 5mg daily cialis
<a href="http://cialisgenericsa.com/">buy generic cialis</a>
cialis soft tabs 40mg

AntonLotAntonLot2018/06/30 10:06cialis generico mejor precio
<a href="http://cialisgenericsa.com/">generic cialis</a>
actress in cialis commercial
<a href="http://cialisgenericsa.com/">cialis generic</a>
generic cialis released yet

FloydDydayFloydDyday2018/06/30 10:39kamagra jelly side effects
<a href="http://kamagradyn.com/">kamagra 100mg</a>
kamagra oral jelly online usa
<a href="http://kamagraonl.com/">kamagra oral jelly</a>
kamagra gold 100mg reviews

AllanaropsAllanarops2018/07/01 23:44cialis 20mg dosage frequency
<a href="http://cialispaxl.com/">buy generic cialis</a>
woman tennis player in cialis commercial
<a href="http://cialispaxl.com/">generic cialis</a>
cialis generic safe

RobertDeeskRobertDeesk2018/07/13 10:28kamagra oral jelly wirkungszeit
<a href="https://www.kamagrapos.com/">kamagra oral jelly</a>
kamagra store in nyc
<a href="https://www.kamagrapos.com/">kamagra oral jelly</a>
kamagra store in nyc

CharlesUtinkCharlesUtink2018/07/15 14:26viagra cialis genericos
<a href="http://viagrapipls.com/">generic viagra</a>
viagra generic 100mg cost
<a href="http://viagrapipls.com/">viagra generic</a>
best generic viagra brands
http://viagrapipls.com/
viagra professional

HaroldgowHaroldgow2018/07/16 07:59kamagra store
<a href="https://www.kamagradax.com/">kamagra</a>
kamagra store reviews
<a href="https://www.kamagradax.com/">kamagra 100mg oral jelly</a>
kamagra oral jelly price in india

JackieIsolOJackieIsolO2018/07/30 11:27kamagra 100mg tablets usage
<a href="https://www.kamagrapos.com/">kamagra jelly</a>
kamagra jelly use
<a href="https://www.kamagrapos.com/">buy kamagra oral jelly</a>
kamagra 100mg oral jelly suppliers indiana

FloydSenFloydSen2018/08/04 23:585mg cialis daily reviews
<a href="http://airband.ru/Catalog-ab/skachat-minusovku-pesni-aurika-rotaru-a-trava-na-lugu.html">скачать минусовку песни аурика ротару-а трава на лугу</a>
buy cialis viagra online
<a href="http://airband.ru/Catalog-ab/luk-patcher-skachat-na-android.html">лук патчер скачать на андроид</a>
cialis commercial bathtub
http://airband.ru/Catalog-ab/plan-vihovno-roboti-klasnogo-kervnika-dlya-6-klasu-skachati.html
cialis generic name india

2012-12-19

SMT Solver (z3) で探索問題を解く

23:01 | SMT Solver (z3) で探索問題を解く - (iwi) { 反省します を含むブックマーク はてなブックマーク - SMT Solver (z3) で探索問題を解く - (iwi) { 反省します SMT Solver (z3) で探索問題を解く - (iwi) { 反省します のブックマークコメント

ちょっと触る機会があったのでメモ程度に書いておく.Python は普段使わないのでコードはあまりよくないかもしれない.


はじめに

SMT Solver?

SMT Solver とは SAT Solver より色々できるひとたち. SMT って,SAT に比べてあまり名前を聞かないという人も多いかと思うが,SAT Solver の界隈では,実は SAT と SMT は並列にタイトルに入るぐらいには話題沸騰なのである.


z3?

最強の SMT Solver の 1 つっぽい. Microsoft Research で開発されている. Python から簡単に呼べる z3py というのがあって,ウェブからすぐ使ってみることのできるデモまである.すごい.これを見れば大体 SMT Solver でどんなことができるかの雰囲気がよく分かると思う.

最新版を git から clone してビルドしてインストールしたらスグに z3 が python から使えた.ビルドの際,dos2unix がないと駄々をこねていたので,ln -s todos unix2dos してやった.



書いてみたコード

Captain Q's Treasure (ICPC福岡2011 G)

公式データセットに対して 4 秒で走る.とはいえそもそも IP だから SMT Solver で解く意義は薄い.とりあえず定式化が簡単そうなのでやってみた.

from z3 import *

while 1:
    #
    # Input
    #
    h, w = map(int, raw_input().split())
    if h == 0 and w == 0:
        break
    field = [raw_input() for i in range(h)]

    #
    # Constraints
    #
    var_x = [ [ Int("x_%s_%s" % (i + 1, j + 1)) for j in range(w) ] for i in range(h) ]

    solver = Solver()
    solver.add([var_x[y][x] == 0 if field[y][x] == '.' else And(0 <= var_x[y][x], var_x[y][x] <= 1)
                for x in range(w) for y in range(h) ])

    for y in range(h):
        for x in range(w):
            if '0' <= field[y][x] and field[y][x] <= '9':
                xs = []
                for dy in [-1, 0, 1]:
                    for dx in [-1, 0, 1]:
                        cx = x + dx
                        cy = y + dy
                        if cx >= 0 and cx < w and cy >= 0 and cy < h:
                            xs += [var_x[cy][cx]]
                solver.add(Sum(xs) == int(field[y][x]))

    xs = [var_x[y][x] for y in range(h) for x in range(w)]

    #
    # Solve
    #
    low = -1
    high = h * w
    while high - low > 1:
        mid = (low + high) / 2
        solver.push()
        solver.add(Sum(xs) <= mid)
        if solver.check() == sat:
            high = mid
        else:
            solver.pop()
            low = mid
    print high

15 パズル

次に挑戦するものとしてはタフすぎた気配がするw 定式化大変だった.

で,性能だが,3x3 の 8 パズルだとわりと何とかなるぽいが,4x4 の 15 パズルだと 10 手以下のものは解けるけど増えるにしたがってやばくなっていく.

しょんぼりやな.

from z3 import *

god = 20  # limit...

def solve(field, goal):
    #goal = ((1,2,3),(4,5,6),(7,8,0))
    h = len(field)
    w = len(field[0])

    print [h, w]

    x0, y0 = -1, -1
    for x in range(w):
        for y in range(h):
            if field[y][x] == 0:
                x0 = x
                y0 = y

    print [x0, y0]

    var_f = [ [ [ Int("f_%s_%s_%s" % (g, y + 1, x + 1)) for x in range(w) ] for y in range(h) ] for g in range(god + 1) ]
    var_d = [ Int("d_%s" % (g)) for g in range(god) ]
    var_x = [ Int("x_%s" % (g)) for g in range(god + 1) ]
    var_y = [ Int("y_%s" % (g)) for g in range(god + 1) ]

    #
    # Placement
    #
    constraint_init = []

    for g in range(god):
        constraint_init += [var_f[0][y][x] == field[y][x] for x in range(w) for y in range(h) ]
        constraint_init += [var_x[0] == x0]
        constraint_init += [var_y[0] == y0]
        constraint_init += [var_f[god - 1][y][x] == goal[y][x] for x in range(w) for y in range(h) ]

    #
    # Movement
    #
    constraint_move = []
    dx = [1, 0, -1, 0, 0]
    dy = [0, 1, 0, -1, 0]

    for g in range(god):
        cx = var_x[g]
        cy = var_y[g]
        d = var_d[g]
        nx = var_x[g + 1]
        ny = var_y[g + 1]
        constraint_move += [Or([And(d == i, nx == cx + dx[i], ny == cy + dy[i]) for i in range(5)])]
        constraint_move += [0 <= nx, nx < w, 0 <= ny, ny < h]

    #
    # Board
    #
    constraint_board = []

    def gen_move(cf, nf, x, y, d, r, i = 0):
        if i == 4:
            return nf[y][x] == cf[y][x]
        else:
            j = (4 if i == 4 else (i + 2) % 4) if r else i
            tx = min(max(x + dx[j], 0), w - 1)
            ty = min(max(y + dy[j], 0), h - 1)
            return If(d == i, nf[ty][tx] == cf[y][x], gen_move(cf, nf, x, y, d, r, i + 1))

    for g in range(god):
        cx = var_x[g]
        cy = var_y[g]
        cf = var_f[g]
        nx = var_x[g + 1]
        ny = var_y[g + 1]
        nf = var_f[g + 1]
        d = var_d[g]
        for x in range(w):
            for y in range(h):
                constraint_board += [
                    If(And(x == cx, y == cy), gen_move(cf, nf, x, y, d, False),
                       If(And(x == nx, y == ny), gen_move(cf, nf, x, y, d, True),
                          nf[y][x] == cf[y][x]))]

    #
    # Solve!
    #
    solver = Solver()
    solver.add(constraint_init + constraint_move + constraint_board)
    for target in reversed(xrange(god)):
        solver.add(var_d[target] == 4)
        print [target, solver.check()]

solve(((1,2,3,4),(9,5,6,7),(13,10,11,8),(0,14,15,12)),
      ((1,2,3,4),(5,6,7,8),(9,10,11,12),(13,14,15,0)))
|