考察:
这题主要考察了struct的使用,以及边界的判断
思路:
我一开始想用bool isVisit[]来简化最后的碰撞判断,但总是错,经过调试发现这就是问题,虽然没明白,如果哪位朋友知道为什么错了,可以留言探讨
该段代码中的注释包含自己错的地方
相关代码如下:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
struct ball{
int d;
int p;
};
vector<ball> v;
int num,len,time;
int i,j,k;
int main(){
/***cin***/
cin>>num>>len>>time;
int shu;
for(i=0;i<num;i++){
ball nball;
cin>>nball.p;
nball.d=1;
v.push_back(nball);
}
/***solve***/
int l=0,r=len;
//bool isV[num];
for(i=0;i<time;i++){
for(j=0;j<num;j++){
//边界判断
if(v[j].d==-1){
v[j].p-=1;
if(v[j].p<l){
v[j].p+=2;
v[j].d=1;
}
}
else{
v[j].p+=1;
if(v[j].p>r){
v[j].p-=2;
v[j].d=-1;
}
}
}
for(j=0;j<num;j++){
//next direction if conflict
//cout<<"j: "<<j<<endl;
for(k=j+1;k<num;k++){
if(v[j].p==v[k].p){
//碰撞判断
v[j].d=-v[j].d;
v[k].d=-v[k].d;
//isV[k]=1;
//cout<<"k: "<<k<<endl;
break;
}
}
//isV[j]=1;
}
/***output***/
cout<<v[0].p;
for(i=1;i<num;i++){
cout<<" "<<v[i].p;
}
cout<<endl;
return 0;
} */
然后还参考了网上的答案
url:https://blog.csdn.net/tigerisland45/article/details/81660041
同样是struct的思路,他用了sort排序,时复明显降低
/* CCF201803-2 碰撞的小球 */
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100;
struct Node {
int id; // 小球编号
int pos; // 位置
int step; // 运动方向,1表示向右,-1表示向左
} b[N];
bool cmp1(Node a, Node b)
{
return a.pos < b.pos;
}
bool cmp2(Node a, Node b)
{
return a.id < b.id;
}
int main()
{
int n, l, t, id = 0;
cin >> n >> l >> t;
for(int i = 0; i < n; i++) {
b[i].id = ++id;
cin >> b[i].pos;
// 开始往右走,到达两端则回头
b[i].step = 1;
if(b[i].pos == l || b[i].pos == 0)
b[i].step = -b[i].step;
}
sort(b, b + n, cmp1);
for(int i = 0; i < t; i++) {
// 走一步
for(int j = 0; j < n; j++) {
b[j].pos += b[j].step;
// 到达两端则回头
if(b[j].pos == l || b[j].pos == 0)
b[j].step = -b[j].step;
}
// 判断是否碰头,碰头则掉头(排序后只需要比较相邻的)
for(int j = 1; j < n; j++)
if(b[j].pos == b[j - 1].pos)
b[j].step = -b[j].step, b[j - 1].step = -b[j - 1].step;
}
sort(b, b + n, cmp2);
for(int i = 0; i < n; i++)
cout << b[i].pos << " ";
cout << endl;
return 0;
}