jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
use std::cmp;

struct Solver {
    w: i32,
    cells: Vec<Vec<i32>>,
}

impl Solver {
    fn new() -> Solver {
        let w = read();
        let h = 2;
        Solver {
            w: w,
            cells: read_lines(h),
        }
    }

    fn run(&self) {
        let mut best = 0;

        // 最も良いルートを探索
        for i in 0..self.w as usize {
            let mut value = 0;
            let mut y = 0;
            for x in 0..self.w as usize {
                if i == x {
                    y = 1;
                    value = value + self.cells[0][x];
                }
                value = value + self.cells[y][x];
            }
            best = cmp::max(best, value);
        }

        println!("{}", best);
    }

    fn show(&self) {
        for row in &self.cells {
            for i in row {
                print!("{} ", i);
            }
            println!("");
        }
    }
}

fn read() -> i32 {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_lines(h: i32) -> Vec<Vec<i32>> {
    let mut v2 = Vec::new();
    for _ in 0..h {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).ok();
        let v = s.trim()
            .split_whitespace()
            .map(|e| e.parse().ok().unwrap())
            .collect();
        v2.push(v);
    }
    v2
}

fn main() {
    let solver = Solver::new();
    // solver.show()
    solver.run();
}
//  [swift]
let N = Int(readLine()!)!

var A = [[Int]]()
for _ in stride(from: 0, to: 2, by: 1) {
    let row = readLine()!.split(separator: " ").map { Int($0)! }
    A.append(row)
}

var dp = Array(repeating: Array(repeating: 0, count: N), count: 2)
for j in stride(from: 0, to: N, by: 1) {
    for i in stride(from: 0, to: 2, by: 1) {
        switch (i == 0, j == 0) {
        case (true, true):
            dp[0][0] = A[0][0]
        case (false, true):
            dp[1][0] = dp[0][0] + A[1][0]
        case (true, false):
            dp[0][j] = dp[0][j - 1] + A[0][j]
        case (false, false):
            dp[1][j] = max(dp[0][j], dp[1][j - 1]) + A[1][j]
        }
    }
}

print(dp.last!.last!)
//  [typescript]
import * as fs from "fs";

let input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");

const n = +input[0];
const a0 = input[1].split(" ").map((x: string): number => +x);
const a1 = input[2].split(" ").map((x: string): number => +x);

const s0: number[] = [];
for (let i = 0; i < n; i++) {
	if (i === 0) s0[i] = a0[i];
	else s0[i] = a0[i] + s0[i - 1];
}

const s1: number[] = [];
for (let i = n - 1; i >= 0; i--) {
	if (i === n - 1) s1[i] = a1[i];
	else s1[i] = a1[i] + s1[i + 1];
}

let result = -1;
for (let i = 0; i < n; i++) {
	const sum = s0[i] + s1[i];
	if (sum > result) result = sum;
}
console.log(result);
//  [python]
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7


def main():
    a = input()
    b = input()
    c = input()
    t = {'a':a, 'b':b, 'c':c}
    k = 'a'
    if len(a) < 1:
        return 'A'
    while len(t[k]) > 0:
        kk = t[k][0]
        t[k] = t[k][1:]
        k = kk
    if k == 'a':
        return 'A'
    if k == 'b':
        return 'B'
    return 'C'


print(main())
//  [python]
a=list(input())
b=list(input())
c=list(input())
order='a'
while True:
  if order=='a':
    if len(a)==0:
      print('A')
      break
    else:
      order=a[0]
      a=a[1:]
  elif order=='b':
    if len(b)==0:
      print('B')
      break
    else:
      order=b[0]
      b=b[1:]
  elif order=='c':
    if len(c)==0:
      print('C')
      break
    else:
      order=c[0]
      c=c[1:]
//  [python]
import numpy as np
Sa = input()
Sb = input()
Sc = input()

def string2int(in_list):
    out_list = np.array(in_list, dtype='S')
    out_list[out_list==b'a'] = 0
    out_list[out_list==b'b'] = 1
    out_list[out_list==b'c'] = 2
    return np.array(out_list, dtype=int)
Sa = string2int(list(Sa))
Sb = string2int(list(Sb))
Sc = string2int(list(Sc))
ALL = [list(Sa), list(Sb), list(Sc)]

current = 0
pre = 0
while True:
    left = len(ALL[current])
    if left == 0:
        break
    current = ALL[current][0]
    ALL[pre] = ALL[pre][1:]
    pre = current

cor = ['A','B','C']
print( cor[current] )
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		StringBuilder sbA = new StringBuilder();
		sbA.append(scan.nextLine());
		StringBuilder sbB = new StringBuilder();
		sbB.append(scan.nextLine());
		StringBuilder sbC = new StringBuilder();
		sbC.append(scan.nextLine());
		char tern = sbA.charAt(0);
		sbA.deleteCharAt(0);
		while (true) {

			switch (tern) {
			case 'a':
				if (sbA.length() == 0) {
					System.out.println("A");
					return;
				}
				tern = sbA.charAt(0);
				sbA.deleteCharAt(0);
				break;
			case 'b':
				if (sbB.length() == 0) {
					System.out.println("B");
					return;
				}
				tern = sbB.charAt(0);
				sbB.deleteCharAt(0);
				break;
			case 'c':
				if (sbC.length() == 0) {
					System.out.println("C");
					return;
				}
				tern = sbC.charAt(0);
				sbC.deleteCharAt(0);
				break;
			}
		}
	}

}
//  [java]
import java.util.Scanner;

public class Main{
	public static void main(String[] args){
		
		Scanner scan = new Scanner(System.in);
		
		String a = scan.next();
		String b = scan.next();
		String c = scan.next();
		
		int sum = a.length() + b.length() + c.length();
		
		int flag = 0;
		
		int f_a = 0;
		int f_b = 0;
		int f_c = 0;
		
		for(int i = 0 ; i < sum ; i++){
			
			if(flag == 0){
				
				if(f_a == a.length()){
					
					System.out.println("A");
					break;
				}
				
				if(a.charAt(f_a) == 'a'){
					flag = 0;
				} else if(a.charAt(f_a) == 'b'){
					flag = 1;
				} else if(a.charAt(f_a) == 'c'){
					flag = 2;
				}
				
				f_a++;
				
			
			} else if(flag == 1){
				
				if(f_b == b.length()){
					
					System.out.println("B");
					break;
				}
				
				if(b.charAt(f_b) == 'a'){
					flag = 0;
				} else if(b.charAt(f_b) == 'b'){
					flag = 1;
				} else if(b.charAt(f_b) == 'c'){
					flag = 2;
				}
				
				f_b++;
				
			
			} else if(flag == 2){
				
				if(f_c == c.length()){
					
					System.out.println("C");
					break;
				}
				
				if(c.charAt(f_c) == 'a'){
					flag = 0;
				} else if(c.charAt(f_c) == 'b'){
					flag = 1;
				} else if(c.charAt(f_c) == 'c'){
					flag = 2;
				}
				
				f_c++;
				
			}
			
		}
	}
}
//  [java]
import java.util.Scanner;

