「CF437B」The Child and Set
At the children’s day, the child came to Picks’s house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set S:
- its elements were distinct integers from 1 to limit;
- the value of was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102) = 102, lowbit(100012) = 12, lowbit(100002) = 100002 (binary representation).
Can you help Picks and find any set S, that satisfies all the above conditions?
The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 105).
In the first line print an integer n (1 ≤ n ≤ 105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them.
If it’s impossible to find a suitable set, print -1.
1 |
5 5 |
1 2 |
2 4 5 |
1 |
4 3 |
1 2 |
3 2 3 1 |
1 |
5 1 |
1 |
-1 |
In sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5.
In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4.
题意 orz wyl8899
在儿童节这一天,我们的小朋友来到了Picks的家,把他家里弄得一团糟。Picks非常生气。很多重要的东西都不见了,这其中包括了Picks最喜欢的集合。
幸运的是,Picks记得一些关于他的集合S的事情:
1. 其元素是1至limit间的互异整数;
2. 所有lowbit(x)之和(x取遍S中的所有元素)等于sum,这里lowbit(x)等于2^k,k是x的二进制表示中第一个1的位置。例如(以下数字均为二进制表示),lowbit(10010)=10,lowbit(10001)=1,lowbit(10000)=10000。
你能帮助Picks找到一个符合上述条件的集合S吗?
Input
一行,两个整数,依次是sum和limit(1<=sum,limit<=10^5)。
Output
第一行输出n(1<=n<=10^5),为集合S的大小。然后在下一行以任意顺序输出S的所有元素。如果有多个符合要求的集合,输出任意一个即可。
如果找不到这样的集合,输出-1。
题解
首先可以得出1到limit每一个数对于答案的贡献
然后从大往小取就行了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include<iostream> #include<cstdio> #include<algorithm> #define ll long long using namespace std; inline ll read() { ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x*=10;x+=ch-'0';ch=getchar();} return x*f; } int sum,limit; int ans[100005]; struct data{int x,key;}a[100005]; inline int lowbit(int x){return x&(-x);} inline bool cmp(data a,data b) {return a.key>b.key;} int main() { sum=read();limit=read(); for(int i=1;i<=limit;i++) { a[i].x=i;a[i].key=lowbit(i); } sort(a+1,a+limit+1,cmp); for(int i=1;i<=limit;i++) { if(a[i].key<=sum) { sum-=a[i].key; ans[++ans[0]]=a[i].x; } } if(sum)printf("-1"); else { printf("%d\n",ans[0]); for(int i=1;i<=ans[0];i++) printf("%d ",ans[i]); } return 0; } |