JustPaste.it

CHEFWED

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define FORit(it,a) for(auto it=a.begin();it!=a.end();it++)
#define ROF(i,a,b) for(int i=a;i>=b;i--)
#define vec vector
#define pb push_back
#define pop pop_back
#define STF() shrink_to_fit()
#define all(x) x.begin(),x.end()
#define testcases ll t;cin>>t;while(t--)
#define mem(a,k) memset(a,k,sizeof(a))
#define F first
#define S second
#define MP(x,y) make_pair(x,y)
#define rt return
#define br break
#define ct continue
#define elif else if
#define arrin(a,n,index) for(int i=index;i<n;i++)cin>>a[i]
//ll mod = 1000000007;
int n, k;
int Fcnt(int a[], int l, int r, int hash[]) {
    FOR(i, 0, 101)hash[i] = 0;
    int cnt = k;
    FOR(i, l, r + 1)hash[a[i]]++;
    FOR(i, 0, 101)if (hash[i] > 1)cnt += hash[i];
    rt cnt;
}
int solve(int a[], int l, int r, int hash[], int ans) {
    int tmp = 0, tmp1 = 0, tmp2 = 0, TMP1 = 0, TMP2 = 0, TMP = INT_MAX;
    int split = 0;
    FOR(i, l, r ) {
        tmp1 = Fcnt(a, l, i, hash);
        tmp2 = Fcnt(a, i + 1, r, hash);
        if ((tmp1 + tmp2) < TMP) {TMP = tmp1 + tmp2, TMP1 = tmp1, TMP2 = tmp2, split = i;}
        //TMP is total cost, tmp1 is 1st group's cost ,similar for tmp2
    }

    if (TMP <= ans) {
        // we have to check if there is an efficent ans(min cost) after further breaking thats why less than equal to
        ans = TMP;
        if (TMP1 == k && TMP2 == k)rt ans;
        elif(TMP1 == k && TMP2 > k)rt k + solve(a, split + 1 , r, hash, TMP2);
        elif(TMP1 > k && TMP2 == k)rt k + solve(a, l, split , hash, TMP1);
        else rt solve(a, l, split , hash, TMP1) + solve(a, split + 1  , r, hash, TMP2);
    }
    else rt ans;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    // START FROM HERE :)
    testcases{
        cin >> n >> k;
        int F[n + 1];
        int hash[101] = {0};
        arrin(F, n + 1, 1);
        // we have to check for k=1 differently (using cnt arr)//we just have to group them so every grp contains only elmnts with freq 1
        if (k == 1) {
            int ans = 1;
            FOR(i, 1, n + 1) {
                hash[F[i]]++;
                if (hash[F[i]] > 1) {
                    FOR(j, 1, i)hash[F[j]] = 0;
                    ans++;
                    hash[F[i]]++;
                }
            }
            cout << ans << endl;
        }
        else{
            int cnt = Fcnt(F, 1, n, hash);
            int inef = solve(F, 1, n, hash, cnt);
            cout << inef << endl;
        }

    }

}