public class Main {
	void run() {
		Scanner sc = new Scanner(System.in);

		char[] a = sc.next().toCharArray();
		char[] b = sc.next().toCharArray();
		char[] c = sc.next().toCharArray();

		int turn = 0;
		int aid = 0, bid = 0, cid = 0;
		while (true) {
			if (turn == 0) {
				if (a.length <= aid) {
					System.out.println("A");
					return;
				}
				turn = a[aid++] - 'a';
			} else if (turn == 1) {
				if (b.length <= bid) {
					System.out.println("B");
					return;
				}
				turn = b[bid++] - 'a';
			} else {
				if (c.length <= cid) {
					System.out.println("C");
					return;
				}
				turn = c[cid++] - 'a';
			}
		}
	}

	public static void main(String[] args) {
		new Main().run();
	}
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main(){
  vector<string> cards(3);
  for(int i=0;i<3;++i) cin >> cards[i];

  int turn = 0;
  while(true){
	if(cards[turn].empty()){
	  cout << (char)('A' + turn) << endl;
	  break;
	}
	int next = cards[turn][0] - 'a';
	cards[turn].erase(0, 1);
	turn = next;
  }

  return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main(){
    
    string Sa,Sb,Sc;
    cin >> Sa >> Sb >> Sc;
    int a=0,b=0,c=0;
    char next='a';

    while(1){
        if(next=='a'){
            if(a==Sa.size()){
                cout << 'A' << endl;
                break;
            }
            else{
                next=Sa.at(a);
                a++;
            }
        }
        if(next=='b'){
            if(b==Sb.size()){
                cout << 'B' << endl;
                break;
            }
            else{
                next=Sb.at(b);
                b++;
            }
        }
        if(next=='c'){
            if(c==Sc.size()){
                cout << 'C' << endl;
                break;
            }
            else{
                next=Sc.at(c);
                c++;
            }
        }
    }
}
//  [cpp]
#include <bits/stdc++.h>
#define rep(i, a, n) for(int i = a; i < n; i++)
#define repb(i, a, b) for(int i = a; i >= b; i--)
#define all(a) a.begin(), a.end()
#define int long long
using namespace std;

signed main(){
    string s[3];
    rep(i, 0, 3) cin >> s[i];
    int ans = -1, now = 0;
    rep(i, 0, 1000001){
        int tmp;
        tmp = s[now][0] - 'a';
        s[now] = s[now].substr(1);
        now = tmp;
        if(s[now].size() == 0){
            ans = now;
            break;
        }
    }
    cout << (char)('A' + ans) << endl;
}
//  [c]
int main(void){
    char sa[100]={'\0'};
    char sb[100]={'\0'};
    char sc[100]={'\0'};
    int yoa=0,yob=0,yoc=0;
    int la,lb,lc;
    char key;
    scanf("%s",sa);la=strlen(sa);sa[la]='A';
    scanf("%s",sb);lb=strlen(sb);sb[lb]='B';
    scanf("%s",sc);lc=strlen(sc);sc[lc]='C';
    key=sa[yoa];
    yoa++;
    while(!(key=='A'||key=='B'||key=='C')){
      
        switch(key){
            case 'a':
            if(yoa==la){
                printf("A");
                return 0;
            }
            key=sa[yoa];
            yoa++;
            break;
            case 'b':
            if(yob==lb){
                printf("B");
                return 0;
            }
            key=sb[yob];
            yob++;
            break;
            case 'c':
            if(yoc==lc){
                printf("C");
                return 0;
            }
            key=sc[yoc];
            yoc++;
            break;
        }
    }
    printf("\n");
    return 0;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int nextplayer(char s[3][128], int p[3], int player, int *winner) {
	char temp;
	temp = s[player][p[player]];
	p[player] += 1;

	if(temp == '\n' || temp == '\0') {
		*winner = player;
	}
	if(temp == 'a') {
		return 0;
	} else if(temp == 'b') {
		return 1;
	} else {
		return 2;
	}
}

int main(void) {
	int p[3];
	int winner = -1;
	int player;
	char buf[128], *ch;
	char s[3][128];

	fgets(s[0], sizeof(buf), stdin);//a's card
	fgets(s[1], sizeof(buf), stdin);//b
	fgets(s[2], sizeof(buf), stdin);//c
	p[0] = 0;
	p[1] = 0;
	p[2] = 0;

	player = 0;
	while(winner == -1) {
		player = nextplayer(s, p, player, &winner);
	}

	if(winner == 0) {
		printf("A\n");
	} else if(winner == 1) {
		printf("B\n");
	} else {
		printf("C\n");
	}

	return 0;
}
//  [javascript]
'use strict'

const main = (input) => {
    input = input.split('\n').map(v => v.split(''))
    const a = input[0]
    const b = input[1]
    const c = input[2]

    let i = 'a'
    let item = []
    while(true){
        if(i === 'a'){
            item = a
        }else if(i === 'b'){
            item = b
        }else{
            item = c
        }
        if(item.length === 0){
            console.log(i.toUpperCase())
            break
        }
        i = item.shift()
    }
}

main(require('fs').readFileSync('/dev/stdin', 'utf-8'))
//  [javascript]
console.log((args=>{
  const [a,b,c] = args.trim().split`\n`.map(r=>r.split``.reverse());
  const S = {a,b,c};
  let p = 'a';
  while ( S[p].length ) p = S[p].pop();
  return p.toUpperCase();
})(require('fs').readFileSync('/dev/stdin', 'utf8')));
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const A = arg[0].split("");
    const B = arg[1].split("");
    const C = arg[2].split("");
    
    let now = "a";
    
    while(true) {
        // console.log("now:" + now);
        // console.log("A:" + A);
        // console.log("B:" + B);
        // console.log("C:" + C);
        // console.log("--------")
        
        if(now === "a") {
            if(A.length === 0) break;
            let temp = A.shift();

            now = temp;
        } else if(now === "b") {
            if(B.length === 0) break;
            let temp = B.shift();
            
            now = temp;
        } else {
            if(C.length === 0) break;
            let temp = C.shift();
            
            now = temp;
        }
    }
    
    let answer;
    
    if(now === "a") {
        answer = "A";
    } else if(now === "b") {
        answer = "B";
    } else {
        answer = "C";
    }
    
    console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import (
	"fmt"
	"strings"
)

func main() {
	var sa, sb, sc string
	fmt.Scan(&sa)
	fmt.Scan(&sb)
	fmt.Scan(&sc)
	num := len(sa + sb + sc)
	// fmt.Printf("sa = %s, sb = %s, sc = %s, num = %d\n", sa, sb, sc, num)

	var player string
	var ia, ib, ic int

	player = sa[0:1]
	ia++

	for i := 1; i < num; i++ {
		// fmt.Printf("player = %s, ia = %d, ib = %d, ic = %d\n", player, ia, ib, ic)
		if player == "a" {
			if ia >= len(sa) {
				break
			}
			player = sa[ia : ia+1]
			ia++
		} else if player == "b" {
			if ib >= len(sb) {
				break
			}
			player = sb[ib : ib+1]
			ib++
		} else if player == "c" {
			if ic >= len(sc) {
				break
			}
			player = sc[ic : ic+1]
			ic++
		}
	}
	fmt.Println(strings.ToUpper(player))
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}
func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}
func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	sa := getNextString(scanner)
	sb := getNextString(scanner)
	sc := getNextString(scanner)
	la := 0
	lb := 0
	lc := 0
	p := 0
	for {
		switch p {
		case 0:
			if len(sa) == la {
				fmt.Fprintln(writer, "A")
				return
			}
			p = int(sa[la] - 'a')
			la++
		case 1:
			if len(sb) == lb {
				fmt.Fprintln(writer, "B")
				return
			}
			p = int(sb[lb] - 'a')
			lb++
		case 2:
			if len(sc) == lc {
				fmt.Fprintln(writer, "C")
				return
			}
			p = int(sc[lc] - 'a')
			lc++
		}
	}
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

type player struct {
	name  string
	cards []string
}

func (p *player) playCard() string {
	card := p.cards[0]
	p.cards = p.cards[1:]
	return card
}

func main() {
	var a, b, c string
	fmt.Scan(&a, &b, &c)

	playerA := &player{name: "A", cards: strings.Split(a, "")}
	playerB := &player{name: "B", cards: strings.Split(b, "")}
	playerC := &player{name: "C", cards: strings.Split(c, "")}
	cardPlayerMap := map[string]*player{"a": playerA, "b": playerB, "c": playerC}

	curPlayer := playerA
	for {
		if len(curPlayer.cards) == 0 {
			fmt.Println(curPlayer.name)
			return
		}
		curPlayer = cardPlayerMap[curPlayer.playCard()]
	}
}
//  [ruby]
# hand_a = 'abcb'.chars.to_a
# hand_b = 'aacb'.chars.to_a
# hand_c = 'bccc'.chars.to_a
hand_a, hand_b, hand_c  = 3.times.map{gets.chomp.chars.to_a}

class Card
    attr_accessor :str, :hand_a, :hand_b, :hand_c
    
    def initialize(str)
        @str = str
    end
    
    def logic(str)
        
        # p "bef-str:", @hand_a
        if str == 'a'
            @str = @hand_a[0]
            @hand_a.delete_at(0)
        elsif str == 'b'
            @str = @hand_b[0]
            @hand_b.delete_at(0)
        elsif str == 'c'
            @str = @hand_c[0]
            @hand_c.delete_at(0)
        end
        # p "aft-str:", @hand_a
            
    end
end

card = Card.new(hand_a[0])
card.hand_a = hand_a
card.hand_b = hand_b
card.hand_c = hand_c


# puts hand_a.class
# puts hand_b
# puts hand_c

# puts "length", card.hand_a.length, card.hand_b.length, card.hand_c.length
end_A = true
end_B = true
end_C = true

while end_A and end_B and end_C do 
    card.logic(card.str)
    
    if (card.hand_a.length == 0 && card.str == "a")
        end_A = false
        win = "A"
    end
    if (card.hand_b.length == 0 && card.str == "b")
        end_B = false
        win = "B"
    end
    if (card.hand_c.length == 0 && card.str == "c")
        end_C = false
        win = "C"
    end
end
# puts "length", card.hand_a.length, card.hand_b.length, card.hand_c.length

puts win
# p "a:", card.hand_a
# p "b:", card.hand_b
# p "c:", card.hand_c
//  [ruby]
$A = gets.chomp.chars
$B = gets.chomp.chars
$C = gets.chomp.chars

def game(player, player_hand)
  return player if player_hand.empty?
  case player_hand.shift
  when "a" then
    game("A", $A)
  when "b" then
    game("B", $B)
  when "c" then
    game("C", $C)
  end
end

puts game("A", $A)
//  [ruby]
# https://atcoder.jp/contests/abc045/tasks/abc045_b

a = gets.upcase
b = gets.upcase
c = gets.upcase
hash = { A: a, B: b, C: c }

next_user = hash[:A].slice!(..0)
winner = "A"

while next_user != nil
  next_user = hash[next_user.intern]&.slice!(..0)
  if next_user == 'A' || next_user == 'B' || next_user == 'C'
    winner = next_user
  end
end

puts winner
//  [rust]
use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;
use std::collections::*;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[fastout]
fn main() {
    input!{
        sa: Chars,
        sb: Chars,
        sc: Chars,
    }
    let mut sa_deq: VecDeque<char> = VecDeque::new();
    let mut sb_deq: VecDeque<char> = VecDeque::new();
    let mut sc_deq: VecDeque<char> = VecDeque::new();
    for i in sa {
        sa_deq.push_back(i);
    }
    for i in sb {
        sb_deq.push_back(i);
    }
    for i in sc {
        sc_deq.push_back(i);
    }

    // let mut turn: char = sa_deq.pop_front().unwrap();
    let mut turn: char = 'a';
    loop {
        if sa_deq.is_empty() && turn=='a' {
            println!("A");
            return;
        }
        if sb_deq.is_empty() && turn=='b' {
            println!("B");
            return;
        }
        if sc_deq.is_empty() && turn=='c' {
            println!("C");
            return;
        }
        match turn {
            'a' => turn = sa_deq.pop_front().unwrap(),
            'b' => turn = sb_deq.pop_front().unwrap(),
            'c' => turn = sc_deq.pop_front().unwrap(),
            _ => return,
        }
        debug!(sa_deq);
        debug!(sb_deq);
        debug!(sc_deq);
    }

}
//  [rust]
use proconio::input;
use proconio::marker::Chars;

fn main() {
    input! {
        mut s_a: Chars,
        mut s_b: Chars,
        mut s_c: Chars,
    }

    println!("{}", solve(&mut s_a, &mut s_b, &mut s_c));
}

fn solve(s_a: &mut Vec<char>, s_b: &mut Vec<char>, s_c: &mut Vec<char>) -> String {
    s_a.reverse();
    s_b.reverse();
    s_c.reverse();

    let mut x = s_a.pop().unwrap();
    loop {
        if x == 'a' && s_a.len() == 0 {
            return String::from("A");
        }
        if x == 'b' && s_b.len() == 0 {
            return String::from("B");
        }
        if x == 'c' && s_c.len() == 0 {
            return String::from("C");
        }
        match x {
            'a' => x = s_a.pop().unwrap(),
            'b' => x = s_b.pop().unwrap(),
            _ => x = s_c.pop().unwrap(),
        }
    }
}
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const S = {
    A: input[0][0].split(""),
    B: input[1][0].split(""),
    C: input[2][0].split(""),
  };

  type Players = keyof typeof S;

  let cursor: Players = "A";

  while (S[cursor].length !== 0) {
    cursor = S[cursor].shift()!.toUpperCase() as Players;
  }

  return cursor;
};

console.log(main(read()));
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const S = {
    A: input[0][0].split(""),
    B: input[1][0].split(""),
    C: input[2][0].split(""),
  };

  let current: keyof typeof S = "A";

  while (S[current].length !== 0) {
    current = S[current].shift()!.toUpperCase() as keyof typeof S;
  }

  return current;
};

console.log(main(read()));
//  [typescript]
import * as fs from "fs";
const input = fs.readFileSync("/dev/stdin", "utf-8");

const main = (input: string): void => {
  const [a, b, c] = input.split("\n").map((str) => str.split(""));
  let next: string | undefined;

  const term = (str: string) => {
    if (str === "a") next = a.shift();
    else if (str === "b") next = b.shift();
    else if (str === "c") next = c.shift();

    if (!next) console.log(str.toUpperCase());
    else term(next);
  };

  term(a[0]);
};

main(input);
//  [python]
def getN():
    return int(input())

def getMN():
    a = input().split()
    b = [int(i) for i in a]
    return b[0],b[1]

def getlist():
    a = input().split()
    b = [int(i) for i in a]
    return b

def zen(n,used, new):

    usednum = len(used|set([new]))
    #print("keta",usednum)
    if n == 0:
        if usednum == 3:
            return 1
        else:
            return 0

    if usednum == 3:
        return 3**n
    if usednum == 2:
        return 3**n - 2**n
    if usednum == 1:
        return 3**n - 2*(2**n) +1
    return 3**n - 3*(2**n) + 3

