1. 程式人生 > >題解 P2196 【挖地雷】

題解 P2196 【挖地雷】

方法:

作為一個剛剛接觸OI的蒟蒻,看到題目想都沒想就寫了一個搜尋,列舉每一個地窖作為起點再比較答案然後記錄下最優的,雖然此方法十分地暴力,但由於n<=20所以仍然能AC的


 

程式碼:

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

const int MAXN = 20;

int n, max1, ans, depth, final;
//數量,最大的地雷數,每一個作為起點的最大價值,每一次地窖數,最優的地窖數
int a[MAXN], f[MAXN], vis[MAXN], path[MAXN]; //每一個地窖的地雷數,最終的答案,是否訪問過,每一次的路徑 vector <int> G[MAXN]; //標記相連 bool dfs(int x) { if(x == n) //到達終點 { path[depth] = x; return true; } if(vis[x]) //已訪問過 { return false; } vis[x] = true; //標記 path[depth] = x;
++depth; for(int i=0; i<G[x].size(); i++) //訪問和當前相鄰的每個節點 { int u = G[x][i]; if(dfs(u) == true) { return true; } } --depth; return false; } int main() { cin >> n; for(int i=1; i<=n; i++) cin >> a[i];
for(int i=1; i<=n; i++) { for(int j=1; j<=n-i; j++) { int x; cin >> x; if(x == 1) G[i].push_back(i + j); //標記相連 } } for(int i=1; i<=n; i++) { ans = depth = 0;//初始化 memset(path, 0, sizeof(path)); memset(vis, 0, sizeof(vis)); dfs(i); //訪問 for(int i=0; i<=depth; i++) ans += a[path[i]]; if(ans > max1) //當前更優 { max1 = ans; final = depth; for(int i=0; i<=depth; i++) f[i] = path[i]; } } for(int i=0; i<=final; i++) { cout << f[i] << " "; } cout << endl << max1; return 0; }

請各位大佬指出本蒟蒻程式碼中的(太多的)不足,以便改正,謝謝!!!


剛學完搜尋的蒟蒻的第一道獨立完成的搜尋題,以此紀念!