CSP-201803-2 碰撞的小球

本文分享了一道CSP考试中的小球碰撞题目解析,通过使用数组跟踪每个位置的小球数量来判断是否发生碰撞,并调整小球移动方向。文章讨论了如何正确使用memset初始化数组及循环遍历实现球的位置更新。

这道题我在csp考试时候,当时没有做出来,当时没用debug,不知道怎么错的。

今天重新做一次,发现memset我用错了。

memset只能置0或者-1,其他的要用for循环进行。

题目思路:

这个题还是挺简单的。既然球一开始不会重合,只要判断某个位置上有两个球的时候,就改变这两个球的方向。

如果在边缘,也要改变方向,这样使得球可以正常移动。

用一个循环表示时间的流逝,遍历每一个球。

 1 #include <iostream>
 2 #include <string.h>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int n, L, t;//小球的个数、线段长度和t秒
 9     cin>>n>>L>>t;
10     int location[n+1];
11     int direction[n+1];
12     int LL[L];
13 
14     memset(LL,0,L*sizeof(int));
15 
16     for(int i=0; i<n; i++)
17         direction[i]=1;
18 
19     for(int i=0; i<n; i++)
20     {
21         cin>>location[i];
22         LL[location[i]]++;
23     }
24     //memset(direction,1,sizeof(int));
25 
26     for(int j=0; j<t; j++)
27     {//每一个时间
28         for(int i=0; i<n; i++)
29         {//对于每一个球
30             //先判断边缘问题
31             LL[location[i]]--;
32             location[i] += direction[i];
33             LL[location[i]]++;
34         }
35         for(int i=0; i<n; i++)
36         {//对于每一个球
37             //判断边缘
38             if(location[i] == L && direction[i] == 1)
39                 direction[i]=-1;
40             if(location[i] == 0 && direction[i] == -1)
41                 direction[i]=1;
42 
43             if(LL[location[i]] == 2)
44                 direction[i]*=int(-1);
45         }
46     }
47 
48     //output
49     for(int i=0; i<n; i++)
50     {
51         cout<<location[i];
52         if(i!=n-1)
53             cout<<' ';
54     }
55     cout<<endl;
56 }

 

转载于:https://www.cnblogs.com/amtop/p/9373965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值