zl程序教程

您现在的位置是:首页 >  其它

当前栏目

C - Ladder Takahashi -- ATCODER

-- Atcoder
2023-09-27 14:28:34 时间

C - Ladder Takahashi

https://atcoder.jp/contests/abc277/tasks/abc277_c

 

思路

把梯子可达楼层看成图的节点

把梯子看成节点之间的连线

所以整个问题变成图的遍历问题,找到所有节点的最大值

 

 Code

https://atcoder.jp/contests/abc277/submissions/36429190

/******************************** GRAPH START ***************************************/
// Graph class represents a directed graph
// using adjacency list representation
class Graph {
public:
    map<int, bool> visited;
    map<int, list<int>> adj;
    int max = 1;
 
    // function to add an edge to graph
    void addEdge(int v, int w);
 
    // DFS traversal of the vertices
    // reachable from v
    void DFS(int v);
};
 
void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}
 
void Graph::DFS(int v)
{
    // Mark the current node as visited and
    // print it
    visited[v] = true;
//    cout << v << " ";
 
    if (v > max){
        max = v;
    }
 
    // Recur for all the vertices adjacent
    // to this vertex
    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFS(*i);
}
 
/******************************** GRAPH END ***************************************/
 
/*
https://atcoder.jp/contests/abcxxx/tasks/abcxxx_d
*/
 
int n;
Graph gp;
 
int main()
{
    cin >> n;
 
    for(int i=1; i<=n; i++){
        int a, b;
        cin >> a >> b;
        
        gp.addEdge(a, b);
        gp.addEdge(b, a);
    }
 
    gp.DFS(1);
    
    cout << gp.max << endl;
 
    return 0;
}