def simo_init(n):
    if n == 0:
        return 0
    return 3 ** n - 3 * (2 ** n) + 3

n = input()
digit = len(n)

answer = 0
for i in range(digit):
    answer += simo_init(i)

def get_simo(n, dig,used):
    global answer
    if n == "":
        if len(used) == 3:
            answer += 1
        return
    if int(n[0]) > 3:
        answer += zen(dig-1, used, 3)
    if int(n[0]) > 5:
        answer += zen(dig-1, used, 5)
    if int(n[0]) > 7:
        answer += zen(dig-1, used, 7)

    #print("all: ",answer)
    #print("dig: ", dig, n)
    first = int(n[0])
    if first in [3,5,7]:
        get_simo(n[1:], dig-1, used|set([first]))


get_simo(n,digit,set())
print(answer)

#print(zen(3,set()))
//  [python]
N = input()


def f(d, used, next):
    num = len(used | set(next))
    if d == 0:
        if num == 3:
            return 1
        else:
            return 0
    elif num == 3:
        return 3 ** d
    elif num == 2:
        return 3 ** d - 2 ** d
    else:
        return 3 ** d - 2 * (2 ** d) + 1


def high(N, used, ret):
    if N:
        if N[0] > "3":
            ret += f(len(N) - 1, used, "3")
        if N[0] > "5":
            ret += f(len(N) - 1, used, "5")
        if N[0] > "7":
            ret += f(len(N) - 1, used, "7")
    else:
        if len(used) == 3:
            ret += 1
        return ret
    if N[0] in "357":
        ret = high(N[1:], used | set(N[0]), ret)
    return ret


def low():
    ret = 0
    for i in range(len(N) - 1):
        ret += 3 * (3 ** i - 2 ** (i + 1) + 1)
    return ret


def main():
    print(high(N, set(), low()))
    return


main()
//  [python]
def f(N, D, b=False):
    if len(N)==0: return 0 if b else 1

    n0 = int(N[0])
    m = 0
    for d in D:
        if d==n0:
            m += f(N[1:], D)
        if d<n0:
            m += len(D)**len(N[1:])
    return m + f('9'*len(N[1:]), D, True) if b else m

N = input()
print(( f(N,[3,5,7],True)
       -f(N,[3,5  ],True)
       -f(N,[  5,7],True)
       -f(N,[3,  7],True)
       +f(N,[3    ],True)
       +f(N,[  5  ],True)
       +f(N,[    7],True)))
//  [python]
from sys import stdin
import sys
sys.setrecursionlimit(10**6) 
import bisect

n = int(stdin.readline().rstrip())

li = [7,5,3]

if n < 357:
    print(0)
    exit()

def Base_10_to_n(X, n):
    if (int(X/n)):
        return Base_10_to_n(int(X/n), n)+str(X%n)
    return str(X%n)

