The only difference between easy and hard versions is constraints.

There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed.

For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on.

Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$.

Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids:  after the $1$-st day it will belong to the $5$-th kid,  after the $2$-nd day it will belong to the $3$-rd kid,  after the $3$-rd day it will belong to the $2$-nd kid,  after the $4$-th day it will belong to the $1$-st kid. 

So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.

You have to answer $q$ independent queries.


-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 1000$) — the number of queries. Then $q$ queries follow.

The first line of the query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of kids in the query. The second line of the query contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct, i.e. $p$ is a permutation), where $p_i$ is the kid which will get the book of the $i$-th kid.

It is guaranteed that $\sum n \le 2 \cdot 10^5$ (sum of $n$ over all queries does not exceed $2 \cdot 10^5$).


-----Output-----

For each query, print the answer on it: $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ is the number of the day the book of the $i$-th child is returned back to him for the first time in this query.


-----Example-----
Input
6
5
1 2 3 4 5
3
2 3 1
6
4 6 2 1 5 3
1
1
4
3 4 1 2
5
5 1 2 4 3

Output
1 1 1 1 1 
3 3 3 
2 3 3 2 1 3 
1 
2 2 2 2 
4 4 4 1 4

Difficulty: introductory

Starter code:

Solutions:
for _ in range(int(input())):
    n = int(input())
    P = list(map(int, input().split()))
    ans = [0] * n
    for i in range(n):
        if ans[i] == 0:
            now = i
            cnt = 0
            cll = []
            while True:
                now = P[now] - 1
                cnt += 1
                cll.append(now)
                if now == i:
                    break
            for u in cll:
                ans[u] = cnt
    print(' '.join(list(map(str, ans))))

import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
# print = stdout.write
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
for _ in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    for i in range(n):
        a[i]-=1
    col = [0 for i in range(n)]
    c = 1
    for i in range(n):
        if not col[i]:
            s = i
            while col[s] == 0:
                col[s] = c
                s = a[s]
            c+=1
    d = defaultdict(int)
    for i in col:
        d[i]+=1
    ans = [0 for i in range(n)]
    for i in range(n):
        ans[i] = d[col[i]]
    print(*ans)

tc = int(input())

while tc > 0:
	tc -= 1
	n = int(input())
	p = [0] + list(map(int, input().split()))

	ans = [0] * (n + 1)
	mk = [False] * (n + 1)

	for i in range(1 , n + 1):
		if not mk[i]:
			sz = 1
			curr = p[i]
			mk[i] = True
			while curr != i:
				sz += 1
				mk[curr] = True
				curr = p[curr]

			ans[i] = sz
			curr = p[i]
			while curr != i:
				ans[curr] = sz
				curr = p[curr]

	print(" ".join([str(x) for x in ans[1:]]))




tc = int(input())

while tc > 0:
	tc -= 1
	n = int(input())
	p = [0] + list(map(int, input().split()))

	ans = [0] * (n + 1)
	mk = [False] * (n + 1)

	for i in range(1 , n + 1):
		if not mk[i]:
			sz = 1
			curr = p[i]
			mk[i] = True
			while curr != i:
				sz += 1
				mk[curr] = True
				curr = p[curr]

			ans[i] = sz
			curr = p[i]
			while curr != i:
				ans[curr] = sz
				curr = p[curr]

	print(" ".join([str(x) for x in ans[1:]]))




t = int(input())
for _ in range(t):
    n = int(input())
    p = list(map(int, input().split()))
    ans = [-1] * n
    for i in range(n):
        if ans[i] != -1:
            continue
        memo = {}
        tmp = i
        memo[tmp] = 1
        cnt = 1
        while True:
            tmp = p[tmp] - 1
            if tmp in memo:
                break
            else:
                memo[tmp] = 1
                cnt += 1
        for j in memo:
            ans[j] = cnt
    print(*ans)


import sys
input = sys.stdin.readline

q=int(input())

def find(x):
    while Group[x] != x:
        x=Group[x]
    return x

