Skip to content

779. K-th Symbol in Grammar #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

fhiyo
Copy link
Owner

@fhiyo fhiyo commented Jul 19, 2024

Copy link

@hayashi-ay hayashi-ay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

良いと思います。

@SuperHotDogCat
Copy link

良いと思います。

assert n >= 2
half_num_elements = 2 ** (n - 2) # 2**(n-1) // 2
assumption = 0
x = assumption

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assumptionは不要な気がしました。(意図的だったらすみません。)

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

一応意図的ではありました 🙏
この変数あった方が分かりやすいかな?と思って書きましたが諸説あるかも...

Comment on lines +12 to +13
- 時間計算量: O((log n)^2)
- 空間計算量: O(1)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これってどういう計算でしょうか。

最悪n-1回再起呼び出しがあって、whileループが最初n-1回から1つずつ減っていって、
(n-1) + (n-2) + ... + 1 = (n-1)(n-2)/2 で
時間がO(n^2)で、空間がO(n)かなと思いましたが勘違いしてますかね。

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

たぶん何を n としているかが違っていて、桁数ではなくて引数の n 自体のことでしょう。
それだと空間は確かに O(log n) ですね。関数の呼び出しスタックがあります。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O(1)は明らかに変ですね、ありがとうございます。

桁数ではなくて引数の n 自体のことでしょう

そのつもりで書きましたが、改めて考えるとよくわからなくなりました。 1 <= k <= 2**n - 1 の条件から、

空間計算量: k/2 <= power < k から k-power <= k/2 なので、kは再帰のたびに少なくとも半分に減っていくので再帰の数はO(log k), つまりO(n) で抑えられる。

時間計算量: 関数呼び出しのたびに毎回ln k 回ループを回すので、i番目の再帰のときのkの数をk(i)とすると、

$$ \begin{align} &\ln k(0) + \ln k(1) + ... + \ln k(a)\ (k(a) = 1) \\ &= \sum_{i=0}^{a} \ln k(i) \\ &\approx \sum_{i=0}^{a} \ln k/2^i \\ &= \sum_{i=0}^{a} \ln k - i \\ &= (a+1)\ln k - (1/2) * a(a+1) \\ \end{align} $$

a = O(log k) = O(n) なので、O((log k)^2) = O(n^2)

なのかなと計算して思いましたが、自信はないです

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants