上次面试的时候遇到这么一道题目:一辆汽车加满油后可以行驶N千米。旅途中有若干个加油站。若要使沿途的加油次数最少,设计一个有效的算法,指出应在那些加油站停靠加油。
一个简单的算法如下:只要加油站站距小于汽车可行驶距离,就将其累加,累加标记打开,当累加的和大于行车距时,上一个加油站点便是必须要加油的站点,使用当前站距为起始累加;当累加的和等于行车距时,当前站点则为必须要加油的站点,使用累加站距清零,累加标记关闭;
namespace test
{
class Program
{
static void Main(string[] args)
{
int[] point = { 40, 20, 15, 12, 22, 15, 22, 10, 20, 30, 16, 15, 22, 16, 8, 2, 40, 22, 10, 5, 3 };
int distance = 40;
findAllPoint(point,distance);
}
private static void findAllPoint(int[] point, int distance)
{
for (int i = 0; i < point.Length; i++)
{
Console.Write(point[i] + " ");
}
Console.WriteLine();
Console.WriteLine("------------------------------------------");
//累加标记
bool countFlag = false;
//第N次加油
int jPoint = 1;
//累加存放
int sumValue = 0;
for (int i = 0; i < point.Length; i++)
{
//与行车距的检查
if (point[i] > distance)
{
Console.Write("行车距过大!!!");
break;
}
//与行车距相等
if ((point[i] == distance) && (countFlag == false))
{
Console.WriteLine("第{0}次加油是在站点{1}", jPoint, i);
jPoint++;
continue;
}
//比行车距相小,开始累加
if ((point[i] < distance) && (countFlag == false))
{
countFlag = true;
sumValue = point[i];
continue;
}
//有累加
if (countFlag == true)
{
//加上当前段距
sumValue = sumValue + point[i];
//比行车距大了
if (sumValue > distance)
{
countFlag = true;
sumValue = point[i];
Console.WriteLine("第{0}次加油是在站点{1}", jPoint, i - 1);
jPoint++;
continue;
}
//与行车距相等
if (sumValue == distance)
{
countFlag = false;
sumValue = 0;
Console.WriteLine("第{0}次加油是在站点{1}", jPoint, i);
jPoint++;
continue;
}
//继续累加
continue;
}
}
}
}
}
一个简单的算法如下:只要加油站站距小于汽车可行驶距离,就将其累加,累加标记打开,当累加的和大于行车距时,上一个加油站点便是必须要加油的站点,使用当前站距为起始累加;当累加的和等于行车距时,当前站点则为必须要加油的站点,使用累加站距清零,累加标记关闭;
namespace test
{
class Program
{
static void Main(string[] args)
{
int[] point = { 40, 20, 15, 12, 22, 15, 22, 10, 20, 30, 16, 15, 22, 16, 8, 2, 40, 22, 10, 5, 3 };
int distance = 40;
findAllPoint(point,distance);
}
private static void findAllPoint(int[] point, int distance)
{
for (int i = 0; i < point.Length; i++)
{
Console.Write(point[i] + " ");
}
Console.WriteLine();
Console.WriteLine("------------------------------------------");
//累加标记
bool countFlag = false;
//第N次加油
int jPoint = 1;
//累加存放
int sumValue = 0;
for (int i = 0; i < point.Length; i++)
{
//与行车距的检查
if (point[i] > distance)
{
Console.Write("行车距过大!!!");
break;
}
//与行车距相等
if ((point[i] == distance) && (countFlag == false))
{
Console.WriteLine("第{0}次加油是在站点{1}", jPoint, i);
jPoint++;
continue;
}
//比行车距相小,开始累加
if ((point[i] < distance) && (countFlag == false))
{
countFlag = true;
sumValue = point[i];
continue;
}
//有累加
if (countFlag == true)
{
//加上当前段距
sumValue = sumValue + point[i];
//比行车距大了
if (sumValue > distance)
{
countFlag = true;
sumValue = point[i];
Console.WriteLine("第{0}次加油是在站点{1}", jPoint, i - 1);
jPoint++;
continue;
}
//与行车距相等
if (sumValue == distance)
{
countFlag = false;
sumValue = 0;
Console.WriteLine("第{0}次加油是在站点{1}", jPoint, i);
jPoint++;
continue;
}
//继续累加
continue;
}
}
}
}
}