zoukankan      html  css  js  c++  java
  • Mergeable Stack(链表实现栈)

    C - Mergeable Stack

     ZOJ - 4016 

    一开始用stl中内置的栈来写,其中第三个操作,我先复制到一个数组,再将其倒给另一个栈

    这个方法有两个错误的地方:

    1.栈在内存很大需要扩容时,内存会成倍增长,解决办法是提前规定每个栈的大小,但这样还是不适用于这题

    2.如果每次都用一个数组来过度,时间复杂度是O(N*N)

    #include<iostream>
    #include<cstdio>
    using namespace std;
    const int maxn=3*1e5+5;
    struct node
    {
    	node *nex;
    	int num;
    };
    node *head[maxn];
    node *tail[maxn];
    int num[maxn];
    void add(int s,int v)
    {	
    	node *chan=head[s];
        head[s]=new node;
    	if(tail[s]==NULL)
    	{
    		tail[s]=head[s];
    	}
        head[s]->num=v;
    	head[s]->nex=chan;
    }
    int main()
    {
    	int T,s,v,t,q,n,comd;
    	cin>>T;
    	for(int i=1;i<=T;i++)
    	{
    		 scanf("%d %d",&n,&q);
    		 for(int j=1;j<=n;j++)
    			 head[j]=tail[j]=NULL;
    		 for(int j=1;j<=q;j++)
    		 {
    			 scanf("%d",&comd);
    			 if(comd==1)
    			 {
    				 scanf("%d %d",&s,&v);
    				 add(s,v);
    			 }
    			 else if(comd==2)
    			 {
    				 scanf("%d",&s);
    				 if(head[s]==NULL)
    				   printf("EMPTY
    ");
    				 else 
    				 {
    					 printf("%d
    ",head[s]->num);
    					 head[s]=head[s]->nex;
    					 if(head[s]==NULL)tail[s]=NULL;
    				 }
    			 }
    			 else if(comd==3)
    			 {
    				 scanf("%d %d",&s,&t);
    				 if(tail[t]!=NULL&&tail[s]!=NULL)
    				 {
    					 tail[t]->nex=head[s];
    					 head[s]=head[t];
    					 tail[t]=NULL;
    					 head[t]=NULL;
    				 }
    				 else if(tail[s]==NULL)
    				 {
    					 head[s]=head[t];
    					 tail[s]=tail[t];
    					 head[t]=NULL;
    					 tail[t]=NULL;
    				 }
    			 }
    		 }
    
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    POJ 1251 Jungle Roads
    1111 Online Map (30 分)
    1122 Hamiltonian Cycle (25 分)
    POJ 2560 Freckles
    1087 All Roads Lead to Rome (30 分)
    1072 Gas Station (30 分)
    1018 Public Bike Management (30 分)
    1030 Travel Plan (30 分)
    22. bootstrap组件#巨幕和旋转图标
    3. Spring配置文件
  • 原文地址:https://www.cnblogs.com/carcar/p/9231729.html
Copyright © 2011-2022 走看看