Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long jc[14]; long long ans[14]; int n, k; int vis[14]; void f(long long k, int dep) { if (dep == 0) { return; } if (jc[dep - 1] > k) { for (int i = 1; i <= n; i++) { if (!vis[i]) { ans[min(n, 13) - dep] = i; vis[i] = 1; f(k, dep - 1); return; } } } else { int d = 1; while (dep != 1 && jc[dep - 1] * (d) <= k) { d++; } int ff = 0; int i; for (i = 1; i <= n; i++) { if (!vis[i]) { ff++; } if (ff == d) { vis[i] = 1; break; } } ans[min(n, 13) - dep] = i; f(k - jc[dep - 1] * (d - 1), dep - 1); } } bool is(int p) { if (p == 0) return false; while (p) { if (p % 10 != 4 && p % 10 != 7) return false; p /= 10; } return true; } int main(int argc, char** argv) { scanf("%d%d", &n, &k); jc[0] = 0; jc[1] = 1; int p = n, st = 1; for (int i = 2; i <= 13; i++) { jc[i] = jc[i - 1] * i; } k--; if (n <= 13 && jc[n] <= k) { cout << -1; return 0; } if (n > 13) { p = 13; st = n - 13 + 1; } f(k, min(13, n)); int anss = 0; int qq = n - p, fl = 1; if (qq) for (int k = 1; k <= 9; k++) { for (int i = 0; i < (1 << k); i++) { long long g = 0; long long q = 1; for (int j = 0; j < k; j++) { if ((1 << j) & i) { g += 7 * q; } else { g += 4 * q; } q *= 10; } if (g > qq) { fl = 0; break; } if (g <= qq) anss++; } if (!fl) break; } for (int i = 0; i < p; i++) { if (is(ans[i] - 1 + st) && is(i + st)) { anss++; } } cout << anss; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int findFirstNumIndex(int& k, int n) { if (n == 1) return 0; n--; int first_num_index; int n_partial_fact = n; while (k >= n_partial_fact && n > 1) { n_partial_fact = n_partial_fact * (n - 1); n--; } first_num_index = k / n_partial_fact; k = k % n_partial_fact; return first_num_index; } vector<int> findKthPermutation(int n, int k) { vector<int> ans; set<int> s; for (int i = 1; i <= n; i++) s.insert(i); set<int>::iterator itr; itr = s.begin(); k = k - 1; for (int i = 0; i < n; i++) { int index = findFirstNumIndex(k, n - i); advance(itr, index); ans.push_back((*itr)); s.erase(itr); itr = s.begin(); } return ans; } bool islucky(int n) { while (n > 0) { if ((n % 10 != 4) && (n % 10 != 7)) return false; n /= 10; } return true; } int getans(long long x, int n) { if (x > n) return 0; return getans(x * 10LL + 4LL, n) + getans(x * 10LL + 7LL, n) + (x != 0); } int main() { int n, k; cin >> n >> k; vector<long long> fact(14); fact[0] = 1; for (long long i = 1; i < 14; i++) { fact[i] = fact[i - 1] * i; } if (n < 14 && fact[n] < k) { cout << -1 << endl; return 0; } int y = min(13, n); vector<int> ans = findKthPermutation(y, k); long long cnt = 0; map<int, int> mm; for (int i = n, j = y; i > n - y; --i, --j) { mm[j] = i; } for (int i = 0; i < ans.size(); i++) { ans[i] = mm[ans[i]]; } cnt += (getans(0, n - y)); for (int x = n - y + 1, i = 0; x <= n; ++x, ++i) { cnt += (islucky(x) && islucky(ans[i])); } cout << cnt << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; map<long long, int> ha; long long n, m, mm; int ans; int a[20], s, vis[20]; long long p[10000]; long long ch[20]; void dfs(int k, long long t) { long long tt; if (k == 10) return; tt = t * 10 + 4; p[++s] = tt; ha[tt] = 1; dfs(k + 1, tt); tt = t * 10 + 7; p[++s] = tt; ha[tt] = 1; dfs(k + 1, tt); } void work() { int i, j, len, k; memset(vis, 0, sizeof(vis)); ch[0] = 1; for (i = 1; i <= 13; i++) ch[i] = ch[i - 1] * i; m--; for (i = 1; i <= 13; i++) { k = 13 - i; for (j = 1; j <= 13; j++) { if (vis[j]) continue; if (m >= ch[k]) m -= ch[k]; else { a[i] = j; vis[j] = 1; break; } } } } void solve() { int i, j, k; ans = 0; if (n > 13) { for (i = 1; i <= s; i++) if (p[i] <= n - 13) ans++; else break; for (i = 1; i <= 13; i++) if (ha[a[i] + n - 13] > 0 && ha[n - 13 + i] > 0) ans++; } else { if (ch[n] < mm) { printf("-1\n"); return; } k = 13 - n; for (i = 1; i <= n; i++) if (ha[a[i + k] - k] && ha[i]) ans++; } printf("%d\n", ans); } int main() { int i, j, k; s = 0; ha.clear(); dfs(0, 0); sort(p + 1, p + s + 1); scanf("%I64d%I64d", &n, &m); mm = m; work(); solve(); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> std::vector<long long> generateLuckyNumbers(long long limit) { std::vector<long long> result; std::queue<long long> Q; Q.push(4); Q.push(7); while (!Q.empty()) { long long x = Q.front(); Q.pop(); if (x <= limit) { result.push_back(x); Q.push(x * 10 + 4); Q.push(x * 10 + 7); } } sort(result.begin(), result.end()); return result; } inline bool is_lucky(long long n) { std::stringstream ss; ss << n; std::string s; ss >> s; for (int i = 0; i < (s.size()); ++i) if (s[i] != '4' && s[i] != '7') { return false; } return true; } long long silnie[16]; bool used[16]; int main() { silnie[0] = 1; for (int i = (1); i <= (14); ++i) silnie[i] = silnie[i - 1] * i; long long n, k; std::cin >> n >> k; long long limit = 1, silnia = 1; while (silnia < k) { ++limit; silnia *= limit; } if (limit > n) { std::cout << -1 << std::endl; return 0; } std::vector<int> permutacja; for (int i = 0; i < (limit); ++i) { used[i] = false; } for (int i = 0; i < (limit); ++i) { int wskaznik = 0; while (used[wskaznik]) { ++wskaznik; } while (k > silnie[limit - i - 1]) { k -= silnie[limit - i - 1]; do { ++wskaznik; } while (used[wskaznik]); } permutacja.push_back(wskaznik); used[wskaznik] = true; } std::vector<long long> luckyNums = generateLuckyNumbers(n); std::vector<int> wartosci; for (int i = (n - limit + 1); i <= (n); ++i) { if (std::find(luckyNums.begin(), luckyNums.end(), i) != luckyNums.end()) { wartosci.push_back(1); } else { wartosci.push_back(0); } } int dodatek = 0; for (int i = 0; i < (limit); ++i) if (wartosci[i] && is_lucky(permutacja[i] + n - limit + 1)) { ++dodatek; } int ilu_najpierw = std::upper_bound(luckyNums.begin(), luckyNums.end(), n - limit) - luckyNums.begin(); std::cout << ilu_najpierw + dodatek << std::endl; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long fac[14]; vector<long long> lucky; bool isLucky(long long n) { int x; while (n) { x = n % 10; n /= 10; if (x == 4 || x == 7) continue; return 0; } return 1; } void gen(long long n) { long long x = n * 10; if (x > 1000000000ll) return; x += 4; lucky.push_back(x); gen(x); x += 3; lucky.push_back(x); gen(x); } int main() { int i, j, r, ans; long long n, k, m; cin >> n >> k; fac[0] = 1; for (i = 1; i < 14; i++) fac[i] = i * fac[i - 1]; if (n < 14 && fac[n] < k) { cout << -1; return 0; } gen(0); lucky.push_back(4444444444ll); sort(lucky.begin(), lucky.end()); m = max(n - 13, 0ll); ans = upper_bound(lucky.begin(), lucky.end(), m) - lucky.begin(); vector<bool> used(n - m + 1, false); for (i = n - m; i >= 1; i--) { r = (k + fac[i - 1] - 1) / fac[i - 1]; k -= (r - 1) * fac[i - 1]; for (j = 1;; j++) if (!used[j]) { r--; if (!r) break; } used[j] = 1; if (isLucky(n - i + 1) && isLucky(m + j)) ans++; } cout << ans; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> const double eps = 1e-9; const int int_inf = 1 << 31 - 1; const long long i64_inf = 1ll << 63 - 1; const double pi = acos(-1.0); using namespace std; int n; long long k; int res = 0; int a[20]; int b[20]; long long fac[20]; vector<int> L; void gen(int a = 0, int len = 0) { L.push_back(a); if (len == 9) return; gen(a * 10 + 4, len + 1); gen(a * 10 + 7, len + 1); } int lucky(int a) { if (a < 4) return 0; int l = 0; int r = L.size(); while (l != r - 1) { int m = (l + r) >> 1; if (L[m] <= a) l = m; else r = m; } return l; } bool isluck(int a) { return *lower_bound(L.begin(), L.end(), a) == a; } int main() { fac[1] = 1ll; for (int i = 2; i < 15; i++) fac[i] = fac[i - 1] * 1ll * (long long)i; gen(); sort(L.begin(), L.end()); cin >> n >> k; if (n <= 13 && fac[n] < k) { puts("-1"); return 0; } int sz = min(n, 13); for (int i = sz - 1; i >= 0; i--) a[i] = n - (sz - i - 1); for (int i = 0; i < sz; i++) { sort(a + i, a + sz); for (int j = i; j < sz; j++) { long long m = j - i; if (k <= fac[sz - i - 1] * (m + 1)) { swap(a[i], a[j]); k -= fac[sz - i - 1] * m; break; } } } for (int i = sz - 1; i >= 0; i--) b[i] = n - (sz - i - 1); res = lucky(n - 13); for (int i = 0; i < sz; i++) res += isluck(a[i]) && isluck(b[i]); cout << res << "\n"; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; bool ok(long long n, long long k) { if (n >= 13) return true; long long r = 1; for (int i = 0; i < n; i++) r *= (i + 1); if (r > k) return true; return false; } long long fact(int n) { if (n >= 13) return 10000000007ll; long long ret = 1ll; for (int i = 0; i < n; i++) ret *= 1ll * (i + 1ll); return ret; } bool islucky(long long a) { while (a) { if (a % 10 != 4 && a % 10 != 7) return false; a /= 10ll; } return true; } long long n, k; void oku() { cin >> n >> k; k--; int cnt = 0; if (!ok(n, k)) { cout << -1; return; } set<int> s; for (int len = 1; len < 10; len++) for (int mask = 0; mask < 1 << len; mask++) { long long sum = 0; for (int j = 0; j < len; j++) if ((mask & (1 << j)) > 0) sum = sum * 10 + 4ll; else sum = sum * 10 + 7ll; if (sum < n - 50 && islucky(sum)) cnt++; } int index = 0; for (int i = max(n - 50, 0ll); i < n; i++) s.insert(i + 1); for (int i = max(n - 50ll, 0ll); i < n; i++) { long long left = n - i - 1; long long fct = fact(left); if (fct > k) { if (islucky(i + 1) && islucky(*s.begin())) cnt++; s.erase(s.begin()); continue; } long long a1 = k / fct; k -= fct * a1; int take; for (typeof((s).begin()) it = (s).begin(); it != (s).end(); it++) { if (a1 == 0) { take = *it; if (islucky(i + 1) && islucky(take)) cnt++; s.erase(it); break; } a1--; } } cout << cnt; } int main() { oku(); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.lang.Long; import java.math.BigDecimal; import java.math.BigInteger; /** * Problem statement: http://codeforces.com/problemset/problem/431/D * * @author thepham * */ public class C_Round_91_Div1 { static long Mod = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int k = in.nextInt(); boolean ok = true; if (n <= 14) { long max = 1; for (int i = 1; i <= n; i++) { max *= i; } if (max < k) { ok = false; out.println(-1); } } if (ok) { PriorityQueue<Long> q = new PriorityQueue(); TreeSet<Integer> set = new TreeSet(); q.add(4L); q.add(7L); while (!q.isEmpty()) { long v = q.poll(); if (v > n) { break; } set.add((int)v); q.add(v * 10 + 4); q.add(v * 10 + 7); } //out.println(set); int left = 0; long cur = 1; for(int i = 1; i <= 14 ; i++){ cur *= i; if(cur >= k){ left = i ; break; } } int other = n - left; int result = set.headSet(other, true).size(); int start = other + 1; ArrayList<Integer> list = new ArrayList(); for(int i = 0; i < left; i++){ list.add(start + i); } for(int i = 0; i < left; i++){ int min = 0; int max = list.size() - 1; long re= -1; int id = -1; while(min <= max){ int mid = (min + max)/2; long large = mid; for(int j = 1; j < left - i; j++ ){ large *= j; } if(large < k){ if(large > re){ re = large; id = mid; } min = mid + 1; }else{ max = mid - 1; } } k -= re; int v = list.remove((int)id); //System.out.println(v + " " + id + " " + start + " " + re); if(set.contains(v) && set.contains(start)){ result++; } start++; } out.println(result); } out.close(); } static class Segment implements Comparable<Segment> { int x, y; public Segment(int x, int y) { super(); this.x = x; this.y = y; } public String toString() { return x + " " + y; } @Override public int compareTo(Segment o) { if (x != o.x) { return x - o.x; } return o.y - y; } } public static int[] buildKMP(String val) { int[] data = new int[val.length() + 1]; int i = 0; int j = -1; data[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(i) != val.charAt(j)) { j = data[j]; } i++; j++; data[i] = j; // System.out.println(val + " " + i + " " + data[i]); } return data; } static int find(int index, int[] u) { if (u[index] != index) { return u[index] = find(u[index], u); } return index; } static int crossProduct(Point a, Point b) { return a.x * b.y + a.y * b.x; } static long squareDist(Point a) { long x = a.x; long y = a.y; return x * x + y * y; } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.y); } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } static class Point { int x, y; public Point(int x, int y) { super(); this.x = x; this.y = y; } public String toString() { return "{" + x + " " + y + "}"; } } static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static class FT { int[] data; FT(int n) { data = new int[n]; } public void update(int index, int value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public int get(int index) { int result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream( // new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; long long f[15], all[15]; long long n, k; int solve(int rem) { if (!rem) return 1; return solve(rem - 1) * 2; } long long solve(int i, string& str) { if (i == str.size()) return 1; long long ret = solve(i + 1, str); if (str[i] == '1') ret += all[str.size() - i - 1]; return ret; } bool lucky(long long x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return 0; x /= 10; } return 1; } int main() { all[0] = f[0] = 1; for (int i = 1; i < 15; ++i) { f[i] = f[i - 1] * i; all[i] = 2ll * all[i - 1]; } cin >> n >> k; if (n < 15 && f[n] < k) return cout << -1, 0; long long nn = n; int rem = 0; for (int i = 0; i < 14; ++i) if (f[i] < k) rem = i; long long ans = 0; set<long long> rem_num; if (n > rem + 1) { long long m = n - rem - 1; string cur = "", s = ""; stringstream mycin; mycin << m; mycin >> cur; bool ok = 0, is = 0; int lstseven = -1; for (int i = 0; i < cur.size(); ++i) { int ch = cur[i] - '0'; if (ok) break; if (ch < 4) { is = 1; break; } else if (ch > 7) ok = 1, lstseven = 1e9 + 5; else if (ch == 7) lstseven = max(lstseven, i); else if (ch > 4) ok = 1; } if (is && lstseven == -1) { int sz = cur.size(); --sz; while (sz--) s += '1'; } else { ok = 0; for (int i = 0; i < cur.size(); ++i) { int ch = cur[i] - '0'; if (ok) s += '1'; else if (is && lstseven == i) s += '0', ok = 1; else if (ch > 7) ok = 1, s += '1'; else if (ch == 7) s += '1'; else if (ch > 4) s += '0', ok = 1; else s += '0'; } } if (s.size()) { ans += solve(0, s); for (int i = 1; i < s.size(); ++i) ans += all[i]; } for (int i = n; rem_num.size() <= rem; --i) rem_num.insert(i); n = rem + 1; } else for (int i = 1; i <= n; ++i) rem_num.insert(i); for (int i = nn - n + 1; i <= nn; ++i) { vector<int> v; while (f[nn - i] < k) { k -= f[nn - i]; v.push_back(*rem_num.begin()); rem_num.erase(rem_num.begin()); } int x = *rem_num.begin(); rem_num.erase(rem_num.begin()); for (int j : v) rem_num.insert(j); ans += lucky(i) && lucky(x); } cout << ans; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int N = 1 << 20; long long fac[20]; vector<long long> lst; vector<long long> lucky; void prepare(int cnt, int all, long long now) { if (cnt == all) { lucky.push_back(now); return; } prepare(cnt + 1, all, now * 10 + 4); prepare(cnt + 1, all, now * 10 + 7); } inline bool chk(long long x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } int main() { ios::sync_with_stdio(false); for (int i = 0; i <= 10; i++) prepare(0, i, 0); fac[0] = 1; for (int i = 1; i < 20; i++) fac[i] = fac[i - 1] * i; long long n, k; cin >> n >> k; long long p = 1; while (fac[p] < k) p++; if (p > n) return cout << -1 << '\n', 0; k--; for (long long i = n - p + 1; i <= n; i++) lst.push_back(i); while (k) { int i; for (i = p; ~i; i--) if (fac[i] <= k) break; int w = k / fac[i]; k -= fac[i] * w; for (int s = 0; s < w; s++) swap(lst[p - 1 - i], lst[p - i + s]); } long long res = upper_bound(lucky.begin(), lucky.end(), n - p) - lucky.begin() - 1; for (int i = 0; i < lst.size(); i++) if (chk(n - p + i + 1) && chk(lst[i])) res++; cout << res << '\n'; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 10/27/11 * Time: 5:55 PM * To change this template use File | Settings | File Templates. */ import sun.misc.Sort; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.FileReader; import java.io.IOException; import java.util.*; public class TaskC extends Thread { public TaskC(int type) { try { if (type == 0) { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); } else { this.input = new BufferedReader(new FileReader(INPUT_FILE)); this.output = new PrintWriter(OUTPUT_FILE); } this.setPriority(Thread.MAX_PRIORITY); } catch (Throwable e) { e.printStackTrace(); System.exit(666); } } static boolean isLucky(int value) { char []now = Integer.toString(value).toCharArray(); for (char c : now) { if (c != '4' && c != '7') { return false; } } return true; } static void generate(long now, long length) { if (length == 10) { return; } luckies.add(now * 10 + 4); luckies.add(now * 10 + 7); generate(now * 10 + 4, length + 1); generate(now * 10 + 7, length + 1); } //12 ! - max private void solve() throws Throwable { long facts[] = new long[14]; facts[0] = 1; for (int i = 1; i < facts.length; ++i) { facts[i] = facts[i - 1] * i; } int n = nextInt(); long k = nextLong(); if (n <= 12) { if (facts[n] < k) { output.println(-1); return; } } int result = 0; int N = 1; while (facts[N] < k) { ++N; } long MAX = (long) n - N; int index = 0; while (index < values.size() && values.get(index) <= MAX) { ++result; ++index; } int values[] = new int[N]; boolean used[] = new boolean[N]; Arrays.fill(values, -1); for (int i = 0; i < N; ++i) { for (int wanted = 0; wanted < N; ++wanted) { if (used[wanted]) { continue; } long remaining = facts[N - 1 - i]; if (remaining < k) { k -= remaining; } else { values[i] = wanted + 1; used[wanted] = true; break; } } } for (int i = 0; i < N; ++i) { int pos = (int)MAX + i + 1; if (isLucky(pos) && isLucky((int) MAX + values[i])) { ++result; } } output.println(result); } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new TaskC(0).start(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } static ArrayList<Long> values = new ArrayList<Long>(); static HashSet<Long> luckies = new HashSet<Long>(); static { generate(0, 1); values.addAll(luckies); Collections.sort(values); } private static final String INPUT_FILE = null; private static final String OUTPUT_FILE = null; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const double EPS = 1e-9; const double PI = acos(-1.); template <class T> inline T sq(T x) { return x * x; } template <class T> inline void upd_min(T &lhs, T rhs) { if (lhs > rhs) lhs = rhs; } template <class T> inline void upd_max(T &lhs, T rhs) { if (lhs < rhs) lhs = rhs; } long long fact[16] = {1}; void gen() { for (int i = (1); i < (16); ++i) fact[i] = i * fact[i - 1]; } long long lucky(int n, int k) { return k ? (n & 1 ? 7 : 4) + lucky(n >> 1, k - 1) * 10 : 0; } bool isLucky(long long n) { return n ? (n % 10 == 4 || n % 10 == 7) && isLucky(n / 10) : true; } void solve() { gen(); int n, k; cin >> n >> k; if (n < 14 && fact[n] < k) { cout << -1 << endl; return; } vector<int> perm1; int _k = k - 1; for (int i = 13; i >= 0; --i) { perm1.push_back(_k / fact[i]); _k -= _k / fact[i] * fact[i]; } vector<int> perm2; for (int i = (0); i < (14); ++i) perm2.push_back(i + 1); vector<int> perm; for (int i = (0); i < (14); ++i) { perm.push_back(perm2[perm1[i]]); perm2.erase(perm2.begin() + perm1[i]); } vector<long long> luckys; for (int i = (1); i < (11); ++i) { for (int j = (0); j < (1 << i); ++j) { luckys.push_back(lucky(j, i)); } } sort((luckys).begin(), (luckys).end()); int ans = 0; for (int i = 0; luckys[i] <= n - 14; ++i) { ++ans; } if (n < 14) { for (int i = 0; i < n; ++i) { if ((i + 1 == 4 || i + 1 == 7) && isLucky(perm[14 - n + i] - (14 - n))) { ++ans; } } } else { for (int i = 0; i < 14; ++i) { if (isLucky(n - 14 + i + 1) && isLucky(n - 14 + perm[i])) { ++ans; } } } cout << ans << endl; } int main() { solve(); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; set<long long> S; void go(const long long &x, const int &M, const long long &U) { if (x > U) return; if (x > M) S.insert(x); go(10 * x + 4, M, U), go(10 * x + 7, M, U); } bool ok(long long x) { for (; x; x /= 10) { int a = x % 10; if (a != 4 && a != 7) return false; } return true; } int main() { long long N, K; cin >> N >> K; int M = 1; for (long long f = 1; f * M < K; f *= M, M++) ; if (M > (int)N) { cout << -1 << endl; return 0; } M = min((int)N, 20); go(0, 0, N - M); vector<long long> a(M); for (int _n(M), i(0); i < _n; i++) a[i] = N - M + i + 1; for (long long k = K - 1; k > 0;) { long long f = 1; int i = 1; while (f * (i + 1) <= k) f *= ++i; int j = k / f; swap(a[M - i - 1], a[M - i + j - 1]); sort(&a[0] + M - i, &a[0] + M); k -= f * j; } int ans = 0; for (int _n(M), i(0); i < _n; i++) if (ok(N - M + i + 1) && ok(a[i])) ans++; ans += S.size(); cout << ans << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { new Main().start(); } private long fact(long m) { long ret = 1; for (long i = 1; i <= m; i++) { ret *= i; } return ret; } int[] data = new int[1022]; long N, K; int[] ten = new int[10]; private void start() { Scanner in = new Scanner(System.in); N = in.nextLong(); K = in.nextLong(); if (N < 13 && fact(N) < K) { System.out.println(-1); return; } ten[0] = 1; for (int i = 1; i < 10; i++) { ten[i] = ten[i - 1] * 10; } int c = 0; for (int i = 1; i < 10; i++) { int n = 1 << i; for (int j = 0; j < n; j++) { int tmp = 0; for (int k = 0; k < i; k++) { long q; if (0 != (j & (1 << k))) { q = 7; } else { q = 4; } tmp += q * ten[k]; } data[c++] = tmp; } } Arrays.sort(data); long s[]; if (N >= 13) { s = kth(13, K); for (int i = 0; i < s.length; i++) { s[i] += N - 13; } int ans = 0; for (int i = 0; i < c && data[i] <= N; i++) { if (data[i] <= N - 13) { ans++; } else { if (is(s[(int) (data[i] - (N - 13))])) { ans++; } } } System.out.println(ans); } else { s = kth((int)N, K); int ans = 0; for (int i = 0; i < c && data[i] <= N; i++) { if (is(s[data[i]])) { ans++; } } System.out.println(ans); } } private boolean is(long v) { String s = Long.toString(v); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != '4' && s.charAt(i) != '7') { return false; } } return true; } private long[] kth(int n, long k) { ArrayList<Integer> c = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { c.add(i); } long[] ret = new long[n + 1]; for (int i = 1; i <= n; i++) { long t = fact(n - i); int ct = 1; while (k > t) { k -= t; ct++; } ret[i] = c.get(ct - 1); c.remove(ct - 1); } return ret; } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { static ArrayList<Long> aa; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(),k = in.nextInt(); aa = new ArrayList<Long>(2500); dfs(7);dfs(4); int nn = n,l = Math.min(13, n); n = l; if (n < 13 && k > fact(n)) { System.out.println(-1); System.exit(0); } int[] a = new int[l]; boolean[] v = new boolean[l]; for (int i = 0; i < a.length; i++) a[i] = nn - i; Arrays.sort(a); int[] ans = new int[a.length]; long g, kk = k, f; boolean d; for (int i = 0; i < a.length; i++) { g = kk / (f = fact(n - 1)) + 1; if (kk % f == 0) g--; int cnt = 0, j; for (j = 0; j < a.length; j++) { if (!v[j]) cnt++; if (cnt == g) break; } v[j] = true; ans[i] = a[j]; d = false; if (kk >= f) d = true; kk %= f; if (d && kk == 0) kk += f; n--; } Collections.sort(aa); int ret = 0; for (int i = 0; i < aa.size(); i++) if (aa.get(i) > nn - 13 + 1) { ret = i; break; } for (int i = 0; i < ans.length; i++) if (aa.contains((long) ans[i]) && aa.contains((long) (i + nn - l + 1))) ret++; System.out.println(ret); } public static long fact(long n) { if (n == 1 || n == 0) return 1; return n * fact(n - 1); } public static void dfs(long n) { aa.add(n); if (n > 1000000000) return; dfs(n * 10 + 4); dfs(n * 10 + 7); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; public class Main { public static void main(String[]args){ new Main().run(); } private void debug(Object...os){ System.err.println(deepToString(os)); } private void run() { Scanner sc = new Scanner(System.in); int n=sc.nextInt(),K=sc.nextInt(); long[] fact = new long[19]; for (int i = 0; i < 19; i++)fact[i] = i==0 ? 1 : fact[i-1]*i; int tail = min(n,18); if(fact[tail] < K){ System.out.println(-1);return; } int off = n-tail+1; int res = 0; boolean[] used = new boolean[tail]; for (int i = 0; i < tail; i++){ for (int j = 0; j < tail; j++)if(!used[j]){ if(fact[tail-1-i] >= K){ used[j] = true; if(lucky(off+j) && lucky(off+i))res++; break; }else{ K -= fact[tail-1-i]; } } } for (int i = 1; i < 11; i++){ for (int j = 0; j < 1<<i; j++){ long val=0; for (int k = 0; k < i; k++){ val*=10; val+= ((j>>k&1)==1) ? 4:7; } if(val <= n-tail)res++; } } System.out.println(res); } private boolean lucky(int i) { if(i==0)return false; while(i>0){ if(i%10!=7 && i%10!=4)return false; i/=10; } return true; } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long a[100010], fac[20], vis[20], ans1[20], ans; int n, k, tmp1, tmp2; void dfs(long long now) { if (now <= tmp2 && now) { ans++; } if (now >= 1000000000) { return; } dfs(now * 10 + 4); dfs(now * 10 + 7); } void solve(int now) { if (now > tmp1) { return; } int l = 1; while (vis[l]) l++; while (k >= fac[tmp1 - now]) { l++; while (vis[l]) { l++; } k -= fac[tmp1 - now]; } while (vis[l]) l++; ans1[now] = l + tmp2; vis[l] = 1; solve(now + 1); } int main() { fac[0] = 1LL; for (int i = 1; i <= 14; i++) { fac[i] = 1LL * i * fac[i - 1]; } scanf("%d%d", &n, &k); if (n <= 14 && fac[n] < k) { puts("-1"); return 0; } for (int i = 0; i <= 14; i++) { if (fac[i] >= k) { tmp1 = i; break; } } tmp2 = n - tmp1; dfs(0); k--; solve(1); for (int i = tmp2 + 1; i <= n; i++) { int flag = 1; int tmp3 = i; while (tmp3) { if (tmp3 % 10 == 4 || tmp3 % 10 == 7) { } else { flag = 0; break; } tmp3 /= 10; } tmp3 = ans1[i - tmp2]; while (tmp3) { if (tmp3 % 10 == 4 || tmp3 % 10 == 7) { } else { flag = 0; break; } tmp3 /= 10; } if (flag) { ans++; } } printf("%lld\n", ans); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int maxn = 200; vector<long long> luck; void dfs(long long a, long long len) { if (len > 11) return; if (a) luck.push_back(a); dfs(a * 10 + 4, len + 1); dfs(a * 10 + 7, len + 1); } long long fact[30]; long long arr[50]; void find(long long n, long long x) { vector<long long> v; for (int i = 0; i < n; i++) v.push_back(i + 1); for (int i = 0; i < n; i++) { long long y = x / (fact[n - i - 1]); arr[i] = v[y]; v.erase(v.begin() + y); x %= (fact[n - i - 1]); } } bool isl(long long a) { if (!a) return 0; while (a) { int g = a % 10; if (g != 4 && g != 7) return 0; a /= 10; } return true; } int main() { dfs(0, 0); sort(luck.begin(), luck.end()); long long n, k; cin >> n >> k; fact[0] = 1; for (int i = 1; i < 30; i++) fact[i] = fact[i - 1] * i; if (n <= 20 && k > fact[n]) { cout << -1 << endl; return 0; } long long len = min(20ll, n); find(len, k - 1); long long p = n - len; long long ind = upper_bound(luck.begin(), luck.end(), p) - luck.begin(); long long ans = ind; for (int i = 0; i < len; i++) { arr[i] += p; if (isl(arr[i]) && isl(i + p + 1)) ans++; } cout << ans << endl; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; template <typename T> vector<T> readvector(size_t size) { vector<T> res(size); for (size_t i = 0; i < size; ++i) { cin >> res[i]; } return res; } template <typename T> void printvector(vector<T>& arr, string sep = " ", string ends = "\n") { for (size_t i = 0; i < arr.size(); ++i) { cout << arr.at(i) << sep; } cout << ends; } const long long MAXN = 1e5; bool is_lucky(long long n) { while (n) { if (n % 10 != 4 && n % 10 != 7) return 0; n /= 10; } return 1; } vector<long long> lucky = { 4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777, 4444, 4447, 4474, 4477, 4744, 4747, 4774, 4777, 7444, 7447, 7474, 7477, 7744, 7747, 7774, 7777, 44444, 44447, 44474, 44477, 44744, 44747, 44774, 44777, 47444, 47447, 47474, 47477, 47744, 47747, 47774, 47777, 74444, 74447, 74474, 74477, 74744, 74747, 74774, 74777, 77444, 77447, 77474, 77477, 77744, 77747, 77774, 77777, 444444, 444447, 444474, 444477, 444744, 444747, 444774, 444777, 447444, 447447, 447474, 447477, 447744, 447747, 447774, 447777, 474444, 474447, 474474, 474477, 474744, 474747, 474774, 474777, 477444, 477447, 477474, 477477, 477744, 477747, 477774, 477777, 744444, 744447, 744474, 744477, 744744, 744747, 744774, 744777, 747444, 747447, 747474, 747477, 747744, 747747, 747774, 747777, 774444, 774447, 774474, 774477, 774744, 774747, 774774, 774777, 777444, 777447, 777474, 777477, 777744, 777747, 777774, 777777, 4444444, 4444447, 4444474, 4444477, 4444744, 4444747, 4444774, 4444777, 4447444, 4447447, 4447474, 4447477, 4447744, 4447747, 4447774, 4447777, 4474444, 4474447, 4474474, 4474477, 4474744, 4474747, 4474774, 4474777, 4477444, 4477447, 4477474, 4477477, 4477744, 4477747, 4477774, 4477777, 4744444, 4744447, 4744474, 4744477, 4744744, 4744747, 4744774, 4744777, 4747444, 4747447, 4747474, 4747477, 4747744, 4747747, 4747774, 4747777, 4774444, 4774447, 4774474, 4774477, 4774744, 4774747, 4774774, 4774777, 4777444, 4777447, 4777474, 4777477, 4777744, 4777747, 4777774, 4777777, 7444444, 7444447, 7444474, 7444477, 7444744, 7444747, 7444774, 7444777, 7447444, 7447447, 7447474, 7447477, 7447744, 7447747, 7447774, 7447777, 7474444, 7474447, 7474474, 7474477, 7474744, 7474747, 7474774, 7474777, 7477444, 7477447, 7477474, 7477477, 7477744, 7477747, 7477774, 7477777, 7744444, 7744447, 7744474, 7744477, 7744744, 7744747, 7744774, 7744777, 7747444, 7747447, 7747474, 7747477, 7747744, 7747747, 7747774, 7747777, 7774444, 7774447, 7774474, 7774477, 7774744, 7774747, 7774774, 7774777, 7777444, 7777447, 7777474, 7777477, 7777744, 7777747, 7777774, 7777777, 44444444, 44444447, 44444474, 44444477, 44444744, 44444747, 44444774, 44444777, 44447444, 44447447, 44447474, 44447477, 44447744, 44447747, 44447774, 44447777, 44474444, 44474447, 44474474, 44474477, 44474744, 44474747, 44474774, 44474777, 44477444, 44477447, 44477474, 44477477, 44477744, 44477747, 44477774, 44477777, 44744444, 44744447, 44744474, 44744477, 44744744, 44744747, 44744774, 44744777, 44747444, 44747447, 44747474, 44747477, 44747744, 44747747, 44747774, 44747777, 44774444, 44774447, 44774474, 44774477, 44774744, 44774747, 44774774, 44774777, 44777444, 44777447, 44777474, 44777477, 44777744, 44777747, 44777774, 44777777, 47444444, 47444447, 47444474, 47444477, 47444744, 47444747, 47444774, 47444777, 47447444, 47447447, 47447474, 47447477, 47447744, 47447747, 47447774, 47447777, 47474444, 47474447, 47474474, 47474477, 47474744, 47474747, 47474774, 47474777, 47477444, 47477447, 47477474, 47477477, 47477744, 47477747, 47477774, 47477777, 47744444, 47744447, 47744474, 47744477, 47744744, 47744747, 47744774, 47744777, 47747444, 47747447, 47747474, 47747477, 47747744, 47747747, 47747774, 47747777, 47774444, 47774447, 47774474, 47774477, 47774744, 47774747, 47774774, 47774777, 47777444, 47777447, 47777474, 47777477, 47777744, 47777747, 47777774, 47777777, 74444444, 74444447, 74444474, 74444477, 74444744, 74444747, 74444774, 74444777, 74447444, 74447447, 74447474, 74447477, 74447744, 74447747, 74447774, 74447777, 74474444, 74474447, 74474474, 74474477, 74474744, 74474747, 74474774, 74474777, 74477444, 74477447, 74477474, 74477477, 74477744, 74477747, 74477774, 74477777, 74744444, 74744447, 74744474, 74744477, 74744744, 74744747, 74744774, 74744777, 74747444, 74747447, 74747474, 74747477, 74747744, 74747747, 74747774, 74747777, 74774444, 74774447, 74774474, 74774477, 74774744, 74774747, 74774774, 74774777, 74777444, 74777447, 74777474, 74777477, 74777744, 74777747, 74777774, 74777777, 77444444, 77444447, 77444474, 77444477, 77444744, 77444747, 77444774, 77444777, 77447444, 77447447, 77447474, 77447477, 77447744, 77447747, 77447774, 77447777, 77474444, 77474447, 77474474, 77474477, 77474744, 77474747, 77474774, 77474777, 77477444, 77477447, 77477474, 77477477, 77477744, 77477747, 77477774, 77477777, 77744444, 77744447, 77744474, 77744477, 77744744, 77744747, 77744774, 77744777, 77747444, 77747447, 77747474, 77747477, 77747744, 77747747, 77747774, 77747777, 77774444, 77774447, 77774474, 77774477, 77774744, 77774747, 77774774, 77774777, 77777444, 77777447, 77777474, 77777477, 77777744, 77777747, 77777774, 77777777, 444444444, 444444447, 444444474, 444444477, 444444744, 444444747, 444444774, 444444777, 444447444, 444447447, 444447474, 444447477, 444447744, 444447747, 444447774, 444447777, 444474444, 444474447, 444474474, 444474477, 444474744, 444474747, 444474774, 444474777, 444477444, 444477447, 444477474, 444477477, 444477744, 444477747, 444477774, 444477777, 444744444, 444744447, 444744474, 444744477, 444744744, 444744747, 444744774, 444744777, 444747444, 444747447, 444747474, 444747477, 444747744, 444747747, 444747774, 444747777, 444774444, 444774447, 444774474, 444774477, 444774744, 444774747, 444774774, 444774777, 444777444, 444777447, 444777474, 444777477, 444777744, 444777747, 444777774, 444777777, 447444444, 447444447, 447444474, 447444477, 447444744, 447444747, 447444774, 447444777, 447447444, 447447447, 447447474, 447447477, 447447744, 447447747, 447447774, 447447777, 447474444, 447474447, 447474474, 447474477, 447474744, 447474747, 447474774, 447474777, 447477444, 447477447, 447477474, 447477477, 447477744, 447477747, 447477774, 447477777, 447744444, 447744447, 447744474, 447744477, 447744744, 447744747, 447744774, 447744777, 447747444, 447747447, 447747474, 447747477, 447747744, 447747747, 447747774, 447747777, 447774444, 447774447, 447774474, 447774477, 447774744, 447774747, 447774774, 447774777, 447777444, 447777447, 447777474, 447777477, 447777744, 447777747, 447777774, 447777777, 474444444, 474444447, 474444474, 474444477, 474444744, 474444747, 474444774, 474444777, 474447444, 474447447, 474447474, 474447477, 474447744, 474447747, 474447774, 474447777, 474474444, 474474447, 474474474, 474474477, 474474744, 474474747, 474474774, 474474777, 474477444, 474477447, 474477474, 474477477, 474477744, 474477747, 474477774, 474477777, 474744444, 474744447, 474744474, 474744477, 474744744, 474744747, 474744774, 474744777, 474747444, 474747447, 474747474, 474747477, 474747744, 474747747, 474747774, 474747777, 474774444, 474774447, 474774474, 474774477, 474774744, 474774747, 474774774, 474774777, 474777444, 474777447, 474777474, 474777477, 474777744, 474777747, 474777774, 474777777, 477444444, 477444447, 477444474, 477444477, 477444744, 477444747, 477444774, 477444777, 477447444, 477447447, 477447474, 477447477, 477447744, 477447747, 477447774, 477447777, 477474444, 477474447, 477474474, 477474477, 477474744, 477474747, 477474774, 477474777, 477477444, 477477447, 477477474, 477477477, 477477744, 477477747, 477477774, 477477777, 477744444, 477744447, 477744474, 477744477, 477744744, 477744747, 477744774, 477744777, 477747444, 477747447, 477747474, 477747477, 477747744, 477747747, 477747774, 477747777, 477774444, 477774447, 477774474, 477774477, 477774744, 477774747, 477774774, 477774777, 477777444, 477777447, 477777474, 477777477, 477777744, 477777747, 477777774, 477777777, 744444444, 744444447, 744444474, 744444477, 744444744, 744444747, 744444774, 744444777, 744447444, 744447447, 744447474, 744447477, 744447744, 744447747, 744447774, 744447777, 744474444, 744474447, 744474474, 744474477, 744474744, 744474747, 744474774, 744474777, 744477444, 744477447, 744477474, 744477477, 744477744, 744477747, 744477774, 744477777, 744744444, 744744447, 744744474, 744744477, 744744744, 744744747, 744744774, 744744777, 744747444, 744747447, 744747474, 744747477, 744747744, 744747747, 744747774, 744747777, 744774444, 744774447, 744774474, 744774477, 744774744, 744774747, 744774774, 744774777, 744777444, 744777447, 744777474, 744777477, 744777744, 744777747, 744777774, 744777777, 747444444, 747444447, 747444474, 747444477, 747444744, 747444747, 747444774, 747444777, 747447444, 747447447, 747447474, 747447477, 747447744, 747447747, 747447774, 747447777, 747474444, 747474447, 747474474, 747474477, 747474744, 747474747, 747474774, 747474777, 747477444, 747477447, 747477474, 747477477, 747477744, 747477747, 747477774, 747477777, 747744444, 747744447, 747744474, 747744477, 747744744, 747744747, 747744774, 747744777, 747747444, 747747447, 747747474, 747747477, 747747744, 747747747, 747747774, 747747777, 747774444, 747774447, 747774474, 747774477, 747774744, 747774747, 747774774, 747774777, 747777444, 747777447, 747777474, 747777477, 747777744, 747777747, 747777774, 747777777, 774444444, 774444447, 774444474, 774444477, 774444744, 774444747, 774444774, 774444777, 774447444, 774447447, 774447474, 774447477, 774447744, 774447747, 774447774, 774447777, 774474444, 774474447, 774474474, 774474477, 774474744, 774474747, 774474774, 774474777, 774477444, 774477447, 774477474, 774477477, 774477744, 774477747, 774477774, 774477777, 774744444, 774744447, 774744474, 774744477, 774744744, 774744747, 774744774, 774744777, 774747444, 774747447, 774747474, 774747477, 774747744, 774747747, 774747774, 774747777, 774774444, 774774447, 774774474, 774774477, 774774744, 774774747, 774774774, 774774777, 774777444, 774777447, 774777474, 774777477, 774777744, 774777747, 774777774, 774777777, 777444444, 777444447, 777444474, 777444477, 777444744, 777444747, 777444774, 777444777, 777447444, 777447447, 777447474, 777447477, 777447744, 777447747, 777447774, 777447777, 777474444, 777474447, 777474474, 777474477, 777474744, 777474747, 777474774, 777474777, 777477444, 777477447, 777477474, 777477477, 777477744, 777477747, 777477774, 777477777, 777744444, 777744447, 777744474, 777744477, 777744744, 777744747, 777744774, 777744777, 777747444, 777747447, 777747474, 777747477, 777747744, 777747747, 777747774, 777747777, 777774444, 777774447, 777774474, 777774477, 777774744, 777774747, 777774774, 777774777, 777777444, 777777447, 777777474, 777777477, 777777744, 777777747, 777777774, 777777777, 4444444444}; long long safe_fact(long long n) { if (n >= 20) return 1e18; long long ans = 1; while (n) { ans *= (n--); } return ans; } vector<long long> generate(vector<long long> left, long long k) { if (left.empty()) return std::vector<long long>(0); long long step = safe_fact(left.size() - 1); long long ind = k / step; long long elem = left[ind]; left.erase(left.begin() + ind); auto e = generate(left, k % step); e.insert(e.begin(), elem); return e; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n, k; cin >> n >> k; if (safe_fact(n) < k) { cout << -1 << endl; return 0; } long long m = min(19ll, n); vector<long long> generated; for (long long i = n - m + 1; i <= n; i++) { generated.push_back(i); } generated = generate(generated, k - 1); long long ans = 0; for (auto e : lucky) { if (e < n - m + 1) { ans++; } } for (long long i = 0; i < m; i++) { long long pos = n - m + 1 + i; long long elem = generated[i]; if (is_lucky(pos) && is_lucky(elem)) ans++; } cout << ans << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long n, k, f[25]; vector<long long> v, sol; set<long long> s; void dfs(long long now) { if (now > 1000000000) return; v.push_back(now); s.insert(now); dfs(now * 10 + 4); dfs(now * 10 + 7); } void build() { dfs(4); dfs(7); sort(v.begin(), v.end()); f[0] = 1; for (int i = 1; i < 20; i++) f[i] = i * f[i - 1]; } bool che(long long now) { return s.count(now); } long long getnum(int now) { long long cnt = 0, num = 0; for (int i = 0; i < sol.size(); i++) { if (sol[i] != -1000000000) cnt++; if (cnt == now) { num = sol[i]; sol[i] = -1000000000; break; } } return num; } int main() { build(); cin >> n >> k; if (n <= 15 && k > f[n]) { cout << -1 << '\n'; return 0; } long long pos = n - 14, ans = 0; for (auto i : v) { if (i < pos) ans++; } for (int i = 14; i >= 0; i--) sol.push_back(n - i); for (int i = 15; i >= 1; i--) { int cnt = 1; while (k > f[i - 1]) { k -= f[i - 1]; cnt++; } long long now = getnum(cnt); if (che(pos) && che(now)) ans++; pos++; } cout << ans << '\n'; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#!/usr/bin/python import sys a = [] def gen (n, d): global a if n > 0: a += [n] if d > 0: gen (n * 10 + 4, d - 1) gen (n * 10 + 7, d - 1) def go (l, r, pos, c): l = max (l, pos) r = min (r, c) # print l, r, c return max (r - l + 1, 0) * c def fact (n): if n > 12: return 10 ** 9 + 1 if n == 0: return 1 return n * fact (n - 1) gen (0, 9) a.sort () while True: s = sys.stdin.readline ().strip () if s == '': s = sys.stdin.readline ().strip () if s == '': break n, k = [int (x) for x in s.split ()] if n <= 12: if k > fact (n): print -1 continue m = max (n - 13, 0) d = n - m res = 0 for c in a: if c <= m: res = res + 1 b = range (n - d + 1, n + 1) p = range (n - d + 1, n + 1) q = [] k -= 1 for i in range (d)[::-1]: j = k / fact (i) # print k, fact (i), j k %= fact (i) q += [b[j]] b = b[:j] + b[j + 1:] # print p, q, b for i in range (d): if p[i] in a and q[i] in a: res += 1 print res
PYTHON
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Author - * User: kansal * Date: 10/27/11 * Time: 8:49 PM */ public class CF91E { public static void main(String[] args) { reader = new BufferedReader(new InputStreamReader(System.in)); List<Integer> luckyNums = genAll(); long[] f = new long[14]; f[0] = 1; for(int i = 1; i < 14; ++i) { f[i] = i * f[i-1]; } int n = nextInt(), k = nextInt(); if (n <= 13 && k > f[n]) { System.out.println(-1); return; } int x = 1; for(; f[x] < k; ++x); int res = 0; for(int lucky: luckyNums) { if (lucky < n-x+1) ++res; } int[] p = getKthPerm(k-1, n-x+1, n, x, f); for(int i = 0; i < x; ++i) { if (isLucky(p[i]) && isLucky(n-x+1+i)) { ++res; } } System.out.println(res); } private static int[] getKthPerm(int k, int a, int b, int n, long[] fac) { int[] res = new int[n]; for(int i = a; i <= b; ++i) { res[i-a] = i; } for(int i = 0; i < n; ++i) { int x = (int)(k / fac[n-i-1]); int y = res[x+i]; for(int j = x + i - 1; j >= i; --j) { res[j+1] = res[j]; } res[i] = y; k = (int)(k % fac[n-i-1]); } return res; } private static boolean isLucky(int x) { if (x == 0) return false; while (x > 0) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } private static List<Integer> genAll() { List<Integer> ret = new ArrayList<Integer>(); for(int i = 1; i < 10; ++i) { for(int set = 0; set < (1 << i); ++set) { int x = 0; for(int j = i-1; j >= 0; --j) { if (((set >> j) & 1) == 1) { x = x * 10 + 7; } else { x = x * 10 + 4; } } ret.add(x); } } return ret; } public static BufferedReader reader; public static StringTokenizer tokenizer = null; static String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } static public int nextInt() { return Integer.parseInt(nextToken()); } static public long nextLong() { return Long.parseLong(nextToken()); } static public String next() { return nextToken(); } static public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> long long permu[14]; bool is_used[14]; int permu_pos[14]; long long lucks[2000]; int luck_cnt; int main() { long long i, j, k; int N, K, p1, p2, t1, t2, t3, m = 1e9; permu[0] = 1; for (i = 1; i < 14; i++) { permu[i] = 1; for (j = 1, k = 1; j <= i; j++) permu[i] *= j; } luck_cnt = 0; lucks[luck_cnt++] = 4; lucks[luck_cnt++] = 7; for (i = 0; true; i++) { lucks[luck_cnt++] = lucks[i] * 10 + 4; if (lucks[luck_cnt - 1] >= m) break; lucks[luck_cnt++] = lucks[i] * 10 + 7; if (lucks[luck_cnt - 1] >= m) break; } scanf("%d %d", &N, &K); p1 = N > 13 ? N - 13 : 0; p2 = N > 13 ? p1 + 1 : 1; j = N - p1; if ((long long)K > permu[j]) { printf("-1\n"); return 0; } for (i = j - 1; i >= 0; i--) { t1 = (((long long)K + permu[i] - 1) / permu[i]); for (k = 1, t2 = 0; t2 < t1; k++) if (!is_used[k]) t2++; permu_pos[j - i] = k - 1; is_used[k - 1] = true; K -= (t1 - 1) * permu[i]; } for (i = 0; lucks[i] <= p1; i++) ; t3 = i; for (i = 1; i <= N - p1; i++) { t1 = permu_pos[i] + p1; t2 = i + p1; for (j = 0, k = 0; j < luck_cnt && k < 2; j++) { if (t1 == lucks[j]) k++; if (t2 == lucks[j]) k++; } if (k == 2) t3++; } printf("%d\n", t3); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long n, k, i, j, Length, result, a[30]; queue<long long> q, q2; bool check[30]; bool Lucky(long long x) { while (x > 0) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } void process() { long long t, t2; q2.push(4); q2.push(7); while (!q2.empty()) { t = q2.front(); q2.pop(); q.push(t); if (t * 10 + 4 <= n) q2.push(t * 10 + 4); if (t * 10 + 7 <= n) q2.push(t * 10 + 7); } t = 1; memset(check, true, sizeof(check)); for (Length = 1; Length < 15; ++Length) { t *= Length; if (t >= k) break; a[i] = Length; } if (Length > n) { cout << "-1"; return; } if (k > 0) { for (i = 1; i <= Length; ++i) { t /= (Length - i + 1); t2 = (k - 1) / t; for (j = 1; j <= Length; ++j) if (check[j] && t2 == 0) { a[i] = j; check[j] = false; break; } else if (check[j]) --t2; t2 = a[i] - 1; for (j = 1; j <= Length; ++j) if (j == a[i]) break; else if (!check[j]) --t2; k -= (t2 * t); if (k == 0) { for (j = 1; j <= Length; ++j) if (check[j]) a[i++] = j; break; } } } result = 0; for (i = 1; i <= Length; ++i) a[i] += (n - Length); while (!q.empty()) { t = q.front(); q.pop(); if (t <= n - Length) ++result; else if (t > n) break; else { t -= (n - Length); if (Lucky(a[t])) ++result; } } cout << result; } int main() { scanf("%d %d", &n, &k); process(); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long fact[20]; int offset[20]; int vals[20]; vector<int> lidx; bool islucky(int x) { while (x > 0) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } int main() { fact[0] = fact[1] = 1; for (int i = 2; i < 20; i++) fact[i] = (fact[i - 1] * i); int N, K; cin >> N >> K; K -= 1; for (int i = min(13, N - 1); i >= 0; i--) { offset[i] = K / fact[i]; if (offset[i] > i) { cout << -1 << endl; return 0; } K -= fact[i] * offset[i]; } set<int> rem; for (int i = max(1, N - 13); i <= N; i++) rem.insert(i); for (int i = min(13, N - 1); i >= 0; i--) { auto it = rem.begin(); for (int j = 0; j < offset[i]; j++, it++) ; vals[i] = (*it); rem.erase(it); } queue<long long> q; q.push(4); q.push(7); while (!q.empty()) { long long x = q.front(); q.pop(); if (x > N) continue; else lidx.push_back(x); q.push(x * 10 + 4); q.push(x * 10 + 7); } sort(lidx.begin(), lidx.end()); int total = 0; for (auto x : lidx) if (N - x > 13) total += 1; for (int i = min(13, N - 1), j = max(N - 13, 1); i >= 0; i--, j++) if (islucky(j) && islucky(vals[i])) total += 1; cout << total << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; signed main() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(false); long long n, k; cin >> n >> k; auto lucky_check = [&](long long x) { while (x) { if (x % 10 != 4 and x % 10 != 7) return false; x /= 10; } return true; }; vector<long long> lucky_nos; for (long long mask = 1; mask < (1 << 10); mask++) { long long num1 = 0, num2 = 0; bool ok = 0; for (long long i = 0; i < 10; i++) { num1 *= 10; num2 *= 10; if (mask >> i & 1) ok = 1; if (ok) num1 += ((mask >> i) & 1) ? 7 : 4, num2 += ((mask >> i) & 1) ? 4 : 7; } lucky_nos.push_back(num1); lucky_nos.push_back(num2); } sort(begin(lucky_nos), end(lucky_nos)); map<long long, long long> m; long long fac[14] = {1}; for (long long i = 1; i <= 13; i++) fac[i] = (fac[i - 1] * i); k--; for (long long i = n - 13; i <= n; i++) { long long temp = (k / fac[n - i]); k -= temp * fac[n - i]; for (long long j = 13; j >= 0; j--) { if (temp == 0 and !m.count(n - j)) { m[n - j] = i; break; } if (!m.count(n - j)) temp--; } } for (auto x : m) { if (x.first <= 0 and x.second != x.first) return cout << "-1\n", 0; } long long ans = 0; for (auto x : lucky_nos) { if (x > n) break; if (n - x <= 13) { long long pos = m[x]; ans += lucky_check(pos); } else ans++; } cout << ans << '\n'; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.*; import java.io.*; public class Main { public static void main ( String args[] ) throws Exception { (new Task23()).solve(); } } class Task23 { Scanner in; int[] getPermutation ( int[] a, long k ) { boolean seen[] = new boolean[a.length]; int r[] = new int[a.length]; Arrays.fill ( r, -1 ); for ( int i = 0; i < a.length; ++i ) { long fact = 1; for ( int j = 1; j < a.length-i; ++j ) fact *= j; long id = (k-1) / fact; k -= id*fact; for ( int j = 0; j < a.length; ++j ) if ( !seen[j] ) { if ( id == 0 ) { r[i] = a[j]; seen[j] = true; break; } id--; } } return r; } boolean isLucky ( int n ) { for ( ; n > 0; n /= 10 ) if ( n%10 != 4 && n%10 != 7 ) return false; return true; } int countLucky ( long num, long limit ) { if ( num > limit ) return 0; int ans = 1; ans += countLucky ( num*10 + 4, limit ); ans += countLucky ( num*10 + 7, limit ); return ans; } public void solve ( ) throws Exception { in = new Scanner ( System.in ); int n = in.nextInt(); long k = in.nextLong(); if ( n <= 15 ) { long fact = 1; for ( int i = 1; i <= n; ++i ) fact *= i; if ( k > fact ) { println ( "-1\n" ); return; } } int last[] = new int[Math.min(15,n)]; for ( int i = 0; i < last.length; ++i ) last[i] = n-last.length+i+1; int ans = 0; last = getPermutation ( last, k ); for ( int i = 0; i < last.length; ++i ) if ( isLucky(last[i]) && isLucky(n-last.length+i+1) ) ans++; ans += countLucky ( 0, n-last.length )-1; println ( ans ); } public static void println ( Object o ) { System.out.println ( o ); } public static void print ( Object o ) { System.out.print ( o ); } public static void println ( ) { System.out.println ( ); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; vector<unsigned long long> luck; unsigned long long f[15]; vector<unsigned long long> v; int L; set<unsigned long long> S; void build() { int cnt = 2; luck.push_back(4); luck.push_back(7); for (int i = 2; i <= 9; ++i) { int p = ((int)luck.size()); for (int w = 0; w < cnt; w++) { p--; luck.push_back(luck[p] * 10 + 4); luck.push_back(luck[p] * 10 + 7); } cnt *= 2; } for (int i = 0; i < ((int)luck.size()); ++i) S.insert(luck[i]); } unsigned long long go(unsigned long long p, unsigned long long n) { unsigned long long ans = 0; for (int i = 0; i < ((int)luck.size()); ++i) { if (p <= luck[i] && luck[i] <= n) ans++; } return ans; } int get(unsigned long long n) { int ans = 0; while (f[ans] < n) { ans++; } return ans - 1; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); ; build(); unsigned long long n, k; cin >> n >> k; f[0] = 1; for (int i = 1; i < 15; ++i) { f[i] = i * f[i - 1]; } unsigned long long m; for (int i = 2; i < 15; ++i) { if (f[i - 1] < k && k <= f[i]) { break; m = i - 1; } } if (n < 13 && f[n] < k) { cout << "-1" << endl; return 0; } if (k == 1) cout << go(1, n); else { int w = get(k); L = w; unsigned long long ans = go(1, n - w - 1); for (int i = n - w; i <= n; ++i) v.push_back(i); while (k != 1) { sort(v.begin() + L - w, v.end()); w = get(k); int t = (k - 1) / f[w]; k -= t * f[w]; unsigned long long aux = v[L - w]; v[L - w] = v[L - w + t]; v[L - w + t] = aux; w--; } for (int i = 0; i < L + 1; ++i) { if (S.find(n - L + i) != S.end() && S.find(v[i]) != S.end()) ans++; } cout << ans << endl; } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { static ArrayList<Long> aa; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); aa = new ArrayList<Long>(2500); dfs(7); dfs(4); int nn = n; int l = Math.min(13, n); n = l; if (n < 13 && k > fact(n)) { System.out.println(-1); System.exit(0); } int[] a = new int[l]; boolean[] v = new boolean[l]; for (int i = 0; i < a.length; i++) a[i] = nn - i; Arrays.sort(a); int[] ans = new int[a.length]; long g; long kk = k; long f; boolean d; for (int i = 0; i < a.length; i++) { g = kk / (f = fact(n - 1)) + 1; if (kk % f == 0) g--; int cnt = 0, j; for (j = 0; j < a.length; j++) { if (!v[j]) cnt++; if (cnt == g) break; } v[j] = true; ans[i] = a[j]; d = false; if (kk >= f) d = true; kk %= f; if (d && kk == 0) kk += f; n--; } Collections.sort(aa); int ret = 0; for (int i = 0; i < aa.size(); i++) if (aa.get(i) > nn - 13 + 1) { ret = i; break; } for (int i = 0; i < ans.length; i++) if (aa.contains((long) ans[i]) && aa.contains((long) (i + nn - l + 1))) ret++; System.out.println(ret); } public static long fact(long n) { if (n == 1 || n == 0) return 1; return n * fact(n - 1); } public static void dfs(long n) { aa.add(n); if (n > 1000000000) return; dfs(n * 10 + 4); dfs(n * 10 + 7); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.ArrayList; import java.util.Scanner; public class E { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if (n < 13) { if (k > fac(n)) { System.out.println(-1); return; } } int[]a = new int[14]; int m, ans = 0, add; if (n <= 13) { m = n; for (int i = 1; i <= m; i++) { a[i] = i; } add = 0; } else { m = 13; for (int i = 1; i <= 13; i++) { a[i] = n-13+i; } add = n-13; ans = num_lucly(n-13); } long[]fac = new long[m+1]; fac[0] = 1; ArrayList<Integer> remain = new ArrayList<Integer>(); for (int i = 1; i <= m; i++) { fac[i] = fac[i-1] * i; remain.add(i); } for (int i = 1; i <= m; i++) { int t = (int) (k / fac[m-i]); if (k % fac[m-i] != 0) t++; int ind = (t-1) % (m-i+1); int temp = remain.get(ind); remain.remove(ind); if (luckly(a[temp]) && luckly(i+add)) ans++; } System.out.println(ans); } private static boolean luckly(int k) { String s = k+""; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != '4' && s.charAt(i) != '7') return false; } return true; } private static int num_lucly(int k) { int res = 0, L; String s; int lucly; for (int i = 1; i <= 9; i++) { if (i <= (k+"").length()) { for (int j = 0; j < (1 << i); j++) { s = Integer.toBinaryString(j); L = s.length(); for (int j2 = 1; j2 <= i-L; j2++) { s = "0"+s; } lucly = 0; for (int j2 = 0; j2 < i; j2++) { lucly *= 10; if (s.charAt(j2)=='0') lucly += 4; else lucly += 7; } if (lucly <= k) res++; } } } return res; } private static long fac(int n) { if (n < 2) return 1; return n * fac(n-1); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const long long maxn = 1e5 + 10, maxe = 15; long long n, k, x, ans = -1; long long fact[maxe], A[maxe], use[maxe]; void lucky_generator(long long a) { if (a > x) return; ans++; lucky_generator(a * 10 + 4); lucky_generator(a * 10 + 7); } bool is_lucky(long long a) { if (a < 3) return 0; a++; while (a) { if (a % 10 != 4 && a % 10 != 7) return 0; a /= 10; } return 1; } void solve(long long index, long long size) { if (index == size) return; int a = k / fact[size - index - 1] + 1, i = 0; k -= (a - 1) * fact[size - index - 1]; for (;; i++) { if (!use[i]) { a--; if (!a) break; } } A[index] = i; use[i] = 1; if (is_lucky(index + x) && is_lucky(i + x)) { ans++; } solve(index + 1, size); } int main() { fact[0] = 1; for (int i = 1; i < maxe + 1; i++) fact[i] = i * fact[i - 1]; cin >> n >> k; k--; if (n < maxe && k >= fact[n]) { cout << "-1\n"; return 0; } x = max(0ll, n - maxe); lucky_generator(0); solve(0ll, n - x); cout << ans << endl; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int N, num = 0, co = 0, tempo[16], tag[17]; long long temp[10001], K, dp[16], ans[16]; void DFS(long long now) { if (now > N) { temp[num++] = now; return; } temp[num++] = now; DFS(now * 10 + 4); DFS(now * 10 + 7); } int Check(long long key) { for (int i = 1; i < num; i++) if (temp[i] == key) return true; return false; } int main() { scanf("%d%I64d", &N, &K); K--; DFS(0); sort(temp, temp + num); dp[0] = 1; for (long long i = 1; dp[i - 1] * i <= K; i++) dp[i] = dp[i - 1] * i, co++; for (int i = co; i >= 0; i--) { long long x = (K / dp[i]); int gg = 0; for (int j = 0; j <= x; j++) if (tag[j] == 1) gg++; while (gg > 0) { x++; if (tag[x] == 1) gg++; gg--; } tag[x] = 1; ans[i] = x; K -= (K / dp[i]) * dp[i]; } if (co >= N) printf("-1\n"); else { int show = 0, run = 1; for (; run < num && temp[run] <= N - co - 1; run++) show++; run--; for (int i = co; i >= 0; i--) { if (Check(N - i) && Check(ans[i] + 1 + (N - co - 1))) show++; } printf("%d\n", show); } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long P[2000], sz, Ans, N, K; long long Q[10000]; int size; void Dfs(int k, long long s) { Q[++size] = s; if (k == 11) { return; } Dfs(k + 1, s * 10 + 4); Dfs(k + 1, s * 10 + 7); } void Init() { Dfs(1, 0); sort(Q + 1, Q + size + 1); } long long Fac(long long s) { if (s == 1) return 1; return s * Fac(s - 1); } bool Check(long long n) { stringstream ss; string s; ss << n; ss >> s; bool f = 1; for (int i = 0; i < s.size(); i++) if (s[i] != '4' && s[i] != '7') { f = 0; break; } return f; } int main() { scanf("%I64d%I64d", &N, &K); K--; long long last = 1; Init(); for (int i = 1; i <= size; i++) if (Q[i] < max(1ll, N - 13) && Check(Q[i])) Ans++; for (int i = max(1ll, N - 13); i < N; i++) { long long tmp = Fac(N - i); long long l = 0, r = N - i, mid, ans = 0; while (l <= r) { mid = (l + r) >> 1; if (mid * tmp > K) r = mid - 1; else ans = mid, l = mid + 1; } K -= ans * tmp; last += ans; ans++; for (int j = 1; j <= sz; j++) if (P[j] <= ans) ans++; P[++sz] = ans; sort(P + 1, P + sz + 1); if (Check(i) && Check(max(0ll, N - 14) + ans)) Ans++; } long long ans = 1; for (int j = 1; j <= sz; j++) if (P[j] <= ans) ans++; if (Check(N) && Check(max(0ll, N - 14) + ans)) Ans++; if (K > 0) puts("-1"); else printf("%I64d\n", Ans); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 10; const long long int INFLL = 1e18 + 10; const long double EPS = 1e-8; const long double EPSLD = 1e-14; const long long int MOD = 1e9 + 7; template <class T> T &chmin(T &a, const T &b) { return a = min(a, b); } template <class T> T &chmax(T &a, const T &b) { return a = max(a, b); } long long int mask_to_luckynumber(int mask) { long long int base = 1; long long int res = 0; bool end = false; for (int i = (0); i < (int)(10); i++) { if (mask % 3 == 0) end = true; else if (end) return INFLL; if (mask % 3 == 1) res += base * 4; if (mask % 3 == 2) res += base * 7; base *= 10; mask /= 3; } return res; } long long int fact[72]; int n; long long int k; bool used[72]; int res[72]; int main() { fact[0] = 1; for (int i = (1); i < (int)(16); i++) fact[i] = fact[i - 1] * i; cin >> n >> k; if (n < 16 && fact[n] < k) return puts("-1"); if (n < 4) return puts("0"); if (n < 7) { vector<int> v(0); for (int i = (0); i < (int)(n); i++) v.emplace_back(i); do { k--; if (k == 0) break; } while (next_permutation((v).begin(), (v).end())); if (v[3] == 3) return puts("1"); return puts("0"); } for (int i = (0); i < (int)(min(n, 15)); i++) { int p = 0; while (used[p]) p++; while (k > fact[min(n, 15) - 1 - i]) { k -= fact[min(n, 15) - 1 - i]; p++; while (used[p]) p++; } res[i] = p; used[p] = true; } int ans = 0; long long int e = 1; for (int i = (0); i < (int)(10); i++) e *= 3; vector<int> v; for (int mask = (1); mask < (int)(e); mask++) { long long int lucky = mask_to_luckynumber(mask); if (lucky == INFLL) continue; if (lucky < n - 14) ans++; else if (lucky <= n) v.emplace_back(lucky); } for (auto &w : v) for (auto &ww : v) if (res[min(n, 15) - 1 - (n - w)] == min(n, 15) - 1 - (n - ww)) ans++; cout << ans << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; void ga(int N, int *A) { for (int i(0); i < N; i++) scanf("%d", A + i); } long long f[(20) + 1] = {1}; int C[26], X; char s[666], r[666]; void nth(long long K, char *o, char *s) { if (!X++) for (int k(1); k < (20) + 1; k++) f[k] = f[k - 1] * k; long long L(strlen(s)), X(f[L]), T, l(0); (memset(C, o[L] = 0, sizeof(C))); for (int i(0); i < L; i++) ++C[s[i] - 97]; for (int i(0); i < 26; i++) X /= f[C[i]]; if (K > X) { *o = 0; return; }; for (int i(0); i < L; i++) for (int j(0); j < 26; j++) if (C[j]) { --C[j]; T = f[L - i - 1]; for (int i(0); i < 26; i++) T /= f[C[i]]; if (K <= T) { o[l++] = 'a' + j; break; } ++C[j], K -= T; } } long long fc(int a) { return a ? fc(a - 1) * a : 1; } int N, K, T; void rc(int r, long long S) { if (S > N - (20)) return; if (!r) { ++T; return; } rc(r - 1, S * 10 + 4), rc(r - 1, S * 10 + 7); } bool LC(int N) { while (N) { if (N % 10 != 7 && N % 10 != 4) return 0; N /= 10; } return 1; } int main(void) { scanf("%d%d", &N, &K); if (N <= (20) && fc(N) < K) return puts("-1"); if (N < (20)) { for (int i(0); i < N; i++) s[i] = r[i] = 97 + i; nth(K, s, r); for (int i(0); i < N; i++) T += LC(s[i] - 96) && LC(i + 1); printf("%d\n", T); return 0; } for (int i(0); i < 10; i++) rc(i + 1, 0); for (int i(0); i < (20); i++) s[i] = r[i] = 97 + i; nth(K, s, r); for (int i(0); i < (20); i++) T += LC(s[i] - 96 + N - (20)) && LC(N - (20) + i + 1); printf("%d\n", T); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:256777216") using namespace std; long long num[10000]; int nn = 0; long long fact[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200}; void gen(long long x) { if (x > 4444444447) { return; } num[nn] = x * 10 + 4; nn++; num[nn] = x * 10 + 7; nn++; gen(x * 10 + 4); gen(x * 10 + 7); } int notUsed(vector<bool> &used, int blockNum) { int j, pos = 0; for (j = 1; j < used.size(); j++) { if (!used[j]) pos++; if (blockNum == pos) break; } return j; } vector<int> permutation_by_num(int n, int num) { vector<int> res(n); vector<bool> used(n + 1, false); for (int i = 0; i < n; i++) { long long blockNum = (num - 1) / fact[n - i - 1] + 1; long long j = notUsed(used, blockNum); res[i] = j; used[j] = true; num = (num - 1) % fact[n - i - 1] + 1; } return res; } bool f(long long a) { if (a == 0) return false; while (a != 0) { if (a % 10 != 7 && a % 10 != 4) return false; a /= 10; } return true; } bool prov(long long a, long long b) { return f(a) && f(b); } int main() { gen(0); sort(num, num + nn); long long n, k; cin >> n >> k; int t = 14; if (n < 14) { t = n; } if (k > fact[t]) { cout << -1; return 0; } vector<int> ansMs = permutation_by_num(t, k); int ans = 0; if (t == 14) { for (int i = 0; i < nn; i++) { if (num[i] > n - 14) { ans = i; break; } } for (int i = 0; i < t; i++) { if (prov(n - 14 + i + 1, ansMs[i] + n - 14)) ans++; } } else { for (int i = 0; i < t; i++) { if (prov(1 + i, ansMs[i])) ans++; } } cout << endl; cout << ans; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Collection; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int count = in.readInt(); int index = in.readInt() - 1; int tail = -1; for (int i = 0; i <= count; i++) { if (IntegerUtils.factorial(i) > index) { tail = i; break; } } if (tail == -1) { out.println(-1); return; } long[] happy = generateHappy(); int answer = Arrays.binarySearch(happy, count - tail); if (answer < 0) answer = -answer - 1; else answer++; boolean[] taken = new boolean[tail]; int start = count - tail + 1; for (int i = 0; i < tail; i++) { long factorial = IntegerUtils.factorial(tail - i - 1); for (int j = 0; j < tail; j++) { if (!taken[j]) { if (factorial > index) { taken[j] = true; if (Arrays.binarySearch(happy, start + i) >= 0 && Arrays.binarySearch(happy, start + j) >= 0) answer++; break; } else index -= factorial; } } } out.println(answer); } private long[] generateHappy() { long[] happy = new long[(1 << 10) - 2]; happy[0] = 4; happy[1] = 7; int first = 0; int last = 2; for (int i = 2; i <= 9; i++) { for (int j = 0; j < last - first; j++) { happy[last + 2 * j] = 10 * happy[first + j] + 4; happy[last + 2 * j + 1] = 10 * happy[first + j] + 7; } int next = last + 2 * (last - first); first = last; last = next; } return happy; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class IntegerUtils { public static long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; map<long long int, bool> mp; int N, sayi = 1, dizi[20], ekle, mark[20], T, end = 0, Q, bsmk, sayac; long long int K, carp = 1, carp2 = 1; int bul(int X) { int T = 0; for (int i = 1; i <= Q; i++) { if (!mark[i]) T++; if (T == X) return i; } } void Kth(int N) { carp = 1; for (int i = 2; i <= N - 1; i++) carp *= i; T = N - 1; while (sayi != N) { if (K % carp == 0 && K != 0) ekle = K / carp; else ekle = K / carp + 1; K -= (ekle - 1) * carp; ekle = bul(ekle); mark[ekle] = 1; dizi[sayi] = ekle; sayi++; carp /= T--; } dizi[N] = bul(1); } int bol(int K) { while (K > 0) { K /= 10; bsmk++; } return bsmk; } void rec(int H, long long int K) { if (H <= bsmk) { if (K >= 1 && K <= N - Q) sayac++; if (H == bsmk) return; } rec(H + 1, K * 10 + 4); rec(H + 1, K * 10 + 7); } bool isluck(long long int P) { int tzv; while (P > 0) { tzv = P % 10; P /= 10; if (tzv != 4 && tzv != 7) return 0; } return 1; } int main() { scanf("%d %lli", &N, &K); for (int i = 2; i < 16; i++) carp *= i; Q = 15; while (carp >= K && Q != 0) carp /= Q--; Q++; if (Q > N) { printf("-1\n"); return 0; } T = Q - 1; bsmk = bol(N - Q); rec(0, 0); Kth(Q); for (int i = 1; i <= Q; i++) { if (isluck(dizi[i] + N - Q) && isluck(i + N - Q)) sayac++; } printf("%d\n", sayac); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; /** * @author Ivan Pryvalov ([email protected]) */ public class Codeforces_Round_91_Div1_C implements Runnable{ long[] cnt = new long[20]; private void solve() throws IOException { int n = scanner.nextInt(); int k = scanner.nextInt();//10^9 long curCnt = 1; int maxCnt = 1; for (; maxCnt<=n; maxCnt++){ curCnt *= maxCnt; if (curCnt >= k){ // cnt[maxCnt] = res; // maxCnt++; break; } cnt[maxCnt] = curCnt; } if (curCnt < k){ out.println(-1); return; } int firstIdx = n - maxCnt + 1; int[] perm = new int[maxCnt]; Set<Integer> avail = new TreeSet<Integer>(); for (int i = 0; i < perm.length; i++) { avail.add(i); } int left = k; int j = maxCnt-1; for (int i=0; i<maxCnt-1; i++, j--){ long full = 0; if (left>0){ full = (left-1) / cnt[j]; } Integer num = (Integer)avail.toArray()[(int)(full)]; perm[i] = num; avail.remove(num); left -= full * cnt[j]; } Integer lastNum = (Integer)avail.toArray()[0]; perm[maxCnt-1] = lastNum; int res = 0; for(int i=0; i<perm.length; i++){ if (isLucky(perm[i]+firstIdx) && isLucky(i+firstIdx)){ res++; } } cntFirst = 0; R = firstIdx-1; go(0); out.println(cntFirst+res); } private static boolean isLucky(int i) { while(i>0){ int d = i%10; if (d!=7 && d!=4) return false; i/=10; } return true; } int cntFirst; int R; private void go(long i) { if (i>R){ return; } if (i!=0){ cntFirst++; } go (i*10+4); go (i*10+7); } ///////////////////////////////////////////////// final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ; final int BUF_SIZE_INPUT = 1024; final int BUF_SIZE_OUT = 1024; boolean inputFromFile = false; String filenamePrefix = "A-small-attempt0"; String inSuffix = ".in"; String outSuffix = ".out"; //InputStream bis; //OutputStream bos; PrintStream out; ByteScanner scanner; ByteWriter writer; @Override public void run() { try{ InputStream bis = null; OutputStream bos = null; //PrintStream out = null; if (inputFromFile){ File baseFile = new File(getClass().getResource("/").getFile()); bis = new BufferedInputStream( new FileInputStream(new File( baseFile, filenamePrefix+inSuffix)), INPUT_BUFFER_SIZE); bos = new BufferedOutputStream( new FileOutputStream( new File(baseFile, filenamePrefix+outSuffix))); out = new PrintStream(bos); }else{ bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE); bos = new BufferedOutputStream(System.out); out = new PrintStream(bos); } scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE); writer = new ByteWriter(bos, BUF_SIZE_OUT); solve(); out.flush(); }catch (Exception e) { e.printStackTrace(); System.exit(1); } } public interface Constants{ final static byte ZERO = '0';//48 or 0x30 final static byte NINE = '9'; final static byte SPACEBAR = ' '; //32 or 0x20 final static byte MINUS = '-'; //45 or 0x2d final static char FLOAT_POINT = '.'; } public static class EofException extends IOException{ } public static class ByteWriter implements Constants { int bufSize = 1024; byte[] byteBuf = new byte[bufSize]; OutputStream os; public ByteWriter(OutputStream os, int bufSize){ this.os = os; this.bufSize = bufSize; } public void writeInt(int num) throws IOException{ int byteWriteOffset = byteBuf.length; if (num==0){ byteBuf[--byteWriteOffset] = ZERO; }else{ int numAbs = Math.abs(num); while (numAbs>0){ byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO); numAbs /= 10; } if (num<0) byteBuf[--byteWriteOffset] = MINUS; } os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset); } /** * Please ensure ar.length <= byteBuf.length! * * @param ar * @throws IOException */ public void writeByteAr(byte[] ar) throws IOException{ for (int i = 0; i < ar.length; i++) { byteBuf[i] = ar[i]; } os.write(byteBuf,0,ar.length); } public void writeSpaceBar() throws IOException{ byteBuf[0] = SPACEBAR; os.write(byteBuf,0,1); } } public static class ByteScanner implements Constants{ InputStream is; public ByteScanner(InputStream is, int bufSizeInput, int bufSize){ this.is = is; this.bufSizeInput = bufSizeInput; this.bufSize = bufSize; byteBufInput = new byte[this.bufSizeInput]; byteBuf = new byte[this.bufSize]; } public ByteScanner(byte[] data){ byteBufInput = data; bufSizeInput = data.length; bufSize = data.length; byteBuf = new byte[bufSize]; byteRead = data.length; bytePos = 0; } private int bufSizeInput; private int bufSize; byte[] byteBufInput; byte by=-1; int byteRead=-1; int bytePos=-1; byte[] byteBuf; int totalBytes; boolean eofMet = false; private byte nextByte() throws IOException{ if (bytePos<0 || bytePos>=byteRead){ byteRead = is==null? -1: is.read(byteBufInput); bytePos=0; if (byteRead<0){ byteBufInput[bytePos]=-1;//!!! if (eofMet) throw new EofException(); eofMet = true; } } return byteBufInput[bytePos++]; } /** * Returns next meaningful character as a byte.<br> * * @return * @throws IOException */ public byte nextChar() throws IOException{ while ((by=nextByte())<=0x20); return by; } /** * Returns next meaningful character OR space as a byte.<br> * * @return * @throws IOException */ public byte nextCharOrSpacebar() throws IOException{ while ((by=nextByte())<0x20); return by; } /** * Reads line. * * @return * @throws IOException */ public String nextLine() throws IOException { readToken((byte)0x20); return new String(byteBuf,0,totalBytes); } public byte[] nextLineAsArray() throws IOException { readToken((byte)0x20); byte[] out = new byte[totalBytes]; System.arraycopy(byteBuf, 0, out, 0, totalBytes); return out; } /** * Reads token. Spacebar is separator char. * * @return * @throws IOException */ public String nextToken() throws IOException { readToken((byte)0x21); return new String(byteBuf,0,totalBytes); } /** * Spacebar is included as separator char * * @throws IOException */ private void readToken() throws IOException { readToken((byte)0x21); } private void readToken(byte acceptFrom) throws IOException { totalBytes = 0; while ((by=nextByte())<acceptFrom); byteBuf[totalBytes++] = by; while ((by=nextByte())>=acceptFrom){ byteBuf[totalBytes++] = by; } } public int nextInt() throws IOException{ readToken(); int num=0, i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i<totalBytes; i++){ num*=10; num+=byteBuf[i]-ZERO; } return sign?-num:num; } public long nextLong() throws IOException{ readToken(); long num=0; int i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i<totalBytes; i++){ num*=10; num+=byteBuf[i]-ZERO; } return sign?-num:num; } /* //TODO test Unix/Windows formats public void toNextLine() throws IOException{ while ((ch=nextChar())!='\n'); } */ public double nextDouble() throws IOException{ readToken(); char[] token = new char[totalBytes]; for (int i = 0; i < totalBytes; i++) { token[i] = (char)byteBuf[i]; } return Double.parseDouble(new String(token)); } } public static void main(String[] args) { new Codeforces_Round_91_Div1_C().run(); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; set<long long> lucky; void gen(long long g, long long lim) { if (g + 4 > lim) return; else lucky.insert(g + 4); gen(10 * (g + 4), lim); if (g + 7 > lim) return; else gen(10 * (g + 7), lim); lucky.insert(g + 7); } bool check(long long num) { for (long long x = num; x > 0; x /= 10) { if (x % 10 != 4 && x % 10 != 7) { return false; } } return true; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n, k; cin >> n >> k; if (n < 13) { long long fat = 1; for (int i = 2; i <= n; ++i) fat *= i; if (fat < k) { cout << -1 << '\n'; return 0; } } --k; stack<int> f; for (int i = 1; k > 0; ++i) { f.push(k % i); k /= i; } gen(0, n - f.size()); int len = f.size(); vector<long long> nums(len), perm(len, 0); iota(nums.begin(), nums.end(), n - len + 1); for (long long i = 0; i < len; ++i) { perm[i] = nums[f.top()]; nums.erase(nums.begin() + f.top()); f.pop(); } long long ans = lucky.size(); for (long long j = n - len, i = 0; i < len; ++i, ++j) { if (check(j + 1) && check(perm[i])) { ++ans; } } cout << ans << '\n'; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.*; public class LuckyPermutation { public static void main (String [] arg) { Scanner sc = new Scanner(System.in); long N = sc.nextInt(); long K = sc.nextInt()-1; boolean overflow = (N > 15); int [] P = (overflow) ? permutation(15, K) : permutation((int)N,K); if (P == null) { System.out.println("-1"); return;} if (overflow) for (int i = 0; i<P.length; ++i) P[i] += (N-15); //System.err.println(Arrays.toString(P)); long count = 0; for (int i = 0; i<P.length; ++i) { long index = (overflow) ? (N-15)+i+1 : i+1; //System.err.println("Trying " + index + " and " + P[i]); if (isLucky(index) && isLucky(P[i])) count++; } ArrayList<Long> Lucky = new ArrayList<Long>(1<<12); Lucky.add(4L); Lucky.add(7L); for (int LEN = 2; LEN <= 10; ++LEN) { for (int i = 0; i<(1<<LEN); ++i) { long NUM = 0; for (int j = 0; j<LEN; ++j) { NUM += ((i & (1L<<j)) != 0) ? 4 : 7; NUM *= 10L; } Lucky.add(NUM/10); } } Collections.sort(Lucky); int start = 0; long L = N-15; for (int i = 0; i<Lucky.size(); ++i) if (L < Lucky.get(i)) {start=i; break;} count += (start); System.out.println(count); } public static boolean isLucky(long i) { //System.err.println(i + " : " + Long.toString(i).replaceAll("[47]","")); return (Long.toString(i).replaceAll("[47]","").length() == 0); } public static int [] permutation (int N, long kk) { long tA = kk; long tF = fact(N); if (kk >= tF) return null; boolean [] used = new boolean [N]; int [] B = new int [N]; for (int i = B.length-1; i>0; --i) { tF /= (i+1); long k = tA / tF; int j = 0; for (;j<B.length; ++j) { if (used[j]) continue; if (--k < 0) break; } used[j] = true; B[B.length-1-i] = j+1; tA %= tF; } for (int j = 0; j<B.length; ++j) if (!used[j]) {B[B.length-1]=j+1;break;} return B; } public static long fact (long N) { long F = 1; for (long i = 2; i<=N; ++i) F*=i; return F; } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.io.*; import java.math.*; import java.util.*; import java.util.Random; import static java.lang.Math.*; public class Solution implements Runnable { public static void main(String[] args) throws Exception { new Thread(null, new Solution(), "", 1 << 25).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; final String fname = ""; private String next() throws Exception { if (st == null || !st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } private int nextInt() throws Exception { return Integer.parseInt(next()); } private long nextLong() throws Exception { return Long.parseLong(next()); } private double nextDouble() throws Exception { return Double.parseDouble(next()); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { out.close(); } } void rec(long num) { if (num>1000000000) { return; } if (num!=0) { lucky.add(num); } rec(num*10+4); rec(num*10+7); } ArrayList<Long> lucky = new ArrayList<Long>(); long fact(long num) { if (num==0) return 1; long ret=1; for (long i=1;i<=num;i++) ret*=i; return ret; } boolean isLucky(long num) { while (num>0) { if (num%10!=4 && num%10!=7) return false; num/=10; } return true; } public void solve() throws Exception { long n=nextLong(); long k=nextLong(); long fact=1; long j=-1; for (long i=1;i<=n;i++) { fact=fact*i; if (fact>=k) { j=i; break; } } if (fact<k) { out.println(-1); return; } rec(0); Collections.sort(lucky); long ans=0; long bound = n-j; int l=-1; int r=lucky.size(); while (r-l>1) { int mid=(r+l)/2; if (lucky.get(mid)<=bound) l=mid; else r=mid; } ans+=(l+1); ArrayList<Long> numbers = new ArrayList<Long>(); for (long pos=n-j+1;pos<=n;pos++) numbers.add(pos); long cur=0; for (long pos=n-j+1;pos<=n;pos++) { for (int i=0;i<numbers.size();i++) { cur+=fact(n-pos); if (cur>=k) { cur-=fact(n-pos); if (isLucky(pos) && isLucky(numbers.get(i))) ans++; numbers.remove(i); break; } } } out.println(ans); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; vector<long long> lucky, f; vector<int> u; long long n, k; void dfs(long long v) { if (v > 7777777777LL) return; if (v) lucky.push_back(v); dfs(v * 10 + 4); dfs(v * 10 + 7); } int main() { dfs(0); sort(lucky.begin(), lucky.end()); f.push_back(1); cin >> n >> k; for (int i = 2; i <= n; i++) { if (f.back() >= k) break; f.push_back(f.back() * i); } if (f.size() == n && k > f.back()) { puts("-1"); return 0; } int cnt = 0; for (int i = 0; i < (int)lucky.size(); i++) if (lucky[i] > n - (int)f.size()) break; else cnt++; u.resize(f.size()); reverse(f.begin(), f.end()); f.push_back(2000); k--; for (int i = 0; i < (int)u.size(); i++) { int c = 0, a; while (k >= f[i + 1]) { k -= f[i + 1]; c++; } for (int j = 0; j < (int)u.size(); j++) if (!u[j]) if (c) c--; else { a = j; u[j] = 1; break; } a += n - (int)u.size() + 1; int j = i + n - (int)u.size() + 1; if (binary_search(lucky.begin(), lucky.end(), a) && binary_search(lucky.begin(), lucky.end(), j)) cnt++; } cout << cnt << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; inline void read(register int *n) { register char c; *n = 0; do { c = getchar(); } while (c < '0' || c > '9'); do { *n = c - '0' + *n * 10; c = getchar(); } while (c >= '0' && c <= '9'); } vector<int> kperm(vector<int> V, long long k) { k--; vector<int> res; long long fac[20] = {1}; for (register int i = (1); i < (20); ++i) fac[i] = i * fac[i - 1]; if (k >= fac[((int)(V).size())]) { cout << -1 << "\n"; exit(0); } while (!V.empty()) { long long f = fac[((int)(V).size()) - 1]; res.push_back(V[k / f]); V.erase(V.begin() + k / f); k %= f; } return res; } vector<long long> V; void gen(long long x) { if (x > 0) V.push_back(x); if (x > 1000LL * 1000 * 1000 * 100) return; gen(x * 10 + 7); gen(x * 10 + 4); } bool islucky(int x) { while (x % 10 == 7 || x % 10 == 4) x /= 10; return x == 0; } int main(int argv, char **argc) { gen(0); long long n, k, m; cin >> n >> k; m = min(16LL, n); vector<int> tmp; for (register int i = (0); i < (m); ++i) tmp.push_back(n - i); sort((tmp).begin(), (tmp).end()); int cnt = 0; for (register int i = (0); i < (((int)(V).size())); ++i) if (V[i] <= n - 16) cnt++; tmp = kperm(tmp, k); for (register int i = (0); i < (m); ++i) if (islucky(tmp[((int)(tmp).size()) - 1 - i]) && islucky(n - i)) cnt++; cout << cnt << "\n"; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using std::cin; using std::cout; using std::endl; using std::min; using std::string; using std::vector; long long next(long long x) { if (x == 0) return 0; if (x % 10 <= 4) { long long a = next(x / 10); return a * 10 + 4; } if (x % 10 <= 7) { long long a = next(x / 10); if (a > x / 10) return a * 10 + 4; else return a * 10 + 7; } return next((x + 10 - (x % 10)) / 10) * 10 + 4; } struct pair { int x, y; }; int main() { int n, k; cin >> n >> k; long long x = 1; int i = 1; vector<int> fac; fac.push_back(1); while (x < k) { ++i; x *= i; fac.push_back(x); } if (i > n) { cout << -1 << endl; return 0; } int out = 0; long long l = 4; while (l <= n - i) { ++out; l = next(l + 1); } vector<pair> data(i); for (int j = 0; j < i; ++j) { data[j].x = j + n - i + 1; if (i == j + 1) data[j].y = 1 + data[j].x; else { int q = k / fac[i - j - 2]; ++q; if (k % fac[i - j - 2] == 0) --q; k = k - (q - 1) * fac[i - j - 2]; data[j].y = q + data[j].x; } } vector<bool> use(i, false); for (int j = 0; j < i; ++j) { int num = data[j].y - data[j].x; int qq = 0; while ((num > 1) || (use[qq])) { if (!use[qq]) --num; ++qq; } data[j].y = data[0].x + qq; use[qq] = true; if ((data[j].x == next(data[j].x)) && (data[j].y == next(data[j].y))) ++out; } cout << out << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import sys from math import factorial def kth_perm(seq, index): result = [] fact = factorial(len(seq)) index %= fact while seq: fact = fact / len(seq) choice, index = index // fact, index % fact result.append(seq.pop(choice)) return result def inc_lucky(s, index): if index == -1: s = ['4'] + s return s if s[index] == '4': s[index] = '7' return s s[index] = '4' return inc_lucky(s, index - 1) def is_lucky(s): for e in s: if e != '4' and e != '7': return False return True n, k = map(int, raw_input().split()) seq = range(max(n - 12, 1), n + 1) if k > factorial(len(seq)): print -1 sys.exit(0) seq = kth_perm(seq, k - 1) r = 0 num = ['4'] while int(''.join(num)) < n - 12: r += 1 num = inc_lucky(num, len(num) - 1) for i, num in enumerate(seq): index = i + n - len(seq) + 1 if is_lucky(str(index)) and is_lucky(str(num)): r += 1 print r
PYTHON
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
L = [4,7,44,47,74,77,444,447,474,477,744,747,774,777,4444,4447,4474,4477,4744,4747,4774,4777,7444,7447,7474,7477,7744,7747,7774,7777,44444,44447,44474,44477,44744,44747,44774,44777,47444,47447,47474,47477,47744,47747,47774,47777,74444,74447,74474,74477,74744,74747,74774,74777,77444,77447,77474,77477,77744,77747,77774,77777,444444,444447,444474,444477,444744,444747,444774,444777,447444,447447,447474,447477,447744,447747,447774,447777,474444,474447,474474,474477,474744,474747,474774,474777,477444,477447,477474,477477,477744,477747,477774,477777,744444,744447,744474,744477,744744,744747,744774,744777,747444,747447,747474,747477,747744,747747,747774,747777,774444,774447,774474,774477,774744,774747,774774,774777,777444,777447,777474,777477,777744,777747,777774,777777,4444444,4444447,4444474,4444477,4444744,4444747,4444774,4444777,4447444,4447447,4447474,4447477,4447744,4447747,4447774,4447777,4474444,4474447,4474474,4474477,4474744,4474747,4474774,4474777,4477444,4477447,4477474,4477477,4477744,4477747,4477774,4477777,4744444,4744447,4744474,4744477,4744744,4744747,4744774,4744777,4747444,4747447,4747474,4747477,4747744,4747747,4747774,4747777,4774444,4774447,4774474,4774477,4774744,4774747,4774774,4774777,4777444,4777447,4777474,4777477,4777744,4777747,4777774,4777777,7444444,7444447,7444474,7444477,7444744,7444747,7444774,7444777,7447444,7447447,7447474,7447477,7447744,7447747,7447774,7447777,7474444,7474447,7474474,7474477,7474744,7474747,7474774,7474777,7477444,7477447,7477474,7477477,7477744,7477747,7477774,7477777,7744444,7744447,7744474,7744477,7744744,7744747,7744774,7744777,7747444,7747447,7747474,7747477,7747744,7747747,7747774,7747777,7774444,7774447,7774474,7774477,7774744,7774747,7774774,7774777,7777444,7777447,7777474,7777477,7777744,7777747,7777774,7777777,44444444,44444447,44444474,44444477,44444744,44444747,44444774,44444777,44447444,44447447,44447474,44447477,44447744,44447747,44447774,44447777,44474444,44474447,44474474,44474477,44474744,44474747,44474774,44474777,44477444,44477447,44477474,44477477,44477744,44477747,44477774,44477777,44744444,44744447,44744474,44744477,44744744,44744747,44744774,44744777,44747444,44747447,44747474,44747477,44747744,44747747,44747774,44747777,44774444,44774447,44774474,44774477,44774744,44774747,44774774,44774777,44777444,44777447,44777474,44777477,44777744,44777747,44777774,44777777,47444444,47444447,47444474,47444477,47444744,47444747,47444774,47444777,47447444,47447447,47447474,47447477,47447744,47447747,47447774,47447777,47474444,47474447,47474474,47474477,47474744,47474747,47474774,47474777,47477444,47477447,47477474,47477477,47477744,47477747,47477774,47477777,47744444,47744447,47744474,47744477,47744744,47744747,47744774,47744777,47747444,47747447,47747474,47747477,47747744,47747747,47747774,47747777,47774444,47774447,47774474,47774477,47774744,47774747,47774774,47774777,47777444,47777447,47777474,47777477,47777744,47777747,47777774,47777777,74444444,74444447,74444474,74444477,74444744,74444747,74444774,74444777,74447444,74447447,74447474,74447477,74447744,74447747,74447774,74447777,74474444,74474447,74474474,74474477,74474744,74474747,74474774,74474777,74477444,74477447,74477474,74477477,74477744,74477747,74477774,74477777,74744444,74744447,74744474,74744477,74744744,74744747,74744774,74744777,74747444,74747447,74747474,74747477,74747744,74747747,74747774,74747777,74774444,74774447,74774474,74774477,74774744,74774747,74774774,74774777,74777444,74777447,74777474,74777477,74777744,74777747,74777774,74777777,77444444,77444447,77444474,77444477,77444744,77444747,77444774,77444777,77447444,77447447,77447474,77447477,77447744,77447747,77447774,77447777,77474444,77474447,77474474,77474477,77474744,77474747,77474774,77474777,77477444,77477447,77477474,77477477,77477744,77477747,77477774,77477777,77744444,77744447,77744474,77744477,77744744,77744747,77744774,77744777,77747444,77747447,77747474,77747477,77747744,77747747,77747774,77747777,77774444,77774447,77774474,77774477,77774744,77774747,77774774,77774777,77777444,77777447,77777474,77777477,77777744,77777747,77777774,77777777,444444444,444444447,444444474,444444477,444444744,444444747,444444774,444444777,444447444,444447447,444447474,444447477,444447744,444447747,444447774,444447777,444474444,444474447,444474474,444474477,444474744,444474747,444474774,444474777,444477444,444477447,444477474,444477477,444477744,444477747,444477774,444477777,444744444,444744447,444744474,444744477,444744744,444744747,444744774,444744777,444747444,444747447,444747474,444747477,444747744,444747747,444747774,444747777,444774444,444774447,444774474,444774477,444774744,444774747,444774774,444774777,444777444,444777447,444777474,444777477,444777744,444777747,444777774,444777777,447444444,447444447,447444474,447444477,447444744,447444747,447444774,447444777,447447444,447447447,447447474,447447477,447447744,447447747,447447774,447447777,447474444,447474447,447474474,447474477,447474744,447474747,447474774,447474777,447477444,447477447,447477474,447477477,447477744,447477747,447477774,447477777,447744444,447744447,447744474,447744477,447744744,447744747,447744774,447744777,447747444,447747447,447747474,447747477,447747744,447747747,447747774,447747777,447774444,447774447,447774474,447774477,447774744,447774747,447774774,447774777,447777444,447777447,447777474,447777477,447777744,447777747,447777774,447777777,474444444,474444447,474444474,474444477,474444744,474444747,474444774,474444777,474447444,474447447,474447474,474447477,474447744,474447747,474447774,474447777,474474444,474474447,474474474,474474477,474474744,474474747,474474774,474474777,474477444,474477447,474477474,474477477,474477744,474477747,474477774,474477777,474744444,474744447,474744474,474744477,474744744,474744747,474744774,474744777,474747444,474747447,474747474,474747477,474747744,474747747,474747774,474747777,474774444,474774447,474774474,474774477,474774744,474774747,474774774,474774777,474777444,474777447,474777474,474777477,474777744,474777747,474777774,474777777,477444444,477444447,477444474,477444477,477444744,477444747,477444774,477444777,477447444,477447447,477447474,477447477,477447744,477447747,477447774,477447777,477474444,477474447,477474474,477474477,477474744,477474747,477474774,477474777,477477444,477477447,477477474,477477477,477477744,477477747,477477774,477477777,477744444,477744447,477744474,477744477,477744744,477744747,477744774,477744777,477747444,477747447,477747474,477747477,477747744,477747747,477747774,477747777,477774444,477774447,477774474,477774477,477774744,477774747,477774774,477774777,477777444,477777447,477777474,477777477,477777744,477777747,477777774,477777777,744444444,744444447,744444474,744444477,744444744,744444747,744444774,744444777,744447444,744447447,744447474,744447477,744447744,744447747,744447774,744447777,744474444,744474447,744474474,744474477,744474744,744474747,744474774,744474777,744477444,744477447,744477474,744477477,744477744,744477747,744477774,744477777,744744444,744744447,744744474,744744477,744744744,744744747,744744774,744744777,744747444,744747447,744747474,744747477,744747744,744747747,744747774,744747777,744774444,744774447,744774474,744774477,744774744,744774747,744774774,744774777,744777444,744777447,744777474,744777477,744777744,744777747,744777774,744777777,747444444,747444447,747444474,747444477,747444744,747444747,747444774,747444777,747447444,747447447,747447474,747447477,747447744,747447747,747447774,747447777,747474444,747474447,747474474,747474477,747474744,747474747,747474774,747474777,747477444,747477447,747477474,747477477,747477744,747477747,747477774,747477777,747744444,747744447,747744474,747744477,747744744,747744747,747744774,747744777,747747444,747747447,747747474,747747477,747747744,747747747,747747774,747747777,747774444,747774447,747774474,747774477,747774744,747774747,747774774,747774777,747777444,747777447,747777474,747777477,747777744,747777747,747777774,747777777,774444444,774444447,774444474,774444477,774444744,774444747,774444774,774444777,774447444,774447447,774447474,774447477,774447744,774447747,774447774,774447777,774474444,774474447,774474474,774474477,774474744,774474747,774474774,774474777,774477444,774477447,774477474,774477477,774477744,774477747,774477774,774477777,774744444,774744447,774744474,774744477,774744744,774744747,774744774,774744777,774747444,774747447,774747474,774747477,774747744,774747747,774747774,774747777,774774444,774774447,774774474,774774477,774774744,774774747,774774774,774774777,774777444,774777447,774777474,774777477,774777744,774777747,774777774,774777777,777444444,777444447,777444474,777444477,777444744,777444747,777444774,777444777,777447444,777447447,777447474,777447477,777447744,777447747,777447774,777447777,777474444,777474447,777474474,777474477,777474744,777474747,777474774,777474777,777477444,777477447,777477474,777477477,777477744,777477747,777477774,777477777,777744444,777744447,777744474,777744477,777744744,777744747,777744774,777744777,777747444,777747447,777747474,777747477,777747744,777747747,777747774,777747777,777774444,777774447,777774474,777774477,777774744,777774747,777774774,777774777,777777444,777777447,777777474,777777477,777777744,777777747,777777774,777777777,4444444444] F = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800L] L = [x - 1 for x in L] N, K = map(int, raw_input().strip().split()) if N < len(F) and K > F[N]: print -1 exit() for i in xrange(len(F)): if F[i] >= K: st = N - i break con = 0 for x in L: if x < st: con += 1 else: break L = set(L) used = [False] * 100 for i in xrange(st, N): n = N - i - 1 x = (K - 1) / F[n] K -= x * F[n] cur = 0 cnt = 0 while cnt <= x: if not used[cur]: cnt += 1 cur += 1 used[cur - 1] = True if i in L and st + cur - 1 in L: con += 1 print con
PYTHON
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import static java.lang.Math.*; import java.util.*; import java.io.*; public class E { public void solve() throws Exception { int n = nextInt(), k = nextInt()-1; if (n<=12 && k>=facArr[n]) halt(-1); HashSet<Integer> hs = new HashSet<Integer>(); dfs(4,hs); dfs(7,hs); int len = 0; for (int i=facArr.length-1; i>=0; --i) if (k<facArr[i] && k>=facArr[i-1]) { len = i; break; } debug(len); int[] p = new int[len]; for (int i=0; i<p.length; ++i) p[i] = n-p.length+1+i; debug(p); gen(k,p,0); debug(p); int res = 0; for (Integer i: hs) if (i<=n-len) res++; for (int i=n-len+1; i<=n; ++i) if (hs.contains(i) && hs.contains(p[i-(n-len+1)])) res++; println(res); } void gen (int k, int[] p, int pos) { if (k<1) return; int i = p.length-pos-1; int offset = k/facArr[p.length-pos-1]; if (offset!=0) { p[offset+pos]^=p[pos]; p[pos]^=p[offset+pos]; p[offset+pos]^=p[pos]; debug(k,offset,p); Arrays.sort(p,pos+1,p.length); } gen(k-facArr[i]*offset,p,pos+1); return; } int[] facArr = {0,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,Integer.MAX_VALUE}; void dfs (long x, HashSet<Integer> hs) { if (x>1000000000) return; hs.add((int)x); dfs(10*x+4, hs); dfs(10*x+7, hs); } //////////////////////////////////////////////////////////////////////////// boolean showDebug = true; double EPS = 1e-7; int INF = Integer.MAX_VALUE; long INFL = Long.MAX_VALUE; double INFD = Double.MAX_VALUE; int absPos(int num) { return num<0 ? 0:num; } long absPos(long num) { return num<0 ? 0:num; } double absPos(double num) { return num<0 ? 0:num; } int min(int... nums) { int r = INF; for (int i: nums) if (i<r) r=i; return r; } int max(int... nums) { int r = -INF; for (int i: nums) if (i>r) r=i; return r; } long minL(long... nums) { long r = INFL; for (long i: nums) if (i<r) r=i; return r; } long maxL(long... nums) { long r = -INFL; for (long i: nums) if (i>r) r=i; return r; } double minD(double... nums) { double r = INFD; for (double i: nums) if (i<r) r=i; return r; } double maxD(double... nums) { double r = -INFD; for (double i: nums) if (i>r) r=i; return r; } long sumArr(int[] arr) { long res = 0; for (int i: arr) res+=i; return res; } long sumArr(long[] arr) { long res = 0; for (long i: arr) res+=i; return res; } double sumArr(double[] arr) { double res = 0; for (double i: arr) res+=i; return res; } long partsFitCnt(long partSize, long wholeSize) { return (partSize+wholeSize-1)/partSize; } boolean odd(long num) { return (num&1)==1; } boolean hasBit(int num, int pos) { return (num&(1<<pos))>0; } long binpow(int a, int n) { long r = 1; while (n>0) { if ((n&1)!=0) r*=a; a*=a; n>>=1; } return r; } boolean isLetter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } boolean isLowercase(char c) { return (c>='a' && c<='z'); } boolean isUppercase(char c) { return (c>='A' && c<='Z'); } boolean isDigit(char c) { return (c>='0' && c<='9'); } String stringn(String s, int n) { if (n<1) return ""; StringBuilder sb = new StringBuilder(s.length()*n); for (int i=0; i<n; ++i) sb.append(s); return sb.toString(); } String str(Object o) { return o.toString(); } long timer = System.currentTimeMillis(); void startTimer() { timer = System.currentTimeMillis(); } void stopTimer() { System.err.println("time: "+(System.currentTimeMillis()-timer)/1000.0); } class InputReader { private byte[] buf; private int bufPos = 0, bufLim = -1; public InputReader(int size) { buf = new byte[size]; } private void fillBuf() throws IOException { bufLim = System.in.read(buf); bufPos = 0; } char read() throws IOException { if (bufPos>=bufLim) fillBuf(); return (char)buf[bufPos++]; } boolean hasInput() throws IOException { if (bufPos>=bufLim) fillBuf(); return bufPos<bufLim; } } InputReader inputReader = new InputReader(1<<16); static BufferedWriter outputWriter = new BufferedWriter(new OutputStreamWriter(System.out), 1<<16); char nextChar() throws IOException { return inputReader.read(); } char nextNonWhitespaceChar() throws IOException { char c = inputReader.read(); while (c<=' ') c=inputReader.read(); return c; } String nextWord() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c>' ') { sb.append(c); c = inputReader.read(); } return new String(sb); } String nextLine() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c!='\n' && c!='\r') { sb.append(c); c = inputReader.read(); } return new String(sb); } int nextInt() throws IOException { int r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r=c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10; r+=c-48; c=nextChar(); } return neg ? -r:r; } long nextLong() throws IOException { long r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r = c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10L; r+=c-48L; c=nextChar(); } return neg ? -r:r; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextWord()); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i=0; i<size; ++i) arr[i] = nextInt(); return arr; } long[] nextArrL(int size) throws NumberFormatException, IOException { long[] arr = new long[size]; for (int i=0; i<size; ++i) arr[i] = nextLong(); return arr; } double[] nextArrD(int size) throws NumberFormatException, IOException { double[] arr = new double[size]; for (int i=0; i<size; ++i) arr[i] = nextDouble(); return arr; } String[] nextArrS(int size) throws NumberFormatException, IOException { String[] arr = new String[size]; for (int i=0; i<size; ++i) arr[i] = nextWord(); return arr; } char[] nextArrCh(int size) throws IOException { char[] arr = new char[size]; for (int i=0; i<size; ++i) arr[i] = nextNonWhitespaceChar(); return arr; } char[][] nextArrCh(int rows, int columns) throws IOException { char[][] arr = new char[rows][columns]; for (int i=0; i<rows; ++i) for (int j=0; j<columns; ++j) arr[i][j] = nextNonWhitespaceChar(); return arr; } char[][] nextArrChBorders(int rows, int columns, char border) throws IOException { char[][] arr = new char[rows+2][columns+2]; for (int i=1; i<=rows; ++i) for (int j=1; j<=columns; ++j) arr[i][j] = nextNonWhitespaceChar(); for (int i=0; i<columns+2; ++i) { arr[0][i] = border; arr[rows+1][i] = border; } for (int i=0; i<rows+2; ++i) { arr[i][0] = border; arr[i][columns+1] = border; } return arr; } void printf(String format, Object... args) throws IOException { outputWriter.write(String.format(format, args)); } void print(Object o) throws IOException { outputWriter.write(o.toString()); } void println(Object o) throws IOException { outputWriter.write(o.toString()); outputWriter.newLine(); } void print(Object... o) throws IOException { for (int i=0; i<o.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(o[i].toString()); } } void println(Object... o) throws IOException { print(o); outputWriter.newLine(); } void printn(Object o, int n) throws IOException { String s = o.toString(); for (int i=0; i<n; ++i) { outputWriter.write(s); if (i!=n-1) outputWriter.write(' '); } } void printnln(Object o, int n) throws IOException { printn(o, n); outputWriter.newLine(); } void printArr(int[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Integer.toString(arr[i])); } } void printArr(long[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Long.toString(arr[i])); } } void printArr(double[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Double.toString(arr[i])); } } void printArr(String[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(arr[i]); } } void printArr(char[] arr) throws IOException { for (char c: arr) outputWriter.write(c); } void printlnArr(int[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(long[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(double[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(String[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(char[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void halt(Object... o) throws IOException { if (o.length!=0) println(o); outputWriter.flush(); outputWriter.close(); System.exit(0); } void debug(Object... o) { if (showDebug) System.err.println(Arrays.deepToString(o)); } public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); new E().solve(); outputWriter.flush(); outputWriter.close(); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int n, k; long long fact[14] = {1}; bool cmp(int p) { if (p > 13 || fact[p] >= k) return true; k -= fact[p]; return false; } bool check(int x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } bool used[16]; int s; int calc(int i) { if (i > n) return 0; for (int j = s; j <= n; ++j) if (!used[j - s] && cmp(n - i)) { used[j - s] = true; return (check(i) && check(j)) + calc(i + 1); } return -1; } long long all[2046] = {4, 7}; int allC = 2; int main() { for (int i = 1; i < 14; ++i) fact[i] = fact[i - 1] * i; scanf("%d%d", &n, &k); if (n < 14 && k > fact[n]) { printf("-1"); return 0; } s = 1; if (n < 14) printf("%d", calc(1)); else { for (int i = 0; all[allC - 1] < 7777777777LL; ++i) { all[allC++] = all[i] * 10 + 4; all[allC++] = all[i] * 10 + 7; } s = n - 13; printf("%d", lower_bound(all, all + allC, s) - all + calc(s)); } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 7; const long long mod = 998244353; const long long INF = 5e18 + 7; const int inf = 1e9 + 7; const long long maxx = 1e6 + 700; long long n, k; long long fac[maxn]; vector<int> v; int ans = 0; int find(int x) { sort(v.begin(), v.end()); int t = v[x]; v.erase(v.begin() + x); return t; } bool check(int x) { while (x) { if ((x % 10) != 4 && (x % 10) != 7) return 0; x /= 10; } return 1; } void dfs(long long x, long long y) { if (x > y) return; if (x != 0) ans++; dfs(x * 10 + 4, y); dfs(x * 10 + 7, y); } int main() { scanf("%lld%lld", &n, &k); k = k - 1; long long T = -1; fac[0] = 1; for (int i = 1; i <= n; i++) { fac[i] = i * fac[i - 1]; v.push_back(n - i + 1); if (fac[i] > k) { T = i; break; } } if (T == -1) { puts("-1"); return 0; } dfs(0, n - T); for (int i = T; i >= 1; i--) { int t = find(k / fac[i - 1]), pos = n - i + 1; if (check(pos) && check(t)) ans++; k = k % fac[i - 1]; } printf("%d\n", ans); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; map<int, bool> mp; map<int, bool>::iterator it; long long p[1 << 11] = {0}, psum = 1; long long q[20]; bool flag[20]; void Init() { mp.clear(); memset(flag, 0x00, sizeof(flag)); for (int i = 0; i < psum; i++) { if (p[i] < 1e9) { p[psum++] = p[i] * 10 + 4; p[psum++] = p[i] * 10 + 7; } if (i) mp[p[i]] = true; } q[0] = 1LL; for (int i = 1; i < 14; i++) { q[i] = q[i - 1] * i; } } int n, k; int getNum(int x); int main() { Init(); scanf("%d%d", &n, &k); if (n < 13 && k > q[n]) { printf("-1\n"); return 0; } k--; int x = n > 13 ? n - 13 : 0; int y = n > 13 ? 13 : n; int ans = 0; for (int i = 1; i < psum; i++, ans++) if (p[i] > x) break; for (int i = y; i; i--) { int num = getNum(k / q[i - 1] + 1); k %= q[i - 1]; it = mp.find(x + num); if (it == mp.end()) continue; it = mp.find(x + y - i + 1); if (it == mp.end()) continue; ans++; } printf("%d\n", ans); return 0; } int getNum(int x) { int cnt = 0; for (int i = 1; true; i++) { if (!flag[i]) cnt++; if (cnt == x) { flag[i] = true; return i; } } }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const long long MAXN = 1e6 + 1, mod = 1e9 + 7, INF = 1e9 + 10; const double eps = 1e-9; template <typename A, typename B> inline bool chmin(A &a, B b) { if (a > b) { a = b; return 1; } return 0; } template <typename A, typename B> inline bool chmax(A &a, B b) { if (a < b) { a = b; return 1; } return 0; } template <typename A, typename B> inline long long add(A x, B y) { if (x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y; } template <typename A, typename B> inline void add2(A &x, B y) { if (x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y); } template <typename A, typename B> inline long long mul(A x, B y) { return 1ll * x * y % mod; } template <typename A, typename B> inline void mul2(A &x, B y) { x = (1ll * x * y % mod + mod) % mod; } template <typename A> inline void debug(A a) { cout << a << '\n'; } template <typename A> inline long long sqr(A x) { return 1ll * x * x; } inline long long read() { char c = getchar(); long long x = 0, f = 1; while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } long long N, K, fac[MAXN]; vector<long long> res; long long find(long long x) { sort(res.begin(), res.end()); long long t = res[x]; res.erase(res.begin() + x); return t; } bool check(long long x) { while (x) { if ((x % 10) != 4 && (x % 10) != 7) return 0; x /= 10; } return 1; } long long ans; void dfs(long long x, long long Lim) { if (x > Lim) return; if (x != 0) ans++; dfs(x * 10 + 4, Lim); dfs(x * 10 + 7, Lim); } signed main() { N = read(); K = read() - 1; long long T = -1; fac[0] = 1; for (long long i = 1; i <= N; i++) { fac[i] = i * fac[i - 1]; res.push_back(N - i + 1); if (fac[i] > K) { T = i; break; } } if (T == -1) { puts("-1"); return 0; } dfs(0, N - T); for (long long i = T; i >= 1; i--) { long long t = find(K / fac[i - 1]), pos = N - i + 1; if (check(pos) && check(t)) ans++; K = K % fac[i - 1]; } cout << ans; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long rev(long long t) { long long res = 0; while (t) { if (t % 2) res *= 10, res += 7; else res *= 10, res += 4; t /= 10; } return res; } long long conv(long long t, int len) { long long res = 0, ans = 0, k = 0; while (t) { k++; if (t % 2) res *= 10, res += 7; else res *= 10, res += 4; t /= 2; } res = rev(res); for (int i = 0; i < len - k; i++) ans *= 10, ans += 4; for (int i = 0; i < k; i++) ans *= 10; ans += res; return ans; } const int MAXN = 15; vector<int> num; int n, k, ls, ans; bool se[MAXN + 10]; long long f[MAXN]; bool isluck(int a) { while (a) { if (a % 10 != 4 && a % 10 != 7) return false; a /= 10; } return true; } int main() { cin >> n >> k; f[0] = 1; for (int i = 1; i < MAXN; i++) f[i] = f[i - 1] * i; if (n < 15 && k > f[n]) return cout << -1, 0; for (int i = 1; i <= min(n, MAXN); i++) num.push_back(i); ls = n - num.size(); for (int i = 0; i < num.size(); i++) { int j = 1; while (se[j]) j++; while (k > f[num.size() - i - 1]) { k -= f[num.size() - i - 1]; j++; while (se[j]) j++; } num[i] = j; se[j] = 1; } bool R = 0; for (int i = 1; i < 30; i++) { if (R) break; for (int j = 0; j < (1 << i); j++) { long long t = conv(j, i); if (t > ls) { R = 1; break; } ans++; } } for (int i = 0; i < num.size(); i++) if (isluck(i + ls + 1) && isluck(ls + num[i])) ans++; cout << ans; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long a[10000], jc[20]; int t, o[20], p[20]; int cal(long long x) { if (x <= 0) return 0; int ans = 0; for (int i = (1); i <= (t); i++) if (a[i] <= x) ans++; else { break; }; return ans; } void init() { t = 0; for (int i = (1); i <= (10); i++) for (int j = (0); j <= ((1 << i) - 1); j++) { long long s = 0; for (int k = (i - 1); k >= (0); k--) if ((j >> k) & 1) s = s * 10 + 7; else s = s * 10 + 4; a[++t] = s; }; } bool luck(long long x) { while (x > 0) { if (x % 10 != 4 && x % 10 != 7) return 0; x /= 10; }; return 1; } int main() { int n, k; scanf("%d%d", &n, &k); jc[0] = 1; for (int i = (1); i <= (13); i++) jc[i] = jc[i - 1] * i; if (n < 13) { long long ss = 1; for (int i = (1); i <= (n); i++) ss *= i; if (ss < k) { puts("-1"); return 0; }; }; int ans = 0; k--; for (int i = (12); i >= (0); i--) { long long nh = k / jc[i]; k = k % jc[i]; for (int j = (0); j <= (12); j++) if (!o[j]) { if (!nh) { p[i] = j; o[j] = 1; break; }; nh--; }; if (i < n) { cerr << n - 12 + p[i] << endl; if (luck(n - i) && luck(n - 12 + p[i])) ans++; }; }; init(); printf("%d", cal(n - 13) + ans); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.*; import java.io.*; import java.math.BigInteger; import static java.lang.Math.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int k = in.nextInt(); if (fact(n) < k) { out.println(-1); } else { long res = 0; if (n <= 15) { int[] a = new int[(int) n]; for (int i = 0; i < n; ++i) { a[i] = i; } res = count(a, k, 1); } else { int[] a = new int[15]; for (int i = 0; i < 15; ++i) { a[i] = i; } res = count(a, k, (n - 15) + 1); res += countLucky(n - 15); } out.println(res); } } private long count(int[] a, int k, int start) { setKth(a, k - 1); long res = 0; for (int i = 0; i < a.length; ++i) { if (isLucky(i + start) && isLucky(a[i] + start)) { ++res; } } return res; } private void setKth(int[] a, int k) { long[] fact = new long[a.length + 1]; fact[0] = 1; for (int i = 1; i < fact.length; ++i) { fact[i] = fact[i - 1] * i; } List<Integer> cur = new ArrayList<Integer>(); for (int x : a) { cur.add(x); } for (int i = 0; i < a.length; ++i) { int id = (int) (k / fact[a.length - i - 1]); a[i] = cur.get(id); cur.remove(id); k %= fact[a.length - i - 1]; } } private boolean isLucky(int n) { while (n > 0) { if (n % 10 != 4 && n % 10 != 7) { return false; } n /= 10; } return true; } private long countLucky(int n) { return countLucky(4, n) + countLucky(7, n); } private long countLucky(long cur, int n) { if (cur > n) { return 0; } return 1 + countLucky(cur * 10 + 4, n) + countLucky(cur * 10 + 7, n); } private long fact(int n) { long res = 1; for (int i = 1; i <= n; ++i) { res *= i; if (res > Integer.MAX_VALUE) { break; } } return res; } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } private void debug(Object... objects) { System.out.println(Arrays.toString(objects)); } private static class Scanner { private BufferedReader reader; private StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = reader.readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public int[] nextInts(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; ++i) { res[i] = nextInt(); } return res; } public long[] nextLongs(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; ++i) { res[i] = nextLong(); } return res; } public double[] nextDoubles(int n) throws IOException { double[] res = new double[n]; for (int i = 0; i < n; ++i) { res[i] = nextDouble(); } return res; } public String[] nextStrings(int n) throws IOException { String[] res = new String[n]; for (int i = 0; i < n; ++i) { res[i] = next(); } return res; } } public static void main(String[] args) throws Exception { new Thread(null, new Main(), "Main", 1 << 28).start(); } private Scanner in = new Scanner(new InputStreamReader(System.in)); private PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; vector<long long> lucky; long long l, r; void gen(long long x) { if (x >= 4444444444ll) return; lucky.push_back(x); gen(x * 10 + 4); gen(x * 10 + 7); } bool islucky(int x) { if (!x) return (false); while (x) { if (x % 10 != 4 && x % 10 != 7) return (false); x /= 10; } return (true); } int main() { int n, k, r; long long x = 1; scanf("%d %d", &n, &k); bool ok = false; for (int i = 1; i <= n; i++) { x *= i; if (x >= k) { ok = true; r = i; break; } } if (!ok) return (!printf("-1\n")); gen(0); sort(lucky.begin(), lucky.end()); int res = 0; for (int i = 0; i < lucky.size(); i++) { if (lucky[i] && lucky[i] <= n - r) res++; } bool used[128]; int num[128]; memset(used, false, sizeof(used)); for (int i = 1; i <= r; i++) { int t = 1; x = 1; for (int m = 1; m <= r - i; m++) x *= m; while (t * x < k) t++; int cnt = 0; for (int j = 1; j <= r; j++) { if (!used[j]) cnt++; if (cnt == t && !used[j]) { num[i] = j; used[j] = 1; break; } } k -= (t - 1) * x; if (k <= 0) k = 1; } for (int i = 1; i <= r; i++) { if (islucky(num[i] + n - r) && islucky(i + n - r)) res++; } printf("%d\n", res); return (0); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; void file_open() { freopen("test.txt", "rt", stdin); freopen("test.out", "wt", stdout); } bool check(unsigned long long x) { while (x) { if (x % 10 != 7 && x % 10 != 4) return false; x /= 10; } return true; } void swap(int &a, int &b) { int tmp = a; a = b; b = tmp; } int main() { unsigned long long gt[20] = {}, a[20]; queue<int> qu; qu.push(4); qu.push(7); unsigned long long n, k, t, dem, tmp, tmp2; cin >> n >> k; t = 1; gt[t] = 1; gt[0] = 1; while (gt[t] < k) { ++t; gt[t] = gt[t - 1] * t; } if (t > n) { printf("-1"); return 0; } for (int i = t; i >= 1; --i) a[i] = n - t + i; dem = 0; tmp = 4; tmp2 = 1; while (tmp <= n) { if (qu.empty()) break; tmp = qu.front(); if (tmp > n) break; qu.pop(); if (tmp * 10 + 4 <= n) qu.push(tmp * 10 + 4); if (tmp * 10 + 7 <= n) qu.push(tmp * 10 + 7); if (n - tmp >= t) ++dem; else { while (n - tmp < t) { --t; int i = tmp2; while (k > gt[t]) { k -= gt[t]; ++i; swap(a[i], a[tmp2]); } tmp2++; } if (check(a[tmp2 - 1])) ++dem; } } cout << dem; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution121C { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Solution121C().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ArrayList<Integer> happiens; int[] cur = {4,0,0,0,0,0,0,0,0}; boolean Generate(){ int c = 0; do{ if(cur[c] == 4){ cur[c] = 7; String s = ""; for(int i = 8; i >= 0; i--){ s += Integer.toString(cur[i]); } happiens.add(Integer.parseInt(s)); return true; } if(cur[c] == 0){ cur[c] = 4; String s = ""; for(int i = 8; i >= 0; i--){ s += Integer.toString(cur[i]); } happiens.add(Integer.parseInt(s)); return true; } cur[c] = 4; c++; if(c >= 9){ return false; } }while(true); } ArrayList<Long> perest; long[] p; void Generate(long k, long x, long fact, int i){ if(x == 0) return; p[i] = perest.get((int)(k * x / fact)); perest.remove(p[i]); long t = k % (fact / x); Generate(t, x-1, fact/x, i+1); } void solve() throws IOException{ happiens = new ArrayList<Integer>(); happiens.add(4); boolean c = true; do{ c = Generate(); }while(c); int n = readInt(); int k = readInt(); int x = 1; long fact = 1; while(fact < k){ x++; fact *= x; } int count = 0; int curHap = -1; for(int i = 0; i < happiens.size(); i++){ if(happiens.get(i) < n-x+1){ count++; curHap = i; } else break; } curHap++; if(x > n){ out.println(-1); return; } boolean checkHap = false; perest = new ArrayList<Long>(); for(long i = n-x+1; i <= n; i++){ if(curHap < happiens.size()) if(i == happiens.get(curHap)) checkHap = true; perest.add(i); } if(!checkHap){ out.println(count); return; } p = new long[x]; Generate(k - 1, x, fact, 0); for(int i = 0; i < p.length; i++){ checkHap = false; boolean check2 = false; for(long u: happiens){ if(p[i] == u) checkHap = true; if(n-x+1+i == u) check2 = true; } if(checkHap && check2){ count++; } } out.println(count); } int ModExp(int a, int n, int mod){ int res = 1; while (n!=0) if ((n & 1) != 0) { res = (res*a)%mod; --n; } else { a = (a*a)%mod; n >>= 1; } return res; } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; template <typename X> ostream& operator<<(ostream& x, const vector<X>& v) { for (long long i = 0; i < v.size(); ++i) x << v[i] << " "; return x; } template <typename X> ostream& operator<<(ostream& x, const set<X>& v) { for (auto it : v) x << it << " "; return x; } template <typename X, typename Y> ostream& operator<<(ostream& x, const pair<X, Y>& v) { x << v.ff << " " << v.ss; return x; } template <typename T, typename S> ostream& operator<<(ostream& os, const map<T, S>& v) { for (auto it : v) os << it.first << "=>" << it.second << endl; return os; } struct pair_hash { inline std::size_t operator()( const std::pair<long long, long long>& v) const { return v.first * 31 + v.second; } }; #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") long long fct[33]; bool chk(int n) { for (int i = n; i > 0; i /= 10) { if (i % 10 != 4 && i % 10 != 7) { return false; } } return true; } vector<long long> arr; int xp; void f(vector<long long> rr, int k, int i) { if (arr.size() == xp) { return; } int xx = (k + fct[i - 1] - 1) / fct[i - 1]; xx--; vector<long long> pp; arr.push_back(rr[xx]); for (long long j = 0; j < rr.size(); j++) { if (arr[arr.size() - 1] != rr[j]) { pp.push_back(rr[j]); } } sort(pp.begin(), pp.end()); f(pp, k - (xx * (fct[i - 1])), i - 1); } int main() { fct[0] = 1; long long i = 0; while (fct[i] < 1e13) { fct[i + 1] = (i + 1) * fct[i]; i++; } long long n, k; cin >> n >> k; if (n < i) { if (k > fct[n]) { cout << -1 << endl; return 0; } } i = 0; while (fct[i] <= k) { i++; } i--; if (k != fct[i]) { i++; } xp = i; vector<long long> rr; for (long long j = 0; j < i; j++) { rr.push_back(n - i + 1 + j); } f(rr, k, i); int ans = 0; for (long long j = 0; j < i; j++) { int xx = arr[j]; int poss = n - i + 1 + j; if (chk(poss) && chk(xx)) { ans++; } } vector<long long> xx; for (long long k = 1; k < 11; k++) { for (long long j = 0; j < (1 << k); j++) { string s; for (long long l = 0; l < k; l++) { if (j & (1 << l)) { s += '4'; } else { s += '7'; } } xx.push_back(stoll(s)); } } sort(xx.begin(), xx.end()); for (long long j = 0; j < xx.size(); j++) { if (chk(xx[j])) { if (xx[j] <= n - i) { ans++; } } } cout << ans << endl; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: serparamon * Date: 27.10.11 * Time: 18:39 * To change this template use File | Settings | File Templates. */ public class Contest20111027_C { private static Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in))); private static PrintWriter output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); private static int max = 19; private static boolean good (int x) { while (x>0) { if (x%10 != 4 && x%10 != 7) return false; x /= 10; } return true; } public static void main(String[] args) { int n = input.nextInt(); int k = input.nextInt(); long[] f = new long[max]; f[0] = 1; for (int i=1; i<max; i++) { f[i] = i*f[i-1]; } ArrayList<Long> s = new ArrayList<Long>(); for (int i=1; i<11; i++) { for (int j=0; j<(1<<i); j++) { long x = 0; for (int q=0; q<i; q++) { if ((j & (1<<q)) == 0) { x = 10*x + 4; } else { x = 10*x + 7; } } s.add(x); } } Collections.sort(s); if (n<max && k>f[n]) { output.println(-1); output.flush(); return; } int p = 0; while (k>f[p]) p++; int ans = 0; k--; boolean[] b = new boolean[p+1]; Arrays.fill(b, false); for (int i=1; i<=p; i++) { int q = (int)(k/f[p-i])+1; int x=0; for (int j=1; j<=p; j++) { if (!b[j]) q--; if (q==0) { b[j] = true; x = j+n-p; break; } } int pos = n-p+i; if (good(x) && good(pos)) { ans++; } k %= f[p-i]; } for (long x : s) { if (x <= n-p) ans++; } output.println(ans); output.flush(); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const double eps = 1e-9; long long perm[18]; set<long long> lu; void gen_luck(long long x) { if (x > 100000000000LL) return; lu.insert(x); gen_luck(x * 10LL + 4LL); gen_luck(x * 10LL + 7LL); } int sz; bool ud[21]; vector<int> res, val; void get_res(int x, int k) { if (x <= 0) return; for (int y = 0; y < sz; ++y) if (!ud[y]) { if (k > perm[x - 1]) k -= perm[x - 1]; else { res.push_back(y); ud[y] = true; get_res(x - 1, k); break; } } } bool luck(int x) { while (x > 0) { if ((x % 10 != 7) && (x % 10 != 4)) return false; x /= 10; } return true; } int main() { gen_luck(4LL); gen_luck(7LL); perm[0] = 1LL; for (int x = 1; x < 15; ++x) perm[x] = perm[x - 1] * x; int n, ans = 0; long long k; scanf("%d%I64d", &n, &k); if ((n < 14) && (perm[n] < k)) { printf("-1\n"); return 0; } sz = min(n, 13); get_res(sz, k); for (int x = n - sz; x < n; ++x) val.push_back(x + 1); for (int x = 0; x < sz; ++x) res[x] = val[res[x]]; k = n - sz; for (__typeof((res).begin()) it = (res).begin(); it != (res).end(); ++it) { if ((lu.count(*it)) && luck(k + 1)) ++ans; ++k; } k = *lu.lower_bound(n - sz + 1); for (__typeof((lu).begin()) it = (lu).begin(); it != (lu).end(); ++it) { if (*it == k) break; else ++ans; } printf("%d\n", ans); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; vector<int> lucky; void init() { lucky.push_back(0); for (size_t i = 0; i < lucky.size(); i++) { if (lucky[i] >= 100000000) break; lucky.push_back(lucky[i] * 10 + 4); lucky.push_back(lucky[i] * 10 + 7); } lucky.erase(lucky.begin()); } bool islucky(int x) { do if (x % 10 != 7 && x % 10 != 4) return false; while (x /= 10); return true; } int main() { init(); int n, m, len = 0, ans = 0; long long s = 1; scanf("%d%d", &n, &m); while (s < m) s *= ++len; if (n < len) return puts("-1") & 0; vector<int> u; for (int i = 1; i <= len; i++) u.push_back(n - len + i); for (int i = 1; i <= len; i++) { s /= len + 1 - i; int x = (m - 1) / s; if (islucky(n - len + i) && islucky(u[x])) ans++; u.erase(u.begin() + x); m -= x * s; } ans += upper_bound(lucky.begin(), lucky.end(), n - len) - lucky.begin(); printf("%d\n", ans); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long lucky[1024 * 4]; long long fact[14]; int cnt; void func(long long cur, int pos, int maxpos) { if (pos == maxpos) { lucky[++cnt] = cur * 10 + 4; lucky[++cnt] = cur * 10 + 7; return; } func(cur * 10 + 4, pos + 1, maxpos); func(cur * 10 + 7, pos + 1, maxpos); } void pre() { cnt = 0; for (int d = 1; d <= 10; d++) { func(0, 1, d); } sort(lucky, lucky + cnt); fact[0] = 1; for (int i = 1; i < 14; i++) fact[i] = i * fact[i - 1]; } long long n, k; void in() { cin >> n >> k; } int arr[14] = {0}; int brr[14] = {0}; void rec(int p, long long k, int coun) { if (coun == p) return; int b = (k + fact[p - 1 - coun] - 1) / fact[p - 1 - coun]; int c = 0; for (int i = 0; i < 14; i++) { if (brr[i] == 0) c++; if (b == c) { brr[i] = 1; arr[coun] = i; rec(p, k - fact[p - 1 - coun] * (b - 1), coun + 1); break; } } return; } bool luck(long long q) { for (int i = 0; i < cnt; i++) { if (lucky[i] == q) return true; if (lucky[i] > q) return false; } return false; } void solve() { int p = 0; while (fact[p] < k) p++; if (n < 14 && k > fact[n]) { cout << -1 << endl; return; } rec(p, k, 0); for (int i = 0; i < p; i++) { arr[i] += n - p + 1; } int ans = 1; while (lucky[ans] <= n - p) { ans++; } ans--; for (long long i = n - p + 1; i <= n; i++) { if (luck(i) && luck(arr[i - n - 1 + p])) ans++; } cout << ans << endl; } int main() { pre(); in(); solve(); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long n, k; long long F[15]; vector<long long> p; void dfs(long long c, long long mx) { if (c > mx) return; if (c) p.push_back(c); dfs(10 * c + 4, mx); dfs(10 * c + 7, mx); } int main() { F[0] = 1; for (int i = 1; i < 15; i++) F[i] = F[i - 1] * i; cin >> n >> k; if (n < 15 && F[n] < k) cout << -1 << endl; else { int m = min(n, 15LL); vector<long long> d; for (long long i = n - m + 1; i <= n; i++) d.push_back(i); vector<long long> pp; int K = --k; for (int i = 0; i < m; i++) { int t = 0; while (K >= F[m - i - 1]) { K -= F[m - i - 1]; t++; } pp.push_back(d[t]); d.erase(d.begin() + t); } long long r = 0; dfs(0, n); sort(p.begin(), p.end()); for (int i = 0; i < p.size(); i++) if (p[i] <= n - m) r++; for (int i = 1; i <= m; i++) { if (binary_search(p.begin(), p.end(), n - m + i) && binary_search(p.begin(), p.end(), pp[i - 1])) r++; } cout << r << endl; } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.*; public class Main { public static void main(String args[]) { (new Main()).solve(); } int solve(int n, int k) { int last = 1; long perm = 1; while( k > perm ) { ++last; perm *= last; } if( last > n ) { return - 1; } int ret = count(n - last); int ans[] = createKth(last, k - 1); for(int i=0; i<last; ++i) { int pos = i + n - last + 1; int val = ans[i] + n - last + 1; if( ok(pos) && ok(val) ) { ++ret; } } return ret; } int[] createKth(int digs, int k) { int ret[] = new int[digs]; for(int i=0; i<digs; ++i) { ret[i] = i; } int count = 0; long use = 1; while( count < digs - 1 ) { ++count; use *= count; } for(int i=0; i<digs-1; ++i) { int find = (int)(k / use); int set = ret[i + find]; for(int j=find; j>0; --j) { ret[i + j] = ret[i + j - 1]; } ret[i] = set; k = (int)(k % use); use /= count; --count; } return ret; } boolean ok(int n) { while( n > 0 ) { int k = n % 10; if( !(k == 4 || k == 7) ) { return false; } n /= 10; } return true; } int count(int n) { int ret = 0; for(int i=1; i<12; ++i) { int m = 1 << i; for(int j=0; j<m; ++j) { long cur = 0; long base = 1; for(int k=0; k<i; ++k) { if( (j & (1 << k)) == 0 ) { cur += base * 4; } else { cur += base * 7; } base *= 10; } if( cur <= n ) { ++ret; } } } return ret; } void solve() { Scanner cin = new Scanner(System.in); while( cin.hasNextInt() ) { int n = cin.nextInt(); int k = cin.nextInt(); System.out.println(solve(n, k)); } } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long k; int n; vector<long long> v; long long fact[15]; bool esta[20]; map<long long, bool> es; void go(long long num, int pos) { if (pos > 11) return; v.push_back(num); go(num * 10 + 4, pos + 1); go(num * 10 + 7, pos + 1); } vector<int> get_permutation(int n, long long k) { memset(esta, false, sizeof esta); vector<int> r; long long acu = 0; int cant = n - 1; for (int i = 0; i < n; i++) { acu = 0; for (int j = 0; j < n; j++) { if (esta[j]) continue; if (acu + fact[cant] >= k) { k -= acu; esta[j] = true; r.push_back(j); cant--; break; } acu += fact[cant]; } } return r; } int main() { go(4, 1); go(7, 1); sort((v).begin(), (v).end()); for (int i = 0; i < v.size(); i++) es[v[i]] = true; fact[0] = 1; fact[1] = 1; for (int i = 2; i < 15; i++) fact[i] = fact[i - 1] * i; cin >> n >> k; vector<int> vv; if (n > 13) { vv = get_permutation(13, k); int n2 = n - 13; int res = 0; for (int i = 0; i < v.size(); i++) if (v[i] > n2) break; else res++; int pos = n2 + 1; for (int i = 0; i < 13; i++) if (es[pos++] && es[vv[i] + n2 + 1]) res++; cout << res << endl; } else { if (fact[n] < k) { printf("-1\n"); return 0; } for (int i = 0; i < n; i++) vv.push_back(i); vv = get_permutation(n, k); for (int i = 0; i < n; i++) vv[i]++; int res = 0; for (int i = 0; i < n; i++) if (es[i + 1] && es[vv[i]]) res++; cout << res << endl; } }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int countbit(int n) { return (n == 0) ? 0 : (1 + countbit(n & (n - 1))); } int lowbit(int n) { return (n ^ (n - 1)) & n; } const double pi = acos(-1.0); const double eps = 1e-11; long long p[20]; int N, K; vector<int> path; vector<long long> lucky; int exist; void proc(vector<int> seq, int size, int kth) { if (size == 0 || exist == 0) return; vector<int> next; int r = kth / p[size - 1]; int m = kth % p[size - 1]; if (r >= size) { exist = 0; return; } path.push_back(seq[r]); for (int i = 0; i < size; ++i) if (i != r) next.push_back(seq[i]); proc(next, size - 1, m); } void get(long long n) { if (n) lucky.push_back(n); if (n < 1000000000) { get(n * 10 + 4); get(n * 10 + 7); } } bool isLucky(int n) { while (n) { if (n % 10 != 4 && n % 10 != 7) return false; n /= 10; } return true; } int main() { p[0] = 1; for (int i = 1; i <= 15; ++i) p[i] = i * p[i - 1]; cin >> N >> K; vector<int> seq; int size; if (N < 15) size = N; else size = 15; for (int i = 0; i < size; ++i) seq.push_back(N - i); sort(seq.begin(), seq.end()); K--; exist = 1; proc(seq, size, K); get(0); sort(lucky.begin(), lucky.end()); int ans = 0; if (N < 15) { for (int i = 0; i < path.size(); ++i) if (isLucky(i + 1) && isLucky(path[i])) ans++; } else { int index; for (int i = 0; i < lucky.size(); ++i) { if (lucky[i] > N - 15) { ans += i; break; } } for (int i = 0; i < path.size(); ++i) if (isLucky(i + N - 14) && isLucky(path[i])) ans++; } printf("%d\n", exist ? ans : -1); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int bound[15]; int n, k, ans; long long lucky[3000]; int num; void dfs(long long x, int pos) { long long c1 = x * 10ll + 4ll, c2 = x * 10ll + 7ll; if (pos <= 10) { lucky[num++] = c1; lucky[num++] = c2; dfs(c1, pos + 1); dfs(c2, pos + 1); } } int main() { lucky[num++] = 0; dfs(0, 1); sort(lucky, lucky + num); bound[0] = 0; bound[1] = 1; for (int i = 2; i <= 12; ++i) bound[i] = bound[i - 1] * i; ans = 0; scanf("%d%d", &n, &k); if (n <= 12 && k > bound[n]) puts("-1"); else { int st = (((1) > (n - 12)) ? (1) : (n - 12)); bool used[20]; memset(used, 0, sizeof(used)); ans = lower_bound(lucky, lucky + num, st) - lucky - 1; int c = 0; for (int i = (((12) < (n - 1)) ? (12) : (n - 1)); i >= 1; --i) { while (k > bound[i]) { ++c; k -= bound[i]; } int count = -1; for (int j = 0; j <= (((12) < (n)) ? (12) : (n)); ++j) { if (!used[j]) ++count; if (count == c) { used[j] = 1; int tmp = lower_bound(lucky, lucky + num, st + j) - lucky; int tmp2 = lower_bound(lucky, lucky + num, n - i) - lucky; if (lucky[tmp] == st + j && lucky[tmp2] == n - i) ++ans; break; } } c = 0; } for (int i = 0; i <= (((12) < (n)) ? (12) : (n)); ++i) { if (!used[i]) { int tmp = lower_bound(lucky, lucky + num, st + i) - lucky; int tmp2 = lower_bound(lucky, lucky + num, n) - lucky; if (lucky[tmp] == st + i && lucky[tmp2] == n) ++ans; break; } } printf("%d\n", ans); } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int MAX_N = 15 + 5; long long fact[MAX_N] = {1}; bool mark[MAX_N]; int a[MAX_N]; void Permutation(int k, int id) { if (id == 15) return; int x = (k - 1) / fact[14 - id]; k -= x * fact[14 - id]; for (int i = 0; i < 15; i++) { if (!mark[i] && x) x--; else if (!mark[i]) { a[id] = i, mark[i] = true; return Permutation(k, id + 1); } } } bool isLucky(int n) { return n ? (n % 10 == 4 || n % 10 == 7) && isLucky(n / 10) : true; } int countLucky(int n, long long num = 0) { return num <= n ? (num > 0) + countLucky(n, num * 10 + 4) + countLucky(n, num * 10 + 7) : 0; } int main() { ios_base ::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); int n, k; cin >> n >> k; for (int i = 1; i < MAX_N; i++) fact[i] = fact[i - 1] * i; if (n < MAX_N && k > fact[n]) return cout << "-1\n", 0; Permutation(k, 0); int tmp = n, ans = 0; for (int i = 0; i < 15; i++) if (a[i] != i) { tmp -= 15 - i; for (int j = i; j < 15; j++) ans += (isLucky(tmp + j - i + 1) && isLucky(tmp + a[j] - i + 1)); break; } cout << ans + countLucky(tmp) << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; std::vector<long long> v; long long c(long long i) { while (i) { if (i % 10 == 4 || i % 10 == 7) { } else return 0; i /= 10; } return 1; } long long MAXN = 1e10; int32_t main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.precision(10); std::vector<long long> fact = { 1ll, 1ll, 2ll, 6ll, 24ll, 120ll, 720ll, 5040ll, 40320ll, 362880ll, 3628800ll, 39916800ll, 479001600ll, 6227020800ll, 87178291200ll}; priority_queue<long long, std::vector<long long>, greater<long long> > pq; pq.push(4); pq.push(7); while (!pq.empty()) { long long o = pq.top(); pq.pop(); v.emplace_back(o); if (o * 10ll + 7ll <= MAXN) { pq.push(o * 10ll + 7ll); pq.push(o * 10ll + 4ll); } else if (o * 10ll + 4ll <= MAXN) { pq.push(o * 10ll + 4ll); } } long long n; cin >> n; long long k; cin >> k; if (n <= 13 && fact[n] < k) { cout << -1; exit(0); } long long rem = min(n, 13ll); std::vector<long long> vv; for (long long i = rem - 1; i >= 0; --i) { vv.emplace_back(n - i); } long long r = 0; for (long long vvv : v) if (vvv <= (n - rem)) r++; std::vector<long long> v1; while (rem) { long long y = 0; rem--; while (fact[rem] < k) { k -= fact[rem]; y++; } v1.emplace_back(vv[y]); vv.erase(vv.begin() + y); } rem = min(n, 13ll); for (long long i = 0; i < rem; ++i) { if (c(n - i) && c(v1[rem - i - 1])) { r++; } } cout << r; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class luckPerm { public static void debug(Object... obs) { System.out.println(Arrays.deepToString(obs)); } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); long n=sc.nextLong(); long k=sc.nextLong(); List<Long>q=new ArrayList<Long>(); int idx=0; long l=0; while(l <= n) { long l1=l*10 + 4; long l2=l*10 + 7; if(l1 > n) break; q.add(l1); if(l2 > n) break; q.add(l2); l = q.get(idx); idx++; } int cnt=0; //debug(q); if(n <= 13 && fac(n) < k) { System.out.println(-1); return; } //int[]mapit=new int[(int)n]; //for(int v=1;v<=n;v++) for(long v : q) { //debug(v,n,k); long id=pos(v,n,k); //debug(v,n,k,id); //mapit[(int)id-1]=v; if(isLucky(id)) cnt++; } //debug(mapit); System.out.println(cnt); } private static boolean isLucky(long id) { if(id == 0) return false; while(id > 0) { if(id%10!=4 && id%10!=7) { return false; } id/=10; } return true; } private static long pos(long v, long n, long k) { long res=0; //debug(v,n,k); if(n > 14) { long dif=Math.min(n-14, v-1); res+=dif; n-=dif; v-=dif; } if(n==1) { res+=1; return res; } if(v==1 && n > 14) { return res+=1; } // if(n==2 && v==2) // { // if(k%2==0) res+=2; // else res+=1; // return res; // } // if(n==2 && v==1) // { // if(k%2==0) res+=1; // else res+=2; // return res; // } //debug(v,n,k); long fc=fac(n-1); long nk = (k%fc==0)?fc:k%fc; if( k <= (v-1)*fc) { res+= 1 + pos(v-1,n-1,nk); } else if( k <= v*fc) { res+=1; } else if(k <= n*fc) { res+= 1 + pos(v,n-1,nk); } else { return -1; } return res; } static long fac(long a) { long res=1; for(long i=1;i<=a;i++) { res*=i; } return res; } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.ArrayList; import java.util.Scanner; public class C121 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if (n < 13) { if (k > fac(n)) { System.out.println(-1); return; } } int[]a = new int[14]; int m, ans = 0, add; if (n <= 13) { m = n; for (int i = 1; i <= m; i++) { a[i] = i; } add = 0; } else { m = 13; for (int i = 1; i <= 13; i++) { a[i] = n-13+i; } add = n-13; ans = num_lucly(n-13); } long[]fac = new long[m+1]; fac[0] = 1; ArrayList<Integer> remain = new ArrayList<Integer>(); for (int i = 1; i <= m; i++) { fac[i] = fac[i-1] * i; remain.add(i); } for (int i = 1; i <= m; i++) { int t = (int) (k / fac[m-i]); if (k % fac[m-i] != 0) t++; int ind = (t-1) % (m-i+1); int temp = remain.get(ind); remain.remove(ind); if (luckly(a[temp]) && luckly(i+add)) ans++; } System.out.println(ans); } private static boolean luckly(int k) { String s = k+""; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != '4' && s.charAt(i) != '7') return false; } return true; } private static int num_lucly(int k) { int res = 0, L; String s; int lucly; for (int i = 1; i <= 9; i++) { if (i <= (k+"").length()) { for (int j = 0; j < (1 << i); j++) { s = Integer.toBinaryString(j); L = s.length(); for (int j2 = 1; j2 <= i-L; j2++) { s = "0"+s; } lucly = 0; for (int j2 = 0; j2 < i; j2++) { lucly *= 10; if (s.charAt(j2)=='0') lucly += 4; else lucly += 7; } if (lucly <= k) res++; } } } return res; } private static long fac(int n) { if (n < 2) return 1; return n * fac(n-1); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.lang.*; import java.awt.geom.Line2D; import java.io.*; import java.util.*; import java.math.*; public class C implements Runnable{ ArrayList<Integer> ns; HashSet<Integer> h; private void rec(long cur, int max) { if (cur >= max) { return; } if (cur > 0) { ns.add((int)cur); h.add((int)cur); } rec(cur*10+4, max); rec(cur*10+7, max); } public void run() { int n = nextInt(); int k = nextInt(); ns = new ArrayList<Integer>(); h = new HashSet<Integer>(); rec(0, n+1); long fc = 1; int fck = 1; while (fc < k) { ++fck; fc *= fck; } if (fck > n) { out.println(-1); } else { int[] perm = new int[fck]; ArrayList<Integer> nums = new ArrayList<Integer>(); for (int i = 1; i <= fck; ++i) { nums.add(i); } int kk = k-1; fc /= fck; for (int i = 0; i < fck; ++i) { int idx = (int)(kk/fc); perm[i] = nums.get(idx); nums.remove(idx); kk %= fc; if (fck-i-1 != 0) { fc /= (fck-i-1); } } for (int i = 0; i < fck; ++i) { perm[i] += (n-fck); } int ans = 0; for (int i = 0; i < ns.size(); ++i) { if (ns.get(i) < n-fck+1) { ++ans; } } for (int i = 0; i < fck; ++i) { // System.err.println((i+n-fck+1) + " " + perm[i]); if (h.contains(i+n-fck+1) && h.contains(perm[i])) { ++ans; } } out.println(ans); } out.flush(); } private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new Thread(new C())).start(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } private Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } private Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } private String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } private Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 11; const long long MOD = 1e18; long long n, k; int ans = 0; vector<long long> vv; bool good(long long c) { while (c > 0) { if (c % 10 == 4 || c % 10 == 7) { } else return false; c /= 10; } return true; } void dfs(long long l) { if (l > n) return; if (l >= 1) { if (l < n - 15ll) { ans++; } else { long long pos = l - max(1ll, (n - 15)); if (good(vv[pos])) ans++; } } dfs(l * 10ll + 4ll); dfs(l * 10ll + 7ll); } long long kol_perm(long long x) { long long k = 1; for (long long i = 1; i <= x; i++) k *= i; return k; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> k; if (n <= 15 && kol_perm(n) < k) { cout << "-1" << endl; return 0; } vector<long long> v, dd; for (int i = max(1ll, n - 15ll); i <= n; i++) v.push_back(i); int t = min(16ll, n); for (int i = 1; i <= t; i++) { int c = 0; for (long long j = 0; j < v.size(); j++) if (kol_perm(t - i) * (j + 1) >= k) { vv.push_back(v[j]); c = j; k -= kol_perm(t - i) * j; break; } dd.clear(); for (int j = 0; j < c; j++) dd.push_back(v[j]); for (int j = c + 1; j < v.size(); j++) dd.push_back(v[j]); v = dd; } dfs(0); cout << ans << endl; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.io.*; import java.util.*; import java.math.*; //created at 7:48 PM 10/27/11 by Abrackadabra public class C { int IOMode = 0; //0 - consoleIO, 1 - <taskName>.in/out, 2 - input.txt/output.txt, 3 - test case generator String taskName = ""; int l, n; int[] a; long[] f; void solve() throws IOException { n = nextInt(); int k = nextInt() - 1; l = 100; a = new int[l + 1]; f = new long[l + 1]; for (int i = l; i >= 0; i--) { a[i] = n - l + i; } long fac = 1; int s = -1; for (int i = l; i >= 0; i--) { fac *= (long)l - i + 1; f[i] = fac; if (fac > k) { s = i; if (a[s] <= 0) { out.println(-1); return; } break; } } rotate(s, k); TreeSet<Long> g = new TreeSet<Long>(); g.add((long)4); g.add((long)7); for (int i = 2; i < 12; i++) { TreeSet<Long> g1 = new TreeSet<Long>(); for (Long t : g) { g1.add(t); g1.add(t * 10 + 4); g1.add(t * 10 + 7); } g = g1; } int r = 0; for (Long t : g) { if (t > n) break; long p = l - n + t; if (p < 0 || a[(int)p] <= 0) { r++; } else { if (g.contains((long)a[(int)p])) r++; } } out.println(r); } void rotate(int s, int k) { if (s > l || k <= 0) return; int p = 0; while (k >= f[s + 1]) { k -= f[s + 1]; p++; } for (int i = s + 1; i < l + 1; i++) if (i - s == p) { int t = a[s]; a[s] = a[i]; a[i] = t; break; } Arrays.sort(a, s + 1, l + 1); rotate(s + 1, k); } public static void main(String[] args) throws IOException { if (args.length > 0 && args[0].equals("Abra")) debugMode = true; new C().run(); } long startTime = System.nanoTime(), tempTime = startTime, finishTime = startTime; long startMem = Runtime.getRuntime().totalMemory(), finishMem = startMem; void run() throws IOException { init(); if (debugMode) { con.println("Start"); con.println("Console output:"); } solve(); finishTime = System.nanoTime(); finishMem = Runtime.getRuntime().totalMemory(); out.flush(); if (debugMode) { int maxSymbols = 1000, c = 0; BufferedReader tbr = new BufferedReader(new FileReader("input.txt")); char[] a = new char[maxSymbols]; tbr.read(a); if (a[0] != 0) { con.println(); con.println("File input:"); con.print(a); } boolean left = true; for (int i = 0; i < maxSymbols; i++) left = left && a[i] != 0; if (left) con.println("..."); else con.println(); tbr = new BufferedReader(new FileReader("output.txt")); a = new char[maxSymbols]; tbr.read(a); if (a[0] != 0) { con.println(); con.println("File output:"); con.print(a); } left = true; for (int i = 0; i < maxSymbols; i++) left = left && a[i] != 0; if (left) con.println("..."); else con.println(); con.println("Time passed: " + (finishTime - startTime) / 1000000000.0 + " sec"); con.println("Memory used: " + (finishMem - startMem) + " bytes"); con.println("Total memory: " + Runtime.getRuntime().totalMemory() + " bytes"); } } boolean tick(double x) { if (System.nanoTime() - tempTime > x) { tempTime = System.nanoTime(); con.println("Tick at " + (tempTime - startTime) / 1000000000 + " sec"); con.print(" "); return true; } return false; } void printTime() { con.println((System.nanoTime() - tempTime) + " nanos passed"); tempTime = System.nanoTime(); } static boolean debugMode = false; PrintStream con = System.out; void init() throws IOException { if (debugMode) { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } else switch (IOMode) { case 0: br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); break; case 1: br = new BufferedReader(new FileReader(taskName + ".in")); out = new PrintWriter(new FileWriter(taskName + ".out")); break; case 2: br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); break; case 3: out = new PrintWriter(new FileWriter("input.txt")); break; } } BufferedReader br; PrintWriter out; StringTokenizer in; boolean hasMoreTokens() throws IOException { while (in == null || !in.hasMoreTokens()) { String line = br.readLine(); if (line == null) return false; in = new StringTokenizer(line); } return true; } String nextString() throws IOException { return hasMoreTokens() ? in.nextToken() : null; } int nextInt() throws IOException { return Integer.parseInt(nextString()); } long nextLong() throws IOException { return Long.parseLong(nextString()); } double nextDouble() throws IOException { return Double.parseDouble(nextString()); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long Fact[20]; vector<int> v; vector<int> nthPerm(vector<int>& identity, int nth) { vector<int> perm(identity.size()); int len = identity.size(); for (int i = identity.size() - 1; i >= 0; i--) { int p = nth / Fact[i]; perm[len - 1 - i] = identity[p]; identity.erase(identity.begin() + p); nth %= Fact[i]; } return perm; } set<long long> lucky; void f(long long x) { if (x > 1e9) return; if (x) lucky.insert(x); f(x * 10 + 4); f(x * 10 + 7); } int main() { Fact[0] = Fact[1] = 1; for (int i = 2; i < 20; i++) Fact[i] = Fact[i - 1] * i; int n, k; cin >> n >> k; if (n <= 13 && Fact[n] < k) { cout << -1 << endl; return 0; } int r = n, l = max(1, n - 13); for (int i = l; i <= r; i++) v.push_back(i); k--; vector<int> perm = nthPerm(v, k); f(0); int ans = 0; for (int i = 0; i < perm.size(); i++) { int idx = i + l; if (lucky.find(idx) != lucky.end() && lucky.find(perm[i]) != lucky.end()) ans++; } for (auto it = lucky.begin(); *it < l; it++) { ans++; } cout << ans << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> bool DEBUG = false; using namespace std; int val[5000]; int l, cur, n, k, result; int sel[15], sl, perm[15]; bool used[15]; int fact[13], os; int main() { l = 0; val[l++] = 4; val[l++] = 7; cur = 0; while (l < 1000) { int tmp = l; for (int i = (cur); i < (tmp); ++i) { val[l++] = val[i] * 10 + 4; val[l++] = val[i] * 10 + 7; } cur = tmp; } scanf("%d%d", &n, &k); result = 0; for (int i = 0; i < (l); ++i) if (val[i] < n - 12) result++; fact[0] = 1; for (int i = (1); i < (13); ++i) fact[i] = i * fact[i - 1]; if (n > 13) os = n - 12; else os = 1; sl = 0; for (int i = (os); i <= (n); ++i) sel[sl++] = i; if (DEBUG) { cout << "sel" << ": "; for (int innercounter = 0; innercounter < (sl); ++innercounter) cout << sel[innercounter] << " "; cout << endl; }; if (sl < 13 && k > fact[sl]) { puts("-1"); return 0; } memset(used, 0, sizeof(used)); for (int i = 0; i < (sl); ++i) { int shft = (k - 1) / fact[sl - i - 1]; if (DEBUG) { cout << "shft" << ": " << (shft) << endl; }; cur = 0; for (int j = 0; j < (sl); ++j) if (!used[j]) { if (DEBUG) { cout << "sel[j]" << ": " << (sel[j]) << endl; }; if (cur < shft) cur++; else { perm[i] = sel[j]; used[j] = true; break; } } k -= shft * fact[sl - i - 1]; } if (DEBUG) { cout << "perm" << ": "; for (int innercounter = 0; innercounter < (sl); ++innercounter) cout << perm[innercounter] << " "; cout << endl; }; set<int> vals; for (int i = 0; i < (l); ++i) vals.insert(val[i]); if (DEBUG) { cout << "os" << ": " << (os) << endl; }; if (DEBUG) { cout << "n" << ": " << (n) << endl; }; if (DEBUG) { cout << "l" << ": " << (l) << endl; }; for (int i = 0; i < (l); ++i) { if (val[i] >= os && val[i] <= n) { if (DEBUG) { cout << "val[i]" << ": " << (val[i]) << endl; }; if (vals.find(perm[val[i] - os]) != vals.end()) result++; } } cout << result; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const double eps = 1e-11; const int inf = 0x7FFFFFFF; template <class T> inline void checkmin(T &a, T b) { if (b < a) a = b; } template <class T> inline void checkmax(T &a, T b) { if (b > a) a = b; } template <class T> inline T sqr(T x) { return x * x; } template <class T> void show(T a, int n) { for (int i = 0; i < n; ++i) cout << a[i] << ' '; cout << endl; } template <class T> void show(T a, int r, int l) { for (int i = 0; i < r; ++i) show(a[i], l); cout << endl; } long long lk[100007], cnt, M = 1e11, ten[15], ni[15]; void init(long long i) { if (i && i <= M) lk[cnt++] = i; if (i <= M) { init(i * 10 + 4); init(i * 10 + 7); } } bool lucky(long long a) { if (a == 0) return false; while (a) { if (!(a % 10 == 4 || a % 10 == 7)) return false; a /= 10; } return true; } void ntoP(long long n, long long t) { for (int i = n - 1; i >= 0; i--) ni[i] = t % (n - i), t /= (n - i); for (int i = n - 1; i != 0; i--) for (int j = i - 1; j >= 0; j--) if (ni[j] <= ni[i]) ni[i]++; } int main() { init(0); sort(lk, lk + cnt); ten[0] = 1; for (int i = 1; i < 15; i++) ten[i] = ten[i - 1] * i; long long n, k; while (cin >> n >> k) { int mx = 1; while (ten[mx] < k) mx++; if (mx > n) { cout << -1 << endl; continue; } long long bas = n - mx, sum = 0; ntoP(mx, k - 1); for (int j = 1; j <= mx; j++) { if (lucky(bas + j) && lucky(ni[j - 1] + bas + 1)) sum++; } for (int i = 0; i < cnt; i++) if (lk[i] <= bas) sum++; else break; cout << sum << endl; } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; template <class T> T _abs(T n) { return (n < 0 ? -n : n); } template <class T> T _max(T a, T b) { return (!(a < b) ? a : b); } template <class T> T _min(T a, T b) { return (a < b ? a : b); } template <class T> T sq(T x) { return x * x; } const double EPS = 1e-9; const int INF = 0x7f7f7f7f; bool isL(int d) { while (d) { if (d % 10 != 4 && d % 10 != 7) return false; d /= 10; } return true; } long long fc[16]; int pr[100100]; void kFact(int k, int p, set<int> &d) { if (p < 0) return; for (auto a : d) { if (fc[p] <= k) k -= fc[p]; else { pr[p] = a; d.erase(a); return kFact(k, p - 1, d); } } } int main() { set<int> d; int i, j, n, k; cin >> n >> k; fc[0] = 1; for (i = 1; i <= 13; i++) fc[i] = i * fc[i - 1]; if (n <= 13 && k > fc[n]) { puts("-1"); return 0; } for (i = n, j = 13; i && j; i--, j--) { d.insert(i); } int st = i, l = d.size(); ; kFact(k - 1, l - 1, d); int r = 0; for (i = 1; i <= l; i++) if (isL(st + i) && isL(pr[l - i])) r++; vector<int> v; if (st >= 4) v.push_back(4); if (st >= 7) v.push_back(7); long long t; for (i = 0; i < v.size(); i++) { t = v[i]; t *= 10; if (t + 4 <= st) v.push_back(t + 4); if (t + 7 <= st) v.push_back(t + 7); } r += v.size(); cout << r << '\n'; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int maxn = 20 + 5, mod = 1e9 + 7, inf = 0x3f3f3f3f; double eps = 1e-8; template <class T> T QuickMod(T a, T b, T c) { T ans = 1; while (b) { if (b & 1) ans = ans * a % c; b >>= 1; a = (a * a) % c; } return ans; } template <class T> T Gcd(T a, T b) { return b != 0 ? Gcd(b, a % b) : a; } template <class T> T Lcm(T a, T b) { return a / Gcd(a, b) * b; } template <class T> void outln(T x) { cout << x << endl; } long long fact[maxn] = {1}; int ans, n, k, p[maxn]; long long a[100000], c; void CantorR(int index, int n) { bool vis[maxn]; memset(vis, false, sizeof vis); index--; for (int i = 0; i < n; i++) { int t = index / fact[n - i - 1]; for (int j = 0; j <= t; j++) if (vis[j]) t++; p[i] = t + 1; vis[t] = true; index %= fact[n - i - 1]; } } void dfs(long long num) { if (num > 1e10) return; a[c++] = num; dfs(num * 10 + 4); dfs(num * 10 + 7); } int main() { for (int i = 1; fact[i - 1] <= mod; i++) fact[i] = fact[i - 1] * i; scanf("%d%d", &n, &k); if (n <= 12 && k > fact[n]) puts("-1"); else { int pos = 13; for (int i = 1; i <= 12; i++) { if (k < fact[i]) { pos = i; break; } } CantorR(k, pos); int rest = n - pos; dfs(0); sort(a, a + c); for (int i = 1; i < c && a[i] <= n; i++) { if (a[i] <= rest) ans++; else { int num = p[a[i] - rest - 1] + rest; for (int j = 1; j < c && a[j] <= n; j++) { if (a[j] == num) { ans++; break; } } } } printf("%d\n", ans); } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; inline void OPEN(const string &file_name) { freopen((file_name + ".in").c_str(), "r", stdin); freopen((file_name + ".out").c_str(), "w", stdout); } long long fact[50]; inline void initfact() { fact[0] = 1; for (int i = (1), _b = (49); i <= _b; i++) fact[i] = fact[i - 1] * i; } vector<long long> lucky; inline void generate() { for (int i = (1), _b = (10); i <= _b; i++) { for (int b = 0, _n = (1 << i); b < _n; b++) { long long tmp = 0; for (int j = 0, _n = (i); j < _n; j++) { tmp *= 10; if (b & (1 << j)) tmp += 4; else tmp += 7; } lucky.push_back(tmp); } } sort((lucky).begin(), (lucky).end()); } int ret = 0; vector<int> v, permut; char s[100]; int n, k; inline bool islucky(int x) { sprintf(s, "%d", x); for (int i = 0; s[i]; i++) { if (s[i] != '4' && s[i] != '7') return false; } return true; } inline void get_kth(int x) { for (int i = (n - x + 1), _b = (n); i <= _b; i++) { v.push_back(i); } for (int i = (1), _b = (x); i <= _b; i++) { long long cnt = 0; for (int j = 0, _n = (x - i + 1); j < _n; j++) { cnt += fact[x - i]; if (cnt >= k) { permut.push_back(v[j]); v.erase(v.begin() + j); cnt -= fact[x - i]; k -= cnt; break; } } } int j = 0; for (int i = (n - x + 1), _b = (n); i <= _b; i++) { if (islucky(i) && islucky(permut[j])) { ret++; } j++; } } int main() { initfact(); cin >> n >> k; generate(); int x = 0; for (; fact[x] < k; x++) ; if (x > n) { puts("-1"); return 0; } ret = 0; for (int i = 0, _n = ((lucky).size()); i < _n; i++) { if (lucky[i] <= n - x) ret++; } get_kth(x); cout << ret << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int N; long long K; long long F[12]; vector<long long> S; void DFS(int a) { if (a > 10) { long long res = 0, flag = 0; for (int i = 1; i <= 10; i++) { if (F[i] == 0) { if (flag) return; } else if (F[i] == 1) { res = res * 10 + 4; flag = 1; } else res = res * 10 + 7, flag = 1; } S.push_back(res); return; } F[a] = 0; DFS(a + 1); F[a] = 1; DFS(a + 1); F[a] = 2; DFS(a + 1); } int C[200], A[200]; long long P[200]; int check(int a) { while (a > 0) { if (a % 10 != 7 && a % 10 != 4) return 0; a /= 10; } return 1; } int main() { DFS(1); scanf("%d%lld", &N, &K); long long pow = 1; bool flag = 0; for (int i = 1; i <= N; i++) if (pow * i >= K) { flag = 1; break; } else pow *= i; if (!flag) { puts("-1"); return 0; } P[1] = P[0] = 1; for (int i = 2; P[i - 1] < 10000000000LL; i++) P[i] = P[i - 1] * (long long)i; pow = 1; int start; for (int i = 1; i <= N; i++) { if (pow * (long long)i >= K) { start = N - i + 1; break; } pow *= (long long)i; } int nn = N - start + 1; for (int i = 1; i <= nn; i++) { for (int j = nn; j >= 1; j--) if (!C[j]) { int x = 0; for (int k = 1; k < j; k++) if (!C[k]) x++; if (x * P[nn - i] < K) { C[j] = 1; A[i] = j; K -= (long long)x * P[nn - i]; break; } } } for (int i = 1; i <= nn; i++) if (!C[i]) A[nn] = i; for (int i = 1; i <= nn; i++) A[i] += start - 1; sort(S.begin(), S.end()); int cnt = 0; for (int i = 1; i < S.size(); i++) { if (start <= S[i]) break; cnt++; } for (int i = 1; i <= nn; i++) { if (check(A[i]) && check(start + i - 1)) cnt++; } printf("%d\n", cnt); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class HappyPermutation implements Runnable { private void solve() throws IOException { List<Long> happy = new ArrayList<Long>(); for (int len = 1; len <= 10; ++len) { for (int mask = 0; mask < (1 << len); ++mask) { long num = 0; for (int i = 0; i < len; ++i) if ((mask & (1 << i)) != 0) num = num * 10 + 4; else num = num * 10 + 7; happy.add(num); } } Collections.sort(happy); long[] fact = new long[20]; fact[0] = 1; for (int i = 1; i < 20; ++i) { fact[i] = i * fact[i - 1]; } long n = nextLong(); long k = nextLong() - 1; if (n < 20 && (k >= fact[(int) n])) { writer.println(-1); return; } long start = 1; long res = 0; List<Long> remaining = new ArrayList<Long>(); if (n > 20) { start = n - 19; res += lowerBound(happy, start); } for (long pos = start; pos <= n; ++pos) { remaining.add(pos); } for (long pos = start; pos <= n; ++pos) { long remFact = fact[(int) (n - pos)]; int index = (int) (k / remFact); k -= index * remFact; long what = remaining.get(index); if (isHappy(happy, pos) && isHappy(happy, what)) { ++res; } remaining.remove(index); } writer.println(res); } private boolean isHappy(List<Long> happy, long what) { return happy.get(lowerBound(happy, what)) == what; } int lowerBound(List<Long> happy, long what) { int left = -1; int right = happy.size(); while (right - left > 1) { int middle = (left + right)/ 2; if (happy.get(middle) < what) left = middle; else right = middle; } return right; } public static void main(String[] args) { new HappyPermutation().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import math def good(x): while x > 0: if x % 10 != 4 and x % 10 != 7: return False x //=10 return True n, k = map(int, input().split()) l = 1 r = n if n >= 15: l = n-14 if n <= 15 and math.factorial(n) < k: print(-1) else: L = r - l + 1 a = [] for i in range(L): a.append(i) b = [] k -= 1 for i in range(L): x = k//math.factorial(L-i-1) y = a[x] b.append(y+l) a.remove(y) k -= x * math.factorial(L-i-1) c = [] if 4 < l: c.append(4) if 7 < l: c.append(7) ans = 0 while len(c) > 0: ans += len(c) cc = [] for x in c: if x * 10 + 4 < l: cc.append(x * 10 + 4) if x * 10 + 7 < l: cc.append(x * 10 + 7) c = cc for i in range(L): if good(i+l) and good(b[i]): ans += 1 print(ans)
PYTHON3
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int p[11]; bool used[15]; long long f[15]; vector<int> g; bool is_good(long long x) { if (x < 4) return false; while (x > 0) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } int main() { int n, ans = 0; long long k; cin >> n >> k; f[1] = f[0] = 1; for (long long i = 2; i < 15; ++i) f[i] = i * f[i - 1]; if (n < 14 && k > f[n]) { cout << -1; return 0; } while (true) { int j = 0; p[j]++; while (p[j] > 2) { p[j] = 0; p[++j]++; } if (p[9] != 0) break; bool good = true; int cur = 0, mul = 1, cnt = 0; for (int i = 0; i < 9; ++i) { if (p[i] != 0) { cur += mul * (p[i] == 1 ? 4 : 7); if (!good) cnt++; } else good = false; mul *= 10; } if (cnt == 0 && cur > 0 && cur <= n - 14) ans++; } int len = (n >= 14 ? 14 : n); vector<int> perm(len); for (int i = 0; i < len; ++i) { int dig = -1; for (int j = 0; j < len && dig == -1; ++j) if (!used[j]) { if (k > f[len - i - 1]) k -= f[len - i - 1]; else { dig = j; used[j] = true; } } perm[i] = max(dig, 0) + (n - len) + 1; } for (int i = 0; i < perm.size(); ++i) if (is_good(perm[i]) && is_good(i + (n - len) + 1)) ans++; cout << ans; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { BufferedReader in; StringTokenizer st; PrintWriter out; static ArrayList<Long> list = new ArrayList<Long>(); static void gen(long a, int len) { // if (a != 0) list.add(a); if (len >= 10) return; gen(a * 10 + 4, len + 1); gen(a * 10 + 7, len + 1); } static { gen(0, 0); Collections.sort(list); } long sol(long a, long b) { long ret = 0; for (int i = 0; i < list.size(); ++i) { long q = list.get(i); if (a <= q && q <= b) ++ret; } return ret; } int n, k; int calc() { long a = 1L; if ((long) k <= a) return 1; for (long i = 2;; ++i) { a *= i; if ((long) k <= a) return (int) i; } } boolean check(int n) { if (n == 0) return false; while (n > 0) { int a = n % 10; if (a == 4 || a == 7) ; else return false; n /= 10; } return true; } long fact(int n) { long ret = 1; for (int i = 2; i <= n; ++i) ret *= (long) i; return ret; } int[] v; boolean[] was; int get(int idx) { int cnt = 0; for (int i = 0; i < v.length; ++i) { if (was[i] == false) { ++cnt; if (cnt == idx) { return i; } } } return -1; } void solve() throws IOException { n = ni(); k = ni(); int a = calc(); if (a > n) { out.println(-1); return; } long ret = sol(1, n - a); v = new int[a]; was = new boolean[a]; for (int i = n, j = 0; j < a; ++j, --i) v[j] = i; Arrays.sort(v); for (int i = 1, pp = n - a + 1; i <= a; ++i, ++pp) { long f = fact(a - i); int position = 1; long qwe = f; while (qwe < k) { ++position; qwe += f; } k -= (qwe - f); int pos = get(position); was[pos] = true; // System.err.println(v[pos]); if (check(pp) && check(v[pos])) ++ret; } out.println(ret); } public Main() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Main(); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int N = 14; vector<int64_t> fact(N, 1); vector<int64_t> happies; vector<int> k_perm(int64_t n, int64_t k) { --k; vector<int> a(n); vector<bool> used(n + 1); for (int i = 0; i < n; ++i) { int64_t alreadyWas = k / fact[n - i - 1]; k %= fact[n - i - 1]; int64_t curFree = 0; for (int j = 1; j <= n; ++j) { if (!used[j]) { ++curFree; if (curFree == alreadyWas + 1) { a[i] = j; used[j] = true; break; } } } } return a; } bool is_happy(int64_t x) { while (x > 0) { int64_t c = x % 10; if (c != 4 && c != 7) return false; x /= 10; } return true; } int first_i(int64_t k) { for (int i = 0; i < N; ++i) { if (k <= fact[i]) { return i; } } return 0; } int main() { ios_base::sync_with_stdio(false); int64_t n, k; cin >> n >> k; for (int i = 2; i < N; ++i) { fact[i] = i * fact[i - 1]; } if (n < N && k > fact[n]) { cout << -1; return 0; } for (int i = 1; i <= 9; ++i) { int64_t jn = 1 << i; for (int j = 0; j < jn; ++j) { int64_t j2 = j, x = 0; j2 = j; while (j2 > 0) { if (j2 & 1) x = x * 10 + 7; else x = x * 10 + 4; j2 >>= 1; } j2 = jn; while (j2 > j) { x = x * 10 + 4; j2 >>= 1; } x /= 10; int64_t x1 = 0; while (x > 0) { x1 = x1 * 10 + x % 10; x /= 10; } happies.push_back(x1); } } int64_t hc = happies.size(); int64_t n1 = n - first_i(k); int64_t ans = 0; for (int i = 0; i < hc; ++i) { if (happies[i] > n1) { ans = i; break; } } if (n1 >= happies.back()) { ans = hc; } vector<int> a = k_perm(n - n1, k % fact[n - n1]); int64_t n2 = a.size(); for (int i = 0; i < n2; ++i) { int64_t ai = a[i] + n1, i1 = i + n1 + 1; if (is_happy(ai) && is_happy(i1)) { ++ans; } } cout << ans; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.*; public class EPerm { static int[] factorial = {-1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600}; static long[] luckyNums = new long[1024]; static HashSet<Long> theNums = new HashSet<Long>(5000); static int[] luckyList = {4, 7}; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int fact = getFact(k); int[] lastPart = new int[fact]; for(int i = 0; i < lastPart.length; ++i) { lastPart[i] = n - fact + i + 1; } makeLucky(); --k; if(fact > n) System.out.println("-1"); else { int index = 0; while(k > 0 && fact > 1) { --fact; int multiple = k/(factorial[fact]); if(multiple == fact + 1) --multiple; k -= multiple*factorial[fact]; int temp = lastPart[multiple+index]; lastPart[multiple+index] = lastPart[index]; lastPart[index] = temp; ++index; Arrays.sort(lastPart, index, lastPart.length); } int total = 0; int save = n - lastPart.length; total += getCount(save); //inclusive //System.out.println("Total is now " + total); //then iterate through the array lastPart to check if anything is a lucky num match for(int i = 0; i < lastPart.length; ++i) { //check if both i + (n - lastPart.length) and lastPart[i + ..] are luckyNums //System.out.printf("Checking %d and %d\n", i + save+1, lastPart[i]); if( theNums.contains((long)(i + save+1)) && theNums.contains((long)lastPart[i]) ) ++total; } System.out.println(total); } } public static int getCount(int n) { int ret = Arrays.binarySearch(luckyNums, n); if(ret < 0) ret = -ret - 2; return ret; } public static int getFact(int k) { int ret = Arrays.binarySearch(factorial, k); if(ret < 0) ret = -ret-1; return ret; } public static void makeLucky() { int prevStart = 0, prevEnd = 0; int curIndex = 1; for(int len = 1; len <= 9; ++len) { for(int i = prevStart; i <= prevEnd; ++i) { for(int poss: luckyList) { luckyNums[curIndex] = luckyNums[i]*10 + poss; theNums.add(luckyNums[curIndex]); ++curIndex; } } prevStart = prevEnd + 1; prevEnd = curIndex - 1; } luckyNums[1023] = 4444444444L; theNums.add(luckyNums[1023]); } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long n, k; vector<long long> perm; bool used[20]; string hf = "4"; int ans; bool ish(long long q) { while (q > 0) { if (q % 10 != 4 && q % 10 != 7) return false; q /= 10; } return true; } long long ltoa() { long long ten = 1; long long ta = 0; for (int i = hf.length() - 1; i >= 0; i--) { ta += ten * (hf[i] - '0'); ten *= 10; } return ta; } void np() { bool ch = false; for (int i = hf.length() - 1; i >= 0; i--) { if (hf[i] == '4') { hf[i] = '7'; ch = true; break; } else { hf[i] = '4'; } } if (!ch) hf.insert(0, 1, '4'); } int main() { long long real = 1, qup = 1; cin >> n >> k; k--; for (; qup <= k; real++) qup *= real; real--; if (real > n) { cout << -1; return 0; } if (k > 0) qup /= real; int mod = n - real; while (ltoa() <= mod) { ans++; np(); } for (long long i = real - 1; i >= 1; i--) { int u = k / qup; for (int i = 0; i < 20; i++) { if (!used[i]) { u--; if (u < 0) { used[i] = true; perm.push_back(i + mod); break; } } } k %= qup; qup /= i; } for (int i = 0; i < 20; i++) if (!used[i]) { perm.push_back(i + mod); break; } for (int i = 0; i < perm.size(); i++) { if (ish(i + mod + 1) && ish(perm[i] + 1)) ans++; } cout << ans; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; map<long long, int> lucky; void func(long long num) { if (num > 1000000007) return; if (num > 0) { lucky[num] = 1; } func(num * 10 + 4); func(num * 10 + 7); } int main() { func(0); vector<long long> fact(21); fact[0] = 1; for (int i = 1; i < 21; i++) { fact[i] = fact[i - 1] * i; } int n; long long k; cin >> n >> k; if (n <= 20 && fact[n] < k) { cout << -1; return 0; } int ans = 0; for (auto g : lucky) { if (g.first < n - 20) ans++; } map<int, bool> vis; for (int i = max(n - 20, 1); i <= n; i++) { if (fact[n - i] < k) { long long val = 0; for (int j = max(n - 20, 1); j <= n; j++) { if (!vis[j]) { val += fact[n - i]; if (val >= k) { ans += (lucky[i] == true && lucky[j] == true); vis[j] = true; k -= (val - fact[n - i]); break; } } } } else { for (int j = max(n - 20, 1); j <= n; j++) { if (!vis[j]) { ans += (lucky[i] == true && lucky[j] == true); vis[j] = true; break; } } } } cout << ans; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long fac[1000000]; long long recursive(long long zxcv, long long hi) { if (zxcv >= hi) return 0; return 1 + recursive(zxcv * 10 + 4, hi) + recursive(zxcv * 10 + 7, hi); } int main() { long long n, k; cin >> n >> k; long long d = 1; fac[0] = 1; for (long long i = 1; i <= n; i++) { d *= i; if (d >= k) break; } if (d < k) { cout << -1; return 0; } d = 1; for (long long i = 1; i <= 20; i++) { d *= i; fac[i] = d; } vector<long long> vi; long long on = 1; for (long long i = max(n - 15, on); i <= n; i++) { vi.push_back(i); } k--; while (k) { for (long long i = n; i >= 1; i--) { long long hi = n - i + 1; if (fac[hi] > k) { long long l = k / fac[hi - 1]; int qwer = n - i; qwer = vi.size() - qwer; swap(vi[qwer - 1], vi[qwer - 1 + l]); sort(vi.begin() + qwer, vi.end()); k -= l * fac[hi - 1]; break; } } } long long u = max(n - 15, on), tot = 0; for (long long i = 0; i < vi.size(); i++) { string asdf = to_string(vi[i]), uio = to_string(u); bool is = true; for (long long j = 0; j < asdf.size(); j++) { if (asdf[j] != '7' && asdf[j] != '4') is = false; if (uio[j] != '7' && uio[j] != '4') is = false; } if (is) tot++; u++; } if (n > 15) { n -= 15; tot += recursive(4, n) + recursive(7, n); } cout << tot; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const signed long long Infinity = 1000000001; const long double Pi = 2.0L * asinl(1.0L); const long double Epsilon = 0.000000001; template <class T, class U> ostream& operator<<(ostream& os, const pair<T, U>& p) { return os << "(" << p.first << "," << p.second << ")"; } template <class T> ostream& operator<<(ostream& os, const vector<T>& V) { for (typeof(V.begin()) i = V.begin(); i != V.end(); ++i) os << *i << " "; return os; } template <class T> ostream& operator<<(ostream& os, const set<T>& S) { for (typeof(S.begin()) i = S.begin(); i != S.end(); ++i) os << *i << " "; return os; } template <class T, class U> ostream& operator<<(ostream& os, const map<T, U>& M) { for (typeof(M.begin()) i = M.begin(); i != M.end(); ++i) os << *i << " "; return os; } vector<signed long long> S; void findLuckies() { for (int(k) = (1); (k) < (12); (k)++) for (int(i) = (0); (i) < (1 << k); (i)++) { signed long long t = i; signed long long r = 0; for (int(j) = (1); (j) <= (k); (j)++) { if (t % 2 == 1) { r *= 10; r += 7; } else { r *= 10; r += 4; } t /= 2; } S.push_back(r); } sort(S.begin(), S.end()); } signed long long factorial(signed long long n) { if (n > 20) return Infinity * Infinity; signed long long result = 1; for (int(i) = (1); (i) <= (n); (i)++) result *= i; return result; } vector<signed long long> kThPermutation(vector<signed long long> A, int k) { k--; vector<signed long long> R; int n = A.size(); for (int(i) = (n); (i) >= (2); (i)--) { int t = i; signed long long q = factorial(i - 1); t = k / q; k -= q * t; R.push_back(A[t]); A.erase(A.begin() + t); } R.push_back(A.front()); return R; } const int Q = 20; bool isLucky(signed long long q) { return binary_search(S.begin(), S.end(), q); } int result() { signed long long n, k; cin >> n >> k; if (k > factorial(n)) return -1; else { vector<signed long long> T; signed long long result = 0; int i = 0; while (S[i] < n - Q) { result++; i++; } int w; if (i > 0) w = S[i - 1] + 1; else w = 0; int b = max(n - Q, (signed long long)w); for (int(j) = (b); (j) <= (n); (j)++) { T.push_back(j); } T = kThPermutation(T, k); for (int(j) = (0); (j) < (T.size()); (j)++) if (isLucky(j + b) and isLucky(T[j])) result++; return result; } } int main() { findLuckies(); cout << result(); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; long long fac[20], n, k; long long answer; void rec(long long x, long long lim) { if (x > lim) return; answer++; rec(10 * x + 4, lim); rec(10 * x + 7, lim); } long long calc(long long lim) { rec(4, lim); rec(7, lim); } long long ohMyLuck(long long x) { while (x > 0) { if (x % 10 == 7 or x % 10 == 4) { x /= 10; } else { return 0; } } return 1; } int main() { cin >> n >> k; fac[0] = 1; for (int i = 1; i <= 15; i++) fac[i] = (fac[i - 1] * i); if (n <= 13 and fac[n] < k) { cout << -1 << endl; return 0; } k--; int mis = -1; for (int i = 1; i <= 15; i++) if (k >= fac[i]) mis = i; calc(n - (mis + 1)); vector<int> vec, my; for (int i = n - mis; i <= n; i++) vec.push_back(i); for (int i = vec.size() - 1; i >= 0; i--) { int d = k / fac[i]; k = k % fac[i]; my.push_back(vec[d]); vec.erase(vec.begin() + d); } for (int i = 0; i < my.size(); i++) { if (ohMyLuck(my[i]) and ohMyLuck(n - mis + i)) { answer++; } } cout << answer << endl; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const long long Fac[14] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800LL}; int Total, Data[5000]; bool Lucky(int T) { while (T) { if (T % 10 != 4 && T % 10 != 7) return false; T /= 10; } return true; } void Init() { Total = 0; for (int i = 1; i <= 9; i++) for (int j = 0; j < (1 << i); j++) { int S = 0; for (int k = 0; k < i; k++) S = S * 10 + ((j & (1 << k)) ? 4 : 7); Data[Total++] = S; } sort(Data, Data + Total); } int Count(int N) { if (Data[Total - 1] <= N) return Total; int P = 0; while (Data[P] <= N) P++; return P; } int Count1(int N, int K) { if (K >= Fac[N]) return -1; int Ans = 0, Kth[20], A[20]; for (int i = 1; i <= N; i++) Kth[i] = i; for (int i = 1; i <= N; i++) { A[i] = Kth[K / Fac[N - i] + 1]; K %= Fac[N - i]; if (Lucky(i) && Lucky(A[i])) Ans++; int P = 1; while (Kth[P] != A[i]) P++; for (int j = P; j <= N - i; j++) Kth[j] = Kth[j + 1]; } return Ans; } int Count2(int N, int K) { int Ans = Count(N), Kth[20], A[20]; for (int i = 1; i <= 13; i++) Kth[i] = N + i; for (int i = 1; i <= 13; i++) { A[i] = Kth[K / Fac[13 - i] + 1]; K %= Fac[13 - i]; if (Lucky(N + i) && Lucky(A[i])) Ans++; int P = 1; while (Kth[P] != A[i]) P++; for (int j = P; j <= 13 - i; j++) Kth[j] = Kth[j + 1]; } return Ans; } int main() { Init(); int N, K; cin >> N >> K; K--; cout << ((N <= 13) ? Count1(N, K) : Count2(N - 13, K)) << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int ans, n, k, m, x; long long fac[15]; int num[15]; bool mark[15]; void dfs(int i = 0, long long num = 0) { if (num && num <= m) ans++; if (i == 9) return; dfs(i + 1, num * 10 + 4); dfs(i + 1, num * 10 + 7); } void make(int i = 1) { if (i > x) return; int j = 1, t; while (mark[j]) j++; while (k >= fac[x - i]) { j++; while (mark[j]) j++; k -= fac[x - i]; } while (mark[j]) j++; num[i] = j + m; mark[j] = 1; make(i + 1); } int main() { fac[0] = 1LL; for (long long i = 1; i < 15; i++) fac[i] = fac[i - 1] * i; while (~scanf("%d%d", &n, &k)) { ans = 0; memset(mark, 0, sizeof(mark)); if (n < 15 && fac[n] < k) { puts("-1"); continue; } for (int i = 0; i < 15; i++) if (fac[i] >= k) { x = i; break; } m = n - x; dfs(); k--; make(); for (int i = m + 1; i <= n; i++) { bool flag = true; int temp = i; while (temp) { if (temp % 10 != 4 && temp % 10 != 7) flag = false; temp /= 10; } temp = num[i - m]; while (temp) { if (temp % 10 != 4 && temp % 10 != 7) flag = false; temp /= 10; } if (flag) ans++; } printf("%d\n", ans); } }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int n, k; long long fact[14] = {1}; bool cmp(int p) { if (p > 13 || fact[p] >= k) return true; k -= fact[p]; return false; } bool check(int x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } bool used[16]; int s; int calc(int i) { if (i > n) return 0; for (int j = s; j <= n; ++j) if (!used[j - s] && cmp(n - i)) { used[j - s] = true; return (check(i) && check(j)) + calc(i + 1); } return -1; } long long all[2046] = {4, 7}; int allC = 2; int main() { for (int i = 1; i < 14; ++i) fact[i] = fact[i - 1] * i; scanf("%d%d", &n, &k); if (n < 14 && k > fact[n]) { printf("-1"); return 0; } s = 1; if (n <= 13) printf("%d", calc(1)); else { for (int i = 0; all[allC - 1] < 7777777777LL; ++i) { all[allC++] = all[i] * 10 + 4; all[allC++] = all[i] * 10 + 7; } s = n - 12; printf("%d", lower_bound(all, all + allC, s) - all + calc(s)); } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; string lower(string s) { for (int i = 0; i < s.size(); i++) s[i] = tolower(s[i]); return s; } vector<string> sep(string s, char c) { string temp; vector<string> res; for (int i = 0; i < s.size(); i++) { if (s[i] == c) { if (temp != "") res.push_back(temp); temp = ""; continue; } temp = temp + s[i]; } if (temp != "") res.push_back(temp); return res; } template <class T> T toint(string s) { stringstream ss(s); T ret; ss >> ret; return ret; } template <class T> string tostr(T inp) { string ret; stringstream ss; ss << inp; ss >> ret; return ret; } template <class T> void D(T A[], int n) { for (int i = 0; i < n; i++) cout << A[i] << " "; cout << endl; } template <class T> void D(vector<T> A, int n = -1) { if (n == -1) n = A.size(); for (int i = 0; i < n; i++) cout << A[i] << " "; cout << endl; } long long fact[21]; set<long long> lnum; int main() { for (int(i) = (1); (i) <= (10); (i)++) { int mask = (1 << i); for (int(j) = (0); (j) < (mask); (j)++) { long long tnum = 0; for (int(k) = (0); (k) < (i); (k)++) { tnum *= 10LL; if ((j & (1 << k))) tnum += 4LL; else tnum += 7LL; } lnum.insert(tnum); } } fact[0] = fact[1] = 1; for (int(i) = (2); (i) < (21); (i)++) fact[i] = (long long)i * fact[i - 1]; int n, k; cin >> n >> k; int ans = 0; for (typeof(lnum.begin()) it = lnum.begin(); it != lnum.end(); it++) { if (*it > n) break; if (n - *it + 1 <= 15) break; ans++; } int sn = max(1, n - 15 + 1); if (fact[n - sn + 1] >= k) { int totaliter = n - sn + 1; set<int> poss; for (int(i) = (sn); (i) <= (n); (i)++) poss.insert(i); for (int(i) = (0); (i) < (totaliter); (i)++) { set<int>::iterator it = poss.begin(); while (k > fact[totaliter - i - 1]) { it++; k -= fact[totaliter - i - 1]; } if (lnum.find(*it) != lnum.end() && lnum.find(sn + i) != lnum.end()) ans++; poss.erase(it); } cout << ans << endl; } else { cout << -1 << endl; } return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; const int c[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600}; int a[10010]; vector<int> b; void dfs(long long x) { if (x >= 1000000000) return; a[++a[0]] = int(x); dfs(x * 10 + 4); dfs(x * 10 + 7); } bool check(int x) { while (x) { int p = x % 10; x /= 10; if (p != 4 && p != 7) return (false); } return (true); } int main() { int n, K; scanf("%d%d", &n, &K); long long now = 1; int t = -1; for (int i = 1; i <= n; i++) { now *= i; if (now >= K) { t = i; break; } } if (t == -1) printf("-1\n"); else { dfs(4); dfs(7); sort(a + 1, a + a[0] + 1); for (int i = 1; i <= t; i++) b.push_back(n - i + 1); reverse(b.begin(), b.end()); int ans = 0; for (int i = 1; i <= a[0]; i++) ans += a[i] <= n - t; int now = n - t; K--; for (int i = t; i; i--) { now++; int p = 0; while (K >= c[i - 1]) { p++; K -= c[i - 1]; } ans += check(now) && check(b[p]); b.erase(b.begin() + p); } printf("%d\n", ans); } return (0); }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import static java.util.Arrays.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import java.util.*; import java.math.*; import java.io.*; public class C implements Runnable { String file = "input"; boolean TEST = false; void solve() throws IOException { int m = nextInt(), k = nextInt(); list = new ArrayList<Long>(); gen(0); long[] a = new long[13]; int n = min(13, m); boolean[] done = new boolean[n + 1]; for(int i = 0; i < n; i++) { long cnt = 0; for(int j = 1; j <= n; j++) if(!done[j]) { cnt += fact(n - i - 1); if(cnt >= k) { a[i] = j; k -= (cnt - fact(n - i - 1)); done[j] = true; break; } } } if(k != 1) { out.println(-1); return; } int res = 0; if(m <= 13) { for(int i = 0; i < m; i++) if(isLucky(i + 1) && isLucky(a[i])) res++; out.println(res); } else { int left = m - 13; for(long x : list) if(x <= left) res++; for(int i = 0; i < n; i++) if(isLucky(i + left + 1) && isLucky(a[i] + left)) res++; out.println(res); } } List<Long> list; boolean isLucky(long n) { while(n > 0) { long q = n % 10; if(q != 4 && q != 7) return false; n /= 10; } return true; } void gen(long x) { if(x > 10000000000L) return; if(x > 0) list.add(x); gen(x * 10 + 4); gen(x * 10 + 7); } long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) res *= i; return res; } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } void print(Object... o) { System.out.println(deepToString(o)); } void gcj(Object o) { String s = String.valueOf(o); out.println("Case #" + test + ": " + s); System.out.println("Case #" + test + ": " + s); } BufferedReader input; PrintWriter out; StringTokenizer st; int test; void init() throws IOException { if(TEST) input = new BufferedReader(new FileReader(file + ".in")); else input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); } public static void main(String[] args) throws IOException { new Thread(null, new C(), "", 1 << 20).start(); } public void run() { try { init(); if(TEST) { int runs = nextInt(); for(int i = 0; i < runs; i++) solve(); } else solve(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
from math import factorial import sys def lucky(x): return str(x).count('4')+str(x).count('7')==len(str(x)) def fun(x): xs, result = str(x), 0 for i in range(len(xs)): rest = 1<<(len(xs)-i-1) if int(xs[i]) == 4: continue elif int(xs[i]) == 7: result += rest continue elif int(xs[i]) < 4: return result elif 4 < int(xs[i]) < 7: return result + rest else: return result + rest * 2 return result + 1 def solve(x): now, result = 9, 0 while now < x: result += fun(now) now = now*10+9 return result + fun(x) n, k = [int(t) for t in raw_input().split()] m = 1 while factorial(m) < k: m += 1 if m > n: print -1 sys.exit(0) lst = range(n-m+1,n+1) for i in range(m): s = sorted(lst[i:]) j = 0 while factorial(m-i-1) < k: j += 1 k -= factorial(m-i-1) s[0], s[j] = s[j], s[0] lst = lst[:i] + s #print range(1,n-m+1) + lst print solve(n-m) + len([1 for a, b in zip(lst, range(n-m+1,n+1)) if lucky(a) and lucky(b)])
PYTHON