pandeysaurav355's blog

By pandeysaurav355, history, 7 weeks 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++:

using namespace std;
int main(){
    int t;
        int n,arr[205];
        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];


# 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]
  • Vote: I like it
  • -1
  • Vote: I do not like it

7 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

At least you should run the program on your own machine with that test to see what's the behavior exactly.

In this case it takes about 2 seconds on my machine, which is understandable given that Python is normally slower than C++.

Either use a fast language, or find a faster algorithm.

7 weeks 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