Codeforces Round #452 (Div. 2) - C. Dividing the numbers (思路)

本文介绍了一个算法问题,即如何将1到n的整数分成两个非空子集,使这两个子集内元素之和的绝对差达到最小,并给出了一种高效的解决方案。该方案通过分析n对4取模的结果来快速确定分组方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C. Dividing the numbers
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. 

Help Petya to split the integers. Each of n integers should be exactly in one group.

Input

The first line contains a single integer n (2 ≤ n ≤ 60 000) — the number of integers Petya has.

Output

Print the smallest possible absolute difference in the first line.

In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.

Examples
input
4
output
0
2 1 4 
input
2
output
1
1 1 
Note

In the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.

In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1.


题意:

把1到n这些数,分成两堆,让他们的差值最小,且任意输出一组。


POINT:

首先可以想到背包做,但是感觉会tle。

因为数字是连续的:

所以n%4==0时,肯定可以平分, 比如1 2 3 4 ,那么(1,4)(2,3)。比如4 5 6 7 ,那么(4,7)(5,6)

所以讨论余1,2,3时。

余1,就先挑出1,然后让2-n平分,最后任意给一个1.差值就是1

余2,就先挑出1,2,然后让3-n平分,最后每边给一个1或2,差值是1.

余3,一边给3,一边给1 2,差值为0


#include <iostream>
#include <string>
#include <string.h>
#include <math.h>
#include <vector>
#include <map>
#include <stdio.h>
#include <algorithm>
using namespace std;
int n;

int main()
{
	cin>>n;
	if(n%4==0){
		printf("0\n");
		printf("%d",n/2);
		int len=n/4;
		for(int i=0;i<len;i++){
			printf(" %d %d",1+i,n-i);
		}
	}else if(n%4==1){
		printf("1\n");
		printf("%d",n/2);
		int len=n/4;
		for(int i=0;i<len;i++){
			printf(" %d %d",2+i,n-i);
		}
	}else if(n%4==2){
		printf("1\n");
		printf("%d",n/2);
		int len=n/4;
		printf(" 1");
		for(int i=0;i<len;i++){
			printf(" %d %d",3+i,n-i);
		}
	}else if(n%4==3){
		printf("0\n");
		printf("%d",n/2);
		int len=n/4;
		printf(" 3");
		for(int i=0;i<len;i++){
			printf(" %d %d",4+i,n-i);
		}
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值