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
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Thread(null, new Runnable() { public void run() { try { new Main().run(); } catch (Throwable e) { e.printStackTrace(); exit(999); } } }, "1", 1 << 23).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); int n = nextInt(); int k = nextInt() - 1; boolean m[] = new boolean[n]; for(int i = 0; i < n; i++) m[i] = nextInt() == 1; while(!m[k]){ k = (k + 1) % n; } out.println(k + 1); in.close(); out.close(); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } 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 nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new Main(), "", 256 * (1L << 20)).start(); } public void run() { try { /*if (System.getProperty("ONLINE_JUDGE") != null) { 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"); } solve(); in.close(); out.close(); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } 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()); } void solve() throws IOException { int n=readInt(); int k=readInt(); int [] a=new int[n]; for(int i=0;i<n;i++) a[i]=readInt(); k=k-1; while(a[k]!=1) { k++; if(k>=n) k=0; } out.println(k+1); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class ele2 { public static void debug(Object... obs) { System.out.println(Arrays.deepToString(obs)); } public static void main(String[]args){ InputStream in = System.in; PrintWriter out = new PrintWriter(System.out); try{ in = new BufferedInputStream(new FileInputStream(new File("input.txt"))); out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt"))); }catch (Exception e) { } new ele2().run(in,out); out.flush(); } public void run(InputStream in, PrintWriter out) { Scanner sc = new Scanner(in); int n=sc.nextInt(); int k=sc.nextInt()-1; int[]z=new int[n]; for(int i=0;i<n;i++) z[i]=sc.nextInt(); for(int i=0;i<n;i++) { if(z[k]==1) { out.println(k+1); return; } else { k=(k+1)%n; } } } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class B_120 { /** * @param args */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub BufferedReader br=new BufferedReader(new FileReader("input.txt")); StringTokenizer str1=new StringTokenizer(br.readLine(), " "); int n=Integer.valueOf(str1.nextToken()); int k=Integer.valueOf(str1.nextToken()); int answer=-1; str1=new StringTokenizer(br.readLine(), " "); int m=-1; PrintWriter pw=new PrintWriter(new File("output.txt"), "ISO-8859-1"); for(int i=1;i<k;i++){ m=Integer.valueOf(str1.nextToken()); if(m==1 && answer==-1) answer=i; } m=Integer.valueOf(str1.nextToken()); if(m==1){ pw.write(Integer.toString(k)); pw.flush(); return; } for(int i=k+1;i<=n;i++){ m=Integer.valueOf(str1.nextToken()); if(m==1){ pw.write(Integer.toString(i)); pw.flush(); return; } } pw.write(Integer.toString(answer)); pw.flush(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; public class QuizLeague { static boolean[] quiz; static int n, k; public static void main(String[] args) throws IOException { //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedReader in = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter(new FileWriter("output.txt"), true); StringTokenizer st = new StringTokenizer(in.readLine()); n = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); quiz = new boolean[n]; st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { quiz[i] = st.nextToken().equals("1"); } k--; while (!quiz[k]) { k = (k+1)%n; } out.println(k+1); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class QuizLeague { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader("input.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("output.txt")); int n = sc.nextInt(); int k = sc.nextInt() - 1; int[] a = new int[n]; for (int i = 0; i < a.length; i++) a[i] = sc.nextInt(); int i = k; for (; i <= n; i++) { i %= n; if (a[i] == 1) break; } out.write((i + 1) + ""); out.close(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; public class Problem implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer str; private void solve() throws IOException { str = new StringTokenizer(in.readLine()); int n = Integer.parseInt(str.nextToken()); int k = Integer.parseInt(str.nextToken()); str = new StringTokenizer(in.readLine()); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = Integer.parseInt(str.nextToken()); int i = k-1; while(a[i % n] != 1){ i++; } out.print(i%n+1); } public void run() { try{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); solve(); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) throws IOException { new Problem().run(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { private void Problem() throws IOException { int n = nextInt(), k = nextInt(), a[] = new int[n+1]; for (int i = 1; i < n + 1; i ++) a[i] = nextInt(); for (int i = k; i < n + 1; i ++) { if (a[i] == 1) { out.print(i); break; } if (i == n) i = 0; } } BufferedReader in; StringTokenizer tokenizer; PrintWriter out; int nextInt() throws IOException, NumberFormatException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException, NumberFormatException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException, NumberFormatException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } public void Solution() throws IOException { in = new BufferedReader(new FileReader(new File("input.txt"))); out = new PrintWriter(new File("output.txt")); tokenizer = null; Problem(); in.close(); out.close(); } public static void main(String[] args) throws IOException { new B().Solution(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.Scanner; public class quiz { public static void main(String args[])throws Exception { FileInputStream fs=new FileInputStream("input.txt"); DataInputStream in=new DataInputStream(fs); String s=in.readLine(),s1=in.readLine(); Scanner sc=new Scanner(s); int n=sc.nextInt(); int k=sc.nextInt(); int a[]=new int [n]; Scanner sc1=new Scanner(s1); for(int i=0;i<n;i++) a[i]=sc1.nextInt(); FileOutputStream out=new FileOutputStream("output.txt"); PrintStream p=new PrintStream(out); for(int i=k-1;i<n;i=(i+1)%n) { if(a[i]==1) { p.println(i+1); break; } } } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class Main { ///////////////////////////////////////////////////////////////// // IO ///////////////////////////////////////////////////////////////// private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static boolean FILE=true; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ try { out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out); inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in)); } catch(Exception e) {e.printStackTrace();} in = new StreamTokenizer(inB); } ///////////////////////////////////////////////////////////////// public static void main(String[] args)throws Exception { int n = nextInt(), k = nextInt(); int[] mas = new int[n]; for(int i = 0; i<n; i++){mas[i] = nextInt();} for(int j = k-1; ; j = (j < n-1) ? j+1 : 0) { if(mas[j] == 1) { exit(j+1); } } } ///////////////////////////////////////////////////////////////// // pre - written ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { out.println(o); out.flush(); } private static void exit(Object o) throws Exception { println(o); exit(); } private static void exit() { System.exit(0); } private static final int INF = Integer.MAX_VALUE; private static final int MINF = Integer.MIN_VALUE; ////////////////////////////////////////////////////////////////// }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { PrintWriter pr = new PrintWriter(new FileOutputStream(new File("output.txt")),true); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); StringTokenizer tz = new StringTokenizer(in.readLine()); //Scanner s = new Scanner(new File("input.txt")); int n = Integer.parseInt(tz.nextToken()); int k = Integer.parseInt(tz.nextToken()); tz = new StringTokenizer(in.readLine()); int mas[] = new int[n]; for(int i = 0;i < n;i++) mas[i] = Integer.parseInt(tz.nextToken()); int i = k-1; while(mas[i] != 1) { i++; i%=n; } pr.println(i+1); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.File; import java.io.PrintWriter; import java.lang.*; import java.util.*; public class Abhishek { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int n = sc.nextInt(); int k = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } k--; while (a[k]!=1){ k++; k%=n; } out.println(k+1); out.close(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; public class P1 { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter("output.txt"); while(in.hasNext()){ int n = in.nextInt(); int k = in.nextInt(); int [] q = new int[n]; for (int i = 0; i < q.length; i++) q[i]=in.nextInt(); for (int i = k-1; ; i++) {if(i==n)i=0;if(q[i]==1){out.print(i+1);break;}} out.flush(); } } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class _1057QuizLeague { public static void main(String[] args) throws IOException { File f = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(f)); String in[] =br.readLine().split(" "); int n=Integer.parseInt(in[0]); int k=Integer.parseInt(in[1]); String[] bottles= br.readLine().split(" "); int[] arr = new int[n]; for(int i=0;i<n;i++) { int temp=Integer.parseInt(bottles[i]); arr[i]=temp; } boolean found=false; int ans=0; int index=k-1; while(!found) { if(arr[index%n]==1) { found=true; ans=(index)%n; } else { index++; } // System.out.println(ans); } ans++; // System.out.println(ans); FileWriter fw=new FileWriter("output.txt"); fw.write(ans+""); fw.close(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
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 B implements Runnable { String file = "input"; boolean TEST = false; void solve() throws IOException { int n = nextInt(), k = nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); int j; for(j = k - 1; a[j] == 0; j = (j + 1) % n); out.println(j + 1); } 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 { input = new BufferedReader(new FileReader(file + ".txt")); if(TEST) out = new PrintWriter(new BufferedOutputStream(System.out)); else out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); } public static void main(String[] args) throws IOException { new Thread(null, new B(), "", 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
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Main{ static class Run implements Runnable{ //TODO parameters final boolean consoleIO = false; final String inFile = "input.txt"; final String outFile = "output.txt"; @Override public void run() { int n = nextInt(); int k = nextInt()-1; boolean[] busy = new boolean[n]; for(int i = 0; i < n; ++i) busy[i] = nextInt() == 0; int cur = k; while(busy[cur]) { cur++; cur %= n; } print(cur+1); close(); } //========================================================================================================================= BufferedReader in; PrintWriter out; StringTokenizer strTok; Run() { if (consoleIO) { initConsoleIO(); } else { initFileIO(); } } void initConsoleIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } void initFileIO() { try { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new FileWriter(outFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } void close() { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } int nextInt() { return Integer.parseInt(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } float nextFloat() { return Float.parseFloat(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } String nextLine() { try { return in.readLine(); } catch (IOException e) { return "__NULL"; } } boolean hasMoreTokens() { return (strTok == null) || (strTok.hasMoreTokens()); } String nextToken() { while (strTok == null || !strTok.hasMoreTokens()) { String line; try { line = in.readLine(); strTok = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return strTok.nextToken(); } void cout(Object o){ System.out.println(o); } void print(Object o) { out.write(o.toString()); } void println(Object o) { out.write(o.toString() + '\n'); } void printf(String format, Object... args) { out.printf(format, args); } String sprintf(String format, Object... args) { return MessageFormat.format(format, args); } } static class Pair<A, B> { A a; B b; A f() { return a; } B s() { return b; } Pair(A a, B b) { this.a = a; this.b = b; } Pair(Pair<A, B> p) { a = p.f(); b = p.s(); } } public static void main(String[] args) throws IOException { Run run = new Run(); Thread thread = new Thread(run); thread.run(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.util.*; import java.math.*; import java.io.*; public class LOL { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File("input.txt")); PrintStream out = new PrintStream(new File("output.txt")); int N = in.nextInt(); int K = in.nextInt()-1; boolean[] vals = new boolean[N]; for (int i=0; i<N; i++) vals[i] = in.nextInt()==0; while(vals[K]) K = (K+1)%N; out.println(K+1); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; public class Main { Scanner in; PrintWriter out; void solve() { int n = in.nextInt(); int k = in.nextInt() - 1; int[] a = new int[2 * n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); a[i + n] = a[i]; } int i = k; while (true) { if (a[i] == 1) { out.println((i + 1) % n == 0 ? i + 1 : (i + 1) % n); return; } i++; } } void run() { try { in = new Scanner(new File("input.txt")); out = new PrintWriter("output.txt"); } catch (IOException e) { throw new Error(e); } try { solve(); } finally { out.close(); } } public static void main(String args[]) { new Main().run(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Scanner; //joutf.close(); public class TaskB { public static void main(String[] args) throws Exception { Scanner jinf = new Scanner(new FileReader("input.txt")); PrintWriter joutf = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); int n = jinf.nextInt(); int k = jinf.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = jinf.nextInt(); } int i = k-1; while (i < n) { if (a[i]==1) { joutf.print(i+1); joutf.close(); return; } ++i; } i = 0; while (i < n) { if (a[i]==1) { joutf.print(i+1); joutf.close(); return; } ++i; } joutf.close(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.awt.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("input.txt")); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] list = new int[n]; st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++) list[i] = Integer.parseInt(st.nextToken()); k--; while(list[k] == 0) { k++; k %= n; } pw.println(k+1); pw.close(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main{ public static void main(String[]args){ InputStream in = System.in; PrintWriter out = new PrintWriter(System.out); try{ in = new BufferedInputStream(new FileInputStream(new File("input.txt"))); out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt"))); }catch (Exception e) { } new Main().run(in,out); out.flush(); } private void debug(Object...os){ System.err.println(deepToString(os)); } private void run(InputStream in,PrintWriter out){ int n=nextInt(in),k=nextInt(in)-1; int[] as=new int[n]; for(int i=0;i<n;i++)as[i]=nextInt(in); for(int i=k;;i++)if(as[i%n]==1){ out.println(i%n+1); return; } } private String next(InputStream in) { try { StringBuilder res = new StringBuilder(""); int c = in.read(); while (Character.isWhitespace(c)) c = in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = in.read())); return res.toString(); } catch (Exception e) { return null; } } private int nextInt(InputStream in){ try{ int c=in.read(); if(c==-1) return c; while(c!='-'&&(c<'0'||'9'<c)){ c=in.read(); if(c==-1) return c; } if(c=='-') return -nextInt(in); int res=0; do{ res*=10; res+=c-'0'; c=in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; public class test { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int size = sc.nextInt(); int start = sc.nextInt()-1; int[] array = new int[size]; for(int a=0;a<size;a++){ array[a]=sc.nextInt(); } //start=start%size; while(array[start]==0){start++;start=start%size;} out.print(start+1); out.close(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; public class problemB implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer st; public static void main(String[] args) throws Exception { new Thread(new problemB()).start(); } 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 { if (file) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); if (file) out = new PrintWriter(new FileWriter("output.txt")); else out = new PrintWriter(System.out); solve(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { out.close(); } } boolean file = true; public void solve() throws Exception { int n = nextInt(), k = nextInt(), a[] = new int[n+1], curr = k; for(int i=1; i<=n; i++){ a[i] = nextInt(); } while(true){ if(a[curr] > 0){ out.println(curr); return; } curr++; if (curr == n+1) curr = 1; } } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; public class Solution { public static void main(String args[]) throws Exception { Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int n = in.nextInt(); int k = in.nextInt(); int a[] = new int[n + 1]; for(int i = 1; i <= n; i++) { a[i] = in.nextInt(); } int sol = -1; for(int i = k; i <= n; i++) { if(a[i] == 1) { sol = i; break; } } if(sol == -1) { for(int i = 1; i < k; i++) { if(a[i] == 1) { sol = i; break; } } } out.println(sol); out.flush(); out.close(); } }
JAVA
120_B. Quiz League
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k. Input The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one. Output Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked. Examples Input 5 5 0 1 0 1 0 Output 2 Input 2 1 1 1 Output 1
2
8
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private Random rnd; public void solve() throws IOException { int n = nextInt(), k = nextInt() - 1; int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); while(true) { if(a[k] == 1) { out.println(k + 1); return; } k = (k + 1) % n; } } public static void main(String[] args) { new Main().run(); } public void run() { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); //in = new BufferedReader(new InputStreamReader((System.in))); //out = new PrintWriter(System.out); st = null; rnd = new Random(); solve(); out.close(); } catch(IOException e) { e.printStackTrace(); } } private String nextToken() throws IOException, NullPointerException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } 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()); } }
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.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import java.util.Queue; import static java.lang.Math.max; import static java.lang.Math.min; public class C implements Runnable{ // SOLUTION!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! private final static Random rnd = new Random(); private final static String fileName = ""; private final static long MODULO = 1000 * 1000 * 1000 + 7; private void solve() { int n = readInt(); long k = readInt(); int size = min(15, n); long[] factorials = new long[size + 1]; factorials[0] = 1; for (int i = 1; i < factorials.length; ++i) { factorials[i] = factorials[i - 1] * i; } if (n < factorials.length && k > factorials[n]) { out.println(-1); return; } boolean[] used = new boolean[size]; int[] p = new int[size]; for (int i = 0; i < size; ++i) { long cur = 0; int next = -1; long nextK = k; for (int j = 0; j < size; ++j) { if (used[j]) continue; if (cur < k) { next = j; nextK = k - cur; } cur += factorials[size - i - 1]; } used[next] = true; p[i] = next; k = nextK; } n -= size; long fixedCount = 0; for (int len = 1; len <= 9; ++len) { for (int mask = 0; mask < (1 << len); ++mask) { long number = 0; for (int bit = 0; bit < len; ++bit) { number *= 10; number += (checkBit(mask, bit) ? 4 : 7); } if (number <= n) ++fixedCount; } } long permCount = 0; for (int i = 0; i < size; ++i) { int position = (n + 1 + i); int value = (n + 1 + p[i]); if (isLucky(position) && isLucky(value)) { permCount++; } } long answer = fixedCount + permCount; out.println(answer); } boolean isLucky(int value) { while (value > 0) { if (value % 10 != 4 && value % 10 != 7) return false; value /= 10; } return true; } ///////////////////////////////////////////////////////////////////// private static long add(long a, long b) { return (a + b) % MODULO; } private static long subtract(long a, long b) { return add(a, MODULO - b) % MODULO; } private static long mult(long a, long b) { return (a * b) % MODULO; } ///////////////////////////////////////////////////////////////////// private final static boolean FIRST_INPUT_STRING = false; private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = !new File("input.txt").exists(); // private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); } catch (NumberFormatException e) { break; } catch (NullPointerException e) { if (FIRST_INPUT_STRING) break; else throw e; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new C(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readString() { try { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine(), delim); } return tok.nextToken(delim); } catch (NullPointerException e) { return null; } } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// private BigInteger readBigInteger() { return new BigInteger(readString()); } private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<Integer>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1; private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) { return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed ) { GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber); for (int i = 0; i < edgesNumber; ++i) { int from = readInt() - indexation; int to = readInt() - indexation; if (directed) graphBuilder.addDirectedEdge(from, to); else graphBuilder.addEdge(from, to); } return graphBuilder.build(); } private static class Edge { int to; int w; Edge(int to, int w) { this.to = to; this.w = w; } } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) { return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed) { @SuppressWarnings("unchecked") List<Edge>[] graph = new List[vertexNumber]; for (int v = 0; v < vertexNumber; ++v) { graph[v] = new ArrayList<Edge>(); } while (edgesNumber --> 0) { int from = readInt() - indexation; int to = readInt() - indexation; int w = readInt(); graph[from].add(new Edge(to, w)); if (!directed) graph[to].add(new Edge(from, w)); } Edge[][] graphArrays = new Edge[vertexNumber][]; for (int v = 0; v < vertexNumber; ++v) { graphArrays[v] = graph[v].toArray(new Edge[0]); } return graphArrays; } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } int getRealIndex() { return index + 1; } } private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } @Override public void println(double d){ print(d); println(); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } void printlnAll(double... d){ printAll(d); println(); } void printAll(int... array) { for (int value : array) { print(value + " "); } } void printlnAll(int... array) { printAll(array); println(); } void printAll(long... array) { for (long value : array) { print(value + " "); } } void printlnAll(long... array) { printAll(array); println(); } } ///////////////////////////////////////////////////////////////////// private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants andTo functions //////////////// ///////////////////////////////////////////////////////////////////// private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); } private static boolean checkBit(long mask, int bit){ return getBit(mask, bit) != 0; } ///////////////////////////////////////////////////////////////////// private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// int[] getDivisors(int value) { List<Integer> divisors = new ArrayList<Integer>(); for (int divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castInt(divisors); } ///////////////////////////////////////////////////////////////////// private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private interface MultiSet<ValueType> { int size(); void inc(ValueType value); boolean dec(ValueType value); int count(ValueType value); } private static abstract class MultiSetImpl <ValueType, MapType extends Map<ValueType, Integer>> implements MultiSet<ValueType> { protected final MapType map; protected int size; protected MultiSetImpl(MapType map) { this.map = map; this.size = 0; } public int size() { return size; } public void inc(ValueType value) { int count = count(value); map.put(value, count + 1); ++size; } public boolean dec(ValueType value) { int count = count(value); if (count == 0) return false; if (count == 1) map.remove(value); else map.put(value, count - 1); --size; return true; } public int count(ValueType value) { Integer count = map.get(value); return (count == null ? 0 : count); } } private static class HashMultiSet<ValueType> extends MultiSetImpl<ValueType, Map<ValueType, Integer>> { public static <ValueType> MultiSet<ValueType> createMultiSet() { Map<ValueType, Integer> map = new HashMap<ValueType, Integer>(); return new HashMultiSet<ValueType>(map); } HashMultiSet(Map<ValueType, Integer> map) { super(map); } } ///////////////////////////////////////////////////////////////////// private interface SortedMultiSet<ValueType> extends MultiSet<ValueType> { ValueType min(); ValueType max(); ValueType pollMin(); ValueType pollMax(); ValueType lower(ValueType value); ValueType floor(ValueType value); ValueType ceiling(ValueType value); ValueType higher(ValueType value); } private static abstract class SortedMultiSetImpl<ValueType> extends MultiSetImpl<ValueType, NavigableMap<ValueType, Integer>> implements SortedMultiSet<ValueType> { SortedMultiSetImpl(NavigableMap<ValueType, Integer> map) { super(map); } @Override public ValueType min() { return (size == 0 ? null : map.firstKey()); } @Override public ValueType max() { return (size == 0 ? null : map.lastKey()); } @Override public ValueType pollMin() { ValueType first = min(); if (first != null) dec(first); return first; } @Override public ValueType pollMax() { ValueType last = max(); dec(last); return last; } @Override public ValueType lower(ValueType value) { return map.lowerKey(value); } @Override public ValueType floor(ValueType value) { return map.floorKey(value); } @Override public ValueType ceiling(ValueType value) { return map.ceilingKey(value); } @Override public ValueType higher(ValueType value) { return map.higherKey(value); } } private static class TreeMultiSet<ValueType> extends SortedMultiSetImpl<ValueType> { public static <ValueType> SortedMultiSet<ValueType> createMultiSet() { NavigableMap<ValueType, Integer> map = new TreeMap<ValueType, Integer>(); return new TreeMultiSet<ValueType>(map); } TreeMultiSet(NavigableMap<ValueType, Integer> map) { super(map); } } ///////////////////////////////////////////////////////////////////// private static class IdMap<KeyType> extends HashMap<KeyType, Integer> { /** * */ private static final long serialVersionUID = -3793737771950984481L; public IdMap() { super(); } int register(KeyType key) { Integer id = super.get(key); if (id == null) { super.put(key, id = size()); } return id; } int getId(KeyType key) { return get(key); } } ///////////////////////////////////////////////////////////////////// private static class SortedIdMapper<ValueType extends Comparable<ValueType>> { private final List<ValueType> values; public SortedIdMapper() { this.values = new ArrayList<ValueType>(); } void addValue(ValueType value) { values.add(value); } IdMap<ValueType> build() { Collections.sort(values); IdMap<ValueType> ids = new IdMap<ValueType>(); for (int index = 0; index < values.size(); ++index) { ValueType value = values.get(index); if (index == 0 || values.get(index - 1).compareTo(value) != 0) { ids.register(value); } } return ids; } } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } ///////////////////////////////////////////////////////////////////// /** * Generates list with keys 0..<n * @param n - exclusive limit of sequence */ private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } ///////////////////////////////////////////////////////////////////// interface Rmq { int getMin(int left, int right); int getMinIndex(int left, int right); } private static class SparseTable implements Rmq { private static final int MAX_BIT = 20; int n; int[] array; SparseTable(int[] array) { this.n = array.length; this.array = array; } int[] lengthMaxBits; int[][] table; int getIndexOfLess(int leftIndex, int rightIndex) { return (array[leftIndex] <= array[rightIndex]) ? leftIndex : rightIndex; } SparseTable build() { this.lengthMaxBits = new int[n + 1]; lengthMaxBits[0] = 0; for (int i = 1; i <= n; ++i) { lengthMaxBits[i] = lengthMaxBits[i - 1]; int length = (1 << lengthMaxBits[i]); if (length + length <= i) ++lengthMaxBits[i]; } this.table = new int[MAX_BIT][n]; table[0] = castInt(order(n)); for (int bit = 0; bit < MAX_BIT - 1; ++bit) { for (int i = 0, j = (1 << bit); j < n; ++i, ++j) { table[bit + 1][i] = getIndexOfLess( table[bit][i], table[bit][j] ); } } return this; } @Override public int getMinIndex(int left, int right) { int length = (right - left + 1); int bit = lengthMaxBits[length]; int segmentLength = (1 << bit); return getIndexOfLess( table[bit][left], table[bit][right - segmentLength + 1] ); } @Override public int getMin(int left, int right) { return array[getMinIndex(left, right)]; } } private static Rmq createRmq(int[] array) { return new SparseTable(array).build(); } ///////////////////////////////////////////////////////////////////// interface Lca { Lca build(int root); int lca(int a, int b); int height(int v); } private static class LcaRmq implements Lca { int n; int[][] graph; LcaRmq(int[][] graph) { this.n = graph.length; this.graph = graph; } int time; int[] order; int[] heights; int[] first; Rmq rmq; @Override public LcaRmq build(int root) { this.order = new int[n + n]; this.heights = new int[n]; this.first = new int[n]; Arrays.fill(first, -1); this.time = 0; dfs(root, 0); int[] orderedHeights = new int[n + n]; for (int i = 0; i < order.length; ++i) { orderedHeights[i] = heights[order[i]]; } this.rmq = createRmq(orderedHeights); return this; } void dfs(int from, int height) { first[from] = time; order[time] = from; heights[from] = height; ++time; for (int to : graph[from]) { if (first[to] == -1) { dfs(to, height + 1); order[time] = from; ++time; } } } @Override public int lca(int a, int b) { int aFirst = first[a], bFirst = first[b]; int left = min(aFirst, bFirst), right = max(aFirst, bFirst); int orderIndex = rmq.getMinIndex(left, right); return order[orderIndex]; } @Override public int height(int v) { return heights[v]; } } private static class LcaBinary implements Lca { private static final int MAX_BIT = 20; int n; int[][] graph; int[] h; int[][] parents; LcaBinary(int[][] graph) { this.n = graph.length; this.graph = graph; } @Override public Lca build(int root) { this.h = new int[n]; this.parents = new int[MAX_BIT][n]; Arrays.fill(parents[0], -1); Queue<Integer> queue = new ArrayDeque<Integer>(); queue.add(root); add(root, root); while (queue.size() > 0) { int from = queue.poll(); for (int to : graph[from]) { if (parents[0][to] == -1) { add(from, to); queue.add(to); } } } return this; } void add(int parent, int v) { h[v] = h[parent] + 1; parents[0][v] = parent; for (int bit = 0; bit < MAX_BIT - 1; ++bit) { parents[bit + 1][v] = parents[bit][parents[bit][v]]; } } @Override public int lca(int a, int b) { if (h[a] < h[b]) { int tmp = a; a = b; b = tmp; } int delta = h[a] - h[b]; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { if (delta >= (1 << bit)) { delta -= (1 << bit); a = parents[bit][a]; } } if (a == b) return a; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { int nextA = parents[bit][a], nextB = parents[bit][b]; if (nextA != nextB) { a = nextA; b = nextB; } } return parents[0][a]; } @Override public int height(int v) { return h[v]; } } private static Lca createLca(int[][] graph, int root) { return new LcaRmq(graph).build(root); } ///////////////////////////////////////////////////////////////////// private static class BiconnectedGraph { int n; int[][] graph; BiconnectedGraph(int[][] graph) { this.n = graph.length; this.graph = graph; } int time; int[] tin, up; boolean[] used; BiconnectedGraph build() { calculateTimes(); condensateComponents(); return this; } void calculateTimes() { this.tin = new int[n]; this.up = new int[n]; this.time = 0; this.used = new boolean[n]; timeDfs(0, -1); } void timeDfs(int from, int parent) { used[from] = true; up[from] = tin[from] = time; ++time; for (int to : graph[from]) { if (to == parent) continue; if (used[to]) { up[from] = min(up[from], tin[to]); } else { timeDfs(to, from); up[from] = min(up[from], up[to]); } } } int[] components; int[][] componentsGraph; int component(int v) { return components[v]; } int[][] toGraph() { return componentsGraph; } void condensateComponents() { this.components = new int[n]; Arrays.fill(components, -1); for (int v = 0; v < n; ++v) { if (components[v] == -1) { componentsDfs(v, v); } } GraphBuilder graphBuilder = GraphBuilder.createInstance(n); Set<Point> edges = new HashSet<Point>(); for (int from = 0; from < n; ++from) { int fromComponent = components[from]; for (int to : graph[from]) { int toComponent = components[to]; if (fromComponent == toComponent) continue; Point edge = new Point(fromComponent, toComponent); if (edges.add(edge)) graphBuilder.addDirectedEdge(fromComponent, toComponent); } } this.componentsGraph = graphBuilder.build(); } void componentsDfs(int from, int color) { components[from] = color; for (int to : graph[from]) { if (components[to] != -1) continue; if (tin[from] >= up[to] && tin[to] >= up[from]) { componentsDfs(to, color); } } } } ///////////////////////////////////////////////////////////////////// private static class VertexBiconnectedGraph { static class Edge { int to; int index; Edge(int to, int index) { this.to = to; this.index = index; } } int n, m; List<Edge>[] graph; List<Edge> edges; VertexBiconnectedGraph(int n) { this.n = n; this.m = 0; this.graph = new List[n]; for (int v = 0; v < n; ++v) { graph[v] = new ArrayList<Edge>(); } this.edges = new ArrayList<Edge>(); } void addEdge(int from, int to) { Edge fromToEdge = new Edge(to, m); Edge toFromEdge = new Edge(from, m + 1); edges.add(fromToEdge); edges.add(toFromEdge); graph[from].add(fromToEdge); graph[to].add(toFromEdge); m += 2; } int time; boolean[] used; int[] tin, up; int[] parents; boolean[] isArticulation; boolean[] findArticulationPoints() { this.isArticulation = new boolean[n]; this.used = new boolean[n]; this.parents = new int[n]; Arrays.fill(parents, -1); this.tin = new int[n]; this.up = new int[n]; this.time = 0; for (int v = 0; v < n; ++v) { if (!used[v]) { articulationDfs(v, -1); } } return isArticulation; } void articulationDfs(int from, int parent) { used[from] = true; parents[from] = parent; ++time; up[from] = tin[from] = time; int childrenCount = 0; for (Edge e : graph[from]) { int to = e.to; if (to == parent) continue; if (used[to]) { up[from] = min(up[from], tin[to]); } else { ++childrenCount; articulationDfs(to, from); up[from] = min(up[from], up[to]); if (up[to] >= tin[from] && parent != -1) { isArticulation[from] = true; } } } if (parent == -1 && childrenCount > 1) { isArticulation[from] = true; } } int[] edgeColors; int maxEdgeColor; int[] paintEdges() { this.edgeColors = new int[m]; Arrays.fill(edgeColors, -1); this.maxEdgeColor = -1; this.used = new boolean[n]; for (int v = 0; v < n; ++v) { if (!used[v]) { ++maxEdgeColor; paintDfs(v, maxEdgeColor, -1); } } return edgeColors; } void paintEdge(int edgeIndex, int color) { if (edgeColors[edgeIndex] != -1) return; edgeColors[edgeIndex] = edgeColors[edgeIndex ^ 1] = color; } void paintDfs(int from, int color, int parent) { used[from] = true; for (Edge e : graph[from]) { int to = e.to; if (to == parent) continue; if (!used[to]) { if (up[to] >= tin[from]) { int newColor = ++maxEdgeColor; paintEdge(e.index, newColor); paintDfs(to, newColor, from); } else { paintEdge(e.index, color); paintDfs(to, color, from); } } else if (up[to] <= tin[from]){ paintEdge(e.index, color); } } } Set<Integer>[] collectVertexEdgeColors() { Set<Integer>[] vertexEdgeColors = new Set[n]; for (int v = 0; v < n; ++v) { vertexEdgeColors[v] = new HashSet<Integer>(); for (Edge e : graph[v]) { vertexEdgeColors[v].add(edgeColors[e.index]); } } return vertexEdgeColors; } VertexBiconnectedGraph build() { findArticulationPoints(); paintEdges(); createComponentsGraph(); return this; } int[][] componentsGraph; void createComponentsGraph() { Set<Integer>[] vertexEdgeColors = collectVertexEdgeColors(); int edgeColorShift = vertexEdgeColors.length; int size = vertexEdgeColors.length + maxEdgeColor + 1; GraphBuilder graphBuilder = GraphBuilder.createInstance(size); for (int v = 0; v < vertexEdgeColors.length; ++v) { for (int edgeColor : vertexEdgeColors[v]) { graphBuilder.addEdge(v, edgeColor + edgeColorShift); } } this.componentsGraph = graphBuilder.build(); } int[][] toGraph() { return componentsGraph; } } ///////////////////////////////////////////////////////////////////// private static class DSU { int[] sizes; int[] ranks; int[] parents; static DSU createInstance(int size) { int[] sizes = new int[size]; Arrays.fill(sizes, 1); return new DSU(sizes); } DSU(int[] sizes) { this.sizes = sizes; int size = sizes.length; this.ranks = new int[size]; Arrays.fill(ranks, 1); this.parents = castInt(order(size)); } int get(int v) { if (v == parents[v]) return v; return parents[v] = get(parents[v]); } boolean union(int a, int b) { a = get(a); b = get(b); if (a == b) return false; if (ranks[a] < ranks[b]) { int tmp = a; a = b; b = tmp; } parents[b] = a; sizes[a] += sizes[b]; if (ranks[a] == ranks[b]) ++ranks[a]; 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; const int oo = 0x3f3f3f3f; const double eps = 1e-9; vector<int> lucky; void generate(long long n) { if (n > 1000000000LL) return; else { generate(n * 10 + 4); generate(n * 10 + 7); if (n > 0) lucky.push_back(n); } } void unrank(vector<int> &perm, int n, long long num) { bool used[n]; memset(used, false, n * sizeof(bool)); long long fak = 1; for (int i = (1); i < (n + 1); ++i) fak *= i; for (int i = (0); i < (n); ++i) { fak /= n - i; int k = num / fak; num = num % fak; int j = 0; while (k >= 0) { if (!used[j]) --k; j++; } perm[i] = j - 1; used[j - 1] = true; } } bool isLucky(int n) { while (n > 0) { int c = n % 10; if (c != 7 && c != 4) return false; n /= 10; } return true; } int main() { int N, M = 0, K; scanf("%d %d", &N, &K); generate(0); long long faculty = 1; for (int i = (1); i < (N + 1); ++i) { faculty *= (M = i); if (faculty >= K) break; } if (faculty < K) { printf("-1\n"); return 0; } vector<int> permutation(M); unrank(permutation, M, K - 1); int res = 0; sort((lucky).begin(), (lucky).end()); int changeIndex = N - M + 1; for (int i = (0); i < (int((lucky).size())); ++i) if (lucky[i] < changeIndex) ++res; for (int i = (changeIndex); i < (N + 1); ++i) { int position = i; int element = changeIndex + permutation[i - changeIndex]; if (isLucky(position) && isLucky(element)) ++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; int N, K, A[14 + 1]; int u[14 + 1]; long long fact[2 * 14 + 1]; vector<long long> all_lucky; void gen_lucky(int x, int len) { if (len == 9) { all_lucky.push_back(x); return; } if (len >= 1) { all_lucky.push_back(x); } gen_lucky(x * 10 + 4, len + 1); gen_lucky(x * 10 + 7, len + 1); } int check_lucky(int lucky) { while (lucky) { if (lucky % 10 != 4 && lucky % 10 != 7) { return 0; } lucky /= 10; } return 1; } int check(int lucky) { if (lucky > N) return 0; if (N <= 14) return check_lucky(A[lucky]); int cutoff = N - 14 + 1; if (lucky >= cutoff) { return check_lucky(A[lucky - cutoff + 1]); } else return 1; } int main() { cin >> N >> K; gen_lucky(0, 0); sort(all_lucky.begin(), all_lucky.end()); fact[0] = 1; for (int i = 1; i <= 14 + 1; ++i) fact[i] = fact[i - 1] * i; int n = N; if (N > 14) N = 14; K--; for (int i = 1; i <= N; ++i) { int at = 0; for (int j = 1; j <= N; ++j) { if (!u[j]) { at++; if (K < fact[N - i]) { u[j] = 1; A[i] = j; goto L1; } K -= fact[N - i]; } } cout << -1 << endl; return 0; L1:; } int res = 0; N = n; if (N > 14) { for (int i = 1; i <= 14; ++i) A[i] = N - 14 + A[i]; } for (int i = 0; i < all_lucky.size(); ++i) { int lucky = all_lucky[i]; res += check(lucky); } cout << res << 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, k, N; int fact[13], p[13], a[13]; int first(int n) { queue<long long> q; q.push(0); int res = -1; while (q.front() <= 1LL * n) { long long cur = q.front(); res++; q.pop(); q.push(10 * cur + 4); q.push(10 * cur + 7); } return res; } int ok(int x) { while (x) { if (!(x % 10 == 4 || x % 10 == 7)) { return 0; } x /= 10; } return 1; } int main() { fact[0] = 1; for (int i = 1; i <= 12; i++) { fact[i] = fact[i - 1] * i; a[i] = i; } a[13] = 13; scanf("%d", &n); scanf("%d", &k); if (n < 13 && fact[n] < k) { puts("-1"); return 0; } N = min(n, 13); k--; for (int i = 1; i <= N; i++) { int l = k / fact[N - i]; k %= fact[N - i]; p[i] = a[l + 1]; for (int j = l + 2; j <= N; j++) a[j - 1] = a[j]; } int ans = 0; if (n <= 13) { for (int i = 1; i <= n; i++) { if ((i == 4 || i == 7) && (p[i] == 4 || p[i] == 7)) ans++; } } else { for (int i = n; i > n - 13; i--) { if (ok(i) && ok(p[i - n + 13] + n - 13)) { ans++; } } ans = ans + first(n - 13); } 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 long double PI = 3.14159265358979323; const long long int linf = 1000111000111000111LL; const long long int inf = 1011111111; const long long int N = 100005; vector<long long int> v1[10], v2; set<long long int> st2; int32_t main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int test = 1; while (test--) { long long int n, k; cin >> n >> k; long long int fac[13]; fac[0] = 1; for (long long int i = 1; i <= 12; i++) fac[i] = fac[i - 1] * i; if (n <= 12) { if (k > fac[n]) { cout << "-1\n"; continue; } } v1[1].push_back(4); v1[1].push_back(7); for (long long int i = 2; i <= 9; i++) { for (long long int j = 0; j < (long long int)(v1[i - 1]).size(); j++) { v1[i].push_back(v1[i - 1][j] * 10 + 4); v1[i].push_back(v1[i - 1][j] * 10 + 7); } } for (long long int i = 1; i <= 9; i++) { for (long long int j = 0; j < (long long int)(v1[i]).size(); j++) { v2.push_back({v1[i][j]}); st2.insert(v1[i][j]); } } long long int ans = 0; if (n > 13) { long long int ele = n - 13; long long int p1 = upper_bound((v2).begin(), (v2).end(), ele) - v2.begin(); ans += p1; } set<long long int> st1; for (long long int i = n; i >= max((long long int)1, n - 12); i--) st1.insert(i); long long int pos = max((long long int)1, n - 12); while (!st1.empty()) { long long int len = (long long int)(st1).size(); long long int q1 = fac[len - 1]; long long int num = k / q1; if (k % q1 != 0) num++; auto it = st1.begin(); for (long long int i = 0; i < num - 1; i++) it++; long long int ele = *it; st1.erase(ele); if (st2.find(ele) != st2.end() and st2.find(pos) != st2.end()) ans++; pos++; k = k % q1; if (k == 0) k = q1; } cout << ans << "\n"; } cerr << '\n' << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms\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
#include <bits/stdc++.h> using namespace std; int lucky[3000], cnt; void dfs(long long now) { if (now > 1000000000) return; if (now) lucky[cnt++] = (int)now; dfs(now * 10 + 4); dfs(now * 10 + 7); } long long fact[20]; int n, m, num[20]; bool flag[20]; int find(int k) { for (int i = 1;; i++) { if (!flag[i]) { k--; if (k == 0) return i; } } } void sol(int n, int m) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { m -= max(1ll, fact[n - i]); if (m <= 0) { num[i] = find(j); flag[num[i]] = true; m += fact[n - i]; break; } } } } bool ck(int i) { while (i) { if (i % 10 != 4 && i % 10 != 7) return false; i /= 10; } return true; } int main() { cnt = 0; dfs(0); fact[0] = 1; for (int i = 1; i <= 15; i++) fact[i] = fact[i - 1] * i; fact[0] = 0; scanf("%d%d", &n, &m); if (n <= 15 && fact[n] < m) { printf("-1\n"); return 0; } for (int i = max(1, n - 14); i <= n; i++) { if (fact[n - i + 1] >= m && fact[n - i] < m) { sol(n - i + 1, m); int ans = 0; for (int j = 0; j < cnt; j++) if (lucky[j] < i) ans++; for (int j = i; j <= n; j++) { if (ck(j) && ck(num[j - i + 1] + i - 1)) ans++; } printf("%d\n", ans); break; } } 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[15]; vector<long long> luckies; long long next(int x) { return *lower_bound(luckies.begin(), luckies.end(), x); } long long to_lucky(int x, int l) { long long res = 0; for (int i = 0; i < (l); ++i) if (x & (1 << i)) res = res * 10 + 4; else res = res * 10 + 7; return res; } class A { public: A() { fact[0] = 1; for (int i = (1); i < (15); ++i) fact[i] = i * fact[i - 1]; } } __A; class B { public: B() { for (int i = 0; i < (11); ++i) for (int j = 0; j < (1 << i); ++j) luckies.push_back(to_lucky(j, i)); sort(luckies.begin(), luckies.end()); } } __B; int res = 0; int offset = 0; vector<int> cutit(int n, int k) { if (n == 0) return vector<int>(); long long base = k / fact[n - 1]; long long mod = k % fact[n - 1]; vector<int> t = cutit(n - 1, mod); t.push_back(base + 1); return t; } vector<int> to_permutation(vector<int>& vi) { vector<int> res; map<int, int> num; reverse(vi.begin(), vi.end()); for (int i = 0; i < (vi.size()); ++i) num[i + offset + 1]; for (int i = 0; i < (vi.size()); ++i) { int d = vi[i]; int v = 0; for (typeof(num.begin()) it = num.begin(); it != num.end(); ++it) { d--; if (d == 0) { v = it->first; num.erase(it); break; } } res.push_back(v); } return res; } int isLucky(int x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } int main() { int n, k; cin >> n >> k; if (n > 14) { offset = n - 14; res = lower_bound(luckies.begin(), luckies.end(), offset) - luckies.begin(); if (next(offset) > offset) res -= 1; n = 14; } if (k > fact[n]) { cout << -1; return 0; } vector<int> vi = cutit(n, k - 1); vi = to_permutation(vi); for (int i = 0; i < (vi.size()); ++i) if (isLucky(vi[i]) && isLucky(i + offset + 1)) res++; cout << 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; int main() { int n, k, count = 0, ch = 0, c = 0; int mas[15] = {1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600}; int isp[1000] = {}, dl = 0; long long int mas2[1030] = { 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 int q = 1, numb = 11, num = 1, w = 0; char mas3[10000] = {}; cin >> n >> k; int start = 1; if (n > 16) { for (w = 0; mas2[w] < n - 16; count++, w++) ; start = n - 16; } for (int j = start; j <= n; j++) { for (; k <= mas[numb]; numb--) ; if (numb + 1 >= n) { cout << "-1"; return 0; } if (numb + 1 == n - j) { if (numb >= 0) { c = ((k - 1) / (mas[numb])); k -= (mas[numb] * c); } } int t = j - dl; for (int i = 0; i < dl; i++) { if (t + c >= isp[i]) c++; } ch = t + c; mas3[j - 1] = ch + 48; if (c > 0) { isp[dl] = ch; dl++; sort(isp, isp + dl); } c = 0; if (j == ch && ch == mas2[w]) { count++; w++; } if (j == mas2[w] && j != ch) { for (int e = 0; ch >= mas2[e]; e++) { if (ch == mas2[e]) count++; } w++; } } cout << count; }
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 int fact[14]; long long int perm[13]; set<long long int> lucky; void genfact() { fact[0] = 1; for (long long int i = 1; i < 14; ++i) fact[i] = i * fact[i - 1]; } void genperm(long long int n, long long int k) { list<long long int> a; n = min(n, 13ll); for (long long int i = 0; i < n; ++i) a.push_back(i + 1); for (long long int i = 0; i < n; ++i) { long long int j = k / fact[n - i - 1]; k %= fact[n - i - 1]; list<long long int>::iterator it = a.begin(); while (j--) it++; perm[i] = *it; a.erase(it); } } long long int getperm(long long int n, long long int i) { if (n <= 13) return perm[i]; else { if (i < n - 13) return i + 1; else return perm[i - n + 13] + n - 13; } } void genlucky(int level, long long int n) { lucky.insert(n * 10 + 4); lucky.insert(n * 10 + 7); if (level == 10) return; genlucky(level + 1, n * 10 + 4); genlucky(level + 1, n * 10 + 7); } int main() { long long int n, k; cin >> n >> k; k--; genfact(); if (n <= 13 && fact[n] <= k) { cout << -1 << endl; } else { genlucky(1, 0); genperm(n, k); long long int res = 0; for (set<long long int>::iterator it = lucky.begin(); it != lucky.end() && *it <= n; ++it) if (lucky.find(getperm(n, *it - 1)) != lucky.end()) ++res; cout << res << 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 t[1500], n, k; long long fac[20], base, tmp, rec[20], Ans; bool used[20]; void init(long long x) { if (x > 1e8) return; t[++t[0]] = x * 10 + 4; init(x * 10 + 4); t[++t[0]] = x * 10 + 7; init(x * 10 + 7); } bool check(long long x) { for (long long i = 1; i <= t[0]; i++) { if (t[i] == x) { return true; } } return false; } int main() { t[0] = 0; init(0); sort(t + 1, t + 1 + t[0]); scanf("%I64d%I64d", &n, &k); Ans = 0; base = 0; if (n > 13) { for (long long i = 1; i <= t[0]; i++) { if (t[i] <= n - 13) Ans++; } base = n - 13; n = 13; } fac[0] = 1; for (long long i = 1; i <= 13; i++) fac[i] = 1LL * fac[i - 1] * i; if (k > fac[n]) { puts("-1"); return 0; } k--; memset(used, false, sizeof(used)); memset(rec, 0, sizeof(rec)); for (long long i = n; i >= 1; i--) { tmp = k / fac[i - 1]; k -= tmp * fac[i - 1]; for (long long j = 1; j <= n; j++) { if (!used[j] && tmp == 0) { used[j] = true; rec[n - i + 1] = j; break; } else if (!used[j]) tmp--; } } for (int i = 1; i <= n; i++) { Ans += (check(base + i) && check(base + rec[i])); } 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; template <class T> T abs(T x) { return x > 0 ? x : (-x); } template <class T> T sqr(T x) { return x * x; } vector<long long> gen() { vector<long long> res; for (int len = 1; len <= 11; ++len) for (int mask = 0; mask < (1 << len); ++mask) { long long cur = 0; for (int i = 0; i < len; ++i) cur = cur * 10LL + (long long)(((mask >> i) & 1) ? 7 : 4); res.push_back(cur); } sort((res).begin(), (res).end()); return res; } long long f[40]; vector<int> solve(int n, int k) { --k; f[0] = 1; for (int i = 1; i < 40; ++i) f[i] = f[i - 1] * (long long)i; if (k >= f[n]) { printf("-1\n"); exit(0); } vector<int> res; vector<int> u(n, 0); for (int i = 0; i < n; ++i) { int cur = 0; while (k >= f[n - i - 1]) ++cur, k -= f[n - i - 1]; int x = 0; while (cur > 0) { if (!u[x]) --cur; ++x; } while (u[x]) ++x; u[x] = true; res.push_back(x); } return res; } int main() { vector<long long> v = gen(); int n, k; cin >> n >> k; int res = 0; for (int i = 0; i < ((int)(v).size()); ++i) if (v[i] < n - 14) ++res; vector<int> w; for (int i = max(n - 14, 1); i <= n; ++i) w.push_back(i); vector<int> p = solve(((int)(w).size()), k); vector<int> ww(((int)(w).size())); for (int i = 0; i < ((int)(w).size()); ++i) ww[i] = w[p[i]]; for (int i = 0; i < ((int)(w).size()); ++i) { int x = max(n - 14, 1) + i; if (!binary_search((v).begin(), (v).end(), (long long)x)) continue; if (!binary_search((v).begin(), (v).end(), (long long)ww[i])) continue; ++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
#include <bits/stdc++.h> using namespace std; long long fac[15]; vector<int> getKthPerm(vector<int> arr, long long k) { if (k == 1) return arr; int n = arr.size(); for (int i = 1; i <= n; i++) { if (k <= fac[n - 1] * i) { vector<int> brr; for (int j = 0; j < n; j++) { if (j + 1 == i) continue; brr.push_back(arr[j]); } vector<int> tmp = getKthPerm(brr, k - fac[n - 1] * i + fac[n - 1]); vector<int> ret; ret.push_back(arr[i - 1]); for (auto x : tmp) { ret.push_back(x); } return ret; } } } vector<int> getLuckyNumbers() { vector<int> ret({4, 7}); for (int i = 1; i < 9; i++) { vector<int> tmp({4, 7}); for (auto x : ret) { tmp.push_back(10 * x + 4); tmp.push_back(10 * x + 7); } ret = tmp; } sort(ret.begin(), ret.end()); return ret; } bool isLucky(int n) { while (n) { int d = n % 10; if (d != 4 && d != 7) return false; n /= 10; } return true; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cout << setprecision(32); long long n, k; cin >> n >> k; fac[0] = 1; for (int i = 1; i < 15; i++) { fac[i] = fac[i - 1] * i; } if (n < 15) { if (fac[n] < k) { cout << -1 << endl; return 0; } vector<int> arr; for (int i = 1; i <= n; i++) { arr.push_back(i); } arr = getKthPerm(arr, k); int ans = 0; if (n >= 4 && isLucky(arr[3])) ans++; if (n >= 7 && isLucky(arr[6])) ans++; cout << ans << endl; } else { vector<int> arr; for (int i = 1; i < 15; i++) { arr.push_back(n - 14 + i); } arr = getKthPerm(arr, k); vector<int> lk = getLuckyNumbers(); int ans = 0; for (auto x : lk) { if (x > n) break; if (x < n - 13) ans++; else if (isLucky(arr[x - n + 13])) 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; int n, kk, ans, a[15]; long long ci[15]; bool ok; bool check(int i) { while (i) { if ((i % 10 != 4) && (i % 10 != 7)) return false; i = i / 10; } return true; } int cal(int r) { long long now = 0; int ans = 0, a[11] = {0}; while (now < r) { int j = 1; while ((j <= a[0]) && (a[j] == 7)) j++; if (j == a[0] + 1) { a[++a[0]] = 4; now += ci[j - 1] * 4; } else { a[j] = 7; now += ci[j - 1] * 3; } for (int i = (1); i <= (j - 1); i++) { a[i] = 4; now -= ci[i - 1] * 3; } if (now <= r) ans++; } return ans; } int main() { scanf("%d%d", &n, &kk); kk--; ci[0] = 1; for (int i = (1); i <= (9); i++) ci[i] = ci[i - 1] * 10; ans += cal(n - 13); for (int i = (max(n - 12, 1)); i <= (n); i++) a[++a[0]] = i; for (int i = (max(n - 12, 1)); i <= (n); i++) { int t = 1; ok = false; for (int j = (1); j <= (n - i); j++) t *= j; for (int k = (1); k <= (a[0]); k++) if (a[k]) if (kk >= t) kk -= t; else { ans += check(i) && check(a[k]); a[k] = 0; ok = true; break; } if (!ok) break; } if (ok) printf("%d", ans); else printf("-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; const int MAX = 20; int n; long long int k, fat[MAX], tmp[MAX]; vector<long long int> lk; int lucky(long long int x) { while (x > 0LL) { long long int a = (x % 10LL); if (a != 4LL && a != 7LL) return 0; x /= 10LL; } return 1; } void lk_gen(int pos) { if (pos == 9) { bool allzero = true, valido = true; for (int i = 0; i < 9; i++) { if (tmp[i] != 0LL) allzero = false; if (tmp[i] == 0LL && allzero == false) valido = false; } if (allzero || !valido) return; long long int x = 0LL, base = 1LL; for (int i = 8; i >= 0; i--) { x += (tmp[i] * base); base *= 10LL; } lk.push_back(x); return; } tmp[pos] = 0LL; lk_gen(pos + 1); tmp[pos] = 4LL; lk_gen(pos + 1); tmp[pos] = 7LL; lk_gen(pos + 1); return; } void solve(int ini) { long long int cnt = k, v[20]; int jump, ans = 0; for (int i = 0; i < n - ini + 1; i++) v[i] = i + ini; for (int i = ini; i <= n; i++) { jump = 1; while (fat[n - i] < cnt) { swap(v[i - ini], v[i + jump - ini]); jump++; cnt -= fat[n - i]; } } for (int i = 0; i < n - ini + 1; i++) if (lucky(i + ini) && lucky(v[i])) ans++; for (int i = (int)lk.size() - 1; i >= 0; i--) { if (lk[i] < ini) { ans += i + 1; break; } } printf("%d\n", ans); } int main() { scanf(" %d %lld", &n, &k); fat[0] = 1; for (int i = 1; i <= 13; i++) fat[i] = (long long int)i * fat[i - 1]; lk.clear(); lk_gen(0); if (n <= 13 && fat[n] < k) printf("-1\n"); else { int ini; for (ini = n; ini >= 0; ini--) if (fat[n - ini + 1] >= k) break; solve(ini); } 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 = 1e5 + 50; const int inf = 0x3f3f3f3f; const int MOD = 1e9 + 7; int n, k; int fac[15] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600}; int Hash[20], p[20]; vector<long long> V; long long trans(string s) { long long res = 0; for (int i = 0; s[i]; i++) res = res * 10 + s[i] - '0'; return res; } void dfs(string p) { if (p.length() == 10) return; V.push_back(trans(p + '4')); V.push_back(trans(p + '7')); dfs(p + '4'); dfs(p + '7'); } void CantorReverse(int index, int t) { index--; int i, j; for (i = 0; i < t; i++) { int tmp = index / fac[t - 1 - i]; for (j = 0; j <= tmp; j++) if (Hash[j]) tmp++; p[i] = tmp + 1; Hash[tmp] = 1; index %= fac[t - 1 - i]; } return; } int main() { cin >> n >> k; if (n <= 12 && k > fac[n]) cout << "-1\n"; else { int amount = 13; for (int i = 1; i <= 12; i++) if (k < fac[i]) { amount = i; break; } CantorReverse(k, amount); int dis = n - amount; dfs(""); sort(V.begin(), V.end()); int i = 0; int ans = 0; for (int i = 0; i < V.size(); i++) { if (V[i] > n) { break; } if (V[i] <= dis) ans++; else { int num = p[V[i] - dis - 1] + dis; for (int j = 0; j < V.size() && V[j] <= n; j++) if (num == V[j]) 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; vector<long long> v; void CalcLucky(long long num, long long limit) { long long temp4; temp4 = num * 10 + 4; long long temp7; temp7 = num * 10 + 7; v.push_back(temp4); v.push_back(temp7); if (temp4 <= limit) CalcLucky(temp4, limit); if (temp7 <= limit) CalcLucky(temp7, limit); } int main() { long long fact[20] = {0}; fact[0] = 1; for (int i = 1; i <= 13; i++) { fact[i] = i * fact[i - 1]; } long long n, k; cin >> n >> k; if (n <= 13) { if (k > fact[n]) { cout << -1 << endl; return 0; } } k = k - 1; long long limit; for (int i = 0; i <= 13; i++) { if (fact[i] > k) { limit = i; break; } } int numbers[20]; int indices[20]; int divisor = 1; for (int place = 1; place <= n; place++) { if ((k / divisor) == 0) break; indices[limit - place] = (k / divisor) % place; divisor *= place; } long long stIn = n - limit + 1; for (int i = 0; i < limit; i++) numbers[i] = stIn + i; for (int i = 0; i < limit; i++) { long long index = indices[i] + i; if (index != i) { long long temp = numbers[index]; for (int j = index; j > i; j--) numbers[j] = numbers[j - 1]; numbers[i] = temp; } } CalcLucky(0, stIn); int LuckyNum = 0; sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) if (v[i] < stIn) LuckyNum++; for (int i = 0; i < limit; i++) { long long index = stIn + i; long long num = numbers[i]; if (binary_search(v.begin(), v.end(), index) && binary_search(v.begin(), v.end(), num)) LuckyNum++; } cout << LuckyNum << 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 static java.lang.Math.* ; import static java.util.Arrays.* ; public class Main { public static void main(String[] args) { new Main().solveProblem(); out.close(); } static Scanner in = new Scanner(new InputStreamReader(System.in)); static PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); long[] fac = new long[21] ; public void solveProblem() { fac[0] = 1 ; for( int i = 1 ; i <= 20 ; i++ ) fac[i] = fac[i-1]*i ; int n = in.nextInt() ; int k = in.nextInt() ; if( n <= 20 && fac[n] < k ){ System.out.println(-1); return ; } int t = 0 ; while( fac[t] < k ) t++ ; //System.out.println( n - t + 1 ); int a = luckyNumberUnder( n - t + 1 ) ; int b = ("" + (n - t + 1)).length() - 1 ; for( int i = 1 ; i <= b ; i++ ) a += (1<<i ) ; int[] perm = new int[t] ; for( int i = 0 ; i < t ; i++ ) perm[i] = n - t + 1 + i ; int[] nperm = berekenPerm( k-1, 0, perm ) ; for( int i = 0 ; i < t ; i++ ) if( isLucky(n-t+1+i) && isLucky(nperm[i])) a++ ; //System.out.println(Arrays.toString(nperm)); System.out.println(a); } private int[] berekenPerm(int k, int i, int[] perm) { int n = perm.length ; if( i == n ) return perm ; sort( perm, i, n) ; int d = (int) (k * ( n - i ) / fac[n-i]) ; //System.out.println((k*(n-i)) + " " + fac[n-i]); int tmp = perm[i+d] ; perm[i+d] = perm[i] ; perm[i] = tmp ; return berekenPerm( (int) (k % fac[n-i-1]), i+1, perm ); } private int luckyNumberUnder(int i) { String s = i + "" ; int a = 0 ; if( s.charAt(0) > '4') a += (1 << s.length()-1) ; if( s.charAt(0) > '7' ) a += (1 << s.length()-1) ; if( s.length() > 1 && (s.charAt(0) == '7' || s.charAt(0) == '4' )) a += luckyNumberUnder( Integer.parseInt(s.substring(1))) ; return a; } boolean isLucky( int get ){ while( get > 0 ){ if( get % 10 != 4 && get % 10 != 7 ) return false ; get /= 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; int n, m, p; long long fac[30]; long long Pow[30]; long long who[30]; int v[30]; set<long long> Set; set<int> Hash; void dfs(int dep, long long now) { if (dep < 0) { Set.insert(now); return; } dfs(dep - 1, now + Pow[dep] * 4); dfs(dep - 1, now + Pow[dep] * 7); } void init() { Pow[0] = 1; for (int i = 1; i < 12; i++) Pow[i] = Pow[i - 1] * 10; Set.clear(); for (int st = 0; st <= 9; st++) dfs(st, 0); } void gao() { Hash.clear(); for (int i = p; i >= 0; i--) { int Num = who[i] + 1; int x = n - p - 1; for (int j = 0; j < Num; j++) { ++x; while (Hash.count(x)) x++; } Hash.insert(x); who[i] = x; } } bool Luck(long long x) { char buf[30]; sprintf(buf, "%I64d", x); int L = strlen(buf); for (int i = 0; i < L; i++) if (buf[i] != '4' && buf[i] != '7') return false; return true; } int main() { init(); cin >> n >> m; m--; fac[0] = 1; for (int i = 1;; i++) { fac[i] = fac[i - 1] * i; if (fac[i] > m) { p = i - 1; break; } } long long tmp = m; for (int i = p; i >= 0; i--) { who[i] = tmp / fac[i]; tmp %= fac[i]; } if (p >= n) { puts("-1"); return 0; } gao(); long long ans = 0; for (int i = 0; i <= p; i++) if (Luck(n - i) && Luck(who[i])) ans++; for (set<long long>::iterator it = Set.begin(); it != Set.end(); it++) if (*it <= n && *it <= n - (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; long long bigmod(long long b, long long p) { if (p == 0) return 1; long long my = bigmod(b, p / 2); my *= my; my %= 1000000007; if (p & 1) my *= b, my %= 1000000007; return my; } int setb(int n, int pos) { return n = n | (1 << pos); } int resb(int n, int pos) { return n = n & ~(1 << pos); } bool checkb(int n, int pos) { return (bool)(n & (1 << pos)); } vector<long long> v; long long n, k, len; void fun(long long sum) { if (sum > 1000000000) return; v.push_back(sum); fun(sum * 10 + 4); fun(sum * 10 + 7); } long long last, ara[20], d, taken[20], place[20], fact[20]; bool oka(long long x) { while (x) { long long my = x % 10; x /= 10; if (!(my == 4 || my == 7)) return 0; } return 1; } long long go() { long long x = k, i, j; for (i = d; i >= 1; i--) { long long val = x / fact[i - 1]; if (x % fact[i - 1]) val++; long long y = 0, idx = 0; for (j = 1; j <= d; j++) { if (taken[j] == 0) y++; if (y == val) { idx = j; break; } } taken[idx] = 1; place[d - i + 1] = idx; x -= ((val - 1) * fact[i - 1]); } long long cnt = 0; if (last) { for (i = 1; i < len; i++) { long long my = v[i]; if (my > last) break; cnt++; } for (i = 1; i <= d; i++) { long long my = place[i] + last; long long pos = last + i; if (oka(pos) && oka(my)) cnt++; } return cnt; } else { for (i = 1; i <= d; i++) { long long my = place[i] + last; long long pos = last + i; if (oka(pos) && oka(my)) cnt++; } return cnt; } } int main() { fun(0); len = v.size(); sort(v.begin(), v.end()); long long i; fact[0] = 1; for (i = 1; i <= 16; i++) fact[i] = fact[i - 1] * i; scanf("%lld %lld", &n, &k); if (n <= 15) { if (fact[n] < k) { puts("-1"); return 0; } } if (n <= 15) { for (i = 1; i <= n; i++) ara[i] = i; d = n; long long ret = go(); printf("%lld", ret); printf("\n"); } else { last = n - 15; for (i = 1; i <= 15; i++) ara[i] = i; d = 15; long long ret = go(); printf("%lld", ret); printf("\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 N = 4e3 + 5; const long long mod = 1e9 + 7; long long power(long long a, long long b, long long c) { long long ret = 1; while (b > 0) { if (b % 2 == 1) ret = (ret * a) % c; b /= 2; a = (a * a) % c; } return ret; } int fact[13]; vector<int> values; void pre() { fact[1] = fact[0] = 1; for (int i = 2; i <= 12; i++) { fact[i] = fact[i - 1] * i; } } void func(int ind, int val) { if (ind == 9) return; values.push_back(val * 10 + 4); values.push_back(val * 10 + 7); func(ind + 1, val * 10 + 4); func(ind + 1, val * 10 + 7); } int main() { pre(); int n, k; cin >> n >> k; k--; func(0, 0); set<int> se; sort(values.begin(), values.end()); for (int it : values) { se.insert(it); } vector<int> vec, res; int fl = -1; if (n <= 12 and fact[n] <= k) { cout << "-1\n"; return 0; } for (int i = 12; i >= 0; i--) { if (k >= fact[i]) { if (fl == -1) { for (int j = 0; j <= i; j++) { vec.push_back(j + 1); } fl = i; } int times = k / fact[i]; res.push_back(vec[times] + n - fl - 1); vec.erase(vec.begin() + times, vec.begin() + times + 1); k -= times * fact[i]; } else if (fl >= 0) { res.push_back(vec[0] + n - fl - 1); vec.erase(vec.begin(), vec.begin() + 1); } } int ret = 0; for (int it : values) { if (it < n - fl) { ret++; } } int ind = n - fl; for (auto it : res) { if (se.find(it) != se.end() and se.find(ind) != se.end()) { ret++; } ind++; } 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; const int N = 2005; long long is_luck[N]; long long permu[20]; int get_luck(); int get_permu(long long, long long, long long, long long); bool judge_luck(long long); int main() { long long n, m, res = 0; cin >> n >> m; int cnt = 0; cnt = get_luck(); long long remain = 1, data = 1; while (data < m) { data *= (remain++); } remain--; if (remain > n) { puts("-1"); return 0; } long long end = n - remain; for (int i = 0; i < cnt; i++) { if (is_luck[i] <= end) res++; else break; } cnt = get_permu(remain, end + 1, m - 1, data); for (int i = 0; i < cnt; i++) { if (judge_luck(permu[i]) && judge_luck(i + end + 1)) res++; } cout << res << endl; return 0; } int get_luck() { int cnt = 0; is_luck[cnt++] = 4; is_luck[cnt++] = 7; for (int i = 0; i < cnt; i++) { if (is_luck[cnt - 1] > (1e9)) break; else { is_luck[cnt++] = (is_luck[i] * 10 + 4); is_luck[cnt++] = (is_luck[i] * 10 + 7); } } return cnt; } int get_permu(long long num, long long begin, long long m, long long data) { int cnt = 0; set<long long> choice; for (int i = 0; i < num; i++) choice.insert(begin + i); for (int i = num; i > 0; i--) { data /= i; int pos = m / (data); m -= (pos) * (data); set<long long>::iterator it = choice.begin(); while (it != choice.end() && pos) { it++; pos--; }; permu[cnt++] = (*it); choice.erase(it); } return cnt; } bool judge_luck(long long n) { while (n) { if (n % 10 != 4 && n % 10 != 7) return false; else n /= 10; } return true; }
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.lang.reflect.Array; import java.util.*; public class Main { static BufferedReader newInput() throws IOException { return new BufferedReader(new InputStreamReader(System.in)); } static PrintWriter newOutput() throws IOException { return new PrintWriter(System.out); } public static void main(String[] args) throws IOException { BufferedReader in = newInput(); PrintWriter out = newOutput(); function(in, out); out.flush(); } public static void function(BufferedReader in, PrintWriter out) throws IOException { //StringTokenizer t = new StringTokenizer(in.readLine()); String[] nk = in.readLine().split(" "); long n = Integer.parseInt(nk[0]); long k = Long.parseLong(nk[1]); ArrayList<Integer> nums = new ArrayList<>(); for (int i = Math.max(1, (int)n-13); i <= (int)n; i++) { nums.add(i); } long fact = factorial(Math.min(n, 14)); long x = Math.min(n, 14); int lucks = lucks(Math.max(1, (int)n-13)); for (int i = Math.max(1, (int)n-13); i <= n; i++) { fact /= x; x--; int b = (int)((k-1)/fact); if (b >= n){ out.println("-1"); return; } k -= (b*fact); int num = nums.get(b); nums.remove(b); if (isLucky(num) && isLucky(i)){ lucks++; } } out.println(lucks); } public static long factorial(long num){ long x = num; num--; for (;num != 0; num--) { x *= num; } return x; } public static boolean isLucky(int x){ for (; x != 0; x /= 10) { int b = x % 10; if (b != 7 && b != 4){ return false; } } return true; } public static int lucks(int max){ int lucks = 0; ArrayList<Integer> luckys = new ArrayList<>(); luckys.add(4); luckys.add(7); for (int i = 0; i < 8; i++) { luckys = add(luckys); } for (int i : luckys) { if (i < max){ lucks++; } } return lucks; } public static int prev = 0; public static ArrayList<Integer> add(ArrayList<Integer> lucks){ int len = lucks.size(); for (int i = prev; i < len; i++) { lucks.add(lucks.get(i)+(int)(4*Math.pow(10, String.valueOf(lucks.get(i)).length()))); } for (int i = prev; i < len; i++) { lucks.add(lucks.get(i)+(int)(7*Math.pow(10, String.valueOf(lucks.get(i)).length()))); } prev = len; return lucks; } }
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 javax.sound.sampled.Line; import java.awt.Point; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import static java.math.BigInteger.*; import java.math.MathContext; import java.util.*; public class C{ void testIt() { Random rand=new Random(); for(int test=1;;test++) { int n=Math.abs(rand.nextInt()%1000000000)+1; long k=Math.abs(rand.nextInt()%1000000000)+1; System.out.println(test+" "+n+" "+k); long cur=doIt( n,k); System.out.println(cur); } } private long doIt(int n, long k) { all=new ArrayList<Long>(); get(0,(long)7777777777L); Collections.sort(all); ArrayList<Integer>a=new ArrayList<Integer>(); long z=1; for(int i=1;i<=n;i++) { z*=i; if(z>=k) break; } if(z<k) { return -1; } while (a.size()<15 && n>0) { a.add(n); n--; } Collections.reverse(a); int res=0; for(Long x: all) if(x<=n) res++; long[]fact=new long[a.size()]; for(int i=0;i<fact.length;i++) if(i==0) fact[i]=1; else fact[i]=i*fact[i-1]; boolean []used=new boolean[a.size()]; int[]x=new int[used.length]; for(int at=0;at<a.size();at++) { long who=0; while (k>fact[a.size()-1-at]) { k-=fact[a.size()-1-at]; who++; } int ans=-1; for(int i=0;i<a.size();i++) if(!used[i]) { who--; if(who==-1) { ans=i; break; } } used[ans]=true; x[at]=a.get(ans); //System.out.println(x[at]); } for(int i=0;i<a.size();i++) { if(all.indexOf((long)x[i])>=0 && all.indexOf((long)(i+1+n))>=0) res++; } return res; } ArrayList<Long>all; void solve()throws Exception { int n=nextInt(); long k=nextInt(); System.out.println(doIt(n,k)); } void get(long cur,long max) { if(cur>max) return; if(cur!=0) all.add(cur); get(10*cur+4,max); get(10*cur+7,max); } //////////// BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); stk=null; writer=new PrintWriter(new PrintWriter(System.out)); solve(); reader.close(); writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]args) throws Exception { new 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; long long n, k, num = 1; long long kol = 1, RES = 0; vector<int> mas, other; vector<int> all; int main() { cin >> n >> k; long long num = 4; while (num <= n) { all.push_back(num); string s = ""; int nn = num; while (nn) { if (nn % 10 == 4) s = s + '4'; else s = s + '7'; nn /= 10; } reverse(s.begin(), s.end()); int ch = -1; for (int i = 0; i < s.length(); ++i) if (s[i] == '4') ch = i; if (ch == -1) { for (int i = 0; i < s.length(); ++i) s[i] = '4'; s = s + '4'; } else { s[ch] = '7'; for (int i = ch + 1; i < s.length(); ++i) s[i] = '4'; } num = 0; for (int i = 0; i < s.length(); ++i) num = num * 10 + (int)(s[i] - '0'); } if (k == 1) { cout << all.size(); return 0; } num = 1; while (num * kol < k) { num *= kol; ++kol; } if (kol > n) { cout << -1; return 0; } for (int i = 0; i < all.size(); ++i) { if (all[i] > n - kol) break; ++RES; } for (int i = n - kol; i < n; ++i) other.push_back(i + 1); while (true) { int p = k / num; if (k % num) ++p; if (p == 0) { for (int i = other.size() - 1; i >= 0; --i) mas.push_back(other[i]); break; } mas.push_back(other[p - 1]); other.erase(other.begin() + p - 1); --kol; k = k % num; num /= kol; if (kol == 0) break; } for (int i = 0; i < all.size(); ++i) { int ch; if (all[i] - (n - mas.size()) - 1 >= 0) ch = mas[all[i] - (n - mas.size()) - 1]; for (int j = 0; j < all.size(); ++j) if (ch == all[j]) ++RES; } cout << 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; const double pi = acos(-1.0); vector<long long> a; int main() { for (int _b = (10), len = (1); len <= _b; len++) for (int mask = 0, _n = (1 << len); mask < _n; mask++) { long long x = 0; for (int i = (len)-1; i >= 0; i--) x = x * 10 + ((mask & (1 << i)) ? 7 : 4); a.push_back(x); } sort((a).begin(), (a).end()); int n, k; cin >> n >> k; int suflen = min(n, 13); long long suffact = 1; for (int _b = (suflen), i = (1); i <= _b; i++) suffact *= i; if (k > suffact) { printf("-1\n"); return 0; } vector<int> left; for (int i = 0, _n = (suflen); i < _n; i++) left.push_back(i); --k; long long fact = suffact; int res = upper_bound((a).begin(), (a).end(), n - suflen) - a.begin(); for (int i = 0, _n = (suflen); i < _n; i++) { fact /= (suflen - i); int ord = k / fact; k -= fact * ord; int val = left[ord]; if (binary_search((a).begin(), (a).end(), n - suflen + i + 1) && binary_search((a).begin(), (a).end(), n - suflen + val + 1)) ++res; left.erase(left.begin() + ord); } 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; struct FenwickT { long long t[2100]; void add(long long i, long long val) { for (; i < 2100; i += ((i) & (-i))) t[i] += val; } long long query(long long i) { long long sol = 0; for (; i > 0; i -= ((i) & (-i))) sol += t[i]; return sol; } }; struct FN { long long num[2100], len, per[2100]; FN() { memset(num, 0, sizeof num); memset(per, 0, sizeof per); len = 0; } FN(long long *per, long long n) { len = n; memset(num, 0, sizeof num); FenwickT t = FenwickT(); for (long long i = 1; i <= n; i++) t.add(i, 1); for (long long i = 0; i < n; i++) { long long k = t.query(per[i] + 1); num[i] = k - 1; t.add(per[i] + 1, -1); } } FN(long long idx, long long n) { memset(num, 0, sizeof num); long long iter = 1; do { long long val = idx % iter; num[iter - 1] = val; idx /= iter++; } while (idx > 0); reverse(num, num + n); len = n; } long long get_idx() { long long sol = 0; for (long long i = 0; i < len; i++) sol = sol * (len - i) + num[i]; return sol; } void find_per() { FenwickT t = FenwickT(); for (long long i = 1; i <= len; i++) t.add(i, 1); for (long long i = 0; i < len; i++) { long long lo = 1, hi = len; long long k = num[i] + 1; while (lo < hi) { long long mid = (lo + hi) >> 1; long long q = t.query(mid); if (q >= k) hi = mid; else lo = mid + 1; } per[i] = lo - 1; t.add(lo, -1); } } FN operator+(const FN &o) const { FN sol = FN(); long long add = 0, carrie = 0; for (long long i = len - 1; i >= 0; i--) { add = (num[i] + o.num[i] + carrie) % (len - i); sol.num[i] = add; carrie = (num[i] + o.num[i] + carrie) / (len - i); } sol.len = len; return sol; } void prll() { for (long long J = 0; J < (len); J++) cout << (num)[J] << " \n"[J == (len)-1]; } }; vector<long long> s; const long long oo = 1e10 + 10; void solve(long long x) { if (x > oo) return; if (x > 0) s.push_back(x); solve(x * 10 + 4); solve(x * 10 + 7); } bool is(long long x) { if (x == 0) return false; while (x > 0) { if (x % 10 != 7 && (x % 10 != 4)) return false; x /= 10; } return true; } long long n, k; int main() { ios::sync_with_stdio(0); solve(0); sort(s.begin(), s.end()); cin >> n >> k; long long len = -1; if (n <= 14) { long long fact = 1; for (long long i = 1; i <= n; i++) fact *= i; if (k > fact) { cout << -1 << endl; return 0; } } long long fact = 1; for (long long i = 1; i <= n; i++) { fact *= i; if (fact >= k) { len = i; break; } } long long sol = 0; for (long long i = 0; i < s.size(); i++) { if (s[i] <= n - len) sol++; } FN fx = FN(k - 1, len); fx.find_per(); long long iter = 0; for (long long i = n - len + 1; i <= n; i++, iter++) { long long val = n - len + 1 + fx.per[iter]; if (is(val) && is(i)) sol++; } cout << sol << 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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.TreeSet; public class LuckyPermutation { static class Scanner{ BufferedReader br=null; StringTokenizer tk=null; public Scanner(){ br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException{ while(tk==null || !tk.hasMoreTokens()) tk=new StringTokenizer(br.readLine()); return tk.nextToken(); } public int nextInt() throws NumberFormatException, IOException{ return Integer.valueOf(next()); } } static long[] fact = new long[14]; static TreeSet<Long> set = new TreeSet<Long>(); static void init(){ fact[0] = 1; for(int i = 1; i <= 13; i++) fact[i] = fact[i - 1]*i; for(int tam = 1; tam <= 11; tam++){ for(int i = 0; i < (1<<tam); i++){ long num = 0; for(int k = tam - 1; k >= 0; k--){ int n= ( (((i>>k) & 1) == 1)? 7: 4); num *= 10; num += n; } set.add(num); } } return; } public static void main(String args[]) throws NumberFormatException, IOException{ Scanner sc = new Scanner(); init(); int N = sc.nextInt(); int K = sc.nextInt(); LinkedList<Integer> ans = new LinkedList<Integer>(); if (N <= 13 && fact[N] < K){ System.out.println("-1"); return; } int amount = 0; long left = 1; long right = N - 13; for(long lucky: set){ if (lucky>= left && lucky<=right) amount++; } TreeSet<Integer> current = new TreeSet<Integer>(); for(int i = Math.max(1, N - 12); i <= N; i++) current.add(i); int limit = current.size(); for(int i = 0; i < limit; i++){ int index = 1; for(int e: current){ if (fact[current.size() - 1]*index >= K){ K -= fact[current.size() - 1] * (index - 1); current.remove(e); ans.add(e); break; } index++; } } int pos = Math.max(N - 12,1); for(int e: ans){ if (set.contains(pos + 0L) && set.contains(e + 0L)) amount++; pos++; } System.out.println(amount); } }
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> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,ssse3,sse3,sse4,popcnt,avx,mmx,abm,tune=native") using namespace std; long long n, k, cnt, i, f[20] = {1, 1}, j; vector<long long> vec, rem; set<long long> luck; void gen(long long n, long long tot) { if (n == -1) vec.push_back(tot), luck.insert(tot); else { gen(n - 1, tot * 10 + 4LL); gen(n - 1, tot * 10 + 7LL); } } int main() { scanf("%lld%lld", &n, &k); for (i = 2; i <= 15; i++) f[i] = f[i - 1] * i; for (i = 0; i <= 10; i++) gen(i, 0); for (auto v : vec) { if (v < n - 15) cnt++; } long long tot = 1; for (i = max(1LL, n - 15); i <= n; i++) rem.push_back(i); for (i = max(1LL, n - 15); i <= n; i++) { for (j = 0; j < 20; j++) { if (tot + j * f[n - i] > k) { tot += (--j) * f[n - i]; break; } } if (j >= rem.size()) { printf("-1\n"); return 0; } if (luck.find(i) != luck.end() && luck.find(rem[j]) != luck.end()) cnt++; rem.erase(rem.begin() + j); } printf("%lld\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
#include <bits/stdc++.h> using namespace std; int n, k; int ans = 0; long long fac[30]; map<int, bool> M; bool checklucky(long long x) { for (; x; x /= 10) if (x % 10 != 4 && x % 10 != 7) return 0; return 1; } int check(int cur) { if (cur < max(n - 20 + 1, 1)) return checklucky(cur); int tmp = k; M.clear(); for (int i = max(n - 20 + 1, 1); i <= cur; i++) { int x = max(n - 20 + 1, 1); while (M[x]) x++; while (tmp > fac[n - i]) { x++; tmp -= fac[n - i]; while (M[x]) x++; } M[x] = 1; if (i == cur) return checklucky(x); } } void dfs(long long cur) { if (cur > n) return; ans += check(cur); dfs(cur * 10 + 4); dfs(cur * 10 + 7); } int main() { fac[0] = 1; for (int i = 1; i <= 23; i++) fac[i] = fac[i - 1] * i; cin >> n >> k; dfs(4); dfs(7); if (n <= 18 && k > fac[n]) { puts("-1"); return 0; } 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 fact[22] = {1}; vector<int> solve(int n, long long k) { int i, j, r; vector<int> ans; set<int> st; for (i = n - 1; i >= 0; i--) { int t = (k - 1) / fact[i] + 1; k -= (t - 1) * fact[i]; r = 0; for (j = 1; j <= n; j++) if (st.find(j) == st.end()) { r++; if (r == t) break; } ans.push_back(j); st.insert(j); } return ans; } long long luck[2024]; int size = 0; void back(int i, long long num) { if (i > 8) return; luck[size++] = num; back(i + 1, 10 * num + 4); back(i + 1, 10 * num + 7); } int go(int n) { int i; for (i = 0; luck[i] <= n; i++) ; return i; } bool islucky(int n) { while (n != 0) { if (!(n % 10 == 4 || n % 10 == 7)) return false; n /= 10; } return true; } int main() { int n, i, j, r, ans = 0; long long k; back(0, 4); back(0, 7); luck[size++] = 4444444444L; sort(luck, luck + size); for (i = 1; i <= 18; i++) fact[i] = i * fact[i - 1]; cin >> n >> k; if (n < 15) { if (k > fact[n]) { cout << -1 << endl; return 0; } } vector<int> ans1; if (n > 13) { ans1 = solve(13, k); for (i = 0; i < 13; i++) { if (islucky(i + n - 13 + 1) && islucky(ans1[i] + n - 13)) ans++; } ans += go(n - 13); } else { ans1 = solve(n, k); for (i = 0; i < n; i++) { if (islucky(i + 1) && islucky(ans1[i])) 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; const long long maxn = 14; long long f[maxn]; long long n, k, ANS; vector<long long> ans; vector<long long> v, p; bool is(long long a) { while (a) { if (a % 10 != 4 && a % 10 != 7) { return false; } a /= 10; } return true; } int32_t main() { cin >> n >> k; v.push_back(0); p.push_back(0); while (v.back() < 1000000005) { vector<long long> tmp; for (long long i : p) { v.push_back((i * 10) + 4); tmp.push_back((i * 10) + 4); v.push_back((i * 10) + 7); tmp.push_back((i * 10) + 7); } p.clear(); p = tmp; } f[0] = 1; f[1] = 1; for (long long i = 2; i < maxn; i++) f[i] = f[i - 1] * i; if (n < 14) if (f[n] < k) return cout << -1, 0; set<long long> st; for (long long i = max(1LL, n - 12); i <= n; i++) { st.insert(i); } for (long long i = max(1LL, n - 12); i <= n; i++) { if (!k) break; long long j = n - i; long long l = 0; while (f[j] < k) { l++; k -= f[j]; } auto it = st.begin(); for (long long tmp = 0; tmp < l; tmp++) it++; ans.push_back(*(it)); st.erase(*(it)); } if (n > 13) { long long now = n - 13; auto it = upper_bound(v.begin(), v.end(), now); long long x = distance(v.begin(), it); ANS += x - 1; } for (long long i = 0; i < ans.size(); i++) { long long cnt = 0; if (n > 13) cnt = n - 13; if (is(i + 1 + cnt) && is(ans[i])) 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; const long long SQ = 100000; const long long MAXN = SQ * SQ; long long fact[100]; void init() { fact[0] = 1; for (long long i = 1; fact[i - 1] < MAXN; i++) fact[i] = fact[i - 1] * i; } long long p[100]; void k_perm(long long n, long long k) { k--; for (long long i = 1; i <= n; i++) { long long s = (long long)(k / fact[n - i]); long long t = p[i + s]; for (long long j = i + s; j > i; j--) p[j] = p[j - 1]; p[i] = t; k %= fact[n - i]; } } bool lucky(long long n) { while (n) { if (n % 10 != 4 && n % 10 != 7) return false; n /= 10; } return true; } deque<long long> tod(long long n) { deque<long long> d; do { d.push_front(n % 10); n /= 10; } while (n); return d; } long long toi(const deque<long long>& d) { long long k = 0; for (size_t i = 0; i < d.size(); i++) k *= 10, k += d[i]; return k; } long long next(long long n) { deque<long long> d = tod(n); for (long long i = 0; i < (long long)d.size(); i++) if (d[i] > 7) { for (long long j = i + 1; j < (long long)d.size(); j++) d[j] = 4; while (i >= 0 && d[i] > 7) { d[i] = 4; if (i) d[i - 1]++; else d.push_front(1); i--; } break; } for (long long i = 0; i < (long long)d.size(); i++) { if (d[i] > 7) throw 1; if (d[i] == 4 || d[i] == 7) continue; while (d[i] != 4 && d[i] != 7) d[i]++; for (long long j = i + 1; j < (long long)d.size(); j++) d[j] = 4; break; } return toi(d); } long long number_lucky(long long n) { long long s = 0; for (long long i = 4; i <= n; i = next(++i)) s++; return s; } int main() { long long n, k, s = 0; init(); cin >> n >> k; if (n <= 13 && k > fact[n]) s = -1; else if (n <= 13) { for (long long i = 1; i <= n; i++) p[i] = i; k_perm(n, k); for (long long i = 1; i <= n; i++) if (lucky(i) && lucky(p[i])) s++; } else { for (long long i = 1; i <= 13; i++) p[i] = n - 13 + i; k_perm(13, k); for (long long i = 1; i <= 13; i++) if (lucky(n - 13 + i) && lucky(p[i])) s++; s += number_lucky(n - 13); } cout << s << '\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; vector<long long> sil(14); vector<long long> lucky; set<long long> luckyS; void gen() { for (int i = 1; i <= 10; ++i) { for (int j = 0; j < (1LL << i); ++j) { long long x = 0; for (int k = 0; k < i; ++k) { if ((j & (1LL << k)) > 0) x = x * 10 + 4; else x = x * 10 + 7; } lucky.push_back(x); luckyS.insert(x); } } } int main() { ios_base::sync_with_stdio(0); sil[0] = 1; for (int i = 1; i < 14; ++i) sil[i] = sil[i - 1] * i; long long n, k; cin >> n >> k; if (n <= 13 && k > sil[n]) { cout << "-1"; return 0; } gen(); int norm = 0; if (n > 14) norm = n - 14; int odp = 0; if (norm != 0) for (int i = 0; i < lucky.size(); ++i) if (lucky[i] <= norm) ++odp; map<int, int> M; vector<int> zb; for (int i = norm + 1; i <= n; ++i) { zb.push_back(i); M[i] = -1; } for (int i = norm + 1; i <= n; ++i) { int suf = n - i; int nr = (k - 1) / sil[suf]; M[i] = zb[nr]; k -= nr * sil[suf]; vector<int> t; for (int j = 0; j < zb.size(); ++j) if (j != nr) t.push_back(zb[j]); sort(t.begin(), t.end()); zb = t; } for (int i = norm + 1; i <= n; ++i) if (luckyS.find(i) != luckyS.end() && luckyS.find(M[i]) != luckyS.end()) ++odp; cout << odp; 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_nums; vector<int> datos; vector<long long> factorial; set<long long> numeros; int idx_cambio; void obten_lucky(int n) { numeros.insert(0); for (int i = 0; i < 10; ++i) { set<long long> temp = numeros; for (const auto& act : temp) { long long nuevo; nuevo = act * 10 + 7; if (nuevo <= n) numeros.insert(nuevo); nuevo = act * 10 + 4; if (nuevo <= n) numeros.insert(nuevo); } } numeros.erase(0); for (const auto& act : numeros) { lucky_nums.push_back(act); } } int toma(vector<int>& disponibles, int idx) { int resp = disponibles[idx]; for (int i = idx; i < disponibles.size() - 1; ++i) { disponibles[i] = disponibles[i + 1]; } disponibles.pop_back(); return resp; } void init(int n, int k) { factorial.push_back(1); for (int i = 0; i < 14; ++i) { factorial.push_back(factorial[i] * (i + 1LL)); } if (n <= 13) { if (factorial[n] < k) { cout << "-1\n"; exit(0); } } obten_lucky(n); long long acc = 1; idx_cambio = 0; do { idx_cambio++; acc = acc * (long long)idx_cambio; } while (acc < k); datos.resize(idx_cambio); int restantes = idx_cambio - 1; vector<int> disponibles(idx_cambio); for (int i = 0; i < idx_cambio; ++i) { disponibles[i] = i; } for (int i = 0; i < idx_cambio; ++i) { int num_act = (k + factorial[restantes] - 1) / factorial[restantes]; datos[i] = num_act; k -= (num_act - 1) * factorial[restantes]; datos[i] = toma(disponibles, num_act - 1); restantes--; } int temp = idx_cambio; idx_cambio = n - idx_cambio + 1; for (int i = 0; i < temp; ++i) { datos[i] += idx_cambio; } } int obten_val(int n, int k, int idx) { if (idx < idx_cambio) { return idx; } return datos[idx - idx_cambio]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; init(n, k); int resp = 0; for (const auto& idx : lucky_nums) { resp += (numeros.find(obten_val(n, k, idx)) != numeros.end()); } cout << resp << '\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 long long inf = 1000ll * 1000 * 1000; const int size = 100; long long smb, n, k; int ans; bool used[size]; int perm[size]; void genthemall(long long num) { if (num > inf) return; if (num <= n - 15 && num >= 1) ans++; genthemall(num * 10 + 4); genthemall(num * 10 + 7); } bool islucky(long long num) { if (num == 0) return false; while (num > 0) { if (num % 10 != 4 && num % 10 != 7) return false; num /= 10; } return true; } int main() { cin >> n >> k; long long fct = 1; int h = min(n, 15ll), i, j; for (i = 1; i <= h; i++) fct *= i; if (fct < k) { cout << -1 << endl; return 0; } smb = 15; ans = 0; genthemall(0); for (i = 0; i < h; i++) used[i] = false; for (i = 0; i < h; i++) { fct /= (h - i); for (j = 0; j < h; j++) if (!used[j]) if (fct >= k) { used[j] = true; perm[i] = j; break; } else k -= fct; ans += islucky(n - h + i + 1) && islucky(n - h + perm[i] + 1); } 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.*; public class d { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(), k = input.nextInt(); if(n < 15) { long f = 1; for(int i = 2; i<=n; i++) f *= i; if(f < k) { System.out.println(-1); return; } } findLucky(); int rest = n - 15; int res = countLuckyBelow(rest); long[] fs = new long[16]; fs[0] = 1; for(int i = 1; i<fs.length; i++) fs[i] = fs[i-1] * i; int m = Math.min(n, 15); boolean[] luck = new boolean[m]; for(int i = 0; i<m; i++) { if(lucky(n-i)) luck[m-1-i] = true; } boolean[] used = new boolean[m]; for(int i = 0; i<m; i++) { long fact = fs[m-i-1]; for(int j = 0; j<m; j++) { if(used[j]) continue; if(k > fact) k -= fact; else { used[j] = true; if(luck[i] && lucky(n-m+1+j)) res++; break; } } } System.out.println(res); } static boolean lucky(int n) { while(n>0) { if(n%10 != 4 && n%10 != 7) return false; n /= 10; } return true; } static void findLucky() { lucky = new ArrayList<Integer>(); lucky.add(4); lucky.add(7); ArrayList<Integer> cur = new ArrayList<Integer>(); cur.add(4); cur.add(7); for(int i = 0; i<8; i++) { ArrayList<Integer> next = new ArrayList<Integer>(); for(int x : cur) { next.add(10*x+4); next.add(10*x+7); } for(int x : next) { lucky.add(x); } cur = next; } } static ArrayList<Integer> lucky; static int countLuckyBelow(int x) { int res = 0; for(int k : lucky) { if(k <= x) res++; } 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
F = [1]; while len(F) <= 13: F.append(F[-1]*len(F)); def get_perm(k,S): if k >= F[len(S)]: print -1; exit(0); P = []; while k: i = 0; while F[len(S)-1]*(i+1) <= k: i += 1; k -= F[len(S)-1]*i; P.append(S[i]); S.pop(i); P += S; return P; q = [0]; lucky = []; while len(q): u = q.pop(0); if u > 10**9: continue; if u: lucky.append(u); q.append(u*10 + 4); q.append(u*10 + 7); n,k = map(int,raw_input().split()); k -= 1; while len(lucky) and lucky[-1] > n: lucky.pop(); L = min(13,n); s = n - L + 1; e = n; ans = 0; while len(lucky) and lucky[0] < s: ans += 1; lucky.pop(0); P = get_perm(k,range(s,e+1)); for i in xrange(L): if (i + s) in lucky and P[i] in lucky: ans += 1; print ans;
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
#include <bits/stdc++.h> using namespace std; template <class T> void pv(ostream &out, T a, T b) { for (T i = a; i != b; ++i) { out << *i << " "; } out << endl; } template <class T> void pvp(ostream &out, T a, T b) { for (T i = a; i != b; ++i) { out << "(" << i->first << ", " << i->second << ") "; } out << endl; } const int INF = numeric_limits<int>::max(); const double EPS = 1e-9; vector<long long> a, perm; vector<bool> used; long long get_next(long long a) { int d = 1; while (a) { if (a % 10 == 4) { a += 3; d--; break; } a /= 10; d++; } for (int i = 0; i < d; ++i) { a *= 10; a += 4; } return a; } int fact(int a) { int res = 1; for (int i = 2; i <= a; ++i) { res *= i; } return res; } int main() { int n, k; cin >> n >> k; long long cur = 4; while (cur <= n) { a.push_back(cur); cur = get_next(cur); } long long f = 1, d = 0; for (int i = 2; i < 1000; ++i) { if (f >= k) { d = i - 1; break; } f *= i; } if (k == 1) { d = 0; } if (d > n) { cout << -1 << endl; } else { int safe = n - d; int ans = int(lower_bound(a.begin(), a.end(), (long long)safe) - a.begin()); if (ans < a.size() && a[ans] == safe) { ans++; } perm.resize(d); used.assign(d, false); int n = d; int m = k - 1; for (int i = 0; i < n; ++i) { int f = fact(n - i - 1); int j = m / f; m -= j * f; for (int k = 0; k < n; ++k) { if (!used[k]) { if (j-- == 0) { perm[i] = k + 1; used[k] = true; break; } } } } for (int i = 0; i < n; ++i) { int x = int(lower_bound(a.begin(), a.end(), perm[i] + safe) - a.begin()); int y = int(lower_bound(a.begin(), a.end(), i + 1 + safe) - a.begin()); if (a[x] == perm[i] + safe && a[y] == i + 1 + safe) { 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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; public class Solution{ public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { long n = fs.nextLong(), k = fs.nextLong(); long ans = 0; long first = Math.max(1, n-12); ans += getLucky(first-1); long[] fact = new long[15]; fact[0] = 1; for(int i=1;i<15;i++) fact[i] = fact[i-1]*i; HashSet<Long> set = new HashSet<>(); long pos = first; if(k>fact[(int)(n-pos+1)]) { out.println(-1); out.flush(); return; } for(long p=pos; p<=n;p++) { for(long i=first;i<=n;i++) { if(!set.contains(i)) { long f = fact[(int)(n-p)]; if(f<k) { k -= f; } else { set.add(i); ans += (isLucky(i)&&isLucky(p))?1:0; if(p==n) k--; break; } int l = 1; } } } if(k>0) { out.println(-1); } else { out.println(ans); } } out.close(); } static boolean isLucky(long n) { while(n>0) { int d = (int)n%10; if(!(d==4 || d==7)) return false; n /= 10; } return true; } static long getLucky(long num) { if(num==0) return 0; int d = getDigit(num); long cnt = (1L<<d)-2; long p = 1; for(int i=0;i<d-1;i++) p *= 10; long k = 0; for(int i=d-1;i>=0;i--) { int dig = ((int)(num/(p)))%10; if(i==0) { if(dig>=7) k+= 2; else if(dig>=4) k+= 1; break; } if(dig>7) { k += (1L<<(i+1)); break; } else if(dig==7) { k += (1L<<i); } else if(dig>4) { k += (1L<<i); break; } else if(dig<4) { break; } p /= 10; } cnt += k; return cnt; } static int getDigit(long n) { int cnt = 0; while(n>0) { cnt++; n /= 10; } return cnt; } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void reverse(int[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static void reverse(long[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static <T> void reverse(T[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++) { T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
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> const int MAX_FACT = 14; int N, K; long long fact[MAX_FACT]; int countLucky(long long val, int n) { int sol = 0; if (val <= n) { if (val > 0) ++sol; sol += countLucky(val * 10 + 4, n); sol += countLucky(val * 10 + 7, n); } return sol; } bool isLucky(int val) { do { int digit = val % 10; if (digit != 4 && digit != 7) return false; val /= 10; } while (val > 0); return true; } int solve() { int sol = 0; fact[0] = 1; for (int i = 1; i < MAX_FACT; ++i) fact[i] = fact[i - 1] * i; int pos = 0; for (int i = 0; i < MAX_FACT; ++i) if (fact[i] >= K) { pos = i; break; } if (pos < N) sol += countLucky(0, N - pos); if (pos > N) return -1; int perm[MAX_FACT]; bool fol[MAX_FACT]; memset(fol, false, sizeof(fol)); for (int i = 1; i <= pos; ++i) { long long cnt = 0; for (int j = 1; j <= pos; ++j) if (!fol[j]) { ++cnt; if (cnt * fact[pos - i] >= K) { fol[j] = true; perm[i] = N - pos + j; K -= (cnt - 1) * fact[pos - i]; break; } } } for (int i = 1; i <= pos; ++i) if (isLucky(N - pos + i) && isLucky(perm[i])) ++sol; return sol; } int main() { assert(scanf("%d %d", &N, &K) == 2); printf("%d\n", 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 fact[20]; int permutation[20]; vector<int> canUse; int luckySmaller(int n) { queue<long long> q; while (!q.empty()) q.pop(); q.push(0); int ans = 0; while (!q.empty()) { long long f = q.front(); q.pop(); long long a[2] = {f * 10 + 4, f * 10 + 7}; for (int i = 0; i < 2; i++) if (a[i] < n) { q.push(a[i]); ans++; } } return ans; } void build(int n, int k, int idx) { if (n == 0) return; if (n == 1) { permutation[idx] = canUse[0]; return; } int use = k / fact[n - 1]; permutation[idx] = canUse[use]; swap(canUse[use], canUse[canUse.size() - 1]); canUse.pop_back(); sort(canUse.begin(), canUse.end()); build(n - 1, k % fact[n - 1], idx + 1); } bool isLucky(int n) { while (n != 0) { int d = n % 10; if (d != 4 && d != 7) return false; n /= 10; } return true; } int main() { int n, k; cin >> n >> k; int start = 0; fact[0] = 1; while (fact[start] < k) { start++; fact[start] = fact[start - 1] * start; if (start > n) { cout << -1 << endl; return 0; } } for (int i = n - start + 1; i <= n; i++) canUse.push_back(i); build(start, k - 1, 0); int ans = luckySmaller(n - start + 1); for (int i = 0; i < start; i++) { int idx = n - start + 1 + i; if (isLucky(permutation[i]) && isLucky(idx)) 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; const long long N = 14, LIM = 5e9; vector<long long> vec, per; long long fac[N]; set<long long> s; long long n, k, ind, ans; void bt(long long num) { if (num > LIM) return; vec.push_back(num); bt(num * 10 + 4); bt(num * 10 + 7); } bool f(long long n) { while (n > 0) { long long r = n % 10; n /= 10; if (r != 4 && r != 7) return false; } return true; } int32_t main() { bt(4); bt(7); vec.push_back(0); sort(vec.begin(), vec.end()); fac[0] = 1; for (long long i = 1; i < N; i++) fac[i] = fac[i - 1] * i; ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> k; for (ind = 0; fac[ind] < k; ind++) ; if (n < 13 && fac[n] < k) return cout << -1, 0; long long bu = ind; for (auto x : vec) if (x <= n - ind) ans++; for (long long i = n - ind + 1; i <= n; i++) s.insert(i); while (k && ind) { ind--; long long tmp = k / fac[ind] + (k % fac[ind] > 0); k -= (tmp - 1) * fac[ind]; for (auto x : s) { tmp--; if (tmp == 0) { per.push_back(x); s.erase(x); break; } } } for (long long i = 0; i < per.size(); i++) if (f(per[i]) && f(n - bu + 1 + i)) ans++; return cout << --ans, 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 dinf = 1e200; void ext(int c) {} int ar[30]; bool was[30]; int n; int k; long long fact[30]; vector<long long> nums; void gen(long long v) { if (v > 1000000000) return; nums.push_back(v); gen(v * 10 + 4); gen(v * 10 + 7); } int main() { fact[0] = 1; for (int i = 0; i < (20); ++i) fact[i + 1] = fact[i] * (i + 1); cin >> n >> k; --k; if (n <= 13 && k >= fact[n]) { cout << -1; return 0; } int p = n + 1; while (k >= fact[n - p + 1]) --p; for (int a = p; a <= n; ++a) { for (int v = p;; ++v) { if (was[v - p]) continue; if (k < fact[n - a]) { was[v - p] = true; ar[a - p] = v; break; } k -= fact[n - a]; } } gen(4); gen(7); sort(nums.begin(), nums.end()); long long res = lower_bound(nums.begin(), nums.end(), p) - nums.begin(); for (int a = p; a <= n; ++a) { int i1 = lower_bound(nums.begin(), nums.end(), a) - nums.begin(); int i2 = lower_bound(nums.begin(), nums.end(), ar[a - p]) - nums.begin(); if (i1 == nums.size() || i2 == nums.size() || nums[i1] != a || nums[i2] != ar[a - p]) continue; ++res; } cout << 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; const int mod = 1e9 + 7; const long long inf = 5e18; vector<string> num_string({"4", "7"}); map<long long, int> mp; vector<long long> fact; bool check(long long mid, long long n, long long k) { if (n - mid >= fact.size()) { return false; } else { return fact[n - mid] <= k; } } int main() { fact.push_back(1); while (fact.back() < 6e12) { fact.push_back(fact.back() * (fact.size())); } long long fs = fact.size(); long long n, k; cin >> n >> k; if (n < fact.size() and fact[n] < k) { cout << -1 << endl; return 0; } k--; while (num_string.back().size() < 10) { vector<string> next_num = num_string; for (string s : num_string) { if (s.size() == num_string.back().size()) { s.push_back('4'); next_num.push_back(s); s.back() = '7'; next_num.push_back(s); } } num_string = next_num; } for (string s : num_string) { mp[(stoll(s))] = 1; } long long ans = 0; for (auto& x : mp) { if (x.first <= n) { ans++; } } int i = max(1ll, n - fs + 1); vector<long long> remainingElements; for (int j = i; j <= n; j++) { remainingElements.push_back(j); } while (i <= n) { long long rem = n - i; if (fact[rem] <= k) { long long div = k / fact[rem]; k -= div * fact[rem]; if (mp[i] and !mp[remainingElements[div]]) { ans--; } remainingElements.erase(remainingElements.begin() + div); } else { if (mp[i] and !mp[remainingElements[0]]) { ans--; } remainingElements.erase(remainingElements.begin()); } i++; } 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; long long fact[20], n, k; bool isGood(long long x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return 0; x /= 10; } return 1; } vector<long long> getkth(long long k, long long n, long long x) { vector<long long> v(n + 1, 0); for (long long i = 1; i <= n; ++i) { long long ok = 1, poz = 1; while (ok && poz <= n) { if (v[poz]) poz++; else { if (k > fact[n - i]) k -= fact[n - i]; else break; poz++; } } v[poz] = x + i - 1; } return v; } long long getnext(long long x) { long long sol = x, p10 = 1, ok = 1; while (x && ok) { if (x % 10 == 4) { sol += p10 * 3; ok = 0; } else sol -= p10 * 3; p10 *= 10; x /= 10; } if (ok) sol += p10 * 4; return sol; } long long howmany(long long n) { long long x = 4, sol = 0; while (x <= n) sol++, x = getnext(x); return sol; } int32_t main() { fact[0] = 1; for (long long i = 1; i <= 14; ++i) fact[i] = fact[i - 1] * i; cin >> n >> k; if (n <= 14 && k > fact[n]) { cout << -1 << "\n"; return 0; } long long sol = 0; if (n <= 14) { vector<long long> v = getkth(k, n, 1); for (long long i = 1; i <= n; ++i) { if (isGood(i) && isGood(v[i])) sol++; } } else { sol += howmany(n - 14); vector<long long> v = getkth(k, 14, n - 13); for (long long i = 1; i <= 14; ++i) { if (isGood(i + n - 14) && isGood(v[i])) sol++; } } cout << sol << "\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 math def isLucky(num): s = str(num) for i in s: if i != '4' and i != '7': return False return True def getLucky(d): if d == 1: for i in [4, 7]: yield str(i) else: l = [i for i in getLucky(d-1)] for j in l: yield '4'+j for j in l: yield '7'+j luckies = [] for d in range(1,11): for i in getLucky(d): luckies.append(int(i)) def canto(l, k): # find the k(th) permutation of list l, k counts from 1 n = len(l) p = k - 1 a = [] i = n - 1 mark = [False]*(n+1) while len(a) < n: fac = math.factorial(i) a.append(p/fac) p %= fac i -= 1 j = 1 cnt = 0 while cnt < a[-1]+1: if not mark[j]: cnt += 1 j += 1 a[-1] = j-1 mark[a[-1]] = True return [l[i-1] for i in a] n, k = map(int, raw_input().split()) if n < 20 and k > math.factorial(n): print -1 else: for tail in xrange(1, 31): fac = math.factorial(tail) if fac >= k: break l = [i for i in xrange(n+1-tail, n+1)] p_tail = canto(l, k) # print 'tail',tail # print p_tail ans = 0 for lucky in luckies: if lucky > n: break # print 'lucky is',lucky if lucky <= n-tail: ans += 1 # print lucky else: i = p_tail.index(lucky) if isLucky(n-tail+1+i): ans += 1 # print lucky print ans
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
def lucky(x): return not(set(list(str(x)))-set(['4','7'])) n,k=map(int,raw_input().split()) k-=1 p=[1]*16 for i in xrange(13):p[i+1]=p[i]*(i+1) a=[] def n_th(x): return x if n-x>=13 else (a[x-1-n]+max(0,n-13)+1) if n<=13 and k>=p[n]:print -1 else: s=[1]*16 for b in reversed(xrange(min(13,n))): u=s.index(1) while k>=p[b]: k-=p[b] u+=1 while not s[u]:u+=1 a.append(u) s[u]=0 t=0 for w in xrange(1,10): for x in xrange(1<<w): y=0 for b in xrange(w): y=y*10+(7 if ((1<<b)&x) else 4) if y<=n and lucky(n_th(y)):t+=1 print t
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
#include <bits/stdc++.h> int lucky(int x) { while (x) { if (x % 10 != 4 && x % 10 != 7) break; x /= 10; } if (x == 0) { return 1; } else { return 0; } } int fact(int n) { int x = 1, i; for (i = 1; i <= n; i++) x *= i; return x; } int main() { int n, k, p = 0, q = 2, r = 2, sum = 0, i, j; long long x = 1; int a[10000], b[100]; scanf("%d %d", &n, &k); a[0] = 4; a[1] = 7; for (i = 0; i < 8; i++) { for (j = p; j < q; j++) { a[r++] = a[j] * 10 + 4; a[r++] = a[j] * 10 + 7; } p = q; q = r; } for (i = 1; i <= n; i++) { x *= i; if (x >= k) break; } if (i > n) { puts("-1"); return 0; } for (j = 0; j < r; j++) { if (a[j] > n - i) break; sum++; } q = 0; for (j = n - i + 1; j <= n; j++) b[q++] = j; for (j = n - i + 1; j < n; j++) { p = k / fact(n - j); if (k % fact(n - j) == 0) p--; if (lucky(j) == 1 && lucky(b[p]) == 1) sum++; for (i = p; i < q; i++) b[i] = b[i + 1]; k -= p * fact(n - j); } if (lucky(n) == 1 && lucky(b[0]) == 1) sum++; printf("%d\n", sum); 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; long long f[15]; int count(long long x, long long k) { if (x > k) return 0; return 1 + count(10 * x + 4, k) + count(10 * x + 7, k); } bool check(long long x) { if (x == 0) return false; while (x) { long long r = x % 10; if (r != 4 && r != 7) return false; x /= 10; } return true; } int main() { cin >> N >> K; f[1] = 1; for (int i = 2; i <= 14; i++) f[i] = f[i - 1] * i; if (N <= 14 && K > f[N]) { cout << -1 << endl; return 0; } int ans = count(0, max(N - 13, 0ll)) - 1; vector<int> t; for (int i = N - 12; i <= N; i++) t.push_back(i); K--; for (int i = 13; i > 1 && t.size() > 0; i--) { int tmp = K / f[i - 1]; if (check(N - i + 1) && check(t[tmp])) ans++; t.erase(t.begin() + tmp); K %= f[i - 1]; } if (check(N) && check(t[0])) 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; template <class T> string i2s(T x) { ostringstream o; o << x; return o.str(); } int s2i(string x) { int r = 0; istringstream sin(x); sin >> r; return r; } long long fact[14]; int N, K; bool isLucky(int x) { string s = i2s(x); for (int i = 0; i < s.size(); i++) if (s[i] != '4' && s[i] != '7') return false; return true; } int countLucky(long long val, int mx) { if (val > mx) return 0; int ans = 0; if (val != 0) ans += 1; ans += countLucky(val * 10 + 4, mx); ans += countLucky(val * 10 + 7, mx); return ans; } int solve() { int i, j, sol = 0; fact[0] = fact[1] = 1; for (i = 2; i < 14; i++) fact[i] = i * fact[i - 1]; int pos = 0; for (i = 0; i < 14; i++) if (fact[i] >= K) { pos = i; break; } if (pos > N) return -1; if (pos < N) sol += countLucky(0, N - pos); int perm[14]; bool flag[14]; memset(flag, false, sizeof(flag)); for (i = 1; i <= pos; i++) { long long cnt = 0; for (j = 1; j <= pos; j++) if (!flag[j]) { ++cnt; if (cnt * fact[pos - i] >= K) { flag[j] = true; perm[i] = N - pos + j; K -= (cnt - 1) * fact[pos - i]; break; } } } for (i = 1; i <= pos; ++i) if (isLucky(N - pos + i) && isLucky(perm[i])) ++sol; return sol; } int main() { scanf("%d %d", &N, &K); cout << solve() << 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; double PI = 3.141592653589793; const int mx = 13; long long cnt[mx + 1]; int val[mx + 1]; bool lck(int n) { bool out = 1; while (n != 0) { if (n % 10 != 4 && n % 10 != 7) out = 0; n /= 10; } return out; } const int bmx = 9; vector<int> proc; void init() { for (int i = 1; i < bmx + 1; i++) { for (int j = 0; j < (1 << i); j++) { int val = 0; for (int k = 0; k < i; k++) { if (j & (1 << k)) val = 10 * val + 7; else val = 10 * val + 4; } proc.push_back(val); } } } void solve() { init(); int n, k; cin >> n >> k; k--; cnt[0] = 1; for (int i = 1; i < mx + 1; i++) cnt[i] = cnt[i - 1] * i; if (n <= mx && k + 1 > cnt[n]) { cout << -1; return; } set<int> done; for (int i = 0; i < mx + 1; i++) { long long ccnt = 0, ind = 0; while (done.count(ind)) ind++; while (ccnt + cnt[mx - i] <= k) { ccnt += cnt[mx - i]; ind++; while (done.count(ind)) ind++; } k -= ccnt; val[i] = ind; done.insert(ind); } int ans = 0; if (n <= mx + 1) { for (int i = mx - n + 1; i <= mx; i++) { int in = i - (mx - n); int v = val[i] - (mx - n); if (lck(in) && lck(v)) ans++; } } else { int st = n - mx; for (auto i : proc) ans += (i < st); for (int i = 0; i <= mx; i++) { int in = st + i; int v = st + (val[i]); if (lck(in) && lck(v)) ans++; } } cout << ans; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T = 1; for (int c = 1; c < T + 1; c++) { 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; int m = 0; int nn; long long n, k; long long fact[20]; long long a[20000]; int b[20]; bool check[20]; int per[20]; bool found; int res; void doit(int, int); void gen(int); bool isLucky(int); int main() { cin >> n >> k; fact[0] = fact[1] = 1; for (int i = 2; i <= 13; i++) fact[i] = i * fact[i - 1]; for (int d = 1; d <= 10; d++) { for (int i = 1; i <= d; i++) b[i] = 0; doit(1, d); } res = 0; for (int i = 1; i <= m; i++) if (a[i] > n - 13) break; else res++; found = false; if (n > 13) nn = 13; else nn = n; for (int i = 1; i <= nn; i++) check[i] = true; gen(1); if (!found) cout << -1 << endl; else cout << res << endl; return 0; } void doit(int i, int d) { if (i > d) { long long x = 0; for (int j = 1; j <= d; j++) if (b[j] == 0) x = x * 10 + 4; else x = x * 10 + 7; a[++m] = x; return; } for (int j = 0; j <= 1; j++) { b[i] = j; doit(i + 1, d); b[i] = 0; } } void gen(int i) { if (i > nn) { found = true; int x = n - 13; if (x < 0) x = 0; for (int j = 1; j <= nn; j++) { if (isLucky(x + per[j]) && isLucky(x + j)) res++; } return; } for (int j = 1; j <= nn; j++) if (check[j]) { if (k <= fact[nn - i]) { per[i] = j; check[j] = false; gen(i + 1); if (found) return; } else k = k - fact[nn - i]; } } bool isLucky(int x) { while (x > 0) { if (!(x % 10 == 4 || x % 10 == 7)) return false; x = x / 10; } return true; }
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
lucky=set([]) def gen(x): if x>4444444444: return lucky.add(x) gen(x*10+4) gen(x*10+7) gen(4) gen(7) lucky=sorted(lucky) n,k=map(int,raw_input().split()) z=1 t=0 while z<k: t+=1 z*=t if t>n: print -1 raise SystemExit() def before(x): l=0 r=len(lucky)-1 while r-l>1: if lucky[(r+l)/2]>=x: r=(r+l)/2 else: l=(r+l)/2 if lucky[l]>=x: return l else: return r def islucky(x): if x==0: return False while x>0: if not (x%10 in [4,7]): return False x/=10 return True res=before(n-t+1) if t>0: used=[0]*t perm=list() k-=1 while t>0: z/=t x=0 while used[x]==1: x+=1 while k>=z: k-=z x+=1 while used[x]==1: x+=1 t-=1 used[x]=1 perm.append(x) t=len(perm) for i in xrange(t): if islucky(n-t+i+1) and islucky(n-t+perm[i]+1): 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
#include <bits/stdc++.h> using namespace std; const int INF = (int)1E9 + 5; const long long LINF = (long long)4E18 + 5; const long double PI = acos(-1.0); const long double E = 2.718281828459045L; template <typename T> T gcd(T a, T b) { return (b == 0) ? abs(a) : gcd(b, a % b); } template <typename T> inline T lcm(T a, T b) { return a / gcd(a, b) * b; } template <typename T> inline T mod(T a, T b) { return (a % b + b) % b; } template <typename T> inline T sqr(T x) { return x * x; } template <typename T> inline string toString(const T& x) { ostringstream os; os << x; return os.str(); } inline long long toInt(const string& s) { istringstream is(s); long long x; is >> x; return x; } inline long double toDouble(const string& s) { istringstream is(s); long double x; is >> x; return x; } inline string toLower(string s) { for (typeof((s).begin()) it = (s).begin(); it != (s).end(); ++it) *it = tolower(*it); return s; } inline string toUpper(string s) { for (typeof((s).begin()) it = (s).begin(); it != (s).end(); ++it) *it = toupper(*it); return s; } const char DEBUG_PARAM[] = "__LOCAL_TESTING"; const char IN[] = "_.in"; const char OUT[] = "_.out"; inline void init(); inline void run(); int ntest = 0, test; int main(int argc, char* argv[]) { if (argc > 1 && strcmp(argv[1], DEBUG_PARAM) == 0) { freopen(IN, "r", stdin); } init(); if (ntest == 0) { puts("ntest = ?"); return 0; } for (test = 1; test <= ntest; test++) { run(); } return 0; } inline void stop() { ntest = test - 1; } const int dx[] = {-1, 0, 0, 1}; const int dy[] = {0, -1, 1, 0}; const long double EPS = 1E-9; const long long MODULE = 1000000007LL; vector<long long> v; void dfs(long long x) { if (x > INF * 10LL) { return; } v.push_back(x); dfs(x * 10 + 4); dfs(x * 10 + 7); } inline void init() { ntest = 1; dfs(4LL), dfs(7LL); sort((v).begin(), (v).end()); } int n, k; bool isLucky(int x) { string s = toString(x); for (typeof((s).begin()) it = (s).begin(); it != (s).end(); ++it) { if (*it != '4' && *it != '7') { return false; } } return true; } int find(int x) { int cnt = 0; for (typeof((v).begin()) it = (v).begin(); it != (v).end(); ++it) { if (*it <= x) { cnt++; } } return cnt; } bool check[15]; long long frac[15], tail[15]; inline void run() { scanf("%d%d\n", &n, &k); long long t = 1; int w = 0; for (int i = (1); i <= (n); i++) { t = t * i; if (t >= k) { w = i; break; } } if (!w) { puts("-1"); return; } frac[0] = 1; for (int i = (1); i <= (w); i++) { frac[i] = frac[i - 1] * i; } vector<pair<int, int> > u; memset((check), (true), sizeof(check)); for (int i = (1); i <= (w); i++) { int j = 1; while (1) { while (!check[j]) { j++; } if (k <= frac[w - i]) { check[j] = false; u.push_back(make_pair(n - w + j, n - w + i)); break; } else { k -= frac[w - i]; j++; } } } int ret = 0; for (typeof((u).begin()) it = (u).begin(); it != (u).end(); ++it) { if (isLucky(it->first) && isLucky(it->second)) { ret++; } } int x = n - w; ret += find(x); cout << ret << 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.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class CLuckyPermutation { private static Map<Integer, Integer> map = new HashMap<>(); public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt() - 1; scan.close(); if(k >= count(n)) { System.out.println(-1); return; } int[] factoradic = convertToFactoradic(k, n); List<Integer> last = new ArrayList<>(); for (int i = Math.max(1, n - 12); i <= n; i++) { last.add(i); } int[] permutatedKth = new int[Math.min(n, 13)]; int j = 0; for (int i = permutatedKth.length - 1; i >= 0; i--) { permutatedKth[j] = last.get(factoradic[i]); last.remove(factoradic[i]); j++; } createLuckyNumbers(""); int res = 0; for (Integer i : map.keySet()) { if (i > n) ; else if (i < Math.max(1, n - 12)) res++; else if (map.containsKey(permutatedKth[(i <= permutatedKth.length ? i : 13 - (n - i)) - 1])) res++; } System.out.println(res); } static int count(int n) { if(n == 0) return 1; if(n > 12) return 2000000000; return count(n-1) * n; } static void createLuckyNumbers(String s) { if (s.length() >= 10) return; if (s.length() > 0) { int v = Integer.parseInt(s); map.put(v, 1); } createLuckyNumbers(s + "4"); createLuckyNumbers(s + "7"); } static int[] convertToFactoradic(int k, int n) { int[] res = new int[Math.min(n, 13)]; int mod; for (int i = 1; i <= res.length; i++) { mod = k % i; k = k / i; res[i - 1] = mod; } 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
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10, mod = 1e9 + 7; vector<int> v; long long fac[N]; int n, k; bool check(int x) { while (x) { int y = x % 10; x /= 10; if (y != 4 && y != 7) return 0; } return 1; } vector<int> get(int cnt, int num) { set<int> s; vector<int> ret; for (int i = 1; i <= cnt; i++) s.insert(i); int now = 1; for (int i = 1; i <= cnt; i++) { for (int x : s) { if (now + fac[cnt - i] > k) { ret.push_back(x); s.erase(x); break; } now += fac[cnt - i]; } } return ret; } void go(long long x) { if (x > mod) return; v.push_back(x); x *= 10; go(x + 7); go(x + 4); } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); fac[0] = 1; for (int i = 1; i < N; i++) { fac[i] = 1ll * fac[i - 1] * i; if (fac[i] > mod) break; } go(4); go(7); sort(v.begin(), v.end()); cin >> n >> k; long long nw = 1; int cnt; for (int i = 1; i <= n; i++) { nw *= i; cnt = i; if (nw >= k) break; } if (nw < k) return cout << -1, 0; int x = n - cnt; int ret = upper_bound(v.begin(), v.end(), x) - v.begin(); vector<int> vec = get(cnt, k); for (int i = x + 1; i <= n; i++) { if (check(i) && check(vec[i - x - 1] + x)) ret++; } cout << ret; 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 lu[] = { 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}; void pv(vector<char> v) { cout << "[ "; for (int i = 0; i < int((v).size()); i++) { cout << v[i] << ", "; } cout << "]" << endl; } long long factorial(int n) { long long res = 1; while (n) { res *= n; --n; } return res; } vector<int> ret; void per(vector<int> v, int indx) { if (indx == 0) { sort((v).begin(), (v).end()); for (int i = 0; i < int((v).size()); ++i) ret.push_back(v[i]); return; } int ln = int((v).size()) - 1; vector<long long> rng(ln + 1); for (int i = 0; i <= ln; ++i) { rng[i] = i * factorial(ln); } for (int i = 0; i <= ln; ++i) { if (indx >= rng[i] && indx < rng[i + 1]) { int at = find((v).begin(), (v).end(), v[i]) - v.begin(); int a = v[i]; v.erase(v.begin() + at); sort((v).begin(), (v).end()); ret.push_back(a); per(v, indx - rng[i]); break; } } } bool isluck(int n) { while (n) { if (n % 10 != 7 && n % 10 != 4) return false; n /= 10; } return true; } int main() { long long n, k; int ct = 0; cin >> n >> k; k--; int siz = sizeof lu / sizeof(long long); if (n > 15) { int nn = n - 15; for (int i = 0; i < siz; ++i) { if (lu[i] <= nn) ct++; } vector<int> vec; for (int i = nn + 1; i <= n; ++i) { vec.push_back(i); } per(vec, k); for (int i = 0; i < int((ret).size()); ++i) { int indx = i + nn + 1; if (isluck(indx) && isluck(ret[i])) ct++; } cout << ct << endl; return 0; } else { if (k + 1 > factorial(n)) { cout << -1 << endl; return 0; } vector<int> vec; for (int i = 1; i <= n; ++i) { vec.push_back(i); } per(vec, k); for (int i = 0; i < int((ret).size()); ++i) { if (isluck(i + 1) && isluck(ret[i])) ct++; } cout << ct << endl; return 0; } 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); int n = min(15, m); long[] a = new long[15]; boolean[] chosen = new boolean[15]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) if(!chosen[j]) { if(fact(n - i - 1) >= k) { a[i] = j + 1; chosen[j] = true; break; } else { k -= fact(n - i - 1); } } } boolean ok = true; for(int i = 0; i < n; i++) ok &= chosen[i]; if(!ok) { out.println(-1); return; } int res = 0; if(m <= 15) { for(int i = 0; i < m; i++) if(isLucky(i + 1) && isLucky(a[i])) res++; out.println(res); } else { int left = m - 15; 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
#include <bits/stdc++.h> using namespace std; int n, k; int mx[15]; int cal(int ix) { if (ix == 0) return 0; long long temp = 1, i; for (i = 1;; i++) { temp *= i; if (temp >= ix) break; } int p = i - 1; if (temp == ix) { reverse(mx, mx + p + 1); return 0; } int t = temp / i; t = (ix - 1) / t; swap(mx[p], mx[p - t]); sort(mx, mx + p); reverse(mx, mx + p); cal(ix - temp / i * t); return p; } bool islucky(int x) { while (x) { int t = x % 10; if (t != 4 && t != 7) return 0; x /= 10; } return 1; } int res; long long np; void per(long long x) { if (x >= np) return; if (x) res++; per(x * 10 + 4); per(x * 10 + 7); } int main() { cin >> n >> k; long long temp = 1; bool sign = false; for (int i = 1; i <= n; i++) { temp *= i; if (temp >= k) { sign = true; break; } } if (!sign) { cout << "-1" << endl; return 0; } int nn = n; for (int i = 0; i <= 14; i++) { mx[i] = nn--; } int p = cal(k); np = n - p; per(0); nn = n; for (int i = 0; i <= p; i++) { if (islucky(mx[i]) && islucky(nn)) res++; nn--; } cout << res << 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
def lucky(x): while x>0: d=x%10 x/=10 if d!=4 and d!=7: return False return True n,k=map(int,raw_input().split()) k-=1 p=[1]*16 for i in xrange(13):p[i+1]=p[i]*(i+1) a=[] def n_th(x): if n-x<13: return a[x-1-n]+max(0,n-13)+1 else: return x if n<=13 and k>=p[n]:print -1 else: s=[1]*16 for b in reversed(xrange(min(13,n))): u=0 while k>=p[b]: k-=p[b] while not s[u]:u+=1 u+=1 while not s[u]:u+=1 a.append(u) s[u]=0 t=0 for w in xrange(1,10): for x in xrange(1<<w): y=0 for b in xrange(w): y=y*10+(7 if ((1<<b)&x) else 4) if y<=n and lucky(n_th(y)):t+=1 print t
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.util.*; public class cf121c { static TreeSet<Long> lucky = new TreeSet<Long>(); static long[] facts = new long[20]; public static void main(String[] args) { genLucky(0,12); facts[0] = facts[1] = 1; for(int i=2; i<20; i++) facts[i] = facts[i-1]*i; Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); if(n < 20 && facts[n] < k) { System.out.println(-1); return; } int shift = n-20; long[] v = new long[20]; for(int i=19; i>=0; i--) v[i] = n-(19-i); int ret = lucky.headSet((long)shift, true).size(); k--; long[] last = new long[20]; for(int i=0; i<20; i++) { last[i] = k/facts[19-i]; k %= facts[19-i]; } int[] lasti = new int[20]; ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int i=0; i<20; i++) tmp.add(i); for(int i=0; i<20; i++) lasti[i] = tmp.remove((int)last[i]); long[] lastv = new long[20]; for(int i=0; i<20 ;i++) lastv[i] = v[lasti[i]]; for(int i=0; i<20; i++) if(lucky.contains(lastv[i]) && lucky.contains((long)(shift+i+1))) ret++; System.out.println(ret); } static void genLucky(long cur, int left) { if(left == 0) return; if(cur != 0) lucky.add(cur); genLucky(cur*10+7, left-1); genLucky(cur*10+4, left-1); } } /* 7 4 4 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
#include <bits/stdc++.h> using namespace std; long long mod = 1000000007; vector<int> gen_perm(int n, int k) { long long fact[20]; fact[0] = 1; for (long long i = 1; i < 20; i++) { fact[i] = i * fact[i - 1]; fact[i] %= mod; } bool placed[20] = {0}; vector<int> v; for (int p = 1; p <= n; p++) { for (int i = 1; i <= n; i++) { if (!placed[i]) { if (k > fact[n - p]) { k -= fact[n - p]; } else { placed[i] = 1; v.push_back(i); break; } } } } for (int i = 1; i <= n; i++) { if (!placed[i]) { v.push_back(i); } } return v; } bool islucky(int x) { while (x > 0) { if (x % 10 != 4 and x % 10 != 7) return 0; x /= 10; } return 1; } long long lim; int ans = 0; set<int> s; void dfs(long long v) { if (v > lim) return; if (s.count(v)) return; ans++; s.insert(v); dfs(10 * v + 4); dfs(10 * v + 7); } int main() { int n, k; cin >> n >> k; if (n <= 13) { long long ret = 1; for (int i = 1; i <= n; i++) { ret *= (long long)i; } if (ret < k) { cout << -1; return 0; } vector<int> v = gen_perm(n, k); int ans = 0; for (int i = 0; i < v.size(); i++) { if (islucky(i + 1) and islucky(v[i])) ans++; } cout << ans; } else { vector<int> v = gen_perm(13, k); lim = n - 13; dfs(4); dfs(7); for (int i = lim + 1; i <= n; i++) { if (islucky(i) == 1 and islucky(lim + v[i - lim - 1]) == 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; const long long dx[] = {4LL, 7LL}; vector<long long> lucky; vector<long long> P; int main() { { queue<int> Q; Q.push(0); while (!Q.empty()) { long long x = Q.front(); for (int i = 0; i < 2; i++) { long long x1 = x * 10LL + dx[i]; lucky.push_back(x1); if (x1 <= 1000000000LL) { Q.push(x1); } } Q.pop(); } } for (long long i = 1, p = 1; i <= 14; i++) { P.push_back(p); p *= i; } int n, k; cin >> n >> k; k--; if (n < 13 && P[n] - 1 < k) { cout << -1; return (0); } list<int> L; for (int i = 1;; i++) { L.push_back(i); if (P[i] - 1 >= k) break; } vector<int> perm; for (int i = L.size() - 1; i >= 0; i--) { list<int>::iterator it = L.begin(); while (k >= P[i]) { k -= P[i]; it++; } perm.push_back(*it); L.erase(it); } int res = 0; for (int i = 0; lucky[i] < n - perm.size() + 1; i++) res++; for (int i = 0, pos = n - perm.size() + 1; i < perm.size(); i++, pos++) { int d = perm[i] - (i + 1); int truenum = pos + d; bool f1 = false, f2 = false; for (int i = 0; i < lucky.size(); i++) { if (truenum == lucky[i]) f1 = true; if (pos == lucky[i]) f2 = true; } if (f1 && f2) res++; } cout << res; exit: 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> inline _T sqr(const _T &first) { return first * first; } template <class _T> inline string tostr(const _T &a) { ostringstream os(""); os << a; return os.str(); } const long double PI = 3.1415926535897932384626433832795L; const long double EPS = 1e-9; char TEMPORARY_CHAR; const int INF = 1e9; inline void fft(vector<complex<long double> > &a, bool invert) { int n = (int)a.size(); for (int i = 1, j = 0; i < n; ++i) { int bit = n >> 1; for (; j >= bit; bit >>= 1) j -= bit; j += bit; if (i < j) swap(a[i], a[j]); } for (int len = 2; len <= n; len <<= 1) { long double ang = 2 * PI / len * (invert ? -1 : 1); complex<long double> wlen(cos(ang), sin(ang)); for (int i = 0; i < n; i += len) { complex<long double> w(1); for (int j = 0; j < len / 2; ++j) { complex<long double> u = a[i + j], v = a[i + j + len / 2] * w; a[i + j] = u + v; a[i + j + len / 2] = u - v; w *= wlen; } } } if (invert) for (int i = 0; i < n; ++i) a[i] /= n; } inline void input(int &a) { a = 0; while (((TEMPORARY_CHAR = getchar()) > '9' || TEMPORARY_CHAR < '0') && (TEMPORARY_CHAR != '-')) { } char neg = 0; if (TEMPORARY_CHAR == '-') { neg = 1; TEMPORARY_CHAR = getchar(); } while (TEMPORARY_CHAR <= '9' && TEMPORARY_CHAR >= '0') { a = (a << 3) + (a << 1) + TEMPORARY_CHAR - '0'; TEMPORARY_CHAR = getchar(); } if (neg) a = -a; } inline void out(long long a) { if (!a) putchar('0'); if (a < 0) { putchar('-'); a = -a; } char s[20]; int i; for (i = 0; a; ++i) { s[i] = '0' + a % 10; a /= 10; } for (int j = (i)-1; j >= 0; j--) putchar(s[j]); } inline int nxt() { int(ret); input((ret)); ; return ret; } struct lnum { vector<int> a; int base; lnum(int num = 0, int base = 1000000000) : base(base) { if (!num) a.resize(1); while (num) { a.push_back(num % base); num /= base; } } inline int len() const { return a.size(); } lnum &operator=(const lnum &l) { if (this != &l) { a = l.a; base = l.base; } return *this; } inline friend lnum operator+(const lnum &l, const lnum &r) { lnum ret(0, l.base); int base = l.base; int ln = l.len(), rn = r.len(); int n = max(ln, rn); ret.a.resize(n); int o = 0; for (int i = 0; i < n; ++i) { int s = o; if (i < ln) s += l.a[i]; if (i < rn) s += r.a[i]; o = s >= base; if (o) s -= base; ret.a[i] = s; } if (o) ret.a.push_back(1); return ret; } inline friend lnum operator-(const lnum &l, const lnum &r) { lnum ret(0, l.base); int base = l.base; int n = l.len(); int rn = r.len(); ret.a.resize(n); int o = 0; for (int i = 0; i < n; ++i) { int s = l.a[i] - o; if (i < rn) s -= r.a[i]; o = s < 0; if (o) s += base; ret.a[i] = s; } if (ret.len() > 1 && !ret.a.back()) ret.a.pop_back(); return ret; } inline friend lnum operator*(const lnum &l, const lnum &r) { lnum ret(0, l.base); int base = l.base; if (l.len() * r.len() > 1000000) { vector<complex<long double> > fa(l.a.begin(), l.a.end()), fb(r.a.begin(), r.a.end()); int n = 1; while (n < max(l.len(), r.len())) n <<= 1; n <<= 1; fa.resize(n), fb.resize(n); fft(fa, false), fft(fb, false); for (int i = 0; i < n; ++i) fa[i] *= fb[i]; fft(fa, true); ret.a.resize(n); for (int i = 0; i < n; ++i) ret.a[i] = int(fa[i].real() + 0.5); int carry = 0; for (int i = 0; i < n; ++i) { ret.a[i] += carry; carry = ret.a[i] / base; ret.a[i] %= base; } } else { ret.a.resize(l.len() + r.len()); for (int i = 0; i < l.len(); ++i) for (int j = 0, carry = 0; j < r.len() || carry; ++j) { long long cur = ret.a[i + j] + (long long)l.a[i] * (j < r.len() ? r.a[j] : 0) + carry; ret.a[i + j] = cur % base; carry = cur / base; } } while (ret.len() > 1 && !ret.a.back()) ret.a.pop_back(); return ret; } inline friend lnum operator/(const lnum &l, const int &r) { lnum ret(0, l.base); ret.a.resize(l.len()); int carry = 0; for (int i = l.len() - 1; i >= 0; --i) { long long cur = l.a[i] + (long long)carry * l.base; ret.a[i] = cur / r; carry = cur % r; } while (ret.len() > 1 && ret.a.back() == 0) ret.a.pop_back(); return ret; } inline friend bool operator<(const lnum &l, const lnum &r) { if (l.len() < r.len()) return true; if (l.len() > r.len()) return false; int n = l.len(); for (int i = n - 1; i >= 0; --i) { if (l.a[i] < r.a[i]) return true; if (l.a[i] > r.a[i]) return false; } return false; } inline friend bool operator>(const lnum &l, const lnum &r) { return r < l; } inline friend bool operator==(const lnum &l, const lnum &r) { if (l.len() != r.len()) return false; int n = l.len(); for (int i = n - 1; i; --i) { if (l.a[i] != r.a[i]) return false; } return true; } inline friend bool operator!=(const lnum &l, const lnum &r) { return !(l == r); } inline void print() { if (base == 1000000000) { printf("%d", a.back()); for (int i = a.size() - 2; i >= 0; --i) printf("%09d", a[i]); } else { for (int i = a.size() - 1; i >= 0; --i) printf("%d", a[i]); } } }; bool is_happy(int a) { while (a) { if (a % 10 != 4 && a % 10 != 7) return false; a /= 10; } return true; } int main() { vector<long long> nums; for (int l = 1; l <= 10; ++l) { int n = 1 << l; for (int i = 0; i < (int)(n); i++) { long long cur = 0; for (int j = 0; j < (int)(l); j++) if ((i >> j) & 1) cur = 10 * cur + 4; else cur = 10 * cur + 7; nums.push_back(cur); } } sort((nums).begin(), (nums).end()); int(n); input((n)); ; int(k); input((k)); ; long long f[14]; f[0] = 1; int q = 13; ((q) = (n) < (q) ? (n) : (q)); for (int i = 1; i <= q; ++i) f[i] = i * f[i - 1]; if (n <= q && f[n] < k) { puts("-1"); return 0; } --k; int a[q]; int used[q]; memset((used), 0, sizeof(used)); for (int i = 0; i < q; ++i) { int pos = k / f[q - i - 1]; for (int j = 0; j < (int)(q); j++) { if (!used[j]) { if (!pos) { a[i] = j; used[j] = true; break; } --pos; } } k %= f[q - i - 1]; } int ans = upper_bound((nums).begin(), (nums).end(), n - q) - nums.begin(); for (int j = n - q; j < n; ++j) { int pos = j + 1; int val = a[j - (n - q)] + n - q + 1; if (is_happy(pos) && is_happy(val)) ++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.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.StringTokenizer; public class CodeJ { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextDouble(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public String[] nextStringArray(int n) { String[] vals = new String[n]; for(int i = 0; i < n; i++) vals[i] = next(); return vals; } Integer nextInteger() { String s = next(); if(s == null) return null; return Integer.parseInt(s); } int[][] nextIntMatrix(int n, int m) { int[][] ans = new int[n][]; for(int i = 0; i < n; i++) ans[i] = nextIntArray(m); return ans; } static <T> T fill(T arreglo, int val) { if(arreglo instanceof Object[]) { Object[] a = (Object[]) arreglo; for(Object x : a) fill(x, val); } else if(arreglo instanceof int[]) Arrays.fill((int[]) arreglo, val); else if(arreglo instanceof double[]) Arrays.fill((double[]) arreglo, val); else if(arreglo instanceof long[]) Arrays.fill((long[]) arreglo, val); return arreglo; } <T> T[] nextObjectArray(Class <T> clazz, int size) { @SuppressWarnings("unchecked") T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size); for(int c = 0; c < 3; c++) { Constructor <T> constructor; try { if(c == 0) constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE); else if(c == 1) constructor = clazz.getDeclaredConstructor(Scanner.class); else constructor = clazz.getDeclaredConstructor(); } catch(Exception e) { continue; } try { for(int i = 0; i < result.length; i++) { if(c == 0) result[i] = constructor.newInstance(this, i); else if(c == 1) result[i] = constructor.newInstance(this); else result[i] = constructor.newInstance(); } } catch(Exception e) { throw new RuntimeException(e); } return result; } throw new RuntimeException("Constructor not found"); } } static int factorial(int n) { if(n == 0) return 1; return n * factorial(n - 1); } static int[] permutar(boolean[] usados, int[] numeros, int n, int k) { if(n == usados.length) return numeros; int faltantes = usados.length - n; int sigFact = factorial(faltantes - 1); for(int i = 0; i < usados.length; i++) { if(!usados[i]) { if(sigFact >= k) { usados[i] = true; numeros[n] = i; return permutar(usados, numeros, n + 1, k); } else k -= sigFact; } } return null; } static int contarHasta(int n) { int cuenta = 0; for(int i = 1; i < 10; i++) { int limite = 1 << i; for(int j = 0; j < limite; j++) { char[] val = new char[i]; for(int k = 0; k < i; k++) { if((j & (1 << k)) != 0) val[k] = '4'; else val[k] = '7'; } if(Integer.parseInt(new String(val)) <= n) cuenta++; } } return cuenta; } static boolean esLucky(int j) { for(char c : (j + "").toCharArray()) if(c != '4' && c != '7') return false; return true; } public static void main(String[] args) { Scanner sc = new Scanner(); int n = sc.nextInt(); int k = sc.nextInt(); if(n > 13) { int total = contarHasta(n - 13); int[] vals = permutar(new boolean[13], new int[13], 0, k); for(int i = 0; i < 13; i++) vals[i] += n - 12; for(int i = 0, j = n - 12; i < 13; i++, j++) if(esLucky(vals[i]) && esLucky(j)) total++; System.out.println(total); } else { if(k > factorial(n)) { System.out.println(-1); return; } int total = 0; int[] vals = permutar(new boolean[n], new int[n], 0, k); for(int i = 0; i < n; i++) vals[i] += 1; for(int i = 0, j = 1; i < n; i++, j++) if(esLucky(vals[i]) && esLucky(j)) total++; System.out.println(total); } } }
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> const int N = 100100; using namespace std; long long n, k, cnt; bool used[1000]; void build(long long x, long long mx) { if (x > mx) return; if (x) cnt++; build(x * 10 + 4, mx); build(x * 10 + 7, mx); } bool check(long long x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } int main() { ios_base::sync_with_stdio(0); cin >> n >> k; long long f = 1, g = 1; for (long long i = 1; i <= n; i++) { f *= i; if (f >= k) { g = i; break; } } if (f < k) { cout << -1 << endl; return 0; } vector<long long> v; for (long long i = g; i >= 1; i--) { f /= i; long long s = 0; for (long long j = 1; j <= g; j++) { if (used[j]) continue; else s++; if (f * (s - 1) + 1 <= k && k <= f * s) { k -= f * (s - 1); used[j] = true; v.push_back(j); break; } } } build(0, n - g); for (int i = 0; i < v.size(); i++) if (check(n - g + i + 1) && check(n - g + v[i])) cnt++; cout << cnt << 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 mod = 1e9 + 7, INF = 1e18; long long n, k; long long tot(long long count) { if (count > n) return 0; return 1 + tot(count * 10 + 7) + tot(count * 10 + 4); } long long findit(long long a) { while (a) { if (a % 10 != 4 && a % 10 != 7) return 0; a /= 10; } return 1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long t = 1; while (t--) { cin >> n >> k; vector<long long> vect(1, 1); long long i = 0, ans = tot(4) + tot(7); while (vect[i] < k) { vect.push_back(vect[i] * (i + 2)); i++; } if (vect.size() > n) { cout << "-1\n"; continue; } k--; vector<int> vis(vect.size(), 0), perm; long long m = n - vect.size() + 1, count = 0; while (k) { i = upper_bound(vect.begin(), vect.end(), k) - vect.begin(); long long j = 0; while (count < vis.size() - i - 1) { while (vis[j]) j++; vis[j] = 1; count++; perm.push_back(j); } i--; long long idx = k / vect[i]; k %= vect[i]; while (idx) { while (vis[j]) j++; j++; idx--; } while (vis[j]) j++; vis[j] = 1; count++; perm.push_back(j); } for (i = 0; i < vis.size(); i++) if (!vis[i]) { perm.push_back(i); } for (i = 0; i < perm.size(); i++) { if (findit(perm[i] + m)) { if (!findit(i + m)) { 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
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } long long lb = 10000000000; void vrikodara(long long n = 12) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << setprecision(n) << fixed; } long long n, k; set<long long> s; vector<long long> fact(14, 1); void generator(long long num) { lb--; if (lb < 0) { cout << "exit"; exit(0); }; if (num * 10 + 4 > n) return; s.insert(num * 10 + 4); generator(num * 10 + 4); if (num * 10 + 7 > n) return; s.insert(num * 10 + 7); generator(num * 10 + 7); } void generate_kth_permutation(vector<long long> &v, long long sz) { long long K = k; set<long long> num; v.clear(); for (long long i = 1; i <= sz; i++) num.insert(i); while (sz--) { K -= fact[sz]; for (auto i : num) { if (K > 0) { K -= fact[sz]; continue; } v.push_back(i); break; } num.erase(v.back()); if (!K) break; K += fact[sz]; } vector<long long> vd; for (auto e : num) vd.push_back(e); reverse(vd.begin(), vd.end()); for (auto e : vd) v.push_back(e); } void solve() { cin >> n >> k; bool flag = false; for (long long a = 1, i = n; i >= 1; i--) { a *= i; if (a >= k) { flag = true; break; } } if (!flag) { cout << "-1"; return; } generator(0); long long i = n, p = 1; while (i >= 1 && p < k) { p *= (n - i + 1); i--; } long long ans = 0; for (auto e : s) if (e <= i) ans++; long long sz = n - i; vector<long long> v; for (long long i = 1, a = 1; i <= 13; i++) { a *= i; fact[i] = a; } generate_kth_permutation(v, sz); for (auto &e : v) e += i; for (long long idx = i + 1; idx <= n; idx++) { if (s.count(idx) && s.count(v[idx - i - 1])) ans++; } cout << ans << '\n'; } int32_t main() { vrikodara(); long long t = 1; while (t--) { 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; long long factorial[13], res = 0; bool OK(int n) { stringstream ss; string s; ss << n; ss >> s; ss.clear(); for (int i = 0; i < s.size(); i++) { if (s[i] != '4' && s[i] != '7') return false; } return true; } int main() { int n, k; cin >> n >> k; vector<int> permutation; vector<int> v; vector<long long> luckys; luckys.push_back(4); luckys.push_back(7); for (int i = 0;; i++) { if (luckys[i] > 1e9) break; luckys.push_back(luckys[i] * 10 + 4); luckys.push_back(luckys[i] * 10 + 7); } factorial[0] = 1; for (int i = 1; i <= 13; i++) { factorial[i] = factorial[i - 1] * i; if (i <= n) permutation.push_back(i); } if (n < 13) { if (k > factorial[n]) { cout << -1; return 0; } } res = 0; for (int i = min(n - 1, 12); i >= 1; i--) { for (int j = 0; j < permutation.size(); j++) { if (k > factorial[i]) k -= factorial[i]; else { v.push_back(permutation[j]); permutation.erase(permutation.begin() + j); break; } } } for (int i = 0; i < permutation.size(); i++) v.push_back(permutation[i]); int nn = n; if (n > 12) { for (int i = 0; i < v.size(); i++) { v[i] = n - (13 - v[i]); } } for (int i = v.size() - 1; i >= 0; i--) { if (OK(nn) && OK(v[i])) { res++; } nn--; } for (int i = 0;; i++) { if (luckys[i] < n - 12) res++; else break; } cout << res; }
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 C { static int e; static long count; public static void construct(int l, String cur) { if (l == 0) { if (Integer.parseInt(cur) <= e) { count++; } return; } construct(l - 1, cur + "4"); construct(l - 1, cur + "7"); } public static long getLuckCount(int end) { int length = ("" + end).length(); long res = 0; for (int i = 1; i < length; i++) { res += (1 << i); } e = end; count = 0; construct(length, ""); res += count; return res; } public static boolean isLucky(int numb) { while (numb > 0) { int mod = numb % 10; if (mod != 4 && mod != 7) return false; numb /= 10; } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int idx = n; long cur = 1L; while (true) { if (cur >= k) { break; } idx--; if (idx < 1) { break; } cur *= (n - idx + 1); } cur /= (n - idx + 1); if (idx < 1) { System.out.println(-1); return; } ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = idx; i <= n; i++) { list.add(i); } int tmpIdx=idx; int[] res = new int[n - idx + 1]; int curSto = 0; while (list.size()>0) { long req = (long) Math.ceil((k*1.0) / cur); //System.out.println(k+" "+cur); res[curSto] = list.get((int) (req - 1)); list.remove((int)(req-1)); //System.out.println(Arrays.toString(res)+" "+list.size()); curSto++; k = (int) (k % cur); if(k==0){ k=(int) cur; } tmpIdx++; //System.out.println(k+" "+cur+" "+tmpIdx); if(n-tmpIdx+1!=0) cur=cur/(n-tmpIdx+1); } int print = 0; for (int i = 0, j = idx; i < res.length; i++, j++) { if (isLucky(j) && isLucky(res[i])) print++; } if (idx > 0) print += getLuckCount(idx - 1); System.out.println(print); } }
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.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class E { public static int[] readNNumbers(BufferedReader bf, int n) throws Exception{ int[] nums = new int[n]; int idx = 0; String line = bf.readLine(); for(int i = 0; i < line.length(); i++) { char c = line.charAt(i); if(c == ' ') idx++; else { int d = c - '0'; nums[idx] = 10 * nums[idx] + d; } } return nums; } public static int[] readNums(BufferedReader bf) throws Exception { int idx = 0, n = 0; String line = bf.readLine(); int i; for(i = 0; i < line.length(); i++) { char c = line.charAt(i); if(c == ' ') break; int d = c - '0'; n = 10 * n + d; } int[] nums = new int[n]; for(i = i + 1; i < line.length(); i++) { char c = line.charAt(i); if(c == ' ') idx++; else { int d = c - '0'; nums[idx] = 10 * nums[idx] + d; } } return nums; } public static long fact(long n) { long f = 1; for(int i = 2; i <= n; i++) { f *= i; } return f; } public static Set<Long> luckyNumbers = new TreeSet<Long>(); public static long pow9 = 1000000000L; public static void genLuckyNumbers(long before) { long four = before * 10L + 4L; long seven = before * 10L + 7; if(four <= pow9) { luckyNumbers.add(four); genLuckyNumbers(four); } if(seven <= pow9) { luckyNumbers.add(seven); genLuckyNumbers(seven); } } public static void main(String[] args) throws Exception { // System.setIn(new FileInputStream("e.in")); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); genLuckyNumbers(0L); int[] input = readNNumbers(bf, 2); long N = input[0], K = input[1]; if(N <= 14) { long fact = fact(N); if(K > fact) { System.out.println("-1"); return; } } int count = 0; int P = (int)Math.min(13, N); long remaining = N - P; for(long lucky : luckyNumbers) { if(lucky <= remaining) count++; else break; } int[] permutation = new int[P]; Set<Integer> nums = new TreeSet<Integer>(); for(int i = 1; i <= P; i++) nums.add(i); K--; for(int i = 0; i < P; i++) { long x = P - i - 1; long fact = fact(x); int position = (int)(K / fact); int j = 0, n = 0; for(int l : nums) { if(j > position) break; n = l; j++; } nums.remove(n); permutation[i] = (int)(n + remaining); K -= fact * position; } for(int i = 0; i < P; i++) { long permNumber = permutation[i]; long position = remaining + i + 1; if(!luckyNumbers.contains(permNumber)) continue; if(!luckyNumbers.contains(position)) continue; count++; } System.out.println(count); } }
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> 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; long long F = -1; if (N < 14) { F = 1; for (long long i = 1; i <= N; ++i) F *= i; if (K > F) { cout << -1 << endl; return 0; } } 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; if (K < F || F == -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; } } else if (K == F) { reverse((a).begin(), (a).end()); } 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
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const double eps = 1E-7; const int inf = int(1e9) + 7; int a[200000]; int tot; void dfs(long long x, int th) { if (x > 0) a[tot++] = x; if (th > 0) { dfs(x * 10 + 4, th - 1); dfs(x * 10 + 7, th - 1); } } long long jie(int x) { long long res = 1; for (int(i) = (1); (i) < (x + 1); ++(i)) res *= i; return res; } int ans[30]; void get_permutation(int n, int k) { bool mark[20]; memset((mark), 0, sizeof((mark))); for (int i = n; i >= 1; i--) { for (int j = 1; j <= n; j++) if (!mark[j]) { if (jie(i - 1) >= k) { mark[j] = true; ans[i] = j; break; } else { k -= jie(i - 1); } } } reverse(ans + 1, ans + n + 1); } bool isLuck(int x) { while (x) { int y = x % 10; if (y != 4 && y != 7) return false; x /= 10; } return true; } int main() { dfs(0, 9); sort(a, a + tot); int n, k; cin >> n >> k; int base = 1; while (base <= n && jie(base) < k) base++; if (base > n) { cout << "-1" << endl; return 0; } int num = 0; for (int(i) = 0; (i) < (tot); ++(i)) if (a[i] <= n - base) num = i + 1; get_permutation(base, k); for (int i = 1; i <= base; i++) { if (isLuck(i + n - base) && isLuck(ans[i] + n - base)) num++; } cout << num << 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 getLuckyNumberNoGreater(long long mx) { vector<long long> nums; if (mx >= 4) nums.push_back(4); if (mx >= 7) nums.push_back(7); for (int i = 0; i < nums.size() - 1 + 1; ++i) { auto x = nums[i]; if (x * 10 + 4 <= mx) nums.push_back(x * 10 + 4); if (x * 10 + 7 <= mx) nums.push_back(x * 10 + 7); } return nums.size(); } bool isLucky(long long x) { if (x == 0) return false; while (x > 0) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } int main() { ios_base::sync_with_stdio(false); long long n; cin >> n; ; long long k; cin >> k; ; int digits = 1; long long givePermutations = 1; while (givePermutations < k) { digits++; givePermutations *= digits; } if (digits > n) { cout << -1; return 0; } auto digitsBefore = n - digits; auto res = getLuckyNumberNoGreater(digitsBefore); auto startFrom = digitsBefore + 1; vector<long long> remainingNumbers; for (int i = startFrom; i < n + 1; ++i) remainingNumbers.push_back(i); k--; givePermutations /= digits; for (int i = 1; i < digits + 1; ++i) { auto i2 = k / givePermutations; k %= givePermutations; if (isLucky(remainingNumbers[i2]) && isLucky(startFrom + i - 1)) res++; remainingNumbers.erase(remainingNumbers.begin() + i2); if (i < digits) givePermutations /= (digits - i); } cout << res; }
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 logfac(long long k) { long long fac = 1; int ans = 0; while (fac < k) { ans++; fac *= ans; } return ans; } int a[100]; long long fact[30]; bool mark[100]; void make_permutation(int now, int n, int k) { if (now == n) return; int i; for (i = 1; i <= n; i++) if (!mark[i]) break; while (fact[n - now - 1] < k) { k -= fact[n - now - 1]; i++; while (mark[i]) i++; } a[now] = i; mark[i] = true; make_permutation(now + 1, n, k); } bool lucky(long long n) { while (n != 0) { if (n % 10 != 4 && n % 10 != 7) return false; n /= 10; } return true; } void addLuckeys(long long now, long long Max, int &ans) { if (now > Max) return; if (now != 0) ans++; addLuckeys(now * 10 + 4, Max, ans); addLuckeys(now * 10 + 7, Max, ans); } int main() { int n, k; cin >> n >> k; int changable = logfac(k); if (changable > n) { cout << -1 << endl; return 0; } fact[0] = 1; for (int i = 1; fact[i - 1] < 1e9; i++) fact[i] = fact[i - 1] * i; make_permutation(0, changable, k); int ans = 0; for (int i = 0; i < changable; i++) { if (lucky(n - changable + 1 + i) && lucky(a[i] + n - changable)) ans++; } addLuckeys(0, n - changable, ans); cout << ans << endl; return 0; }
CPP