General
 
 
# Author Problem Lang Verdict Time Memory Sent Judged  
117301798 Practice:
kinibha
1527C - 43 C++17 (GCC 7-32) Accepted 529 ms 5648 KB 2021-05-25 11:33:51 2021-05-25 11:33:51
→ Source
#include<bits/stdc++.h>

using namespace std;
 
#define int long long 

void solve(){
    int n;
    cin>>n;
    vector<int> a( n ) ;
    for( int & i: a) cin>>i;

    // dp[i] will store the sum of all weights of subarrays
    vector<int> dp( n  + 1,0 ) ;

    map<int,int> mp;
    /*
     * we have 1 2 1 1 1 
     * and we have calculated ans till 1 2 1 1]
     * and if we add the new element 1 then what's affect on answer.
     * 1) no of subarrays will increase by i ( i is index of current new element)
     *    subarrays are : 
     *      1 2 1 1 1  -> will increase ans by 3 (   new pairs [0-i] [2-i] [3-i] ) 
     *        2 1 1 1  -> will increase ans by 2 
     *          1 1 1  -> will increase ans by 2 
     *            1 1  -> will increase ans by  1
     *              1  -> no effect on answer
     *
     *  simple observation :: answer will increase by no. of elements from subarrays ending at posion "i-1" ;
     *  which can be stored with map
     * 2)
     *  if we encouter elemnt x then # of subarrays that ends at this positon will increase by j ( j is index of cur element)
     *  
     *  we can use prefix sum for that 
     */

    int total_ans = 0 ;
    for( int i =0 ; i < n; i++) {
        if( i >0 ) dp[i] = dp[i-1];
        
        if( mp[a[i]] ) {
            dp[i] += mp[a[i]];
        }
        // no of element a[i] before index (i+1) will be increased by (i+1) i.e. no. of elements to left including current element 
        mp[a[i]] += (i+1);
        total_ans += dp[i];
    }
    cout<<total_ans<<endl;

    
}



int32_t main(){


    int t=1;
    cin>>t; 

    while(t--){
        solve();
    }
    return 0;
}
 

?
Time: ? ms, memory: ? KB
Verdict: ?
Input
?
Participant's output
?
Jury's answer
?
Checker comment
?
Diagnostics
?
Click to see test details