def Union(x,y):
    if find(x) != find(y):
        Group[find(y)]=Group[find(x)]=min(find(y),find(x))

for testcases in range(q):
    n=int(input())
    P=list(map(int,input().split()))

    Group=[i for i in range(n)]

    for i in range(n):
        Union(i,P[i]-1)

    G=[find(i) for i in range(n)]

    count=[0]*n

    for g in G:
        count[g]+=1

    for i in range(n):
        print(count[G[i]],end=" ")
    print()



    


import sys
def I():
    return sys.stdin.readline().rstrip()
q = int( I() )
for _ in range( q ):
    n = int( I() )
    c = [ -1 ] * n
    def getp( i ):
        s = []
        while c[ i ] >= 0:
            s.append( i )
            i = c[ i ]
        for j in s:
            c[ j ] = i
        return i
    p = list( map( int, I().split() ) )
    p = [ i - 1 for i in p ]
    for i, q in enumerate( p ):
        a, b = getp( i ), getp( q )
        if a != b:
            c[ a ] += c[ b ]
            c[ b ] = a
    for i in p:
        print( -c[ getp( i ) ], end = " " )
    print()


q = int(input())
for i in range(q):
    n = int(input())
    a = list(map(int, input().split()))
    b = [-1 for i in range(n)]
    c = [0 for i in range(n + 2)]
    used = [True for i in range(n)]
    for i in range(n):
        if used[i]:
            d = a[i] - 1
            cell = a[i] - 1
            b[cell] = d
            c[d] += 1
            used[cell] = False
            while cell != i:
                cell = a[cell] - 1
                c[d] += 1
                b[cell] = d
                used[cell] = False
    for i in range(n):
        print(c[b[i]], end=" ")
    print()


q = int(input())

for i in range(q):

    n = int(input())

    lis = [0] * n
    

    a = list(map(int,input().split()))
    
    q = []
    ind = 0
    now = 0
    end = 0
    while end < n:

        while ind < n:
            if lis[ind] == 0:
                now = ind
                break
            ind += 1

        q = []

        while len(q) == 0 or now != q[0]:
            q.append(now)
            now = a[now] - 1

        for i in q:
            lis[i] = len(q)

        end += len(q)

    print(" ".join(map(str,lis)))


for _ in range(int(input())):
    n = int(input())
    l = [int(i) - 1 for i in input().split()]
    res = []
    v = [0] * n
    for i in range(n):
        if (v[i] == 0):
            temp = i
            v[temp] = 1
            res.append({temp})
            while (l[temp] not in res[-1]):
                res[-1].add(l[temp])
                temp = l[temp]
                v[temp] = 1
    # print(res)
    for i in res:
        for j in i:
            v[j] = len(i)
    print(*v)

def read():
    return list(map(int,input().split()))

q = int(input())
for test in range(q):
    n = int(input())
    a = read()
    for i in range(n):
        a[i] -= 1
    used = [False]*n
    ans = [0]*n
    for i in range(n):
        if not used[i]:
            j = a[i]
            k = 1
            while j!=i:
                k += 1
                j = a[j]
            j = a[i]
            ans[i] = k
            while j!=i:
                j = a[j]
                ans[j] = k
                used[j] = True
    print(*ans)


q = int(input())
for i in range(q):
    n = int(input())
    a = [int(i) for i in input().split()]
    ans = [0] * n
    for i in range(n):
        if ans[i] == 0:
            numbers_now = []
            now = a[a[i] - 1]
            numbers_now.append(i)
            numbers_now.append(a[i] - 1)
            count = 1
            while now != a[i]:
                now = a[now - 1]
                numbers_now.append(now - 1)
                count += 1
            for i in numbers_now:
                ans[i] = count
        else:
            continue
    print(*ans)


