Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <unordered_map>
- #include <set>
- #include <utility>
- using namespace std;
- #define M 1000000007
- struct DisjointUnionSets {
- vector<int> rank;
- vector<int> parent;
- DisjointUnionSets(int n) {
- rank.resize(n);
- parent.resize(n);;
- makeSet();
- }
- void makeSet() {
- for (int i=0; i<parent.size(); i++) {
- parent[i] = i;
- }
- }
- int find(int x) {
- if (parent[x]!=x) {
- parent[x] = find(parent[x]);
- }
- return parent[x];
- }
- void union_(int x, int y) {
- int xRoot = find(x);
- int yRoot = find(y);
- if (xRoot == yRoot) {
- return;
- }
- if (rank[xRoot] < rank[yRoot]) {
- parent[xRoot] = yRoot;
- } else if (rank[yRoot] < rank[xRoot]) {
- parent[yRoot] = xRoot;
- } else {
- parent[yRoot] = xRoot;
- rank[xRoot] = rank[xRoot] + 1;
- }
- }
- };
- struct Node {
- int id;
- int parent{-1};
- int cnt{0};
- vector<int> children;
- };
- vector<Node> nodes;
- set<pair<int,int>> red_edge_set;
- bool is_red(int i, int j) {
- auto it = red_edge_set.find(make_pair(min(i,j), max(i,j)));
- return it != red_edge_set.end();
- }
- int build_tree(int n) {
- nodes.reserve(n);
- for (int i = 0; i < n; i++) {
- Node node;
- node.id = i;
- nodes.push_back(node);
- }
- for (int i = 0; i < n-1; i++) {
- int a, b;
- char c;
- cin >> a >> b >> c;
- int xid = a - 1;
- int yid = b - 1;
- if (c == 'r') {
- red_edge_set.insert(make_pair(min(xid,yid), max(xid,yid)));
- }
- if (nodes[yid].parent != -1) {
- vector<int> stack;
- int p = yid;
- while (p != -1) {
- stack.push_back(p);
- p = nodes[p].parent;
- }
- while (stack.size() > 1) {
- p = stack.back();
- stack.pop_back();
- nodes[p].parent = stack.back();
- }
- }
- nodes[yid].parent = xid;
- }
- int root = -1;
- for (auto &n : nodes) {
- if (n.parent != -1) {
- nodes[n.parent].children.push_back(n.id);
- } else {
- root = n.id;
- }
- }
- return root;
- }
- int count(int root) {
- int c = 1;
- for (auto &child : nodes[root].children) {
- c += count(child);
- }
- nodes[root].cnt = c;
- return c;
- }
- int main() {
- int n;
- cin >> n;
- auto root = build_tree(n);
- count(root);
- long result = 0;
- cout << result << endl;
- }
Add Comment
Please, Sign In to add comment