zoj4016 Mergeable Stack
学学c++的list
c++:(借鉴了别人的)
1 //stackµÄ±àºÅÒ²ÐíÒªÀëÉ¢»¯ 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cmath> 6 #include <vector> 7 #include <set> 8 #include <map> 9 #include <list> 10 #include <stack> 11 #include <algorithm> 12 #include <iostream> 13 using namespace std; 14 const long maxn=3e5+5; 15 16 list<long> li[maxn]; 17 18 int main() 19 { 20 long ci,n,q,m,s,v,t,i; 21 scanf("%ld",&ci); 22 while (ci--) 23 { 24 scanf("%ld%ld",&n,&q); 25 for (i=1;i<=n;i++) 26 li[i].clear(); 27 while (q--) 28 { 29 scanf("%ld",&m); 30 if (m==1) 31 { 32 scanf("%ld%ld",&s,&v); 33 li[s].push_back(v); 34 } 35 else if (m==2) 36 { 37 scanf("%ld",&s); 38 if (li[s].empty()) 39 printf("EMPTY\n"); 40 else 41 { 42 printf("%ld\n",li[s].back()); 43 li[s].pop_back(); 44 } 45 } 46 else 47 { 48 scanf("%ld%ld",&s,&t); 49 li[s].splice(li[s].end(),li[t]); 50 } 51 } 52 } 53 return 0; 54 }
写栈(包含释放空间):(易写错)
1 //stack的编号也许要离散化 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cmath> 6 #include <vector> 7 #include <set> 8 #include <map> 9 #include <algorithm> 10 #include <iostream> 11 using namespace std; 12 const long maxn=3e5+5; 13 14 struct node 15 { 16 long d; 17 struct node *next; 18 }*p,*r,*b[maxn],*e[maxn]; 19 20 int main() 21 { 22 long ci,n,q,m,s,v,t,i; 23 scanf("%ld",&ci); 24 while (ci--) 25 { 26 scanf("%ld%ld",&n,&q); 27 for (i=1;i<=n;i++) 28 { 29 p=b[i]; 30 while (p) 31 { 32 r=p; 33 p=p->next; 34 free(r); 35 } 36 b[i]=NULL; 37 e[i]=NULL; 38 } 39 while (q--) 40 { 41 scanf("%ld",&m); 42 if (m==1) 43 { 44 scanf("%ld%ld",&s,&v); 45 p=(struct node *) malloc (sizeof(struct node)); 46 p->d=v; 47 if (b[s]==NULL) 48 { 49 p->next=NULL; 50 b[s]=p; 51 e[s]=p; 52 } 53 else 54 { 55 p->next=b[s]; 56 b[s]=p; 57 } 58 } 59 else if (m==2) 60 { 61 scanf("%ld",&s); 62 if (b[s]==NULL) 63 printf("EMPTY\n"); 64 else 65 { 66 printf("%ld\n",b[s]->d); 67 r=b[s];// 68 b[s]=b[s]->next; 69 if (b[s]==NULL) 70 e[s]=NULL; 71 free(r);// 72 } 73 } 74 else 75 { 76 scanf("%ld%ld",&s,&t); 77 if (b[t]!=NULL) 78 { 79 if (b[s]==NULL) 80 { 81 e[t]->next=b[s]; 82 b[s]=b[t]; 83 e[s]=e[t]; 84 b[t]=NULL; 85 e[t]=NULL; 86 } 87 else 88 { 89 e[t]->next=b[s]; 90 b[s]=b[t]; 91 b[t]=NULL; 92 e[t]=NULL; 93 } 94 } 95 } 96 } 97 } 98 return 0; 99 }