使用 C++ 查找每个辐射站的最终辐射
假设在一条直线上有 N 个站点。每个站点都具有相同的非负辐射功率。每个站点都可以通过以下方式增加其相邻站点的辐射功率。
假设站点 i 的辐射功率为 R,它将使第 (i – 1) 个站点的辐射功率增加 R-1,第 (i - 2) 个站点的辐射功率增加 R-2,并将使第 (i + 1) 个站点的辐射功率增加 R-1,第 (i + 2) 个站点的辐射功率增加 R-2,依此类推。例如,如果数组为 Arr = [1, 2, 3],则输出将为 3, 4, 4。新的辐射将为 [1 + (2 – 1) + (3 - 2), 2 + (1 – 1) + (3 - 1), 3 + (2 – 1)] = [3, 4, 4]
思路很简单。对于每个站点 i,都会按照上述方式增加相邻站点的辐射,直到有效辐射变为负值。
示例
#include <iostream>
using namespace std;
class pump {
public:
int petrol;
int distance;
};
int findStartIndex(pump pumpQueue[], int n) {
int start_point = 0;
int end_point = 1;
int curr_petrol = pumpQueue[start_point].petrol - pumpQueue[start_point].distance;
while (end_point != start_point || curr_petrol < 0) {
while (curr_petrol < 0 && start_point != end_point) {
curr_petrol -= pumpQueue[start_point].petrol - pumpQueue[start_point].distance;
start_point = (start_point + 1) % n;
if (start_point == 0)
return -1;
}
curr_petrol += pumpQueue[end_point].petrol - pumpQueue[end_point].distance;
end_point = (end_point + 1) % n;
}
return start_point;
}
int main() {
pump PumpArray[] = {{4, 6}, {6, 5}, {7, 3}, {4, 5}};
int n = sizeof(PumpArray)/sizeof(PumpArray[0]);
int start = findStartIndex(PumpArray, n);
if(start == -1)
cout<<"No solution";
else
cout<<"Index of first petrol pump : "<<start;
}输出
Index of first petrol pump : 1
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP