平面上 N 点之间唯一直接路径的计数
给定平面上的N个点,其中每个点都有一条直接路径将其连接到不同的点,任务是计算点之间唯一直接路径的总数。
注意: N的值将始终大于2 。
例子:
Input: N = 4
Output: 6
Explanation: Think of 4 points as a 4 sided polygon. There will 4 direct paths (sides of the polygon) as well as 2 diagonals (diagonals of the polygon). Hence the answer will be 6 direct paths.
Input: N = 3
Output: 3
Explanation: Think of 3 points as a 3 sided polygon. There will 3 direct paths (sides of the polygon) as well as 0 diagonals (diagonals of the polygon). Hence the answer will be 3 direct paths.
方法:给定的问题可以通过观察来解决,即对于任何N边都有(边数 + 对角线数)直接路径。对于任何N边多边形,都有N条边和N*(N – 3)/2条对角线。因此,直接路径的总数由N + (N * (N – 3))/2给出。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count the total number
// of direct paths
int countDirectPath(int N)
{
return N + (N * (N - 3)) / 2;
}
// Driver Code
int main()
{
int N = 5;
cout << countDirectPath(N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to count the total number
// of direct paths
static int countDirectPath(int N)
{
return N + (N * (N - 3)) / 2;
}
// Driver Code
public static void main(String []args)
{
int N = 5;
System.out.print(countDirectPath(N));
}
}
// This code is contributed by shivanisinghss2110
Python3
# python program for the above approach
# Function to count the total number
# of direct paths
def countDirectPath(N):
return N + (N * (N - 3)) // 2
# Driver Code
if __name__ == "__main__":
N = 5
print(countDirectPath(N))
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
public class GFG
{
// Function to count the total number
// of direct paths
static int countDirectPath(int N)
{
return N + (N * (N - 3)) / 2;
}
// Driver Code
public static void Main(string []args)
{
int N = 5;
Console.Write(countDirectPath(N));
}
}
// This code is contributed by AnkThon
Javascript
10
时间复杂度: O(1)
辅助空间: O(1)