Problem:
Score : 600 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.

There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.

Notes

A string a is a substring of another string b if and only if there exists an integer x (0 \leq x \leq |b| - |a|) such that, for any y (1 \leq y \leq |a|), a_y = b_{x+y} holds.

We assume that the concatenation of zero copies of any string is the empty string. From the definition above, the empty string is a substring of any string. Thus, for any two strings s and t, i = 0 satisfies the condition in the problem statement.

Constraints

1 \leq |s| \leq 5 \times 10^5

1 \leq |t| \leq 5 \times 10^5

s and t consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print -1.

Sample Input 1

abcabab
ab

Sample Output 1

3

The concatenation of three copies of t, ababab, is a substring of the concatenation of two copies of s, abcabababcabab, so i = 3 satisfies the condition.

On the other hand, the concatenation of four copies of t, abababab, is not a substring of the concatenation of any number of copies of s, so i = 4 does not satisfy the condition.

Similarly, any integer greater than 4 does not satisfy the condition, either. Thus, the number of non-negative integers i satisfying the condition is finite, and the maximum value of such i is 3.

Sample Input 2

aa
aaaaaaa

Sample Output 2

-1

For any non-negative integer i, the concatenation of i copies of t is a substring of the concatenation of 4i copies of s. Thus, there are infinitely many non-negative integers i that satisfy the condition.

Sample Input 3

aba
baaab

Sample Output 3

0

As stated in Notes, i = 0 always satisfies the condition.

Solution in Rust (1.15.1) (judge verdict: Accepted)

