Skip to content

Instantly share code, notes, and snippets.

@wontheone1
Last active September 7, 2018 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wontheone1/141d3e5ce7fc62fcb6c1aa9473589775 to your computer and use it in GitHub Desktop.
Save wontheone1/141d3e5ce7fc62fcb6c1aa9473589775 to your computer and use it in GitHub Desktop.
Hackerrank New Year Chaos
1 2 3 4 5 6 7 8 ; Indices
1 2 3 4 5 6 7 8 ; person-numbers
0 0 0 0 0 0 0 0 ; person-numbers - indices
0 0 0 0 0 0 0 0 ; accumulated difference
; sum of accumulated difference: 0
; Total bribery: 0
1 2 3 4 5 6 7 8 ; Indices
1 2 3 5 4 6 7 8 ; person-numbers
0 0 0 1 -1 0 0 0 ; person-numbers - indices
0 0 0 1 0 0 0 0 ; accumulated difference
; sum of accumulated difference: 1
; Total bribery: 1
1 2 3 4 5 6 7 8 ; Indices
1 2 5 3 4 6 7 8 ; person-numbers
0 0 2 -1 -1 0 0 0 ; person-numbers - indices
0 0 2 1 0 0 0 0 ; accumulated difference
; sum of accumulated difference: 3
; Total bribery: 2
1 2 3 4 5 6 7 8 ; Indices
1 2 5 3 4 7 6 8 ; person-numbers
0 0 2 -1 -1 1 -1 0 ; person-numbers - indices
0 0 2 1 0 1 0 0 ; accumulated difference
; sum of accumulated difference: 4
; Total bribery: 3
1 2 3 4 5 6 7 8 ; Indices
1 2 5 3 7 4 6 8 ; person-numbers
0 0 2 -1 2 -2 -1 0 ; person-numbers - indices
0 0 2 1 3 1 0 0 ; accumulated difference
; sum of accumulated difference: 7
; Total bribery: 4
1 2 3 4 5 6 7 8 ; Indices
1 2 5 3 7 4 8 6 ; person-numbers
0 0 2 -1 2 -2 1 -2 ; person-numbers - indices
0 0 2 1 3 1 2 0 ; accumulated difference
; sum of accumulated difference: 9
; Total bribery: 5
1 2 3 4 5 6 7 8 ; Indices
1 2 5 3 7 8 4 6 ; person-numbers
0 0 2 -1 2 2 -3 -2 ; person-numbers - indices
0 0 2 1 3 5 2 0 ; accumulated difference
; sum of accumulated difference: 13
; Total bribery: 6
1 2 3 4 5 6 7 8 ; Indices
1 2 5 3 7 8 6 4 ; person-numbers
0 0 2 -1 2 2 -1 -4 ; person-numbers - indices
0 0 2 1 3 5 4 0 ; accumulated difference
; sum of accumulated difference: 15
; Total bribery: 7
@wontheone1
Copy link
Author

Since the question only asks the number of bribes, there's no need to really do a sorting, nor element swapping, nor "bubbling up" an element. All you need to do is to count the number of people who overtake a person.

void calc(vector<int> q)
{
    int ans = 0;
    for (int i = q.size() - 1; i >= 0; i--) {
        if (q[i] - (i + 1) > 2) {
            cout << "Too chaotic" << endl;
            return;
        }
        for (int j = max(0, q[i] - 2); j < i; j++)
            if (q[j] > q[i]) ans++;
    }
    cout << ans << endl;
}

@wontheone1
Copy link
Author

wontheone1 commented Sep 7, 2018

0 1 2 3 4 5 6 7 ; Indices
1 2 3 4 5 6 7 8 ; before change
1 2 5 3 7 8 6 4 ; person-numbers
; Total bribery: 7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment