题解 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;
} 

请各位大佬指出本蒟蒻代码中的(太多的)不足,以便改正,谢谢!!!


刚学完搜索的蒟蒻的第一道独立完成的搜索题,以此纪念!

 

猜你喜欢

转载自www.cnblogs.com/Ghostyht/p/9886134.html