Memory Search Topics

Source: Internet
Author: User


What is a memory search? The inefficiency of search is that it is not able to deal with overlapping sub-problems well, while dynamic programming is better than dealing with overlapping sub-problems, it seems helpless in the face of some complicated topological relations. The memory search is precisely in such circumstances, it uses the form of search and the idea of recursive in dynamic programming to combine these two methods organically, to avoid weaknesses, simple and practical, in the informatics has an important role.
In a simple formula, say:Memory Search = The form of search + the idea of dynamic programming.
Dynamic planning: Is a optimization problem, the problem is decomposed into sub-problems, and the sub-problem of these decomposition itself is the best ability on the basis of the problem we want to solve the best solution, otherwise you can find a better consider alternative to this solution, to obtain a new optimal self-problem, This is, of course, contradictory to the premise. The dynamic programming is different from the greedy algorithm, because the greedy algorithm solves the problem from the local optimal, and the dynamic programming is the global optimal. In the case of dynamic programming, it is impossible to make a decision without the optimal solution of the sub-problem, but it is necessary to wait for the sub-problem to get the optimal solution before making a decision on the present situation, so the dynamic programming can be described by one or more recursive expressions. The greedy algorithm is the first to make a decision, and then to solve the sub-problem. This is the difference between greed and dynamic planning.
Generally encountered a problem of dynamic programming type, we must first determine the optimal sub-structure, there are overlapping sub-problems, these two are the most dynamic programming features, and then to write dynamic programming state equation, this step is very important, the writing of the equation is necessary experience, this can be achieved through training to achieve the goal. Then is to solve the problem from the bottom up, first the smallest sub-problem of the optimal solution, and generally use a table to record the solution, to later encounter the same sub-problem when you can directly look up the table to get the answer, and finally through a step by step iteration to obtain the answer to the final question.
The most important thing in my understanding is that you must have an array or other storage structure to store the solution of the sub-problem. This can save a lot of time, that is, the typical space change time
Dynamic programming is a kind of deformation is the memory search, is based on the dynamic return equation to write a recursive, and then directly at the beginning of the function to return the previously computed results, of course, this also requires a storage structure to write down the results of the previous calculations, so it is called the memory of the search.
Recursive dynamic programming of memory search
1. The idea of memory search
The idea of memory search is that there will be a lot of repetition in the search process, and if we can record the answers to some states, we can reduce the amount of repeated searches.
2. Application scope of memory search
According to the idea of memory search, it is to solve the repetitive calculation, rather than repeating the generation, that is, these searches must be in the search extension path in the process of the calculation of the topic, that is, "search answers and path-related" topic, but not to search a path after the calculation of the topic, must be calculated in step, And in the search process, a search result must be built on the results of the same type of problem, which is similar to the kind of dynamic planning solution.
That is to say, his problem is not simply to create a walk plan, but to generate a walk plan cost, and every step, in the search tree/graph to generate a new state, can be accurately calculate the cost of the end, that is, can be calculated in step, so that you can apply the answer already obtained
3, the core realization of memory search
A. First, a table is used to record the search results that have been stored, and the hash table is generally implemented
B. State representation, because it is to be implemented with a hash table, so the state is best to be represented by a number, the common method is to write a state into a P-binary number, and then the number corresponding to the decimal number as the state
C. At the beginning of each state search, efficient use of hash table to search whether this state has occurred, if already done, directly call the answer, backtracking
D. If not, search by normal method
4, the memory search is similar to the dynamic programming, the difference is that it is inverted "recursive dynamic planning."
"Poj1579" Function Run Fun "Online test submission Portal" "Problem description"

