pandeysaurav355's blog

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

#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)

Read more »

 
 
 
 
  • Vote: I like it
  • -1
  • Vote: I do not like it