矢量堆栈对|使用dfs的树中最长的路径

问题描述 投票:0回答:1
#include <bits/stdc++.h>
using namespace std;

vector <int> adj(10001);
bool vis[10001];

void initialize ()
{
    for (int i = 0; i<10001; i++)
        vis[i] = false;
}

pair <int,int> dfs ( int x )
{
    stack < pair<int,int> > s;
    s.push( make_pair (x,0) );
    int maxnode = x, maxlevel = 0;

    while (!s.empty())
    {
        int t = s.top().first;
        int level = s.top().second;
        if (level>maxlevel)
        {
            maxnode = t;
            maxlevel = level;
        }

        s.pop();
        vis[t] = true;

        for ( int i = 0; i<adj[t].size(); i++)
        {
            if ( vis[adj[t][i]]==false)
            {
                s.push( make_pair (adj[t][i], level+1 ));
            } 
        }

    }

    return make_pair (maxnode,maxlevel);
}

int main() {
    // your code goes here
    int n, x;
    cin>>n;

    if (n==1 || n==2)
    {
        cout<<n-1;
        exit(0);
    }

    initialize();

    for (int i = 0; i<n-1; i++)
    {
        int a, b;
        cin>>a>>b;

        if (i==0)
            x = a;

        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    pair <int,int> far1 = dfs (x);
    initialize();
    pair <int,int> far2 = dfs (far1.first);

    cout<<far2.second;


    return 0;
}

Or the code is here.

与向量,堆栈,对相关的错误:

prog.cpp:在函数'std :: pair dfs(int)'中:prog.cpp:32:29:错误:请求'adj.std :: vector <_Tp,_Alloc> :: operator [中的成员'size' ]>(((std :: vector :: size_type)t))',它是非类型类型'__gnu_cxx :: __ alloc_traits> :: value_type {aka int}'for(int i = 0; i ^ prog。 cpp:34:21:错误:无效类型'__gnu_cxx :: __ alloc_traits> :: value_type {aka int} [int]'对于数组下标if(vis [adj [t] [i]] == false) ^ prog.cpp:在函数'int main()'中:prog.cpp:66:10:错误:请求'adj.std :: vector <_Tp,_Alloc> :: operator []>中的成员'push_back'( ((std :: vector :: size_type)a))',它是非类型的类型'__gnu_cxx :: __ alloc_traits> :: value_type {aka int}'adj [a] .push_back(b); ^ prog.cpp:67:10:错误:请求'adj.std :: vector <_Tp,_Alloc> :: operator []>中的成员'push_back'(((std :: vector :: size_type)b)) ',它是非类型的'__gnu_cxx :: __ alloc_traits> :: value_type {aka int}'adj [b] .push_back(a); ^

请帮我纠正这些。

c++ vector stack std-pair push-back
1个回答
0
投票

解决了:vector adj(10001); to vector adj [10001];因为它是一个2d矢量

© www.soinside.com 2019 - 2024. All rights reserved.