一场比赛正在进行,在道路上放置了几块石头。在比赛的起点放置一个水桶,与第一块石头相距5个单位。其他石头彼此相距3个单位,并排成一条直线。即,第一和第二个石头之间的距离是3个单位,第三和第四个石头之间的距离也是3个单位,依此类推。竞争对手从水桶开始,捡起最近的石头,然后回去将其放入桶中,然后再次奔跑以收集下一个最近的石头,向后跑,然后将其放入桶中。这样,过程将继续进行,直到将所有石头都放入铲斗中为止。
现在,如果地面上有n块石头,那么在完成整个过程中,竞争对手将覆盖多少距离。
例子:
Input : n = 3
Output : Distance = 48
Explanation
= 2*5 + 2(5 + 3) + 2(5 + 3 + 3)
= 10 + 16 + 22
= 48
Input : n = 5
Output : Distance = 110
Explanation
= 2*5 + 2(5 + 3) + 2(5 + 3 + 3) + 2(5 + 3 + 3 + 3) + 2(5 + 3 + 3 + 3 + 3)
= 10 + 16 + 22 + 28 + 34
= 110
观察模式:
Distance run by competitor to pick first stone = 2 * 5
Distance run by competitor to pick second stone = 2(5 + 3)
Distance run by competitor to pick third stone = 2(5 + 3 + 3)
= 2(5 + (2 * 3))
Distance run by competitor to pick fourth stone = 2(5 + 3 + 3 + 3)
= 2(5 + (3 * 3))
Distance run by competitor to pick fifth stone = 2(5 + 3 + 3 + 3 + 3)
= 2(5 + (4 * 3))
.
.
.
Distance run by competitor to pick n-th stone = 2(5 + 3 + 3 + ……. + (n-1) times )
= 2(5 + (n-1) *3)
So total distance run by competitor = sum of all the above distances
= (2 * 5) + 2(5 + 3) + 2(5 + (2 * 3)) + 2(5 + (3 * 3)) + ………….. + 2(5 + (n-1) *3)
= 2(5 + (5 + 3) + (5 + (2 * 3)) + (5 + (3 * 3)) + ………………. + (5 + (n-1) * 3)
= 2(5 + 5 + 5 …… + n times) + (3 + (2 * 3) + (3 * 3) + ……… + (n-1) * 3)
= 2(5n + 3(1 + 2 + 3 + ……………. + n-1))
= 2(5n + 3/2[(n-1)*(n-1 + 1)] )
= 2(5n + 3/2[(n-1)*n])
= 2(5n + 3/2(n2 – n))
= 10n + 3*n2 – 3*n
= 3*n2 + 7*n
= n*((3 * n) + 7)
下面是该方法的实现:
C++
// C++ program to calculate
// the distance for given problem
#include
using namespace std;
// function to calculate the
// distance
int find_distance(int n)
{
return n * ((3 * n) + 7);
}
// Driver program
int main()
{
int n = 5;
cout << "Distance = " << find_distance(n);
return 0;
}
Java
// Java program to calculate the
// distance for given problem
class demo {
// function to calculate
// the distance
public static int find_distance(int n)
{
return n * (3 * n + 7);
}
// Driver program
public static void main(String args[])
{
int n = 5;
System.out.print("Distance = ");
System.out.println(find_distance(n));
}
}
Python3
# Python3 code to calculate
# the distance for given problem
# function to calculate the
# distance
def find_distance(n):
return n * ((3 * n) + 7)
# main function
n = 5
ans = find_distance( n )
print (ans)
# This code is contributed by Saloni Gupta
C#
// C# program to calculate
// the distance for given problem
using System;
class GFG {
// function to calculate the
// distance
public static int find_distance(int n)
{
return n * ((3 * n) + 7);
}
// Driver program
public static void Main()
{
int n = 5;
Console.Write(find_distance(n));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
PHP
Javascript
输出:
110