kazu = 0
point = 0
k = "0"
while int(k) <= n:
    k = Base_10_to_n(kazu,4)
    k = k.replace("3","7").replace("1","3").replace("2","5")
    if all(k.count(c)>0 for c in "753")and k.count("0") == 0:
        if int(k) <= n:
            point += 1
    kazu += 1
print(point)
//  [python]
import itertools

N = input()
N1 = int(N)
N2 = len(N)

num753_comb = []
for i in range(N2):
  num753_comb.append([0,3,5,7])
All_comb = list(itertools.product(*num753_comb))

count = 0
for i in range(len(All_comb)):
 tmp = list(All_comb[i])
 tmp_num = 0
 judge0,judge3,judge5,judge7 = 0,0,0,0

 for j in range(N2):
   tmp_num += tmp[j]*(10**(N2-1-j))   
   if((tmp_num > 0)and(tmp[j] == 0)): judge0 += 1
   elif(tmp[j] == 3): judge3 += 1
   elif(tmp[j] == 5): judge5 += 1
   elif(tmp[j] == 7): judge7 += 1
   
 if(tmp_num <= N1):
   if((judge3>=1)and(judge5>=1)and(judge7>=1)and(judge0 == 0)):
      count += 1     
print(count)
//  [python]
N=int(input())
ans=set()
def saiki(A):
    if len(A)>0:
        B="".join(A)
        count=set(A)
        #print(count)
        if eval(B)<=N:
            if len(count)==3:
                ans.add(B)
        else:
            return
    for i in [3,5,7]:
        A.append(str(i))
        saiki(A)
        A.pop()
saiki([])
print(len(ans))
//  [java]
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {  
	public static void main(String[] args) { 
		FastScanner I = new FastScanner(); //Input
		OutPut O = new OutPut(); //Output
		long N = I.nextLong();
		int[] a = new int[10]; //right most indicates ones digit, 2nd rightmost indicates tens
		//digit and so on
		int ans = 0; //GOD
		while (true) {
			UPD(a,9);
			if (!BelowN(a,N)) break;
			//for (int i = 0; i<=9; i++) O.p(a[i]+" ");
			//O.p("\n");
			if (Valid(a)) {
				ans++;
			} 
		}
		O.pln(ans);
	}
	public static void UPD(int[] a, int in) {
		if (a[in]==0) a[in]=3;
		else{
			a[in]+=2;
			if (a[in]>7) {
				a[in]=3; //Reset and recurse backwards
				UPD(a,in-1);
			}
		}
	}
	public static boolean Valid(int[] a) {
		boolean[] vis = new boolean[10];
		for (int i = 0; i<= 9; i++) {
			vis[a[i]]=true; //Remember only valid digits are used
		}
		return vis[3]&&vis[5]&&vis[7]?true:false;
	}
	public static boolean BelowN(int[] a, long N) {
		long sum = 0;
		long mult = 1;
		for (int i = 9; i>= 0; i--) {
			sum+=a[i]*mult;
			mult*=10;
		}
		return sum<=N?true:false;
	}
	public static long ceil(long num, long den) {long ans = num/den; if (num%den!=0) 
	ans++; return ans;}
	public static long GCD(long a, long b) {
		if (a==0||b==0) return Math.max(a,b);
		return GCD(Math.min(a, b),Math.max(a, b)%Math.min(a, b));
	}
	public static long FastExp(long base, long exp, long mod) {
		long ans=1;
		while (exp>0) {
			if (exp%2==1) ans*=base;
			exp/=2;
			base*=base;
			base%=mod;
			ans%=mod;
		}
		return ans;
	}
	public static long ModInv(long num,long mod) {return FastExp(num,mod-2,mod);}
	public static int pop(long x) { //Returns number of bits within a number
		int cnt = 0;
		while (x>0) {
			if (x%2==1) cnt++;
			x/=2;
		}
		return cnt;
	}
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		int nextInt() {return Integer.parseInt(next());}
		long nextLong() {return Long.parseLong(next());};
		double nextDouble() {return Double.parseDouble(next());}
	}
	static class OutPut{
		PrintWriter w = new PrintWriter(System.out);
		void pln(double x) {w.println(x);w.flush();}
		void pln(boolean x) {w.println(x);w.flush();}
		void pln(int x) {w.println(x);w.flush();}
		void pln(long x) {w.println(x);w.flush();}
		void pln(String x) {w.println(x);w.flush();}
		void pln(char x) {w.println(x);w.flush();}
		void pln(StringBuilder x) {w.println(x);w.flush();}
		void pln(BigInteger x) {w.println(x);w.flush();}
		void p(int x) {w.print(x);w.flush();}
		void p(long x) {w.print(x);w.flush();}
		void p(String x) {w.print(x);w.flush();}
		void p(char x) {w.print(x);w.flush();}
		void p(StringBuilder x) {w.print(x);w.flush();}
		void p(BigInteger x) {w.print(x);w.flush();}
		void p(double x) {w.print(x);w.flush();}
		void p(boolean x) {w.print(x);w.flush();}
	}
}
//  [java]
import java.util.Scanner;
    public class Main {
        public static void main(String[] args){
          	Scanner sc = new Scanner(System.in);
    		int N = sc.nextInt();
    		sc.close();
            int M=0;
            int i=357;
            while(i<=N){
                int a=0;
                int b=0;
                int c=0;
                int d=0;
                for(int j=i;j>0;j/=10){
                    if(j%10==3){
                        a++;
                    }else if(j%10==5){
                        b++;
                    }else if(j%10==7){
                        c++;
                    }else{
                        d++;
                        break;
                    }
                }
                if(a!=0&&b!=0&&c!=0&&d==0){
                    M++;
                }
                if(i%100==37||i%10==57){
                  i+=16;
                }else if(i%100==77){
                  i+=56;
                }else {
                  i+=2; 
                }
            }
            System.out.println(M);
        }
    }
//  [java]
import java.util.*;

public class Main {
	
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int count = 0;
		int flag = 2;
		for (int i = 357; i <= n; i += 2) {
			if (is753(i)) {
				count++;
			}
			flag++;
			if (flag == 3) {
				flag = 0;
				i += 14;
			}
		}
		
		System.out.println(count);
		
	}

	
	public static boolean is753(int x) {
		int count7 = 0;
		int count5 = 0;
		int count3 = 0;
		while (x != 0) {
			switch (x % 10) {
				case 7 :
				count7++;
				break;
				case 5 :
				count5++;
				break;
				case 3:
				count3++;
				break;
				default :
				return false;
			}
			x /= 10;
		}
		return (count7 * count5 * count3 > 0);			
	}
	
}
//  [java]
import java.util.*;