q = int(input())
for i in range(q):
    a = int(input())
    cycle = [1 for i in range(a)]

    tab = list(map(int, input().split()))

    for indice, j in enumerate(tab):
        if cycle[indice] != 1:
            continue
        var = indice +1

        while tab[var-1] != indice+1:
            var = tab[var-1]
            cycle[indice] += 1

        var = indice +1

        while tab[var-1] != indice+1:
            var = tab[var-1]
            cycle[var-1] = cycle[indice]


    print(*cycle)

I = lambda: list(map(int, input().split()))

t, = I()
while t:
    t -= 1
    n, = I()
    l = I()
    l = [i-1 for i in l]
    p = [i for i in range(n)]
    v = [0]*n
    for i in range(n):
        if not v[i]:
            v[i] = 1
            j = l[i]
            while not v[j]:
                v[j] = 1
                v[i] += 1
                p[j] = i
                j = l[j]
                
    #print(v)
    for i in range(n):
        print(v[p[i]], end = ' ')
    print()


t = int(input(''))
for _ in range(t):
    n = int(input(''))
    p = list(map(int,input('').split(' ')))
    d = {}
    for i in range(n):
        d[p[i]] = i+1
    exp = [False]*(n+1)
    ans = {}
    for i in range(1,n+1,1):
        if(not exp[i]):
            a = [i]
            c = 1
            t = i
            while(d[t] != i):
                t = d[t]
                exp[t] = True
                c = c+1
                a.append(t)
            for f in a:
                ans[f] = c

    for i in range(1,n+1,1):
        print(ans[i], end = ' ')
    print('')
            

def solve():
    n = int(input())
    a = list(map(int, input().split()))
    for i in range(n):
        a[i] -= 1

    ans = dict()

    for i in range(n):
        # st = i + 1
        if i not in ans:
            p = []

            j = i
            p.append(j)
            ca = 0
            while True:
                ca += 1
                j = a[j]
                p.append(j)
                if j == i:
                    for x in p:
                        ans[x] = ca
                    break

    for i in range(n):
        print(ans   [i], end=" ")
    print()


for _ in range(int(input())):
    solve()


from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
def sieve():
    for i in range(2,MAXN,2):
        spf[i] = 2
    for i in range(3,int(MAXN**0.5)+1):
        if spf[i]==i:
            for j in range(i*i,MAXN,i):
                if spf[j]==j:
                    spf[j]=i
