boj 1329 简单算法 利用栈来计数

寻找相同Submit: 1756   Accepted:421Time Limit: 1000MS  Memory Limit: 65535K

Description
有一组数,很多很多个数,里面有一个数出现了超过一半次,请你把它找出来。

Input
先是一个N (N<=400000),然后接下来一行N个数,多组数据输入。

Output
对每个Case,输出一行,这一行只含有一个在之前数列中出现超过一半次的数。每个case之后输出一个空行。

Sample Input

11
5 5 5 5 5 5 1 2 3 4 6


Sample Output

Case 1: 5


Source


#include<iostream>
using namespace std;
int b[400001];
typedef struct
{
 int *a;           //栈内不可定义太大数组,用动态就可以
 int top;
}stack;

void initstack(stack &s)  //&s 取地址
{
  s.top=-1;
}
bool empty(stack &s)
{
 if(s.top==-1)
  return 1;
 else
  return 0;
}
void pushstack(stack &s,int x)
{
 s.top++;
 s.a[s.top]=x;
}
void popstack(stack &s)
{
  s.top--;
}
int gettop(stack &s)
{

   int x;
   if(s.top==-1)
    return -99999;
   else
   {
    x=s.a[s.top];
       return x;
   }
}


int main()
{


  int i,j,sum=1;
  int temp;
  while(cin>>j)
  {
  stack s;
     initstack(s);
 s.a=new int[j+1];
    for(i=0;i<j;i++)
  cin>>b[i];
 for(i=0;i<j;i++)
 {
   temp=gettop(s);
   if(b[i]!=temp)
   {
    if(empty(s))
     pushstack(s,b[i]);
    else
    {
    popstack(s);
    }
   }
   else
   {
     pushstack(s,b[i]);
   }
 }
 temp=gettop(s);
 cout<<"Case "<<sum<<": "<<temp<<endl;
 cout<<endl;
 sum++;
  }
  return 0;
}

 

 

类栈算法   空间节省 但是时间680MS 依然不太好 需要改进 代码如下:

#include<iostream>
using namespace std;
int a[400001];
int main()
{
  int i,j,n,temp;
  int top;
  int sum=1;
  while(scanf("%d",&n)!=EOF)    //cin改成scanf后  直接从680MS降到121MS 差距极为明显~~1330也顺利AC!!
  {
 top=-1;
    for(i=0;i<n;i++)
 {
   scanf("%d",&temp);                   

    if(top==-1)           //如果栈空
    {
       top++;
    a[top]=temp;
    }
    else
    {
    if(temp==a[top])    //相同入栈 不同出栈
    {
      top++;
   a[top]=temp;
    }
    else
    {
       top--;
    }
    }
 }
 cout<<"Case "<<sum<<": "<<a[top]<<endl;
    cout<<endl;
     sum++;

  }
  return 0;
}

 

总体思路 由于要找超过一般的数,那么与栈顶相同的入栈,不同的话则栈顶出栈,这样超过一半的最后一定是栈顶元素~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值