给定整数序列1,2,3,4,…,n 。任务是将其划分为两个集合A和B ,使得每个元素恰好属于一个集合,并且| sum(A)– sum(B)|是最小的。打印| sum(A)– sum(B)|的值。
例子:
Input: 3
Output: 0
A = {1, 2} and B = {3} ans |sum(A) – sum(B)| = |3 – 3| = 0.
Input: 6
Output: 0
A = {1, 3, 4} and B = {2, 5} ans |sum(A) – sum(B)| = |3 – 3| = 0.
Input: 5
Output: 1
方法:取mod = n%4 ,
- 如果mod = 0或mod = 3,则打印0 。
- 如果mod = 1或mod = 2,则打印1 。
这是因为将选择以下组:A = {N,N – 3,N – 4,N – 7,N – 8,…..},B = {N – 1,N – 2,N – 5 N – 6,…..}
从N到1,在组A中放置第一个元素,然后在B,A,B,A,…..中每隔两个元素交替。
- 当n%4 = 0时: N = 8,A = {1,4,5,8}和B = {2,3,6,7}
- 当n%4 = 1时: N = 9,A = {1、4、5、8、9},B = {2、3、6、7}
- 当n%4 = 2时: N = 10,则A = {1、4、5、8、9},而B = {2、3、6、7、10}
- 当n%4 = 3时: N = 11,A = {1、4、5、8、9},B = {2、3、6、7、10、11}
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimum required
// absolute difference
int minAbsDiff(int n)
{
int mod = n % 4;
if (mod == 0 || mod == 3)
return 0;
return 1;
}
// Driver code
int main()
{
int n = 5;
cout << minAbsDiff(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the minimum required
// absolute difference
static int minAbsDiff(int n)
{
int mod = n % 4;
if (mod == 0 || mod == 3)
{
return 0;
}
return 1;
}
// Driver code
public static void main(String[] args)
{
int n = 5;
System.out.println(minAbsDiff(n));
}
}
// This code is contributed by Rajput-JI
Python 3
# Python3 implementation of the approach
# Function to return the minimum required
# absolute difference
def minAbsDiff(n) :
mod = n % 4;
if (mod == 0 or mod == 3) :
return 0;
return 1;
# Driver code
if __name__ == "__main__" :
n = 5;
print(minAbsDiff(n))
# This code is contributed by Ryuga
C#
// C# implementation of the
// above approach
using System;
class GFG
{
// Function to return the minimum
// required absolute difference
static int minAbsDiff(int n)
{
int mod = n % 4;
if (mod == 0 || mod == 3)
{
return 0;
}
return 1;
}
// Driver code
static public void Main ()
{
int n = 5;
Console.WriteLine(minAbsDiff(n));
}
}
// This code is contributed by akt_mit
PHP
输出:
1