#[doc = " https://github.com/hatoo/competitive-rust-snippets"]
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[macro_export]
macro_rules ! chmax { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: max ( $ x ,$ v ) ; ) + } ; }
#[macro_export]
macro_rules ! chmin { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: min ( $ x ,$ v ) ; ) + } ; }
#[macro_export]
macro_rules ! max { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: max ( $ x , max ! ( $ ( $ xs ) ,+ ) ) } ; }
#[macro_export]
macro_rules ! min { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: min ( $ x , min ! ( $ ( $ xs ) ,+ ) ) } ; }
#[macro_export]
macro_rules ! dvec { ( $ t : expr ; $ len : expr ) => { vec ! [ $ t ; $ len ] } ; ( $ t : expr ; $ len : expr , $ ( $ rest : expr ) ,* ) => { vec ! [ dvec ! ( $ t ; $ ( $ rest ) ,* ) ; $ len ] } ; }
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }
#[macro_export]
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }
#[macro_export]
macro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }
#[macro_export]
macro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( "Parse error" ) } ; }
use std::io;
use std::io::BufRead;
use std::str;
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}
impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}
impl<R: BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len, complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                if len == 0 {
                    break;
                }
                (len, buf2[len - 1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            } else {
                self.update_buf();
            }
        }
    }
}
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }
#[doc = " https://github.com/hatoo/competitive-rust-snippets"]
const BIG_STACK_SIZE: bool = true;
#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}
fn solve() {
    let out = stdout();
    let mut out = BufWriter::new(out.lock());

    input!{
        s:chars,
        t:chars,
    }

    let mut ss = vec![];
    for c in s {
        ss.push(c as u64 - 'a' as u64);
    }

    let mut tt = vec![];
    for c in t {
        tt.push(c as u64 - 'a' as u64);
    }

    let ars = ArithSeq {
        a: 0,
        b: ss.len() as i64,
    };

    let mut sss = vec![];
    let L = ars.next((ss.len() + tt.len()) as i64);
    for _ in 0..(L / ss.len() as i64) {
        sss.append(&mut ss.clone());
    }

    let M = tt.len();
    let kmp = KMP::new(tt);
    let res = kmp.search(&sss);
    let N = ss.len();
    let mut g = vec![HashSet::new(); N];
    for i in res {
        let i = i % N;
        let j = (i + M) % N;
        g[i].insert(j);
    }

    let cycled = cycle_detection_directed(&g);
    if cycled {
        println!("-1");
        return
    }

    let mut ing = vec![vec![]; N];
    for i in 0..N {
        for &to in &g[i] {
            ing[to].push(i);
        }
    }

    let mut rec = Rec {
        ing: ing,
        dp: vec![None;N],
    };
    let mut maxv = 0;
    for i in 0..N {
        chmax!(maxv, rec.solve(i));
    }
    println!("{}", maxv);
}
struct Rec {
    ing: Vec<Vec<usize>>,
    dp: Vec<Option<usize>>,
}
impl Rec {
    fn solve(&mut self, i: usize) -> usize {
        if self.ing[i].len() == 0 {
            return 0
        }
        if let Some(x) = self.dp[i] {
            return x;
        }
        let mut maxv = 0;
        for j in 0..self.ing[i].len() {
            let from = self.ing[i][j];
            chmax!(maxv, self.solve(from) + 1);
        }
        self.dp[i] = Some(maxv);
        return maxv;
    }
}
pub fn cycle_detection_directed(g: &[HashSet<usize>]) -> bool {
    let n = g.len();
    let mut in_g = vec![HashSet::new(); n];
    for v in 0..n {
        for &u in &g[v] {
            in_g[u].insert(v);
        }
    }
    let mut v_indegree0 = vec![];
    for v in 0..n {
        if in_g[v].len() == 0 {
            v_indegree0.push(v);
        }
    }
    let mut m = 0;
    while let Some(v) = v_indegree0.pop() {
        m += 1;
        for &to in &g[v] {
            if in_g[to].remove(&v) && in_g[to].is_empty() {
                v_indegree0.push(to);
            }
        }
    }
    m != n
}
struct ArithSeq {
    a: i64,
    b: i64,
}
impl ArithSeq {
    #[doc = "a+bi >= x"]
    pub fn next(&self, x: i64) -> i64 {
        if x >= self.a {
            let d = x - self.a;
            let i = (d - 1 + self.b) / self.b;
            self.a + self.b * i
        } else {
            let d = self.a - x;
            let i = d / self.b;
            self.a - self.b * i
        }
    }
    #[doc = "a+bi <= x"]
    pub fn prev(&self, x: i64) -> i64 {
        let next = self.next(x);
        if next == x {
            x
        } else {
            next - self.b
        }
    }
    #[doc = "[a+bi, n] <= [l, u]"]
    pub fn range(&self, l: i64, u: i64) -> Option<(i64, i64)> {
        if l > u {
            return None
        }
        let x = self.next(l);
        let y = self.prev(u);
        if x > y {
            return None
        }
        assert!(x <= y);
        if l<=x && x<=u {
            let cnt = (y-x) / self.b;
            Some((x, cnt+1))
        } else {
            None
        }
    }
}

struct KMP {
    pat: Vec<u64>,
    tbl: Vec<i64>,
}
impl KMP {
    #[doc = "O(K)"]
    fn new(pat: Vec<u64>) -> Self {
        let n = pat.len();
        let mut tbl = vec![0; n + 1];
        tbl[0] = -1;
        let mut j: i64 = -1;
        for i in 0..n {
            while j >= 0 && pat[i] != pat[j as usize] {
                j = tbl[j as usize];
            }
            j += 1;
            if i + 1 < n && pat[i + 1] == pat[j as usize] {
                tbl[i + 1] = tbl[j as usize];
            } else {
                tbl[i + 1] = j;
            }
        }
        KMP { pat: pat, tbl: tbl }
    }
    #[doc = "O(N)"]
    fn search(&self, s: &[u64]) -> Vec<usize> {
        let mut res = vec![];
        let mut head: i64 = 0;
        let mut j: i64 = 0;
        while head + j < s.len() as i64 {
            if self.pat[j as usize] == s[(head + j) as usize] {
                j += 1;
                if j != self.pat.len() as i64 {
                    continue;
                }
                res.push(head as usize);
            }
            head += j - self.tbl[j as usize];
            j = std::cmp::max(self.tbl[j as usize], 0);
        }
        res
    }
}