分析: 我们可以按照气球的结束坐标进行排序,然后从左往右遍历气球,并记录当前箭的射出位置。当遇到一个气球的开始坐标大于当前箭的射出位置时,说明需要射出一支新的箭,即当前箭无法引爆该气球。同时更新箭的射出位置为当前气球的结束坐标。最后需要的箭的数量即为射出的新箭的数量。

实现: 我们可以使用结构体来表示每个气球的开始和结束坐标,并按照结束坐标进行排序。然后遍历排序后的气球数组,进行判断和更新箭的射出位置。

代码实现如下:

#include #include using namespace std;

struct Balloon{ int start; int end; };

bool cmp(Balloon a, Balloon b){ return a.end < b.end; }

int main(){ int n; cin >> n;

Balloon balloons[n];
for(int i=0; i<n; i++){
    cin >> balloons[i].start >> balloons[i].end;
}

sort(balloons, balloons+n, cmp);

int arrowPos = balloons[0].end;
int arrowCount = 1;
for(int i=1; i<n; i++){
    if(balloons[i].start > arrowPos){
        arrowCount++;
        arrowPos = balloons[i].end;
    }
}

cout << arrowCount << endl;

return 0;
C++且不使用vector头文件完成:游乐园举办了一场射气球的比赛如果谁能使用最少的弓箭数量引爆所有气球则会得到最佳射手奖。规则如下:在二维空间中有n个直径不同的球形气球对于每个气球提供的是水平方向上气球直径的开始和结束坐标。由于气球是被水平牵引的所以Y坐标并不重要因此只要知道气球直径的开始和结束的X坐标就足够了。每个气球的直径的开始坐标一定小于结束坐标。一支弓箭可以沿着X轴从不同点完全垂直地射出

原文地址: https://www.cveoy.top/t/topic/h7VQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录