Arithmetic Expressions


Problem Statement :


5-year-old Shinchan had just started learning mathematics. Meanwhile, one of his studious classmates, Kazama, had already written a basic calculator which supports only three operations on integers: multiplication , addition , and subtraction . Since he had just learned about these operations, he didn't know about operator precedence, and so, in his calculator, all operators had the same precedence and were left-associative.

As always, Shinchan started to irritate him with his silly questions. He gave Kazama a list of  integers and asked him to insert one of the above operators between each pair of consecutive integers such that the result obtained after feeding the resulting expression in Kazama's calculator is divisible by . At his core, Shinchan is actually a good guy, so he only gave lists of integers for which an answer exists.

Can you help Kazama create the required expression? If multiple solutions exist, print any one of them.

Input Format

The first line contains a single integer  denoting the number of elements in the list. The second line contains  space-separated integers  denoting the elements of the list.


Output Format

Print a single line containing the required expressoin. You may insert spaces between operators and operands.

Note

You are not allowed to permute the list.
All operators have the same precedence and are left-associative, e.g.,  is interpreted as 
Unary plus and minus are not supported, e.g., statements like , , or  are invalid.



Solution :



title-img


                            Solution in C :

In  C  :







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

int main() {
  int n;
  scanf("%d", &n);

  unsigned char * ops = malloc(n);  // '+' - 1, '-' - 2, '*' - 3
  memset(ops, 3, n);

  int * nums = malloc(n * sizeof(unsigned int));
  for (int i = 0; i < n; i ++) {
    scanf("%d", &nums[i]);
  }

  unsigned char t[1000][101][2];

  int i;
  for (i = 0; i < n; i ++) {
    if (0 == i) {
      t[i][nums[i]][0] = 1;
      t[i][nums[i]][1] = 1;
    }
    else {
      int j;
      for (j = 1; j < 101; j ++) {
        if (t[i - 1][j][0]) {
          int tmp = (j + nums[i]) % 101;
          t[i][tmp][0] = j;
          t[i][tmp][1] = 1;
          if (0 == tmp) {
            break;
          }

          tmp = (101 + j - nums[i]) % 101;
          t[i][tmp][0] = j;
          t[i][tmp][1] = 2;
          if (0 == tmp) {
            break;
          }

          tmp = (j * nums[i]) % 101;
          t[i][tmp][0] = j;
          t[i][tmp][1] = 3;
          if (0 == tmp) {
            break;
          }
        }
      }

      if (j < 101) {
        break;
      }
    }
  }

  int p = 0;
  for (int j = i; j > 0; j --) {
    ops[j] = t[j][p][1];
    p = t[j][p][0];
  }

  for (int i = 0; i < n - 1; i ++) {
    printf("%d", nums[i]);
    switch (ops[i + 1]) {
      case 1:
      printf("+");
      break;
      case 2:
      printf("-");
      break;
      default:
      printf("*");
      break;
    }
  }
  printf("%d\n", nums[n - 1]);

  free(nums);
  free(ops);

  return 0;
}
                        


                        Solution in C++ :

In  C++  :








#include <iostream>
#include <vector>
#include <algorithm>
using namespace std; 

typedef struct {
	string opers;
	int remainder; 
} expr; 

int main(void){
	int N; 
	cin >> N; // 2 - 10,000
	vector<int> vals(N); 
	for(int i=0; i<N; i++) cin >> vals[i]; // each 1 - 100

	expr init_expr; 
	init_expr.remainder = -1; 
	vector<expr> results(101, init_expr); 
	results[vals[0]].remainder = vals[0]; 
	for(int step=1; step<N; step++){
		vector<expr> res2(101, init_expr); 
		int stepval = vals[step]; 
		for(int j=0; j<=100; j++){
			int amount = results[j].remainder; 
			if (amount==-1) continue; 
			int ans1 = (amount+stepval)%101; 
			int ans2 = ((amount-stepval)+101)%101; 
			int ans3 = (amount*stepval)%101; 
			res2[ans1].remainder = ans1; 
			res2[ans2].remainder = ans2; 
			res2[ans3].remainder = ans3; 
			res2[ans1].opers = results[j].opers+"+"; 
			res2[ans2].opers = results[j].opers+"-"; 
			res2[ans3].opers = results[j].opers+"*"; 
		}
		results.swap(res2); 
	}
	cout << vals[0]; 
	const string& opstring = results[0].opers; 
	for(int i=1; i<N; i++){
		cout << opstring[i-1] << vals[i];
	}
	cout << 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 {
    static void printResult(int[] arr, String result){
       for(int i=0; i<arr.length;i++){
            System.out.print(arr[i]);
            if(i!=arr.length-1){
                System.out.print(result.charAt(i));
            }
        }
    }
    public static boolean calculation(int index, long cur, String result){
 
        if(cur%101 ==0){
            //System.out.println("optimize" + cur);
            for(int i=result.length(); i<arr.length-1; i++)
                result+="*";
            printResult(arr,result);
            return true;
        }
        if(index == arr.length-1){
            if(((long)arr[index]*cur)%101 ==0){
                result+="*"; 
                printResult(arr,result);
                //System.out.println(((long)arr[index]*cur));
                return true;
            }
            else if(((long)arr[index]+cur)%101 ==0){
                result+="+"; 
                printResult(arr,result);
                //System.out.println(((long)arr[index]+cur));
                return true;
            }
            else if((cur-(long)arr[index])%101 == 0){
                result+="-"; 
                printResult(arr,result);
                //System.out.println((cur-(long)arr[index]));
                return true;
            }
            else
                return false;
        }
        if(!calculation(index+1, ((long)arr[index]*cur)%101,result+"*")){
            if(!calculation(index+1, ((long)arr[index]+cur)%101,result+"+")){
                if(!calculation(index+1, ((long)cur-arr[index])%101,result+"-")){
                    return false;
                } 
            }
            
        }
        

        return true;
    }
    static int[] arr;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a;
        a = in.nextInt();
        arr = new int[a];
        for(int i=0; i<a; i++){
           arr[i] = in.nextInt(); 
        }
        calculation(1, arr[0],"");//System.out.println(result);

    }
}
                    


                        Solution in Python : 
                            
In  Python3 :








import sys

sys.setrecursionlimit(15000)

ops = [lambda x,y: x + y, lambda x,y: x * y, lambda x,y: x - y]
op2s = ['+', '*', '-', '']

def exp(i, value, l):
    if i == n:
        return l if value % 101 == 0 else None
    
    if len(cache[i]) > 0 and value in cache[i]:
        return cache[i][value]
    
    for k in range(3):
        if exp(i + 1, ops[k](value, a[i]), l) != None:
            l[i - 1] = k
            cache[i][value] = l
            return l
        
    cache[i][value] = None
    return None

n = int(input())
a = [int(x) for x in input().strip().split(' ')]

cache = [{}] * n

l = exp(1, a[0], [3] * n)

for i in range(n):
    sys.stdout.write(str(a[i]))
    sys.stdout.write(op2s[l[i]])
    
sys.stdout.flush()
                    


View More Similar Problems

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →

Heavy Light 2 White Falcon

White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr

View Solution →