Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

用二叉搜索树终于过了。。。不过时间还是不够快。。。贴代码傻一下。。。

Posted by lgq1205 at 2009-08-19 19:52:04 on Problem 2503
#include<cstdio>
#include<cstring>
#define N 13
bool flag;

char a[N], b[N],c[N];
typedef struct node {
    char pre[N];
    char s[N];
    node *left;
    node *right;
} BST;

BST *creat_tree(BST *p, char* str1, char* str2) {
    if (p == NULL) {
        p = new BST();
        strcpy(p->pre, str1);
        strcpy(p->s, str2);
        p->left = NULL;
        p->right = NULL;
    } else {
        if (strcmp(str2, p->s) > 0) {
            p->right = creat_tree(p->right, str1, str2);
        } else {
            p->left = creat_tree(p->left, str1, str2);
        }
    }
	return p;
}

void print(BST *p, char *a) {
    if (p) {
        
        if (strcmp(p->s, a) == 0)
        {
            flag = true;
            printf("%s\n", p->pre);
            return;
        }
        else
            if (strcmp(p->s, a) > 0)
            print(p->left, a);
        else
            print(p->right, a);
    }
}

int main() {
    
    BST *root = NULL;
    while (gets(a)) {
        if(strcmp(a,"")==0)
            break;
        int i;
        for(i = 0;a[i]!=' ';i++)
            c[i] = a[i];
        i++;
        c[i] = '\0';
        int t = i;
        for(;i<strlen(a);i++)
            b[i-t] = a[i];
        b[i - t] = '\0';
        //printf("%s\n%s\n",c,b);
        root = creat_tree(root, c, b);
    }
    while (scanf("%s", a) != EOF) {
        flag = false;
        print(root, a);
        if(!flag)
            printf("eh\n");
    }
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator