从偶数和对中删除 Max 和从奇数对中删除 Min 后 2^N 个整数的最后剩余值
给定一个非负整数N ,表示从 1 开始的连续整数相互配对的前2 N个正整数,任务是在执行以下操作后找到最后剩余的数:
- 考虑尚未从2 N个整数中删除的两个连续整数对 (x, y)。
- 如果两个整数 x + y 之和为偶数,则删除 x(最小值)。
- 如果两个整数 x + y 之和为奇数,则删除 y(最大值)。
例子:
Input: N = 2
Output: 3
Explanation:
For N = 2 we have 2^N i.e; 4 integers and 4/2 pairs which are as follows-:
(1, 2), (3, 4)
Now after performing the operations:
1 + 2 = 3 which is odd, delete y. So remains 1.
3 + 4 = 7 which is odd, delete y. So remains 3
Now the remaining numbers are 1 and 3 and the pair is (1, 3).
Sum = 1 + 3 = 4 which is even, so delete 1.
So the last remaining element is 3.
Input: N = 3
Output: 7
Explanation:
For N = 2 we have 2^N i.e; 8 integers and 8/2 pairs which are as follows-:
(1, 2), (3, 4), (5, 6) and (7, 8)
Now after performing the operations:
1 + 2 = 3 which is odd, delete y. So remains 1.
3 + 4 = 7 which is odd, delete y. So remains 3.
5 + 6 = 11 which is odd, delete y. So remains 5.
7 + 8 = 15 which is odd, delete y. So remains 7.
Now the remaining numbers are 1, 3, 5 and 7 and the pairs are (1, 3), (5, 7).
1 + 3 = 4 which is even, delete x. So remains 3.
5 + 7 = 12 which is even, delete x. So remains 7.
Now the remaining numbers are 3 and 7 and the pair is (3, 7)
3 + 7 = 10 which is even, so delete 3.
So the last remaining element is 7.
方法:给定的问题可以使用以下数学观察来解决:
- The idea is to consider when the sum is odd or even while adding two numbers.
- If we add one even and one odd number then sum will always be an odd number
- If we add two odd numbers or two even numbers then sum will always be an even number.
基于以上观察,可以得出问题的解决方案如下:
- 第一次,每对都有一个奇数和一个偶数,其中偶数较大。所以总和总是奇数,偶数被删除。
- 在接下来的步骤中,剩余的数字都是奇数,因此对的总和将始终是偶数。因此,从第一个(较小的)开始的替代奇数在每个步骤中都会被删除。
- 从上面的观察可以清楚地看出,所有奇数中的最大值将是最后一个,即2 N -1
下面是上述方法的实现:
C++
// C++ program to implement the approach
#include
using namespace std;
// Function to calculate
// the last remaining number
long long int lastdigit(int N)
{
// 1<
Java
// Java program to implement the approach
import java.io.*;
class GFG {
// Function to calculate
// the last remaining number
static long lastdigit(int N)
{
// 1<
C#
// C# program to implement the approach
using System;
public class GFG{
// Function to calculate
// the last remaining number
static long lastdigit(int N)
{
// 1<
7
时间复杂度: O(1)
辅助空间: O(1)