题意:输入一大堆字符串,问字典序输出每个字符串占的百分比
分析:二叉搜索树插入,然后中序遍历就是字典序,这里root 被new出来后要指向NULL,RE好几次.这题暴力sort也是可以过的...
//#include <bits/stdc++.h> #include <cstdio> #include <cstring> #include <iostream> using namespace std; struct BST { char name[55]; int cnt; BST *lch, *rch; BST *insert(BST *p, char *s) { if (p == NULL) { BST *t = new BST; strcpy (t->name, s); t->cnt = 1; t->lch = t->rch = NULL; return t; } else if (strcmp (s, p->name) == 0) { (p->cnt)++; } else if (strcmp (s, p->name) < 0) p->lch = insert (p->lch, s); else p->rch = insert (p->rch, s); return p; } void mid_travel(BST *p, int n) { if (p != NULL) { mid_travel (p->lch, n); if (p->cnt != 0) printf ("%s %.4f ", p->name, p->cnt * 1.0 / n * 100); mid_travel (p->rch, n); } } }bst; int main(void) { int n = 0; char str[55]; BST *root = new BST; root = NULL; while (gets (str)) { root = bst.insert (root, str); n++; } bst.mid_travel (root, n); return 0; }
sort
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; int n; struct Name { char str[33]; }name[1000010]; bool cmp(Name a, Name b) { return strcmp (a.str, b.str) < 0; } int main(void) { n = 0; while (gets (name[n++].str)); sort (name, name+n, cmp); int i = 1; while (i < n) { int j = i; while (j < n && strcmp (name[j].str, name[i].str) == 0) j++; printf ("%s %.4f ", name[i].str, (j - i) * 1.0 / (n-1) * 100); i = j; } return 0; }