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 :
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
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 →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →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 →