1675D - Vertical Paths - CodeForces Solution


graphs implementation trees *1300

Please click on ads to support us..

Python Code:

def f():
    n = int(input())
    a = list(map(int, input().split()))
    if n == 1:
        print('1' + "\n" + '1' + "\n" + '1' + "\n")
        return
    visited = [False] * n
    branch = [True] * n
    for i in a:
        branch[i-1] = False
    print(branch.count(True))
    for i in range(n):
        if branch[i]:
            t = i
            path = [i+1]
            while not visited[a[t]-1]:
                visited[a[t]-1] = True
                path.append(a[t])
                t = a[t]-1
            print(len(path))
            print(' '.join(str(x) for x in path[::-1]))
    print()



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

C++ Code:

#include <bits/stdc++.h>
using namespace std;
const int N=2e5+7;
int a[N];
int used[N];
vector<int>leaves;
stack<int>s;
void solve()
{
    int n;
    cin>>n;
    leaves.clear();
    for(int i=1;i<=n;i++) used[i]=0;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        used[a[i]]=1;
    }
    if(n==1)
    {
        cout<<"1\n1\n1\n\n";
        return;
    }
    for(int i=1;i<=n;i++)
    {
        if(!used[i]) leaves.push_back(i);
    }
    int siz=leaves.size();
    cout<<siz<<'\n';
    for(int i=1;i<=n;i++) used[i]=0;
    for(auto &i:leaves)
    {
        int cnt=0;
        int noww=i;
        while(!used[noww])
        {
            cnt++;
            used[noww]=1;
            s.push(noww);
            if(a[noww]==noww) break;
            else noww=a[noww];
        }
        if(cnt>0)
        {
            cout<<cnt<<'\n';
            cout<<s.top();
            s.pop();
            while(!s.empty())
            {
                cout<<" "<<s.top();
                s.pop();
            }
            cout<<'\n';
        }
    }
    cout<<'\n';
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin>>t;
    while(t--) solve();
    return 0;
}


Comments

Submit
0 Comments
More Questions

450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad
233A - Perfect Permutation
1360A - Minimal Square
467A - George and Accommodation
893C - Rumor
227B - Effective Approach
1534B - Histogram Ugliness
1611B - Team Composition Programmers and Mathematicians
110A - Nearly Lucky Number
1220B - Multiplication Table
1644A - Doors and Keys
1644B - Anti-Fibonacci Permutation
1610A - Anti Light's Cell Guessing
349B - Color the Fence
144A - Arrival of the General