D - Erase Leaves
https://atcoder.jp/contests/abc333/tasks/abc333_d
思路
把这个图看成一棵树, 1作为树根,
统计 1树根关联的 子节点作为根的子树的总节点数,
去除 子树中总节点数最大子的 子树, 其它子树的总节点 记做贡献, 最后+1 (对应1节点)。
同时注意一个特殊情况, 1仅有一个子树的情况, 1退化为叶子节点, 只需要一次操作。
Code
https://atcoder.jp/contests/abc333/submissions/48592800
/******************************** GRAPH START ***************************************/ // Graph class represents a directed graph // using adjacency list representation class Graph { public: map<int, int> nodecnt; map<int, bool> visited; map<int, vector<int> > adj; // 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. adj[w].push_back(v); // 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 (adj[v].size() == 0){ nodecnt[v] = 1; return; } // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; long long nodesnum = 1; for (auto one: adj[v]){ if (!visited[one]){ DFS(one); nodesnum += nodecnt[one]; } } nodecnt[v] = nodesnum; } /******************************** GRAPH END ***************************************/ /* https://atcoder.jp/contests/abcxxx/tasks/abcxxx_d */ int n; class Graph g; int main() { cin >> n; for(int i=1; i<n; i++){ int u,v; cin >> u >> v; g.addEdge(u, v); } if(g.adj[1].size() == 1){ cout << 1 << endl; return 0; } g.DFS(1); vector<int> oneadjnodecnt; int oneadj_len = g.adj[1].size(); for(int i=0; i<oneadj_len; i++){ int oneadj_i = g.adj[1][i]; int nodes_i = g.nodecnt[oneadj_i]; oneadjnodecnt.push_back(nodes_i); // if (minnodes > nodes_i){ // minnodes = nodes_i; // } } sort(oneadjnodecnt.begin(), oneadjnodecnt.end()); int nodenumsum = 0; int oneadjnodecnt_len = oneadjnodecnt.size(); for(int i=0; i<oneadjnodecnt_len-1; i++){ nodenumsum += oneadjnodecnt[i]; } cout << nodenumsum+1 << endl; return 0; }
标签:int,oneadjnodecnt,Leaves,Erase,void,Graph,adj,节点 From: https://www.cnblogs.com/lightsong/p/17908505.html