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
Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →Print in Reverse
Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing
View Solution →Reverse a linked list
Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio
View Solution →Compare two linked lists
You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis
View Solution →Merge two sorted linked lists
This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C
View Solution →