CSP 2018年3月第2题 碰撞的小球
-
emm 填坑,之前 不会写了,然后看网上的也不太懂
于是 把去年数据结构作业时 写的代码拿出来测了一下,没问题
-
使用结构体来存储小球的位置和方向
循环
t秒
,依次判断所有的小球,看是否会相碰 (感觉会不会有点复杂,不是相邻的就行了吗,后面再填坑 改吧)相碰的话就改变其方向即可
-
接着判断 其位置是否走到两边的尽头
除此之外的情况 就直接沿着对应的方向前进
-
下面是源码
#include<stdio.h> #include<stdlib.h> typedef struct Ball { int location; int direction; // 1 向 右 ; 0 向 左 }Ball; int main() { int L,n,t; int i,j,time; int temp;//用来 交换 两个小球方向 //printf("输入 n L t 中间用空格 隔开\n"); scanf("%d %d %d",&n,&L,&t); Ball ball[n+1];//建立 Ball 类型数组 for(i=1;i<=n;i++) { scanf("%d",&ball[i].location); ball[i].direction = 1; }//输入 小球 初始位置 for(time = 0;time<t;time++) { for(i=1;i<n;i++) { for(j=i+1;j<=n;j++)//同其余小球判断 是否相碰 { if(ball[i].location == ball[j].location) { temp = ball[i].direction; ball[i].direction = ball[j].direction; ball[j].direction = temp; }//小球交换 前进方向 } } for(i=1;i<=n;i++) { if(ball[i].location == L && ball[i].direction == 1)//向右走到尽头 ball[i].direction = 0; if(ball[i].location == 0 && ball[i].direction == 0)//向左走到尽头 ball[i].direction = 1; if(ball[i].direction == 1) ball[i].location++; else ball[i].location--; } } for(i = 1;i<=n;i++) printf("%d ",ball[i].location); return 0; }