class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String S = sc.next();
		int S_N = Integer.parseInt(S);
		int N = S.length();
		int[] nums = {3, 5, 7, 0};
		int cnt=0;

		String[] str_array = new String[(int)Math.pow(4,N)];
		for (int i=0;i<Math.pow(4,N);i++) {
			int[] array = new int[N];
			for (int j=0;j<N;j++) {
				int tmp = i;
				for (int k=0;k<j;k++) {
					tmp/=4;
				}
				array[j] = tmp%4;
			}
			for (int j=0;j<N;j++) {
				str_array[i]+=String.valueOf(nums[array[j]]);
			}
			str_array[i]=str_array[i].replace("null","");
			int ans = Integer.parseInt(str_array[i]);

			int[] flag = new int[5];
			for (int j=0;j<N;j++) {
				char number = str_array[i].charAt(j);
				if (number=='3') {
					flag[0]=1;
					flag[4]=1;
				} else if (number=='5') {
					flag[1]=1;
					flag[4]=1;
				} else if (number=='7') {
					flag[2]=1;
					flag[4]=1;
				} else if (number=='0') {
					if (flag[4]==1) {
						flag[3]=1;
					}
				}
			}
			if (flag[0]==1 && flag[1]==1 && flag[2]==1 && flag[3]==0) {
				if (ans<=S_N) {
					cnt++;
				}
			}
		}
		System.out.println(cnt);
	}
}
//  [cpp]
#include <bits/stdc++.h>

#define ll long long
#define ull unsigned long long

using namespace std;

ll N;
ll ans;

void dfs(ll cur, int use) {
	if (cur > N){
		return;
	}
	if ( use == 0b111 ){
		ans++;
	}

	dfs(cur * 10 + 3, use | 0b001);
	dfs(cur * 10 + 5, use | 0b010);
	dfs(cur * 10 + 7, use | 0b100);
}

int main() {
	cin >> N;
	ans = 0;

	dfs(0, 0);
	
	cout << ans << "\n";

	return 0;
}
//  [cpp]
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <map>

using namespace std;

namespace {
}

int DFS(long long tmpN, int N, unsigned bitFlags) // tmpNは一時的に1e10になる。
{
	if (tmpN > N) {
		return 0;
	}

	int sum = 0;
	if (bitFlags == 0b111) {
		sum = 1;
	}

	sum += DFS(tmpN * 10 + 3, N, bitFlags | 0b100);
	sum += DFS(tmpN * 10 + 5, N, bitFlags | 0b010);
	sum += DFS(tmpN * 10 + 7, N, bitFlags | 0b001);

	return sum;
}

int main()
{
	int N = 0;
	cin >> N;

	unsigned bitFlags(0b00); // 3, 5, 7 
	cout << DFS(0, N, bitFlags) << endl;

	return 0;
}
//  [cpp]
#include<iostream>
using namespace std;
int main(){
    int a,b,c;
    cin >> a;
    b=0;
    int d3,d5,d7;
    if(a>777777777)a=777777777;
    for(int i=355;i<=a;i+=2){
        c=i;
        d3=d5=d7=0;
        while(c>0){
            if(c%10!=3 && c%10!=5 && c%10!=7)break;
            if(c%10==3) d3=1;
            if(c%10==5) d5=1;
            if(c%10==7) d7=1;
            c/=10;
            if(c==0 && d3==1 && d5==1 && d7==1) {
              b++;
            }
        }
    }
    cout << b << endl;

}
//  [cpp]
#include "bits/stdc++.h"
using namespace std;

// #define int long long

inline bool is753(int n) {
  int three = 0;
  int five = 0;
  int seven = 0;

  while(true){
    switch (n % 10){
    case 3:
      ++three;
      break;
    case 5:
      ++five;
      break;
    case 7:
      ++seven;
      break;
    default:
      return false;
    }
    n /= 10;
    if (n==0)
      break;
  }
  if(three * five * seven == 0)
    return false;
  return true;
}

// bool is753(int n) {
//   string s = to_string(n);
//   if(s.find("0") != string::npos)
//     return false;
//   if(s.find("1") != string::npos)
//     return false;
//   if(s.find("2") != string::npos)
//     return false;
//   if(s.find("4") != string::npos)
//     return false;
//   if(s.find("6") != string::npos)
//     return false;
//   if(s.find("8") != string::npos)
//     return false;
//   if(s.find("9") != string::npos)
//     return false;

//   if(s.find("3") == string::npos)
//     return false;
//   if(s.find("5") == string::npos)
//     return false;
//   if(s.find("7") == string::npos)
//     return false;

//   return true;
// }

signed main(void) {
  int num; // num
  num = 0; // count, result
  // num = numeric_limits<int>::min(); // max
  // num = numeric_limits<int>::max(); // min
  int n;

  cin >> n;

  int i = 357;
  while(true){
    if(i>n)
      break;
    if (is753(i)) // **7
      ++num;
    i += 6;
    if(i>n)
      break;
    if (is753(i)) // **3
      ++num;
    i += 2;
    if(i>n)
      break;
    if (is753(i)) // **5
      ++num;
    i += 2;
  }

  cout << num << endl;
  return 0;
}
//  [cpp]
#include <iostream>
#include <string.h>
using namespace std;
bool if_753(int n){
    int x;
    bool if3=false;
    bool if5=false;
    bool if7=false;
    while(n>0){
        x=n%10;
        if(x==3){
            if3=true;
        }else if(x==5){
            if5=true;
        }else if(x==7){
            if7=true;
        }else{
            return false;
        }
        n/=10;
    }
    return if3&&if5&&if7;
}
int main(void){
    int N;
    int c=0;
    cin>>N;
    int i=357;
    int m=2;
    while(i<=N){
        if(if_753(i))c++;
        if(++m==3){
          m=0;
          i+=4;
        };
        i+=2;
    }
    cout<<c<<endl;
    return 0;
}
//  [c]
n,s=0;
d(long x,int b){
if(x>n)return;
if(x<=n&&b==7)s++;
d(x*10+3,b|1);d(x*10+5,b|2);d(x*10+7,b|4);}
main(){scanf("%d",&n);d(0,0);printf("%d",s);}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h> // uint64_t

