坚持使用DFS / BFS任务(USACO银牌)

时间:2017-01-22 23:37:16

标签: algorithm graph-theory depth-first-search

竞争性编程菜鸟在这里。我一直试图解决这个问题: http://www.usaco.org/index.php?page=viewproblem2&cpid=646

我编写的代码仅适用于第一个测试用例,并为其余测试用例提供了内存限制超出错误 - 或('!')。 这是我的代码(意外混淆了M和N):

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
using std::vector;
vector<int> check;
vector< vector<int> > A;
void dfs(int node)
{
    check[node] = 1;
    int siz = A[node].size();
    for (int i = 0; i < siz; i++)
    {
        int y = A[node][i];
        if (check[y] == 0)
        {
            dfs(y);
        }
    }
}

bool connected(vector<int> C)
{
    for (int i = 1; i <= C.size() - 1; i++)
    {
        if (C[i] == 0)
        {
            return false;
        }
    }
    return true;
}

int main()
{
    freopen("closing.in", "r", stdin);
    freopen("closing.out", "w", stdout);
    ios_base::sync_with_stdio(false);
    int M, N;
    cin >> M >> N;
    check.resize(M + 1);
    A.resize(M + 1);
    for (int i = 0; i < N; i++)
    {
        int u, v;
        cin >> u >> v;
        A[u].push_back(v); A[v].push_back(u);
    }
    dfs(1);
    if (!connected(check)) {
        cout << "NO" << "\n";
    }
    else {
        cout << "YES" << "\n";
    }
    fill(check.begin(), check.end(), 0);
    for (int j = 1; j < M; j++)
    {
        int node;
        bool con = true;
        cin >> node;
        check[node] = -1;
        for (int x = 1; x <= N; x++)
        {
            if (check[x] == 0)
            {
                dfs(x);
                break;
            }
        }
        if (!connected(check)) {
            cout << "NO" << "\n";
        }
        else {
            cout << "YES" << "\n";
        }
        for (int g = 1; g <= M; g++)
        {
            if (check[g] == 1)
            {
                check[g] = 0;
            }
        }
    }
    return 0;
}

基本上, void dfs(int node)搜索从节点开始直到达到死胡同的双向图,对于每个访问过的节点,check [node]将变为1。 (如果已访问 - &gt; 1,未访问 - &gt; 0,已关闭 - &gt; -1)。

bool connected(向量C)将采用检查向量并查看是否有任何未访问的节点。如果此函数返回true,则表示图形已连接,否则为false。

在主要功能中,

1)我将任务中给出的双向图保存为邻接列表。

2)dfs首先查看图表是否最初连接(然后打印&#34;是&#34;或&#34;否&#34;)然后重置检查

3)从1到M,我取出谷仓关闭的输入值,检查[输入值] = -1,并通过它检查dfs。之后,我重置了检查向量,但保留了-1值,以便那些谷仓不能用于下一个dfs循环。

我想我的算法很有意义,但为什么这会给MLE,我怎样才能改进我的解决方案呢?我真的无法弄清楚为什么我的代码会给MLEs。 非常感谢!

1 个答案:

答案 0 :(得分:0)

  1. 您的DFS正在承担大量的堆栈,从而导致MLE
  2. 尝试使用队列实现BFS。尽量将队列保持为全局而不是本地。
  3. 您的方法将为您提供超时限制判决。尝试更有效地解决它。说O(n)。