LG-P1135 Strange Elevator

P1135 Strange Elevator Portal

Violent search, dfs.

Popularize, improve -.

In other words, the next time I encounter a violent search, I will use bfs to write it.

Details/bugs

  1. To open the vis array - to judge whether you have walked or not, reduce the number of times;

  2. Clear vis every time you backtrack (both are possible, see the code);

  3. The initial value of ans is set to 1e7(anyway, it is large enough), don't set 0x7fit, this is small enough intto only 127;

  4. It is necessary to judge in the middle whether cnt (the variable passed recursively) has been greater than or equal to ans (the target state has not been reached), and if so, return directly to reduce the number of times and shorten the time.

Commented out is one way to assign vis, not commented out is another way.

#include<bits/stdc++.h>
using namespace std;

#define int long long
const int maxn = 405;
int n, a, b;
int k[maxn], vis[maxn];
int ans, fla;
int sum;

int read ()
{
    
    
	int x = 1, s = 0;
	char ch = getchar ();
	while (ch < '0' or ch > '9'){
    
    
		if (ch == '-') x = -1;
		ch = getchar ();
	}
	while (ch >= '0' and ch <= '9'){
    
    
		s = s * 10 + ch - '0';
		ch = getchar ();
	}
	return x * s;
}

void dfs (int s, int t, int cnt)
{
    
    
	if (s == t)
	{
    
    
		fla = 1;
		ans = min (ans, cnt);
		return;
	}
	if (cnt >= ans) return;
	int de = k[s];
//	vis[s] = 1;
	if ((s - de) >= 1 and !vis[s - de]) 
	{
    
    
		vis[s - de] = 1;
		dfs (s - de, t, cnt + 1);
		vis[s - de] = 0;
	}
	if ((s + de) <= n and !vis[s + de])
	{
    
    
		vis[s + de] = 1;
		dfs (s + de, t, cnt + 1);
		vis[s + de] = 0;
	} 
//	vis[s] = 0;
}

signed main ()
{
    
    
	ans = 1e7;
	n = read (), a = read (), b = read ();
	for (int i = 1; i <= n; i++) k[i] = read ();
	dfs (a, b, 0);
	if (ans == 1e7) printf ("-1\n");
	else printf ("%lld\n", ans);
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324157849&siteId=291194637