#define max(a,b) ((a) > (b) ? (a) : (b))
#define min(a,b) ((a) > (b) ? (b) : (a))

int get_int(void) {
  int num;
  scanf("%d", &num);
  return num;
}

static int map[10];
static int valid[3] = {3, 5, 7};
int traverse(int64_t cur, int64_t limit) {
    if(cur > limit) return 0;
    int ans = 0;
    int i;
    int flag = 1;
    for(i = 0; i < 3; i++) {
        int d = valid[i];
        if(!map[d]) flag = 0;
        map[d]++;
        ans += traverse(cur*10 + d, limit);
        map[d]--;
    }
    return ans + flag;
}

int main(void) {
    int num = get_int();
    int ans = traverse(0, num);
    printf("%d\n", ans);
    return 0;
}
//  [c]
#include <stdio.h>

long long N;

void dfs(long long x, int bits, long long int *cnt){
    if(x>N) return;
    if(bits == 0b111) *cnt = *cnt+1;
    dfs(x*10+3,bits|0b001,cnt);
    dfs(x*10+5,bits|0b010,cnt);
    dfs(x*10+7,bits|0b100,cnt);
}

int main(void){
    scanf("%lld",&N);
    long long int ans=0;
    dfs(0,0,&ans);
    printf("%lld",ans);
}
//  [c]
#include<stdio.h>

int main(){
	int N;
	int ans=0;
	scanf("%d",&N);
	
	for(int i=573;i<=N;i+=20){
		int exist5=0;
		int exist7=0;
		int j=i;
		while(j>0){
			int k=j%10;
			if(k==5)exist5=1;
			else if(k==7)exist7=1;
			else if(k!=3)break;
			j/=10;
		}
		if(j>0 || exist5==0 || exist7==0)continue;
		ans++;
	}
	for(int i=375;i<=N;i+=20){
		int exist3=0;
		int exist7=0;
		int j=i;
		while(j>0){
			int k=j%10;
			if(k==3)exist3=1;
			else if(k==7)exist7=1;
			else if(k!=5)break;
			j/=10;
		}
		if(j>0 || exist3==0 || exist7==0)continue;
		ans++;
	}
	for(int i=357;i<=N;i+=20){
		int exist5=0;
		int exist3=0;
		int j=i;
		while(j>0){
			int k=j%10;
			if(k==5)exist5=1;
			else if(k==3)exist3=1;
			else if(k!=7) break;
			j/=10;
		}
		if(j>0 || exist5==0 || exist3==0)continue;
		ans++;
	}
	
	printf("%d\n",ans);
	return 0;
}
//  [c]
#include <stdio.h>

int main(void){
    // Your code here!
    int n, amount = 0, flag = 0;
    int key[3] = {0,0,0};
    scanf("%d",&n);
    
    if(n <= 356)
    {
        amount = 0;
    }
    else
    {
        int count = 357;
        while(count <= n)
        {
            key[0] = 0;
            key[1] = 0;
            key[2] = 0;
            flag = 1;
            //printf("%d:\n",count);
            for(int j = count; j > 0 && flag == 1; j /= 10)
            {
                switch(j%10)
                {
                    case 3:
                        key[0]++;
                        break;
                        
                    case 5:
                        key[1]++;
                        break;
                        
                    case 7:
                        key[2]++;
                        break;
                        
                    default:
                        flag = 0;
                }
            }
            //printf("%d, %d %d %d\n",flag,key[0],key[1],key[2]);
            if(flag == 1 && key[0]*key[1]*key[2] != 0) amount++;
            
            switch(count%100)
            {
                case 37:
                    count += 16;
                    break;
                    
                case 57:
                    count += 16;
                    break;
                    
                case 77:
                    count += 56;
                    break;
                    
                default:
                    count += 2;
            }
        }
    }
    printf("%d\n",amount);
}
//  [c]
#include<math.h>
#include<stdio.h>
#define min(a,b) (a)<=(b)?(a):(b)
int main()
{   int n,i,cnt3=0,cnt5=0,cnt7=0,ans=0,start=1;
    scanf("%d",&n);
    if(n>=777777753){
        printf("26484");
        return 0;
    }
           if(n>=100000000&&n<=300000000){
                printf("8334");
                return 0;
            }
            if(n>300000000&&n<=400000000){
                ans=8334;
                start=300000000;
            }
            if(n>400000000&&n<=500000000){
                printf("14384");
                return 0;
            }
            if(n>500000000&&n<=600000000){
                ans=14384;
                start=500000000;
            }
            if(n>600000000&&n<=700000000){
                ans=20434;
                return 0;
            }
            if(n>700000000&&n<=800000000){
                ans=20434;
                start=700000000;
            }
    int s=min(n,777777753);
        for(i=start;i<=s;i++){
            
        cnt3=0;cnt5=0;cnt7=0;
        int num=i;
        while(num>0){if(num%10==3)cnt3++;
        
        else if(num%10==5)cnt5++;
        else if(num%10==7)cnt7++;
        else break;
        num/=10;
        }
        if(num==0&&cnt3>0&&cnt5>0&&cnt7>0)ans++;
    }
    printf("%d",ans);

    return 0;
}
//  [javascript]
  function f(use, x, n, acc) {
    if (x > n) return acc;
    if (use === 0b111) acc += 1;
    acc += f(use | 0b001, x * 10 + 3, n, 0);
    acc += f(use | 0b010, x * 10 + 5, n, 0);
   acc += f(use | 0b100, x * 10 + 7, n, 0);
    return acc;
  }

  function Main(input) {
    var n = parseInt(input);
    console.log(f(0, 0, n, 0));
  }

  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
    const N = input.trim();
    let answer = 0;
    const DFS = (N, num753) => {

        const contains7 = num753.includes('7');
        const contains5 = num753.includes('5');
        const contains3 = num753.includes('3');
        const contains = contains7 && contains5 && contains3;

        // 753数値が完成
        if(N.length == num753.length){
            if(contains && Number(num753) <= Number(N))  {
                answer++;
            }
            return; 
        }
        // 今の桁をチェック
        if(contains && Number(num753) <= Number(N)) {
            answer++;
        }
        // 3を入れるパターン
        DFS(N, num753 + '3');    
        // 5を入れるパターン
        DFS(N, num753 + '5');
        // 7を入れるパターン
        DFS(N, num753 + '7');
    }
    // 一桁目を作る
    DFS(N, '3');
    DFS(N, '7');
    DFS(N, '5');
    console.log(answer);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function f(i, x, n, acc) {
  if (x > n) return acc;
  var p = new Array(10);
  var m = x;
  while (m > 0) {
    switch(m % 10) {
      case 3: {
        p[3] = true;
        break;
      }
      case 5: {
        p[5] = true;
        break;
      }
      case 7: {
        p[7] = true;
        break;
      }
      default: {
        break;
      }
    }
    m = Math.floor(m / 10);
  }
  acc += p[3] === true && p[5] === true && p[7] === true ? 1 : 0;
  acc += f(i + 1, Math.pow(10, i) * 3 + x, n, 0);
  acc += f(i + 1, Math.pow(10, i) * 5 + x, n, 0);
  acc += f(i + 1, Math.pow(10, i) * 7 + x, n, 0);
  return acc;
}

