D - Takahashi Tour
D - Takahashi Tour
https://atcoder.jp/contests/abc213/tasks/abc213_d
思路
图数据结构存储边的关系。
DFS遍历,
对于相邻节点存储使用set。
Code
https://atcoder.jp/contests/abc213/submissions/38555258
/******************************** GRAPH START ***************************************/ // Graph class represents a directed graph // using adjacency list representation class Graph { public: map<int, bool> visited; map<int, set<int> > adj; // vector<int> order; // 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].insert(w); // Add w to v’s list. } void Graph::DFS(int v) { // cout << "------" << endl; // Mark the current node as visited and // print it visited[v] = true; cout << v << " "; // order.push_back(v); // Recur for all the vertices adjacent // to this vertex set<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]){ DFS(*i); // order.push_back(v); cout << v << " "; } } /******************************** GRAPH END ***************************************/ /* https://atcoder.jp/contests/abcxxx/tasks/abcxxx_d */ Graph gp; int n; int main() { cin >> n; for(int i=0; i<n-1; i++){ int ai, bi; cin >> ai >> bi; gp.addEdge(ai, bi); gp.addEdge(bi, ai); } gp.DFS(1); // for(int i=0; i<gp.order.size(); i++){ // cout << gp.order[i] << " "; // } return 0; }
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。