Question D of Codeforces Round #787 (Div. 3) .

Правка en1, от bharatim1221, 2022-05-06 21:02:11

Please help me out. I'm getting "Memory Limit exceeded in test 3" in question D of codeforces https://mirror.codeforces.com/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(); } }

Теги codeforces round #787, question d

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский bharatim1221 2022-05-06 21:03:29 1627
en1 Английский bharatim1221 2022-05-06 21:02:11 1933 Initial revision (published)