boj problem 1326 冒泡的话复杂度太高 TLE错误。输入时就应该进行判断

本文介绍了一个算法问题,涉及多个在一维直线上移动的盒子,在碰撞后改变方向但速度不变的情况下,如何计算达到稳定状态前的碰撞次数。文章通过示例输入输出展示了算法的具体实现。

Description
There are N boxes on one straight line which is long enough.
They move at the same speed, but their directions may be different. That is, some boxes
may move left, while the others move right. As a beautiful girl fond of algorithm and
programming, Alice finds that two boxes moving toward each other will collide, and
after collision their directions change while their speeds remain the same. Alice also
knows that the boxes will not collide any more after many times of collision, she names
this final status as the stable status. The task is to help her count the number of
collisions before reach the stable status.


Input
here are multiple test cases. For each test case, the first line is an integer N (1 <= N <= 10000) representing the number of boxes, and the second line is N integers,
separated by spaces. The i-th integer will be -1 if the i-th box move left, otherwise,
it will be 1.
An negative integer indicates the end of input and should not be processed by your program.


Output
For each test case, output an integer which is the number of collisions to reach the
stable status on a single line in the format as indicated.


Sample Input

3
1 -1 1
4
1 -1 1 -1
-1


Sample Output

Case 1: 1
Case 2: 3

#include<iostream>
using namespace std;
int main()
{

  int i,j,p,k=0;

  int a[10000],b[10000];
  for(i=0;i<10000;i++)
   b[i]=0;
 
  while(cin>>p)
  {
 
     if(p<0)
   break;
  if(p>0)
  {
   int res=0,temp=0;、、//res为结果 //temp为存储目前位置1的个数,只要后面出现一个-1 那么就要碰撞temp次
    k++;
    for(i=0;i<p;i++)
    {
      cin>>a[i];
   if(a[i]==1)
    temp++;            
   else
    res=res+temp;
    }
    b[k]=res;
 
        
   
  }
  }
  for(i=1;i<k+1;i++)
   cout<<"Case "<<i<<":"<<b[i]<<" "<<endl;
  return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值