HDU-2266(How Many Equations Can You Find)

题目链接:https://vjudge.net/problem/HDU-2266

原题

How Many Equations Can You Find

Problem Description

Now give you an string which only contains 0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9.You are asked to add the sign ‘+’ or ’-’ between the characters. Just like give you a string “12345”, you can work out a string “123+4-5”. Now give you an integer N, please tell me how many ways can you find to make the result of the string equal to N .You can only choose at most one sign between two adjacent characters.

input

Each case contains a string s and a number N . You may be sure the length of the string will not exceed 12 and the absolute value of N will not exceed 999999999999.

ouput

The output contains one line for each data set : the number of ways you can find to make the equation.

Sample Input

123456789 3
21 1

Sample Output

18
1

题意分析:

题目的意思是给定一个由数字字符组成的字符串s,和一个整数N。你可以在s中的任意两个字符中添加‘+’号或‘-’号,使得构造出来的数学式子的值与N相等。问对于给定的s和N,一共有多少种不同的这种数学式子。

思路:

因为字符串长度较短,使用三进制枚举每个位置可能运算符的状态即可
值得注意的是:需要提前将字符串s的全部子串相对应的数字的值存储在二维数组to中,否则会超时Time Limit

代码:

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <string>
#define MAXN 100
using namespace std;
int main(){
    
    
	int i, j, x, ans;
	string s;
	while (cin >> s >> ans){
    
    
		int end = 1, k = s.length()-1, cnt = 0;
		//k个运算数(每个运算数三种状态为+,-,或无) 
		for (i = 0; i < k; i++)		end *= 3;
		
		//to[i][j]表示字符串s中下标i开始,长度为j的数字大小 
		int to[MAXN][MAXN] = {
    
    0};
		for (i = 0; i < s.length(); i++){
    
    
			for (j = 1; j < s.length()-i+1; j++){
    
    
				to[i][j] = atoi(s.substr(i, j).data());
			}
		}
		
		//枚举
		for (i = 0; i < end; i++){
    
    
			int a[MAXN];
			//将j转换为k位3进制数 
			for (j = 0, x = i; j < k; j++){
    
    
				a[j] = x%3;
				x /= 3;
			}
			//temp储存分割所得数字,cal储存运算符状态 
			int temp[MAXN], nt = 0;
			int cal[MAXN], nc = 0;
			int pre = 0;
			for (j = 0; j < k ;j++){
    
    
				//如果a[j]不为0,代表运算符为+或- 
				if (a[j]){
    
    
				//	temp[nt++] = atoi(s.substr(pre, j+1-pre).data());
					temp[nt++] = to[pre][j+1-pre];
					pre = j+1;
					cal[nc++] = a[j];
				}
			}
	//		temp[nt++] = atoi(s.substr(pre, j+1-pre).data());
			temp[nt++] = to[pre][j+1-pre];
			int sum = temp[0];
			for (j = 1; j < nt; j++){
    
    
				if (cal[j-1] == 1){
    
    
					sum += temp[j];
				}else{
    
    
					sum -= temp[j];
				}
			}
			cnt += (sum == ans);
		}
		cout << cnt << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40735291/article/details/88938218