#include <bits/stdc++.h>
using namespace std;

void Bumerang(int n, int q, int* p, int* w, int* s, int* k, long long* ans)
{
    int* p2=new int[n+1];
    p2[1]=p[1];
    int br_razlicitih=0;
    int icentar;
    for(int i=2;i<=n;i++)
    {
        p2[i]=p[i];
        if(p2[i]==1)
        {
            icentar=i;
            p2[i]=p2[i-1];
        }
        else if(p2[i]!=p2[i-1])
            br_razlicitih++;
    }
    delete[] p2;
    if(br_razlicitih<2)
    {
        int max1=INT_MIN, max2=INT_MIN, max3=INT_MIN;
        for(int j=1;j<=n;j++)
        {
            if(w[j]>=max1)
            {
                max3=max2;
                max2=max1;
                max1=w[j];
            }
            else if(w[j]>=max2)
            {
                max3=max2;
                max2=w[j];
            }
            else if(w[j]>=max3)
                max3=w[j];
        }
        for(int i=1;i<=q;i++)
        {
            if(w[s[i]]==max1 || w[s[i]]==max2 || w[s[i]]==max3)
            {
                w[s[i]]=k[i];
                max1=INT_MIN;
                max2=INT_MIN;
                max3=INT_MIN;
                for(int j=1;j<=n;j++)
                {
                    if(w[j]>=max1)
                    {
                        max3=max2;
                        max2=max1;
                        max1=w[j];
                    }
                    else if(w[j]>=max2)
                    {
                        max3=max2;
                        max2=w[j];
                    }
                    else if(w[j]>=max3)
                        max3=w[j];
                }
            }
            else
            {
                w[s[i]]=k[i];
                if(k[i]>=max1)
                {
                    max3=max2;
                    max2=max1;
                    max1=k[i];
                }
                else if(k[i]>=max2)
                {
                    max3=max2;
                    max2=k[i];
                }
                else if(k[i]>=max3)
                    max3=k[i];
            }
            ans[i]=max1+max2+max3;
        }
        return;
    }
}