CONFLIP - Editorial

A simple code
#include
using namespace std;

int main() {
int t,g,i,n,q;
cin>>t;
while(t–){
cin>>g;
while(g–){
cin>>i>>n>>q;
if(n%2==0){
cout<<n/2<<endl;
}else{
if(i==q){
cout<<n/2<<endl;
}else{
cout<<(n/2)+1<<endl;
}
}
}
}
return 0;
}

this my code and it works perfectly fine in custom inputs without any problem , but during the submission it shows time limit exceeded.

MY CODE:-

T = int(input())

for i in range(1,T+1):

G = int(input())

for u in range(1,G+1):

    I,N,Q = input().split() 

    I = int(I)

    N = int(N)

    Q = int(Q)

    k = 1

    mylist = list()

    for z in range(0,N):

        mylist.append(I)

    for i in range(0,N):

        for j in range(0,k):

            if (mylist[j] == 1):

                mylist[j] = 2

            else:

                mylist[j] = 1

        k = k + 1

    

    if (Q == 1):

        count = mylist.count(Q)

        print(count)

    else:

        count = mylist.count(Q)

        print(count)

i have written according to what i understood…the code runs fine and gives correct output but at time of submission it shows Time limit exceeded ! How can i optimize it!

#include <iostream>
#include<algorithm>
using namespace std;

int getGuesses(int init, int n, int q) {
    int arr[n];
    int count=0;
    fill_n(arr + 1, n, init);
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=i; j++) {
            arr[j] = (arr[j]%2==0) ? 1 : 2;
        }
    }
    for(int i=1; i<=n; i++) {
        if(arr[i]==q) {
            ++count;
        }
    }
    return count;
    
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int test, g, ini, n, q, count=0;
    cin >> test;
    while(test--) {
        cin >> g;
        while(g--) {
            cin >> ini >> n >> q;
            count = getGuesses(ini, n, q);
            cout << count << "\n";
        }
    }
	return 0;
}