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
Largest Rectangle
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle
View Solution →Simple Text Editor
In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,
View Solution →Poisonous Plants
There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan
View Solution →AND xor OR
Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value
View Solution →Waiter
You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the
View Solution →Queue using Two Stacks
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que
View Solution →