Custom Function W (a,b,c).
if a≤0 or b≤0 or c≤0, the result returned: 1; 
If a, 20 or B, 20 or C, 20, the result is: W (A, B, 
c), if a, B and B, then the result is:   W (A, C, c-1) + W (A, b-1, C-1)-W ( A, b-1, c) 
otherwise returns the result:  W (A-1, B, c) + W (A-1, B-1, C) + W (A-1, B, C-1)-W (A-1, B-1, C-1) 
"input Format"
The input contains several test data, one row per test data, representing the values of a, B, and C, respectively.
the input ends with a-1-1-1 indication.
"Output format"
Several rows, each sequentially outputting the returned result of a function corresponding to the test data.
"Input Sample 1"
1 1 1
2 2 2
ten 4 6-
1 7-
1-1-1
"output Example 1"
2
4
523
1048576
1
Reference code:
#include <bits/stdc++.h>
using namespace std;

int dp[25][25][25];

int dfs (int a,int b,int c)
{
    if (a<=0 | | b<=0 | | c<=0)
        return 1;
    if (a>20 | | b>20 | | c>20)
        return Dfs (20,20,20);
    if (Dp[a][b][c])   //Avoid repeated calculation of
        return dp[a][b][c];
    if (a<b && b<c)
        dp[a][b][c] = DFS (a,b,c-1) +dfs (a,b-1,c-1)-dfs (a,b-1,c);
    else
        dp[a][b][c] = DFS (a-1,b,c) +dfs (a-1,b-1,c) +dfs (a-1,b,c-1)-dfs (a-1,b-1,c-1);
    return dp[a][b][c];
}

int main ()
{
    int a,b,c;
    Memset (Dp,0,sizeof (DP));
    while (~SCANF ("%d%d%d", &a,&b,&c))
    {
        if (a = =-1 && b = =-1 && c = =-1)
            break;< c26/>printf ("%d\n", DFS (A,B,C));
    }
    return 0;
}
"Tyvj1004" Ski "Online test submission Portal" "Problem description"
  TRS likes to ski. He came to a ski resort where the ski was a rectangle, and for the sake of simplicity, we used the matrix of the R row C column to represent each piece of terrain. In order to get faster speeds, the glide route must be tilted downward (i.e. the height decreases).
    For example, the rectangle in the sample, you can slide from one point to the top or bottom four adjacent points. For example 24-17-16-1, in fact 25-24-23 ... 3-2-1 longer, in fact this is the longest one.
"input Format"
Line 1th: Two digits r,c (1≤r,c≤100), representing the rows and columns of a matrix.
2nd.. R+1 Line: The number of c per line, indicating the matrix. 
"Output format"
Only one row: outputs 1 integers representing the maximum length that can be slid.
"Input Sample"
5 5 
1 2 3 4 5, 6 7, 8 (13) 12 11 10 9 

"output Example"
25
#include <cstdio> #include <cstring> #include <algorithm> using namespace std;
const int Dx[4] = {1,0,-1,0};
const int Dy[4] = {0,1,0,-1};
const int MAXRC = 100 + 5;
int r,c;
int M[MAXRC][MAXRC];
int F[MAXRC][MAXRC]; Set F[I][J] to reach [i,j] the optimal value//f[i][j] = Max{f[i+a][i+b] | A and B are 4 coordinate increments, m[i][j]<m[i+a][i+b]} int dfs (int x, int y) {if (f [x]
    [Y]!=0] return f[x][y];//has calculated int maxt = 1;
    int t;
        for (int i=0;i<4;i++) {int tx = x + dx[i], Ty = y + dy[i]; if (Tx>0&&ty>0&&tx<=r&&ty<=c&&m[tx][ty]>m[x][y]) {t =
            DFS (tx,ty) +1;
        MAXT = max (T, MAXT);
}} F[x][y] = maxt;//memory return maxt;
    } int main () {scanf ("%d%d", &r, &c); 
    for (int i=1;i<=r;i++) for (int j=1;j<=c;j++) scanf ("%d", &m[i][j]);
    memset (f, 0, sizeof (f));
    int ans = 0; for (int i=1;i<=r;i++) for (int j=1;j<=c;j++) {f[i][J] = DFS (I,J);
    ans = max (ans, f[i][j]);
    } printf ("%d\n", ans);
return 0; }
"Hdu1501" Zippe "Online test submission Portal" "Problem description"
  Given three strings, determine whether the third string can be composed of the first two strings. The first two strings can be arbitrarily composed, but the relative order of the characters within a single string cannot be changed.
  For example, the first two strings are: Cat,tree. Both strings
  Tcraete and catrtee can have these two string compositions, but the string cttaree cannot.
