给定一个整数N ,您需要猜测一个隐藏的排列(从1到N的数字,每个数字只出现一次)。您可以执行以下操作:
在第一个位置选择一个数字:
- 如果正确,则猜测下一个位置。
- 如果错了,整个排列将重置,然后您回到猜测第一个位置。
您可以进行反复试验以获得正确的排列,也可以将先前的知识用于下一个猜测。例如,如果您正确地知道第一个位置的数字,而错误地找到了第二个位置,那么在下一步操作中,您可以正确输入第一个位置并继续移动到第二个位置。
找到在最坏情况下要使整个排列正确的最小移动量。
例子:
Input: N = 2
Output: 3
You choose 2 for 1st position, and the permutation resets.
You choose 1 for 1st position, the guess is correct and now you are to guess for the 2nd position.
You choose 2 for the 2nd position since that is the only remaining option you have.
Input: N = 3
Output: 7
方法:要正确猜测第i个位置,需要进行(ni)个猜测。对于每次猜测,您总共需要进行i次移动((i-1次)移动以输入您已经知道的正确前缀,并进行1次移动以猜测当前的前缀)。在最后一步中,您将需要N步才能输入正确的排列。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns the required moves
int countMoves(int n)
{
int ct = 0;
for (int i = 1; i <= n; i++)
ct += i * (n - i);
// Final move
ct += n;
return ct;
}
// Driver Program to test above function
int main()
{
int n = 3;
cout << countMoves(n);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG {
// Function that returns the required moves
static int countMoves(int n)
{
int ct = 0;
for (int i = 1; i <= n; i++)
ct += i * (n - i);
// Final move
ct += n;
return ct;
}
// Driver Program to test above function
public static void main (String[] args) {
int n = 3;
System.out.println( countMoves(n));
}
}
// This code is contributed by anuj_67..
Python3
# Python3 implementation of the approach
# Function that returns the
# required moves
def countMoves(n):
ct = 0
for i in range(1, n + 1):
ct += i * (n - i)
# Final move
ct += n
return ct
# Driver Code
if __name__ == "__main__":
n = 3
print(countMoves(n))
# This code is contributed
# by ChitraNayal
C#
// C# implementation of the approach
using System;
class GFG {
// Function that returns the required moves
static int countMoves(int n)
{
int ct = 0;
for (int i = 1; i <= n; i++)
ct += i * (n - i);
// Final move
ct += n;
return ct;
}
// Driver Program to test above function
static void Main()
{
int n = 3;
Console.WriteLine(countMoves(n));
}
// This code is contributed by Ryuga.
}
PHP
Javascript
输出:
7