def fib(n,m):
    if n == 0:
        return [0, 1]
    else:
        a, b = fib(n // 2)
        c = ((a%m) * ((b%m) * 2 - (a%m)))%m
        d = ((a%m) * (a%m))%m + ((b)%m * (b)%m)%m
        if n % 2 == 0:
            return [c, d]
        else:
            return [d, c + d]

def charIN(x= ' '):
    return(sys.stdin.readline().strip().split(x))

def arrIN(x = ' '):
    return list(map(int,sys.stdin.readline().strip().split(x)))

def ncr(n,r):
    num=den=1
    for i in range(r):
        num = (num*(n-i))%MOD
        den = (den*(i+1))%MOD

    return (num*(pow(den,MOD-2,MOD)))%MOD

def flush():
    return sys.stdout.flush()

'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''

def bfs(v):
    q = [v]
    vis[v] = 1
    s = 0
    l = []
    while q:
        x = q.pop(0)
        l.append(x)
        s+=1
        st[x] = s
        for i in d[x]:
            if not vis[i]:
                q.append(i)
                vis[i] = 1
            else:
                t = s+1-st[i]
                break
    for i in l:
        ans[i] = t


for _ in range(int(input())):
    n = int(input())
    a = arrIN()
    d = defaultdict(list)
    for i in range(1,n+1):
        d[i].append(a[i-1])
    vis = [0]*(n+1)
    st = [0]*(n+1)
    ans = [0]*(n+1)
    for i in range(1,n+1):
        if not vis[i]:
            bfs(i)
    print(*ans[1:])

import sys
input = sys.stdin.readline

q = int(input())

for _ in range(q):
    n = int(input())
    p = list(map(int, input().split()))
    
    for i in range(n):
        p[i] -= 1
    
    flag = [-1] * n
    ans = [-1] * n
    
    for i in range(n):
        cur = i
        
        if flag[cur] == 1:
            continue

        flag[cur] = 1
        l = [cur]
        
        while True:
            if flag[p[cur]] == 1:
                break
            
            if flag[p[cur]] == -1:
                flag[p[cur]] = 1
            
            cur = p[cur]
            l.append(cur)
        
        for li in l:
            ans[li] = len(l)
    
    print(*ans)

import sys

input = sys.stdin.readline
sys.setrecursionlimit(100000)


def getN():
    return int(input())


def getList():
    return list(map(int, input().split()))


import math

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        self.size = [1] * (n+1)

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1


    def same_check(self, x, y):
        return self.find(x) == self.find(y)


def solve():
    n = getN()
    nums = getList()
    uf = UnionFind(n)
    # print(nums)
    for i, num in enumerate(nums):
        uf.par[i+1] = uf.find(i+1)
        uf.par[num] = uf.find(num)
        # print(uf.size)
        # print(uf.par)
        # print("============")
        if not uf.same_check(i+1, num):
            uf.union(i+1, num)

    for i in range(n+1):
        uf.find(i)
    ans = []
    for i in range(n):
        ans.append(uf.size[uf.par[i+1]])
    print(*ans)
    # print(uf.size)
    # print(uf.par)

def main():
    q = getN()
    for _ in range(q):
        solve()

def __starting_point():
    main()

"""
1
3
2 3 1
"""
__starting_point()

q = int(input())
for _ in range(q):
    n = int(input())
    Q = list(map(int,input().split()))
    res=[1]*n
    for i in range(n):
        if res[i]==1:
            t = Q[i]
            tl = [t]
            while t!=i+1:
                t=Q[t-1]
                tl.append(t)
                res[i]+=1
            for k in tl:
                res[k-1]=res[i]
    print(*res)

#    !/usr/bin/env python3
#    encoding: UTF-8
#    Last Modified: 22/Oct/2019 08:25:41 PM


import sys


def main():
    for tc in range(int(input())):
        n = int(input())
        arr = get_array()
        for i in range(n):
            arr[i] -= 1
        ans = [1] * n
        d = {}
        for i in range(n):
            if i in d:
                continue
            tmp = {}
            j = arr[i]
            while j != i:
                ans[i] += 1
                j = arr[j]
                tmp[arr[j]] = 1
            for j in tmp:
                ans[j] = ans[i]
                d[j] = 1

        print(*ans)


get_array = lambda: list(map(int, sys.stdin.readline().split()))


get_ints = lambda: list(map(int, sys.stdin.readline().split()))


input = lambda: sys.stdin.readline().strip()


def __starting_point():
    main()

__starting_point()

import sys
import itertools
import math
import collections
from collections import Counter

#########################
# imgur.com/Pkt7iIf.png #
#########################

def sieve(n):
    prime = [True for i in range(n + 1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 1
    prime[0] = prime[1] = False
    r = [p for p in range(n + 1) if prime[p]]
    return r
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def ceil(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return list(map(int, input().split()))
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep=' '): print(sep.join(map(str, a)))
def dd(): return collections.defaultdict(int)

t = ii()
for i in range(t):
    n = ii()
    d = li()
    s = [0]*n
    used = [-1]*n

    for i in range(n):
        if used[i] == -1:
            u, v = i, d[i] - 1
            while True:
                s[i] += 1
                used[u] = i
                u, v = v, d[v] - 1
                if u == i:
                    break
    res = []
    for i in range(n):
        res.append(s[used[d[i] - 1]])
    prr(res)







for _ in range(int(input())):

    n = int(input())
    p = [int(x) - 1 for x in input().split()]

    used = [False] * n
    r = [0] * n

    for i in range(n):
        if not used[i]:
            j = i
            cycle = []
            while not used[j]:
                cycle.append(p[j])
                used[j] = True
                j = p[j]
            for c in cycle:
                r[c] = len(cycle)
    print(*r)