"input Format"
The first line, an integer n (1≤n≤1000), represents the number of test data, for each test data:
a row, consisting of three spaces separated by a string, each consisting of lowercase letters. The first two strings are not longer than 200, and the length of the third string is the length of the first two strings and.
"Output format"
For each test data output line, a string, "yes" means can be constituted, "no" means no.
"Input Sample 1"
3
cat tree tcraete
cat tree catrtee
cat Tree Cttaree
"output Example 1"
Yes
Yes
no
//memory search #include <bits/stdc++.h> using namespace std;
String str1, str2, str;
BOOL Pos;

int vis[205][205];
        void Dfs (int s1, int s2, int s) {if (S1 = = Str1.length () && s2 = = Str2.length ()) {pos = true;
    Return

    } if (str1[s1]! = Str[s] && str2[s2]! = Str[s]) return;

    if (Vis[s1][s2]) return;

    VIS[S1][S2] = 1;
    if (str1[s1] = = Str[s]) DFS (s1 + 1, s2, S + 1);
if (str2[s2] = = Str[s]) dfs (s1, S2 + 1, s + 1);
    } int main () {int t, n;
    scanf ("%d", &t);
        while (T--) {cin >> str1 >> str2 >> str;
        pos = false;
        memset (Vis, 0, sizeof (VIS));
        DFS (0, 0, 0);
        if (POS) printf ("yes\n");
    else printf ("no\n");
} return 0; }
Dynamic programming #include <bits/stdc++.h> using namespace std;
const int N = 205;

const int INF = 1E8;
Char Str1[n], str2[n], str[n * 2];

int dp[n][n];
    int main () {int t, n;
    scanf ("%d", &t);
        while (T--) {scanf ("%s%s%s", str1 + 1, str2 + 1, str + 1);
        Str[0] = str1[0] = str2[0] = ' 0 ';
            for (int i = 1; i < strlen (str1); i + +) {if (str1[i] = = Str[i]) dp[i][0] = 1;
        else break;
            } for (int i = 1; i < strlen (str2); i + +) {if (str2[i] = = Str[i]) dp[0][i] = 1;
        else break;
            } for (int i = 1; i < strlen (str1); i + +) {for (int j = 1; J < strlen (str2); j + +) {Dp[i][j] = ((Dp[i-1][j] && str1[i] = = Str[i + j]) | |
            (Dp[i][j-1] && str2[j] = = Str[i + j]));
        }} if (Dp[strlen (str1)-1][strlen (STR2)-1]) printf ("yes\n");
    else printf ("no\n");
} return 0;
 }
"UVA10118" Free candies "Online test submission Portal" "Problem description"
There are 4 vertical tubes, each with n candies stacked in a basket, with a maximum of 5 candies. Each time you can take a candy from the top of any pipe into the basket, if the basket has two sugars in the same color, you can put the pair of candy in the pocket. Find out how many pairs of sweets you can put in your pocket.
"input Format"
The input has several groups (no more than 10 sets) of test data, for each set of test data:
the first line an integer n (1≤n≤40), which indicates how many candies each tube has, followed by n rows, 4 integers per line, and row J of Line I, which represents the color of the first candy of the first J tube. There are no more than 20 colors of candy, numbered 1 to N, respectively.
Enter the last line, ending with a 0 representation.
"Output format"
Output a number of lines, each group of test data output answer, each row.
"Input Sample 1"
5
1 2 3 4
1 5 6 7 2
3 3 3
4 9 8 6
8 7 2 1
1
1 2 3 4
3
1 2 3 4 5 6
7 8
  1 2 3 4
