A. Integer Sequence Dividing
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an integer sequence 1,2,…,n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A)−sum(B)| is minimum possible.
The value |x| is the absolute value of xx and sum(S) is the sum of elements of the set S.
Input
The first line of the input contains one integer nn (1≤n≤2⋅1091≤n≤2⋅109).
Output
Print one integer — the minimum possible value of |sum(A)−sum(B)| if you divide the initial sequence 1,2,…,n into two sets A and B.
Examples
inputCopy
3
outputCopy
0
inputCopy
5
outputCopy
1
inputCopy
6
outputCopy
1
Note
Some (not all) possible answers to examples:
In the first example you can divide the initial sequence into sets A={1,2} and B={3} so the answer is 0.
In the second example you can divide the initial sequence into sets A={1,3,4} and B={2,5} so the answer is 1.
In the third example you can divide the initial sequence into sets A={1,4,5} and B={2,3,6} so the answer is 1.
题意:有一个整数连续序列,1.2.3…n,把这个整数序列分成两个集合,使得两个集合的元素和差值绝对值最小,A集合和sum1,B集合和sum2,是得|sum1-sum2|最小。
思路:我也是根据样例来推出来的,首先如果n是偶数,例:n=4,1 2 3 4 ,你如果分成1 3 // 2 4 差值就是2,不是最小的,因为它是连续的,所以1+4==2+3,所以1 4可以放在一个聚合里,2 3可以放在一个,但是如果n=6,1 2 3 4 5 6 分为1 6 // 2 5,还剩3 4,就不能组成一个对了,就得分开了,所以它是跟 n / 2 的奇偶性有关。
(1)如果n为偶数:如果 n / 2 是偶数,代表可以分成相等的偶数个对,放在集合中,没有剩余,那么和就相等,|sum1-sum2|==0,如果 n / 2为奇数,就会剩余序列中中间的那两个数,因为是连续的序列,所以这两个数的差值为1。
(2)如果n为奇数,n为奇数,不可能分成相等的两部分,因为差值最小,所以可以先把1提出来,剩下的构成n为偶数个,再根据偶数的规则,来计算,如果 n / 2 是偶数,差值为0,在加上之前的1,差值就是1,如果 n / 2为奇数,差值为 1 / -1,因为是绝对值,所以最小的话取-1再加上之前的1,就是0。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
typedef long long ll;
int main ()
{
ll n;
scanf("%lld",&n);
if(n%2==0){
if((n/2)%2==0){
printf("0\n");
}
else{
printf("1\n");
}
}
else{
if(((n-1)/2)%2==1){
printf("0\n");
}
else{
printf("1\n");
}
}
return 0;
}
3
1 2 3
2 3 2/2=1奇数
2 1
3
5
1
2 3 4 5 4/2偶数
2 5
3 4
7
1 2 3 4 5 6 7
1
2 3 4 5 6 7 6/2=3奇数
1
9
1 2 3 4 5 6 7 8 9
6/2=3奇数
1 2 3 4 5 6
1 6 3
2 5 4
8
1 2 3 4 5 6 7 8 8/2=4偶数
0
探讨如何将连续整数序列1至n最优地划分为两组,使两组元素和的差值绝对值达到最小。通过分析n的奇偶性和n/2的奇偶性,得出不同情况下的解决方案。
1万+





