CSP 201903-2 24.6 (0ms, 404KB)

topic

Here Insert Picture Description

Problem-solving ideas

Do first multiplication and division, addition and subtraction do.
As 3 + 4x5 + 3, it can be first converted to the 3 + 3 + 20, do adder.
The algorithm is: the use of recursive functions, multiplication and division encounter, first calculated, and then come back to add or subtract. + The symbol may be used as the delimiter to divide. It is to be noted that the first initial character is pretreated, as will become 3-4 3 + (- 4), wherein the original characters are 4 '4', and we need to be changed to '0' - ( '4' - '0' characters) of this value, so as to achieve a unified split by +.

! ! ! A pit: 3x5 / 6x4 should be 8, because (although the topic is not very clear) to be met in addition to a number of '/' divisible necessary to complete the operation, rather than the customary equivalent to 3x5x4 / 6 get 10.

Code

#include<stdio.h>
#include<string.h>
char sr[7];
int do_op(int r,int l){
	if(r==l)//只剩下一个数
		return sr[r]-'0';
	else if(r+2==l){//只剩下一次运算 
		if(sr[r+1]=='+') return sr[r]-'0'+sr[l]-'0';
		else if(sr[r+1]=='x') return (sr[r]-'0')*(sr[l]-'0');
		else return (sr[r]-'0')/(sr[l]-'0');
	}
	else{//剩下多次运算,根据'+'进行拆解 
		int res=sr[r]-'0';//取第一个数
		int i=r+1;
		int right=-1,left=-1;
		while(i<l){
			if(sr[i]=='+'){
				if(left==-1)
					left=i;
				else{
					right=i;
					return do_op(r,left-1)+do_op(left+1,right-1)+do_op(right+1,l);
				}
			}
			i+=2;
		}
		if(left==-1){//全是乘除 
			int out=sr[r]-'0';
			for(int j=r+1;j<l;j+=2){
				if(sr[j]=='x')
					out*=sr[j+1]-'0';
				else
					out=out/(sr[j+1]-'0');
			} 
			return (int)out;
		}
		else//只有一个+
			return do_op(r,left-1)+do_op(left+1,l);
	}
}
void pre_do(){//先做预处理,把-m的格式改为+(-m) 
	for(int i=1;i<7;i+=2)
		if(sr[i]=='-'){
			sr[i]='+';
			sr[i+1]='0'-(sr[i+1]-'0');
		} 
}
int main(void){
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%s",sr);
		pre_do(); 
		int out=do_op(0,6);
		if(out==24)
			printf("Yes\n",out);
		else
			printf("No\n",out);
	}
	return 0;
} 

Test case

10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5

Test Results

Here Insert Picture Description

Published 12 original articles · won praise 2 · Views 343

Guess you like

Origin blog.csdn.net/qq_42295427/article/details/104775884