0
"output Example 1"
8
0
3
#include <bits/stdc++.h> using namespace std;

const int MAXN = 42;  int DP[MAXN][MAXN][MAXN][MAXN];

Number of pockets when each pile is left int N,ARR[5],A[5][MAXN]; int dfs (int basket,int candy) {if (dp[arr[1]][arr[2]][arr[3]][arr[4]]! =-1) return dp[arr[1]][arr[2]][arr[3]]
    [Arr[4]];
        else {int sum,t;
        int ans = 0;
            for (int i = 1; I <= 4; i++) {sum = 0;
            ++arr[i]; if (Arr[i] <= N) {if ((t = 1<<a[i][arr[i]) & Basket)//determine if sum in basket = d
                FS ((~T) &basket,candy-1) + 1;  else if (Candy < 4) sum = DFS (t|basket,candy+1);   Add this sugar into the basket}--arr[i];
        Backtracking ans = max (ans,sum);     
    } return dp[arr[1]][arr[2]][arr[3]][arr[4]] = ans; }} int main () {while (scanf ("%d", &n)! = EOF && N) {for (int i = 1; I <= n; i++) F
     or (int j = 1; J <= 4; j + +)           scanf ("%d", &a[j][i]);
        Memset (Dp,-1,sizeof (DP));
        memset (arr,0,sizeof (arr));
    printf ("%d\n", DFS (0,0));
} return 0;
 }
[Hdu1428] stroll the campus "Online test submission Portal" "Problem description"
  LL recently addicted to AC extricate oneself, every day bedroom, room 2.1 line. Lack of exercise because of sitting on the computer for a long time. He decided to take full advantage of every time from the bedroom to the computer room to take a walk on campus. The entire HDU campus is a square layout that can be divided into n*n squares, representing each area. For example, I will live in the 18th dormitory located in the northwest corner of the campus, that is, the square (a quarter) representative of the place, and the room is located in the third laboratory building in the southeast End (N,n). Because there are many routes to choose from, LL hope to take a different route each time. In addition, he considered from the a area to the B area only when there is a route from B to the machine room is closer than any one from a to the computer room (otherwise it may never be able to go to the engine room ...). What
  he wants to know now is how many lines there are to meet the requirements.
"input Format"
The first line is an integer n (2≤n≤50)
, and the next n rows have n numbers for each row, representing the time spent by each region T (0
  
"Output format"
For each set of test data, the total number of routes is output (less than 2^63).
"Input Sample"
3
1 2 3
1 2 3
1 2 3
3
1 1 1
1 1 1
1 1 1
"output Example"
1
6
"problem-solving ideas"
The 
 "he considered from zone A to area B only if there is a route from B to the machine room more near than any one from a to the engine room (otherwise it may never get to the engine room ...") This sentence must be understood clearly. That is, for the current position, this next state is undesirable if the shortest distance from the next state to the end point is greater than or equal to the shortest distance from the current position to the end point.
To this, you can understand that the problem is to find out all the points and the shortest distance from the end, and then from the beginning of the memory search. 
#include <iostream> #include <queue> #include <cstdio> #include <cstring> using namespace std;
const int n=60;

const int inf=99999999;
int map[n][n];

int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};

struct node{int x, y;};
int n;
int dis[n][n],visited[n][n];