function Main(input) {
  var n = parseInt(input);
  var acc = 0;
  acc += f(1, 3, n, 0);
  acc += f(1, 5, n, 0);
  acc += f(1, 7, n, 0);
  console.log(acc);
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict'
function main(input) {
  input = Number(input.trim())
  const check = n => {
    n = String(n)
    return ~n.indexOf('7') && ~n.indexOf('5') && ~n.indexOf('3')
  }
  const dfs = n => {
    if (n === '' || Number(n) <= input) {
      let r = check(n) ? 1 : 0
      r += dfs(Number(n + '7'))
      r += dfs(Number(n + '5'))
      r += dfs(Number(n + '3'))
      return r
    } else {
      return 0
    }
  }
  console.log(dfs(''))
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function Main(input){
	input = ~~input.split("\n")[0];
  var arr = ["0","3","5","7"];
  var count = 0;
  for(var a of arr){
  for(var b of arr){
  for(var c of arr){
  for(var d of arr){
  for(var e of arr){
  for(var f of arr){
  for(var g of arr){
  for(var h of arr){
  for(var i of arr){
  	var hoge = [a,b,c,d,e,f,g,h,i];
    hoge = (""+~~(hoge.join(""))).split("");
    if(hoge.length < 3)continue;
    if(hoge.find((j)=>j==0) !== undefined)continue;
   	if(hoge.find((j)=>j==3) && hoge.find((j)=>j==5) && hoge.find((j)=>j==7)){
    	var value = ~~hoge.join("");
      if(value > input)return count;
      count++;
    }
  }
  }
  }
  }
  }
  }
  }
  }
  }
  return count;
}

// If you are interested in the algorithms I used, 
// there is no need to read down from this line.

((b,c,d)=>"undefined"!=typeof require?console.log(Main(require("fs").readFileSync("/dev/stdin","utf8"))):[b=b.split("\n").slice(1,-1).join("\n"),c=function(){try{return Main(b)}catch(f){return f.stack||f.message}}(),d=typeof c,"string"==d||(c=JSON.stringify(c)),$("<form>").append([[10,b],0,[1,d],0,[10,c]].map(f=>$(f?"<textarea>":"<br>",f&&{rows:f[0],cols:40,text:f[1]}))).appendTo("body")])(`
999999999
`);
//  [javascript]
var toInt = x=>parseInt(x,10);
var toIntArr = arr=>arr.map(x=>toInt(x));
var abs = x=>x>0?x:-x;
function min(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]<val)val = rest[i];return val}
function max(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]>val)val = rest[i];return val}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
 
function Main(input){
	var input = input.split('\n');
	var n = toInt(input[0]);
	var arr = [-1];
	var pow3 = [1];
	for(var i = 1 ; i < 11; i++){
		pow3[i] = 3*pow3[i-1];
	}
	var M = 1000000000;
	var a,b,c;
	var ans = 0;
	var arr357 = [3,5,7];
	for(var i = 0; i < M; i++){
		a = i;
		arr[0]++;
		for(var j = 0; j < 10; j++){
			if(arr[j]===3){
				arr[j]-=3;
				if(arr[j+1]===undefined){
					arr[j+1] = 0;
					break;
				}else{
					arr[j+1]++;
				}
			}

		}
		c = arr.map(el=>arr357[el]);
		//console.log(i,arr,c)
		if(toInt(c.reverse().join(''))>n){
			break;
		}
		if(arr.indexOf(0)===-1 || arr.indexOf(1)===-1 || arr.indexOf(2)===-1){
			continue;
		}
		ans++;

	}
	console.log(ans);
}
//  [go]
package main

import (
	"fmt"
	"os"
)

func solve(N, digits, acc int, d3, d5, d7 bool) int {
	if digits == 0 {
		if acc <= N && d3 && d5 && d7 {
			return 1
		}
		return 0
	}

	res := solve(N, digits-1, acc*10+3, true, d5, d7) +
		solve(N, digits-1, acc*10+5, d3, true, d7) +
		solve(N, digits-1, acc*10+7, d3, d5, true)
	if acc <= N && d3 && d5 && d7 {
		res++
	}
	return res
}

func main() {
	r := os.Stdin
	var N int
	fmt.Fscan(r, &N)

	//generate
	res := solve(N, 9, 0, false, false, false)
	fmt.Println(res)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const (
	initialBufSize = 1e4
	maxBufSize     = 1e6 + 7
	// それぞれをbitで判定する
	three uint = 1
	five       = three << 1
	seven      = five << 1
	all        = seven | five | three
)

var buf []byte = make([]byte, maxBufSize)
var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(buf, maxBufSize)
}

// 見様見真似実装
// https://drken1215.hatenablog.com/entry/2019/04/03/125400
// https://drken1215.hatenablog.com/entry/2020/05/04/190252

func main() {
	X := nextInt()
	var ans int
	dfs(0, 0, &ans, X)
	fmt.Println(ans)
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func dfs(num int, used uint, ans *int, X int) {
	if num > X {
		return
	}
	if used == all {
		*ans++
	}
	// 実際に遷移を見るとわかりやすい
	// fmt.Println(num, used, *ans)
	// なんとなく3からのほうがしっくり来るのでそうしてるがどっちでもいい
	dfs(num*10+3, used|three, ans, X)
	dfs(num*10+5, used|five, ans, X)
	dfs(num*10+7, used|seven, ans, X)
}