1, no root tree turn to have a root tree
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define LL Long Long#define INF 0x7fffffff#include <vector>using namespace std;const int maxn = 1000005;int p[maxn];int n;int root;v Ector<int> g[maxn];void Read_tree () {//input whole tree int u, v;scanf ("%d", &n), for (int i = 0; i < n-1; i++) {scanf (" %d%d ", &u, &v); G[u].push_back (v); G[v].push_back (U);}} void Dfs (int u, int fa) {////recursively convert a subtree with u as root, U's father is fa int d = g[u].size (); for (int i = 0; i < D; i++) {//node U's number of neighboring points int v = g[u] [i];//node U, i-Adjacent point v if (v! = FA) Dfs (V, p[v] = u); Set the father of V to U, and then recursively convert the subtree with V as root}}int main () {//freopen ("In.txt", "R", stdin); Read_tree (); scanf ("%d", &root);p [Root] = 1 ;d FS (root,-1); for (int i = 0; i < n; i++) {printf ("%d", P[i]);} return 0;}
2. Expression tree
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define LL Long Long#define INF 0x7fffffffusing namespace Std;char str[10005]; const int MAXN = 1000;int LCH[MAXN], rch[maxn];//each node's left and right son number and character char op[maxn];int nc;//node int build_tree (char * s, int x, int y) {int I, C1 =-1, c2 =-1, p = 0;int u;if (y-x = = 1) {//Only one character, establish individual node U = ++nc;lch[u] = Rch[u] = 0;op[u] = S[x];ret Urn U;} for (int i = x, i < y; i++) {switch (S[i]) {case ' (': p++; Break;case ') ': p--; Break;case ' + ': Case '-': if (!p) c1 = i; Break;case ' * ': Case '/': if (!p) C2 = i; Break;}} if (C1 < 0) C1 = c2;if (C2 < 0) return Build_tree (S, x + 1, y-1); u = ++nc;lch[u] = Build_tree (s, x, C1); Rch[u] = Bui Ld_tree (S, C1 + 1, y); Op[u] = S[c1];return u;} int main () {while (scanf ("%s", str)! = EOF) {NC = 0;int len = strlen (str); op[0] = Build_tree (str, 0, Len); for (int i = 1; i <= NC; i++) {printf ("%c", Op[i]);}} return 0;}
3. Minimum spanning tree (Mst,kruskal)
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define LL Long Long#define INF 0x7fffffffusing namespace std;struct Edge {int A, b, w;} E[10005];int pa[1000005];int N, m;int cmp (Edge A, edge B) {//indirect sort function return A.W < B.W;} int find (int x) {///And look up set find return x = = Pa[x]? x:pa[x] = Find (Pa[x]);} int join (Edge e) {///and check set union int x = FIND (e.a), y = Find (e.b), if (x! = y) {pa[x] = Y;return e.w;} return 0;} int Kruskal () {//kruskal algorithm for mst int ans = 0;for (int i = 0; i < n; i++) Pa[i] = i;//Initialize and check set sort (E, E + M, CMP);//Sort for (int i = 0; i < n; i++) ans + = join (E[i]); return ans; int main () {while (scanf ("%d%d", &n, &m)! = EOF) {//n points, M-Edge for (int i = 0; i < m; i++) {scanf ("%d%d%d", & E[I].A, &e[i].b, &E[I].W);} printf ("%d\n", Kruskal ());} return 0;}
Data Structure-tree (Basic)