When submitting a solution in C++, please select either C++14 (GCC 6-32) or C++17 (GCC 7-32) as your compiler. ×

pandeysaurav355's blog

By pandeysaurav355, history, 4 years ago, In English

Today i faced a problem of successful hack attempt and these are my code. The code in C++ ran in time and gave T.L.E. in Python.Both code have same logic.

IN C++:

#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        int n,arr[205];
        cin>>n;
        for(int i = 1; i <= n; i++) cin>>arr[i];
        for(int i = 1; i <= n; i++) {
            int x = arr[i];
            int count = 1;
            while (arr[x] != arr[i]){
                count += 1;
                x = arr[x];
            }
            cout<<count<<"\t";
        }
        cout<<endl;
    }
}

IN PYTHON:

# cook your dish here
for _ in range(int(input())):
    n = int(input())
    p = [int(x) for x in input().split()]
    ans = []
    for i in p:
        x = i
        count = 1
        while p[x-1] != i:
            count += 1
            x = p[x-1]
        ans.append(count)
    print(*ans)
  • Vote: I like it
  • -1
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

use pypy3 instead of python and also add fast io

import sys
input=sys.stdin.readline