Long Long res[n][n];
    void BFS () {//bfs to find the shortest way queue<node> myqueue;
    while (!myqueue.empty ()) Myqueue.pop ();
    int i,j,k;
    for (i=0;i<n;i++) for (j=0;j<n;j++) Dis[i][j]=inf;
    memset (visited,0,sizeof (visited));
    Dis[n][n]=map[n][n];
    Node Cur,next;
    Cur.x=n;cur.y=n;
    Myqueue.push (cur);
    Visited[cur.x][cur.y]=1;
    int x, y;
        while (!myqueue.empty ()) {Cur=myqueue.front ();
        Myqueue.pop ();
        visited[cur.x][cur.y]=0;
            for (k=0;k<4;k++) {next.x=x=cur.x+dir[k][0];
            NEXT.Y=Y=CUR.Y+DIR[K][1]; if (x>=1 && x<=n && y>=1 && y<=n && dis[x][y]>d Is[cur.x][cur.y]+map[x][y]) {dis[x][y]=dis[cur.x][cur.y]+map[x][y];
                    if (!visited[x][y]) {visited[x][y]=1;
                Myqueue.push (next);
    }}}}} A long long DFS (int x,int y) {//dfs The number of paths, using memory search optimization.
    if (x==n && y==n) return 1;
    if (res[x][y]!=-1) return res[x][y];
    res[x][y]=0;
    int si,sj,k;
        for (k=0;k<4;k++) {si=x+dir[k][0];
        SJ=Y+DIR[K][1]; if (si>=1 && si<=n && sj>=1 && sj<=n && dis[si][sj]<dis[x][y]) r
    Es[x][y]+=dfs (SI,SJ);
} return Res[x][y];
        } int main () {scanf ("%d", &n);
        for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) scanf ("%d", &map[i][j]);
        BFS ();
        memset (res,-1,sizeof (res));
    printf ("%lld\n", DFS);
return 0; }
[Nkoj3699] Pizza delivery "Online test submission Portal" "Problem description"
  The boss opened a pizza shop and one day suddenly received orders from N customers.
  where the boss of the city only a straight street, we can think of it as the axis, where the location of 0 is the owner of the pizza shop, the first customer is located in the Pi, each customer's location is different. If the boss sends pizza to the first customer, the customer will pay Ei-ti, which TI is the moment the boss arrives at his home. Of course, if arrive too late, will make ei-ti<0, at this time, what boss can choose not to give him to deliver meal, lest he turn to find what boss wants money.
  HO Boss Store only a delivery car (distance per unit of time travel unit length), so only round-trip delivery, as shown below is a line, the figure of the first line is the position pi, the second line is EI.
your task is to help the boss calculate the maximum benefit.

"input Format"

The first line, an integer n the
second row, an integer of n space intervals, gives the position of each customer from left to right pi, namely P1,P2,......, Pn
third row, n space interval integer, from left to right gives each customer corresponding EI, namely E1,e2, ..., En
"Output format"
A line, an integer, that represents the best benefit to ask.
"Input Sample 1"
5
-6-3-1 2 5
 27 10 2 5 20
"output Example 1"
32
"Input Sample 2"
6
 1 2 4 7 3 6 2 5
 18 10
"Output Example 2"
13
"Input Sample 3"
-14-13-12-11-10 1 2 3 4 5 200 200 200
 200 200 200 200 200 200 200 200
"output Example 3"
1937
"Data range"
1≤n≤100
-100,000≤pi≤100,000  and pi!=0
 0< ei≤100,000
"problem-solving ideas"
 #include <cstdio> #include <iostream> #include <algorithm> #include <
Cstdlib> #include <cstring> using namespace std;
int f[205][205][205][2];
BOOL Mark[205][205][205][2];
int n;
int Pos[205],e[205],start;
    int dp (int l,int r,int cnt,int p) {int i;
    if (Mark[l][r][cnt][p]) return f[l][r][cnt][p];
    Mark[l][r][cnt][p]=true;
    if (cnt==0) return f[l][r][cnt][p]=0; if (p==0) {for (i=1;i<l;i++) {F[l][r][cnt][p]=max (F[L][R][CNT][P],DP (i,r,cnt-1,0) +e[i]-cnt*abs (Pos[l]
        -pos[i])); } for (i=r+1;i<=n+1;i++) {F[l][r][cnt][p]=max (F[L][R][CNT][P],DP (l,i,cnt-1,1) +e[i]-cnt*abs (Pos[l]-po
        S[i])); }} else{for</

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.