Iterate It


Problem Statement :


Consider the following pseudocode, run on an array  of length :

rep := 0
while A not empty:
    B := []
    for x in A, y in A:
        if x != y: append absolute_value(x - y) to B
    A := B
    rep := rep + 1
Given the values of  and array , compute and print the final value of  after the pseudocode above terminates; if the loop will never terminate, print -1 instead.

Input Format

The first line contains a single integer, , denoting the length of array .
The second line contains  space-separated integers describing the respective values of .


Output Format

Print the final value of  after the pseudocode terminates; if the loop will never terminate, print -1 instead.



Solution :



title-img


                            Solution in C :

In  C  :






#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef unsigned int uint;

#define MAX_N 100000
#define MAX_VALUE 50000

uint a[MAX_N];
bool b[MAX_VALUE+1];

int main() {
    // read input
    uint n;
    scanf("%u", &n);
    assert(n <= MAX_N);
    for (int i = 0; i < n; i++) {
        uint v;
        scanf("%u", &v);
        assert(v);
        assert(v <= MAX_VALUE);
        b[v] = true;
    }
    
    // start grinding
    uint rep = 0;
    while (true) {
        // transfer from b (presence array) back to a (sorted list)
        uint stride = 0;
        bool in_stride = true;
        n = 0;
        for (uint i = 1; i <= MAX_VALUE; i++) {
            if (b[i]) {
                b[i] = false;
                if (!n) {
                   stride = i;
                } else if (in_stride && i - a[n-1] != stride) {
                    in_stride = false;
                }
                a[n++] = i;
            }
        }
        if (!n) {
            break;
        }
        if (in_stride) {
            // shortcut
            assert(a[n-1]/stride == n);
            rep += n;
            break;
        }
        rep++;
        for (uint ai = 0; ai < n-1; ai++) {
            for (uint aj = ai+1; aj < n; aj++) {
                // no unnecessary code here, performance-critical
                b[a[aj] - a[ai]] = true;
            }
        }
    }
    printf("%u\n", rep);
    return 0;
}
                        


                        Solution in C++ :

In  C  ++  :





#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <sstream>
#include <cmath>
#include <ctime>
#include <bitset>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector< vector<int> > vvi;
typedef vector<ll> vl;
typedef vector< vector<ll> > vvl;

#define forn(i, n) for (int i = 0; i < (int)(n); i++)
#define forv(i, v) forn(i, v.size())
#define all(v) v.begin(), v.end()
#define mp make_pair
#define pb push_back

const int N = 50005;

typedef bitset<N> mask;

int gcd(int x, int y) {
    if (!y) return x;
    return gcd(y, x % y);
}

int main() {
#ifdef NEREVAR_PROJECT
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int n; cin >> n;
    vi a(n);
    forn(i, n) {
        scanf("%d", &a[i]);
    }
    sort(all(a));
    a.erase(unique(all(a)), a.end());
    n = (int)a.size();
    mask diffs;
    mask present;
    for (int i = n - 1; i >= 0; i--) {
        diffs |= present >> a[i];
        present.set(a[i]);
    }
    vi s;
    forn(i, N) {
        if (diffs.test(i)) {
            s.pb(i);
        }
    }
    if (s.empty()) {
        cout << 1 << endl;
        return 0;
    }
    int g = 0;
    forv(i, s) g = gcd(g, s[i]);
    forv(i, s) s[i] /= g;
    
    diffs.reset();
    present.reset();
    for (int i = (int)s.size() - 1; i >= 0; i--) {
        diffs |= present >> (s[i] + 1);
        present.set(s[i]);
    }
    
    int steps = 2, m = s.back() - s[0];
    while (m && !diffs.test(0)) {
        mask next;
        int mNext = m;
        forn(i, m) {
            if (diffs.test(i)) {
                if (mNext == m) {
                    mNext = m - i - 1;
                }
                next |= diffs >> (i + 1);
            }
        }
        m = mNext;
        steps++;
        diffs = next;
    }
    
    cout << steps + m << endl;
    
    return 0;
}
                    


                        Solution in Java :

