Easy to Count
Time Limit:1000MS Memory Limit:65536K
Total Submit:76 Accepted:23
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
此题的意思是,n个相同速度的小球,在一条直线上运动,-1表示向左,1表示
向右运动,假设两小球互相碰撞后,速度不变,但方向改变,球碰撞次数。
解题思路:从左到右,for(i=0;i<m;i++)若小球a[i]=-1,则continue;若a[i+1]=-1
&&a[i]=1;则碰撞次数加1,然后通过while()循环回溯,直到左边的球不再相互
碰撞,继续向前查找。哎,表述的不是很清楚,还是看代码吧:
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int i,m,tag,a[10001],j=0;
while(scanf("%d",&m)!=EOF)
{
if(m==-1) break;
tag=0;
j++;
for(i=0;i<m;i++)
scanf("%d",&a[i]);
for(i=0;i<m-1;i++)
{
if(a[i]==-1) continue;
while(a[i]==1&&a[i+1]==-1)
{
tag++;
a[i]=-1;
a[i+1]=1;
if(i>0) i--;
}
}
printf("Case %d: %d/n",j,tag);
}
return 0;
}