Please help me out. I'm getting "Memory Limit exceeded in test 3" in question D of codeforces https://codeforces.net/problemset/problem/1675/D. I can't figure out where I'm doing wrong. Kindly help me out.
I'm attaching my code here.
include<bits/stdc++.h>
using namespace std;
define ll long long
define lld long double
define pb push_back
define ppb pop_back
define pf push_front
define ppf pop_front
define all(ele) (ele.begin(),ele.end())
vectora,d; vector visited; ll j=0; vectorres; vector<vector>ch;
void dfs(vector<vector>tree, ll v) { visited[v] = true; res.pb(v); for (ll u : tree[v]) { if (!visited[u]) { // res.pb(u); dfs(tree,u);
if(!res.empty()) { ch.pb(res); res.clear(); } } } if(!res.empty()) { ch.pb(res); res.clear(); }
}
void solve() { ll n,i; cin>>n; a.clear(); visited.clear(); ch.clear(); visited.resize(n+2, 0); a.resize(n+2);
for(i=0;i<n;i++) cin>>a[i]; vector<vector<ll>>tree(n+2); ll root=0; for(i=0;i<n;i++) { if(a[i]==i+1) { root=i+1; break; } } for(i=0;i<n;i++) { if(i==root-1) { tree[a[i]].pb(i+1); } else { tree[a[i]].pb(i+1); tree[i+1].pb(a[i]); } } dfs(tree,root); cout<<ch.size()<<endl; for(i=0;i<ch.size();i++) { cout<<ch[i].size()<<endl; for(auto it: ch[i]) { cout<<it<<' '; } cout<<endl; }
}
int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int t; cin>>t; while(t--) { solve(); } }