PTA跳一跳
一、题目描述
二、解题思路
利用map把每一次该层所对应的数值的各个位置存进去,然后进行dfs调用,当发现到了第n - 1层的话就可以比较一下答案了,需要再加上一个剪枝操作,就是当当前的步数已经比答案的步数相等,或者已经大于答案的步数时,再搜下去已经没有必要了。
三、代码实现
1 #include "bits/stdc++.h" 2 #define PII pair<int,int> 3 #define rep(i,z,n) for(int i = z;i <= n; i++) 4 #define per(i,n,z) for(int i = n;i >= z; i--) 5 #define ll long long 6 #define db double 7 #define vi vector<int> 8 #define debug(x) cerr << "!!!" << x << endl; 9 using namespace std; 10 inline ll read() 11 { 12 ll s,r; 13 r = 1; 14 s = 0; 15 char ch = getchar(); 16 while(ch < '0' || ch > '9'){ 17 if(ch == '-') 18 r = -1; 19 ch = getchar(); 20 } 21 while(ch >= '0' && ch <= '9'){ 22 s = (s << 1) + (s << 3) + (ch ^ 48); 23 ch = getchar(); 24 } 25 return s * r; 26 } 27 inline void write(ll x) 28 { 29 if(x < 0) putchar('-'),x = -x; 30 if(x > 9) write(x / 10); 31 putchar(x % 10 + '0'); 32 } 33 map <int,vector<int>> mp; 34 int a[50100]; 35 bool vis[50100]; 36 int n; 37 int ans = INT_MAX; 38 void dfs(int f,int step) 39 { 40 if(f == n - 1){ 41 ans = min(ans,step); 42 return; 43 } 44 if(step >= ans) 45 return; 46 if(f < n - 1 && !vis[f + 1]){ 47 vis[f + 1] = true; 48 dfs(f + 1,step + 1); 49 vis[f + 1] = false; 50 } 51 if(f > 0 && !vis[f - 1]){ 52 vis[f - 1] = true; 53 dfs(f - 1,step + 1); 54 vis[f - 1] = false; 55 } 56 if(mp[a[f]].size() != 0){ 57 for(auto iter = mp[a[f]].begin();iter != mp[a[f]].end();iter++){ 58 if(!vis[*iter]){ 59 vis[*iter] = true; 60 dfs(*iter,step + 1); 61 vis[*iter] = false; 62 } 63 } 64 } 65 } 66 int main() 67 { 68 69 n = read(); 70 rep(i,1,n){ 71 a[i - 1] = read(); 72 mp[a[i - 1]].push_back(i - 1); 73 } 74 dfs(0,0); 75 cout << ans; 76 return 0; 77 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}