给定一个整数X ,任务是找到一组最佳权重{w 1 , w 2 , w 3 , …, w n } ,这样我们就可以使用双边称重来衡量/确定从1到X的所有权重平衡盘。请注意,所有权重必须是唯一的,并且n应尽可能小。
例子:
Input: X = 7
Output: 1 3 9
Weights | Left Side | Right Side |
---|---|---|
1 | 1 | 1 |
2 | 2 + 1 | 3 |
3 | 3 | 3 |
4 | 4 | 1 + 3 |
5 | 5 + 1 + 3 | 9 |
6 | 6 + 3 | 9 |
7 | 7 + 3 | 1 + 9 |
Input: X = 20
Output: 1 3 9 27
方法:
- 一种最佳方法是使用 3 的幂的权重,即{1, 3, 9, 27, 81, 243, …}
- 可以通过归纳证明,使用{1, 3, 9, 27, 81, …, pow(3, n)} ,我们可以平衡从1到(pow(3, n + 1) – 1)的所有权重/ 2 。
- 因此,找到n的值,使得从1到X 的所有值都可以平衡并打印结果。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the optimal weights
void findWeights(int X)
{
int sum = 0;
// Number of weights required
int power = 0;
// Finding the value of required powers of 3
while (sum < X) {
sum = pow(3, power + 1) - 1;
sum /= 2;
power++;
}
// Optimal Weights are powers of 3
int ans = 1;
for (int i = 1; i <= power; i++) {
cout << ans << " ";
ans = ans * 3;
}
}
// Driver code
int main()
{
int X = 2;
findWeights(X);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
public class GFG
{
// Function to find the optimal weights
static void findWeights(int X)
{
int sum = 0;
// Number of weights required
int power = 0;
int number = 3;
// Finding the value of required powers of 3
while (sum < X)
{
sum = number - 1;
sum /= 2;
power++;
number *= 3;
}
// Optimal Weights are powers of 3
int ans = 1;
for (int i = 1; i <= power; i++)
{
System.out.print(ans + " ");
ans = ans * 3;
}
}
// Driver code
public static void main (String[] args)
{
int X = 2;
findWeights(X);
}
}
// This code is contributed by Sam007.
Python3
# Python3 implementation of the approach
# Function to find the optimal weights
def findWeights(X):
sum = 0
# Number of weights required
power = 0
# Finding the value of required powers of 3
while (sum < X):
sum = pow(3, power + 1) - 1
sum //= 2
power += 1
# Optimal Weights are powers of 3
ans = 1
for i in range(1, power + 1):
print(ans, end = " ")
ans = ans * 3
# Driver code
X = 2
findWeights(X)
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find the optimal weights
static void findWeights(int X)
{
int sum = 0;
// Number of weights required
int power = 0;
int number = 3;
// Finding the value of required powers of 3
while (sum < X)
{
sum = number - 1;
sum /= 2;
power++;
number *= 3;
}
// Optimal Weights are powers of 3
int ans = 1;
for (int i = 1; i <= power; i++)
{
Console.Write(ans + " ");
ans = ans * 3;
}
}
// Driver code
static public void Main ()
{
int X = 2;
findWeights(X);
}
}
// This code is contributed by ajit.
Javascript
输出:
1 3
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。