New Year Chaos


Problem Statement :


It is New Year's Day and people are in line for the Wonderland rollercoaster ride. Each person wears a sticker indicating their initial position in the queue from 1 to n. Any person can bribe the person directly in front of them to swap positions, but they still wear their original sticker. One person can bribe at most two others.

Determine the minimum number of bribes that took place to get to a given queue order. Print the number of bribes, or, if anyone has bribed more than two people, print Too chaotic.

Example

q = [1,2,3,5,4,6,7,8]
If person 5 bribes person 4, the queue will look like this: 1,2,3,5,4,6,7,8. Only 1 bribe is required. Print 1.
q = [4,1,2,3]

Person 4 had to bribe 3 people to get to the current position. Print Too chaotic.

Function Description

Complete the function minimumBribes in the editor below.

minimumBribes has the following parameter(s):

int q[n]: the positions of the people after all bribes
Returns

No value is returned. Print the minimum number of bribes necessary or Too chaotic if someone has bribed more than 2 people.
Input Format

The first line contains an integer t, the number of test cases.

Each of the next t pairs of lines are as follows:
- The first line contains an integer t, the number of people in the queue
- The second line has n space-separated integers describing the final state of the queue.

Constraints

1 <= t <= 10
1 <= n <= 10^5



Solution :



title-img


                            Solution in C :

In C++ :





#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main(){
    int T;
    cin >> T;
    for(int a0 = 0; a0 < T; a0++){
        int n;
        cin >> n;
        vector<int> q(n);
        for(int q_i = 0;q_i < n;q_i++){
           cin >> q[q_i];
        }
        int ans = 0;
        for (int i = n - 1; i >= 0; i--){
            if (ans == -1)
                break;
            int k = i;
            while (q[k] != i + 1)
                k--;
            if (i - k > 2){
                ans = -1;
                break;
            } else {
                while (k != i){
                    swap(q[k], q[k + 1]);
                    k++;
                    ans++;
                }
            }
        }
        if (ans == -1)
            puts("Too chaotic");
        else
            cout << ans << "\n";
    }
    return 0;
}









In Java : 





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        int a,c;
        for(int a0 = 0; a0 < T; a0++){
            int n = in.nextInt();
            int q[] = new int[n], q2[] = new int[n];
            for(int q_i=0; q_i < n; q_i++){
                q[q_i] = in.nextInt()-1;
                q2[q_i] = q_i;
            }
            c=0;
            for(int i=0;i<n;i++) {
                if (q[i]==q2[i]) {
                    
                } else if (q[i]==q2[i+1]) {
                    a=q2[i];
                    q2[i]=q2[i+1];
                    q2[i+1]=a;
                    c++;
                } else if (q[i]==q2[i+2]) {
                    a=q2[i+1];
                    q2[i+1]=q2[i+2];
                    q2[i+2]=a;
                    a=q2[i];
                    q2[i]=q2[i+1];
                    q2[i+1]=a;
                    c+=2;
                } else {
                    System.out.println("Too chaotic");
                    i=n;
                }
                if (i==n-1) {
                    System.out.println(c);
                }
            }
        }
    }
}









In C :





#include <stdio.h>
int N;
int ar[100000];

int scan_swap ( int j ) {
	int temp;
	if ( j == ar[j - 1] ){
		return 0;
	}
	else if ( j == ar [j - 2] ){
		temp = ar[j- 2];
		ar[j - 2] = ar[j - 1];
		ar[j - 1] = temp;
		return 1;
	}
	else if (j == ar [j - 3] ){
		temp = ar[j- 3];
		ar[j - 3] = ar[j - 2];
		ar[j - 2] = ar[j - 1];
		ar[j - 1] = temp;
		return 2;
	}
	else return -1;
}



int main (void){
	int T, i, j, k, point;
	scanf ("%d", &T);
	for (i=0;i<T;++i){
		scanf ("%d", &N);
		for (j=0; j<N; ++j) 
			scanf("%d", &ar[j] );
			int total = 0;
		for (j=N; j>0; --j){
			point = scan_swap ( j );
			/*for (k=0; k<N; ++k) 
				printf("%d ", ar[k] );puts("");*/
			if ( point != -1 ){
				total += point;
			}
			else {
				total = -1;
				break;
			}
		}
		if ( -1 == total ){
			puts ("Too chaotic");
		}
		else printf ("%d\n", total);
	}
}









In Python3 :






def count_inversion(lst):
    return merge_count_inversion(lst)[1]

def merge_count_inversion(lst):
    if len(lst) <= 1:
        return lst, 0
    middle = int( len(lst) / 2 )
    left, a = merge_count_inversion(lst[:middle])
    right, b = merge_count_inversion(lst[middle:])
    result, c = merge_count_split_inversion(left, right)
    return result, (a + b + c)

def merge_count_split_inversion(left, right):
    result = []
    count = 0
    i, j = 0, 0
    left_len = len(left)
    while i < left_len and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            count += left_len - i
            j += 1
    result += left[i:]
    result += right[j:]
    return result, count
for _ in range(int(input())):
    N=int(input())
    a=list(map(int,input().split()))
    if any(a[i]-(i+1)>2 for i in range(N)):
        print("Too chaotic")
    else:
        print(count_inversion(a))
                        








View More Similar Problems

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →