There are many ways to order a list of integers from 1 to n. For example, if , the list could be : .
But there is a special way to create another list from the given list of integers. In this list, the position of the integer i is the number in the given list. So following this rule, the given list will be written as: . This list is called the inverse list. Now there exists some list whose inverse list is identical. For example, inverse list of is the same as the given list. Given a list of integers you have to determine whether the list is inverse or not.
Example:
Input: n = 3, arr[] = {1, 2, 3}
Output: inverse
Approach
Java
public class InverseList {public static void main(String[] args) {int n = 3;int arr[] = { 1, 2, 3 };int A[] = new int[n + 1];for (int i = 1; i < n + 1; i++) {A[i] = arr[i - 1];}System.out.println(inverseList(n, A));}static String inverseList(int n, int A[]) {int cnt = 0;int B[] = new int[n + 1];for (int i = 1; i < n + 1; i++) {B[A[i]] = i;}for (int i = 1; i < n + 1; i++) {if (A[i] != B[i]) {cnt++;}}if (cnt != 0)return "not inverse";elsereturn "inverse";}}
C++
#include <bits/stdc++.h>using namespace std;string inverseList(int n, int A[]){int cnt = 0;int B[n + 1] = {0};for (int i = 1; i < n + 1; i++){B[A[i]] = i;}for (int i = 1; i < n + 1; i++){if (A[i] != B[i]){cnt++;}}if (cnt != 0)return "not inverse";elsereturn "inverse";}int main(){int n = 3;int arr[] = {1, 2, 3};int A[n + 1];for (int i = 1; i < n + 1; i++){A[i] = arr[i - 1];}cout << inverseList(n, A) << "\n";return 0;}
No comments:
Post a Comment