跳到正文

题解

[USACO24JAN] Cannonball B 题解

Furina_40416约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年1月27日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 4 分钟
题目
P10132

版本

  1. v2当前
  2. v1

[USACO24JAN] Cannonball B 题解

数据大小分析

我们看一下题目中 数射线 的最高可能长度,是 10510^5,每秒 10910^9 的操作量足够我们直接模拟出答案了。

题面额外说明

1.Bessie 的初始方向是朝右的;
2.Bessie 的初始力量为1。
这两点原题没有讲。(题面我就不贴上来了)

代码1(注意代码会WA,不要抄题解!)

首先我们要初始化一下数组。

C++
#include <iostream>
using namespace std;
int qi[114514];
int vi[114514];

qi,viq_i,v_i 的意义入题目所示,但我选择了 qi,viqi,vi 作为变量名。
接着就是数入和循环内的几个初始化。

C++
int n,myp;
cin >> n >> myp; //Bessie的初始位置
for (int i=1; i<=n; i++){
    cin >> qi[i] >> vi[i]; //按照数射线长度遍历输入
}
int ans=0;//答案--击碎的目标数
int power=1;//初始力量
int directfactor=1;//初始方向--向右

接着就要开始写循环模拟了。

C++
for (int i=1; i<=1919810; i++){
    if (qi[myp]==0){//如果是弹板
        power+=vi[myp];//增加力量
        directfactor*=-1;//换方向
        myp+=directfactor*power;//改变位置
        if (0 >= myp || myp > n){//跳出循环
            break;
        }
        continue;//不加会错!
    }
    if (qi[myp]==1){//如果不是弹板
       if (power>=vi[myp])//如果坏了就加
           ans++;
       }
       myp+=directfactor*power;//同上
       if (myp <= 0 || myp > n){
          break;
       }
    }
}
cout << ans;

但奇怪的是,它WA了!
我就开始构造数据,还真找到了一组!

代码
3 1
1 1
1 1
0 1

应该输出2,但我的程序输出3!
经过检查,这是因为没有处理破碎目标会重复的情况,可以用数组 bib_i 来处理。
最后放标程

C++
#include <iostream>
using namespace std;
int qi[114514];
int vi[114514];
int bi[114514];
int main(){
	int n,myp;
	cin >> n >> myp;
	for (int i=1; i<=n; i++){
		cin >> qi[i] >> vi[i];
	}
	int ans=0;
	int power=1;
	int directfactor=1;
	for (int i=1; i<=1919810; i++){
		if (qi[myp]==0){
			power+=vi[myp];
			directfactor*=-1;
			myp+=directfactor*power;

			if (0 >= myp || myp > n){
				break;
			}

			continue;
		}

		//
		if (qi[myp]==1){
			if (power>=vi[myp]){
				bi[myp]=1;
			}
			myp+=directfactor*power;
		}
		if (myp <= 0 || myp > n){
			break;
		}

	}
	for (int i=1; i<=n; i++){
		if (bi[i]==1){
			ans++;
		}
	}
	cout << ans;
}
原文