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

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

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 →