Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
用dp过了还是不知道贪心错在哪里....In Reply To:我想要我wa的数据啊.......wa的郁闷了... Posted by:lxj2006 at 2008-03-29 22:34:39 用树贪心... 贪心依据:每个右括号如果存在与它匹配的左括号,则与它匹配的左括号必是最后 一个输入或者外面一层的左括号。 #include <iostream> using namespace std; struct tree { char ch; tree *child[102]; int len; tree *parent; int flag; }; void InitTree(tree *&t); void SetTree(tree *&t); void PrintTree(tree *t); int main() { tree *t; while (1) { InitTree(t); SetTree(t); for (int i=0; i<t->len; i++) PrintTree(t->child[i]); printf("\n"); } return 0; } void InitTree(tree *&t) { t=new tree; t->ch='#'; t->len=0; int i; for (i=0; i<100; i++) t->child[i]=NULL; t->parent=NULL; t->flag=0; } void SetTree(tree *&root) { int i; char ct; scanf("%c",&ct); tree *p=root; if (ct=='(' || ct=='[') { p->len++; p->child[p->len-1]=new tree; p=p->child[p->len-1]; p->ch=ct; p->len=0; for (i=0; i<100; i++) p->child[i]=NULL; p->parent=root; p->flag=0; SetTree(p); } else if (ct==')') { while (p->ch!='(' && p->ch!='#') p=p->parent; if (p->ch!='#') { p->flag=1; p=p->parent; } else { p=root; p->len++; p->child[p->len-1]=new tree; p=p->child[p->len-1]; p->ch='('; p->len=0; for (i=0; i<100; i++) p->child[i]=NULL; p->parent=root; p->flag=1; p=root; } SetTree(p); } else if (ct==']') { while (p->ch!='[' && p->ch!='#') p=p->parent; if (p->ch!='#') { p->flag=1; p=p->parent; } else { p=root; p->len++; p->child[p->len-1]=new tree; p=p->child[p->len-1]; p->ch='['; p->len=0; for (i=0; i<100; i++) p->child[i]=NULL; p->parent=root; p->flag=1; p=root; } SetTree(p); } } void PrintTree(tree *t) { int i; if (!t) return ; printf("%c",t->ch); if (t->flag) { for (i=0; i<t->len; i++) PrintTree(t->child[i]); if (t->ch=='(') printf("%c",')'); else printf("%c",']'); } else { if (t->ch=='(') printf("%c",')'); else printf("%c",']'); for (i=0; i<t->len; i++) PrintTree(t->child[i]); } } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator