Ultraviolet A-10400 + dfs + backtracking

Source: Internet
Author: User
Question: & #160; & #160; & #160; enter n positive integers and a target value, and fill in +-& #215; in the middle of the n number for calculation, operations are performed from left to right without considering the priority of operators. And the following rule is given: & #160; & #160; & #160; & #160; & #160; & #160; & #160; & #160; & #160; & #160; & #160

Question:

Enter n positive integers and a target value. you can enter +-×/in the middle of the n number to perform operations from left to right without considering the priority of operators. And the following rules are given:

1. the order of n numbers cannot be changed when the symbol is filled.

2. make sure that the result is an integer when filling in the division sign.

3. the result of each step must be in-32000 ~ In the range of 32000.

Ask if the target value can be obtained.

Ideas:

Obviously, we can use dfs + backtracking to fill in the symbols, but direct dfs will definitely Time Out (I will get WA); then we have to consider pruning, this topic can be used for pruning: we record the results obtained in each step. if we trace this step back and the results are consistent with the original results, we can directly return the results. You can use this pruning to access the AC.

In addition, the calculation result of each step may be negative. to use an array for weight determination, we need to add 50000 to the result and use it as the array subscript.


The code is as follows:


#include
 
  #include
  
   #include
   
    using namespace std;int a[110],n,flag,goal,vis[110][90000];char ans[110];inline int check(int a,int cur){    if(a>=-32000&&a<=32000&&!vis[cur][a+50000])    {        vis[cur][a+50000]=1;        return 1;    }    return 0;}void dfs(int cur,int sum){     if(cur==n-1)     {         if(sum==goal)         {            ans[cur]='=';            for(int i=0;i
    
     


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.