#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; vector<int> G[maxn]; void read_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) { //递归转化以u为根的子树,u的父亲为fa int d = G[u].size(); for(int i = 0; i < d; i++) { //结点u的相邻点个数 int v = G[u][i]; //结点u的第i个相邻点v if(v != fa) dfs(v, p[v] = u); //把v的父亲设为u,然后递归转化以v为根的子树 } } int main() { //freopen("in.txt", "r", stdin); read_tree(); scanf("%d", &root); p[root] = -1; dfs(root, -1); for(int i = 0; i < n; i++) { printf("%d ", p[i]); } return 0; }
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define LL long long #define INF 0x7fffffff using namespace std; char str[10005]; const int maxn = 1000; int lch[maxn], rch[maxn]; //每个结点的左右儿子编号和字符 char op[maxn]; int nc; //结点数 int build_tree(char * s, int x, int y) { int i, c1 = -1, c2 = -1, p = 0; int u; if(y - x == 1) { //仅一个字符,建立单独结点 u = ++nc; lch[u] = rch[u] = 0; op[u] = s[x]; return 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] = build_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; }
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define LL long long #define INF 0x7fffffff using namespace std; struct edge { int a, b, w; }e[10005]; int pa[1000005]; int n, m; int cmp(edge a, edge b) { //间接排序函数 return a.w < b.w; } int find(int x) { //并查集查找 return x == pa[x] ? x : pa[x] = find(pa[x]); } int join(edge e) { //并查集联合 int x = find(e.a), y = find(e.b); if(x != y) { pa[x] = y; return e.w; } return 0; } int kruskal() { //kruskal算法求MST int ans = 0; for(int i = 0; i < n; i++) pa[i] = i;//初始化并查集 sort(e, e + m, cmp);//给边排序 for(int i = 0; i < n; i++) ans += join(e[i]); return ans; } int main() { while(scanf("%d %d", &n, &m) != EOF) { //n个点,m条边 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; }
原文地址:http://blog.csdn.net/u014355480/article/details/45049379