In  Java :







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

public class Solution {
    private static final int l = 60000;
    
    private static int gcd(int a, int b){
        if (a < b) return gcd(b, a);
        if (b == 0) return a;
        return gcd(b, a % b);
    }
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        boolean[] list = new boolean[l+1];
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < n; i++){
            int a = in.nextInt();
            set.add(a);
            list[a] = true;
        }
        boolean[] nList = new boolean[l+1];
        for (int e : set){
            for (int i = 1; i + e < l; i++){
                nList[i] |= list[i + e];
                /*
                if (i < 10){
                    if ((list[i + e / b] >> (e % b)) > 0 || (list[i + e / b + 1] << (b - (e % b))) > 0){
                        System.out.println(bits(list[i + e / b] >> (e % b)));
                        System.out.println(bits(list[i + e / b + 1] << (b - (e % b))));
                    }
                    else{
                        System.out.println(bits(list[i + e / b]) + " " + (e % b));
                        System.out.println(bits(list[i + e / b + 1]) + " " + (b - (e % b)));
                    }
                    System.out.println(e + " " + i);
                }*/
            }
        }
        list = nList;
        int g = 0;
        int min = -1;
        int max = 0;
        //for (int a : set)
            //System.out.println(a);
        //System.out.println("-----");
        set.clear();
        for (int i = 0; i < l+1; i++){
                if (list[i]){
                    //System.out.println(a);
                    set.add(i);
                    if (min < 0) min = i;
                    max = i;
                    g = gcd(i, g);
                }
        }
        //System.out.println("-----");
        //System.out.println(min);
        //System.out.println(max);
        //System.out.println(g);
        int o = 1;
        if (set.size() == 0){
            System.out.println(o);
            return;
        }
        Set<Integer> nSet = new HashSet<Integer>();
        for (int a : set)
            nSet.add(a / g);
        set = nSet;
        min /= g;
        max /= g;
        list = new boolean[l+1];
        for (int a : set)
            list[a] = true;
        while (min > 1){
            nList = new boolean[l+1];
            for (int a = min; a <= max; a++){
                if (list[a]){
                    for (int k = 1; k + a < l; k++){
                        nList[k] |= list[k + a];
                    }
                }
            }
            list = nList;
            max -= min;
            for (int a = 1; a <= max; a++){
                if (list[a]){
                    min = a;
                    break;
                }
            }
            o++;
        }
        System.out.println(o + max);
    }
    /*
    private static String bits(int i){
        String s = "";
        for (int j = b-1; j >= 0; j--)
            s += (i & (1 << j)) > 0 ? 1 : 0;
        return s;
    }*/
}//[]{}
                    


                        Solution in Python : 
                            
In  Python3  :







input()
A = set([int(m) for m in input().strip().split()])

def DeltaBasis2(AList,P=False):
    if type(AList) == set:
        AList = sorted(list(AList))
    if len(AList) == 1:
        return 1
    Count = 0
    
    while len(AList)>0:
        if len(AList) == 1:
            return Count + 1
        LCM = True
        for i1 in AList[1:]:
            if i1 % AList[0] != 0:
                LCM = False
                break
        if LCM:
            AList = [int(m/AList[0]) for m in AList]
        
        if (AList[0] == 1 and AList[1] == 2):
            return Count + AList[-1]
                     
        Delta = set()
        if len(AList) < 100:
            MaxWidth = len(AList) - 1
        else:
            MaxWidth = int(len(AList)**0.75//1)
        for W in range(1,MaxWidth+1):
            for i1 in range(len(AList)-W):
                Delta.add(abs(AList[i1+W]-AList[i1]))
        Delta = sorted(list(Delta))
        
        
        AList = sorted(list(set([m for m in Delta] + [AList[-1] - m for m in AList[:-1]])))
        if P:
            print(AList2)
        Count +=  1
    return Count   

print(DeltaBasis2(A))
                    


View More Similar Problems

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

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 →