Comments

i want help

i have tree node from 1 to N and u and v (basically edge b/w nodes) how to find the number of children for each node from 1 to N

ex N=11

1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11

for node 2-> 6 3-> 2 4->2 5->2 6,7,8,9,10,11->0

i have used DFS but get TLE any optimization

my approach --->

void dfs( un<ll, vector>mp, int parent, int &count)

{

for(auto i:mp[parent]) {

dfs(mp, i,(++count));
}

}

void solve() { int noChild[n+1]={0};

for(int i=2; i<=n; i++)
{
     int count=0;
    dfs(mp,i,count);
    noChild[i]=count;
}

} }

FOR Coder Looking For O(N)=====>>>>

/* BABA JAGAAAAAA */

include<bits/stdc++.h>

define pb push_back

define un unordered_map

define us unordered_set

define ll long long

define PI 3.1415926535897932384626

define fast ios:: sync_with_stdio(false);cin.tie(NULL)

define l long

using namespace std; const int mod= 1e9+7; const int inf=1e9+3; /* vectorparent; vectorrank; int find(int x)

{ if(parent[x]==x) return x; return parent[x]= find(parent[x]); // path compression// O(log n)

}

void merge(int a, int b)
{
     int x1= find(a);
     int x2= find(b);

    if(rank[x1]<rank[x2])
        parent[x1]=x2;
    else if(rank[x2]<rank[x1])  //(lon n)
        parent[x2]=x1;          // union by rank//
    else
    {
        parent[x1]=x2;
        rank[x2]++;
    }

}

*/ void solve() { string s; cin>>s; int n=s.size(); int pre[n],suff[n]; memset(pre,0,sizeof pre); memset(suff,0, sizeof suff); s[0]=='Q'?pre[0]=1:pre[0]=0;

for(int i=1; i<s.size(); i++)
 {
       if(s[i]=='Q')
       pre[i]=1+(pre[i-1]);

       else
       pre[i]=pre[i-1];
 }
 s[n-1]=='Q'?suff[n-1]=1:suff[n-1]=0;

 for(int i=n-2; i>=0; i--)
 {
     if(s[i]=='Q')
     suff[i]=1+suff[i+1];
     else
     suff[i]=suff[i+1];
 }


 int count=0;
  for(int i=1; i<s.size()-1;i++)
  {
       if(s[i]=='A')
       {
           if(pre[i] && suff[i])
           count+=(pre[i]*suff[i]);
       }
  }

  cout<<count;

} int main() { fast;
int t=1; //cin>>t; while(t--) { solve();
cout<<"\n";
} return 0;

}