codechef Partition the numbers(思维)
2018-01-18 22:48
309 查看
Description
You are given two integers x and N. Consider all integers between 1 and N inclusive, except x. We want to partition these integers into two disjoint sets (each integer has to appear in exactly one set) such that the sums of numbers in these sets are equal.Find one valid partition or determine that it doesn’t exist.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.The first and only line of each test case contains two space-separated integers x and N.
Output
For each test case:If there’s no way to partition the numbers into two sets with equal sums, print a single line containing the string “impossible” (without quotes).
Otherwise, print a single line containing a string with length N.
The x-th character of this string should be ‘2’.
For each valid i ≠ x, the i-th character of this string should be ‘0’ if number i should be in the first set or ‘1’ if it should be in the second set.
Constraints
1 ≤ T ≤ 10,0002 ≤ N ≤ 1,000,000
1 ≤ x ≤ N
1 ≤ sum of N in all test cases ≤ 1,000,000
Example
Input: 3 2 4 5 5 1 2 Output: 0201 01102 impossible
题目大意
从1-n中去除x,判断剩下的数能否分成和相等的两部分,如果可以输出分组方法;否则输出impossible.解题思路
先计算去除x之后每部分的和应为多少,然后从n->1进行遍历,如果满足当前数i不为x且sum>=i,则sum-=i并且加上分组标记,但是当sum-i等于x时,代表当前分组不可行,则需要回退。代码实现
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define maxn 1000007 int mark[maxn]; int main() { ios::sync_with_stdio(false); int T; ll x,n; cin>>T; while(T--) { memset(mark,0,sizeof(mark)); cin>>x>>n; ll sum=(n*(n+1)/2-x); if(sum%2!=0) cout<<"impossible"<<endl; else { sum/=2; mark[x]=2; for(ll i=n;i>=1;i--) { if(i!=x&&sum-i>=0) { sum-=i; mark[i]=1; if(sum==x) { sum+=i; mark[i]=0; } if(sum==0) break; } } if(sum==0) { for(ll i=1;i<=n;i++) cout<<mark[i]; cout<<endl; } else cout<<"impossible"<<endl; } } return 0; }
相关文章推荐
- codeChef----Partition the numbers
- CodeChef Protecting The Poison(贪心)
- C - A Game of Balls CodeChef - GAMEBALL 思维模拟
- Codeforces Round #400 (Div. 1 + Div. 2, combined)D. The Door Problem【2-sat Tarjan+思维建图】
- 【codefores 612】 The Union of k-Segments 【思维+ 线段处理】
- codechef Holes in the text 题解
- BSOJ4835刷漆(Codechef October Challenge 2014:Remy paints the fence)
- codechef Chef and The Right Triangles 题解
- C - Dividing the numbers CodeForces - 899C 【补】
- View the format of IEEE 754 floating point numbers source code
- Codeforces Round #426 (Div. 2)The Meaningless Game(思维+二分)
- Codechef A temple of Snakes(思维)
- [主席树维护HASH && SET维护DFS序] Codechef. Walks on the binary tree
- Codeforces Round #215 (Div. 1) C. Sereja and the Arrangement of Numbers(欧拉图)
- Codeforces Round #426 (Div. 2) C. The Meaningless Game 思维 D. The Bakery dp
- codechef The Ball And Cups题解
- codechef Closing the Tweets 题解
- CodeChef - AMR16I Mancunian Hoards Black Money 【前缀 + 思维】
- Educational Codeforces Round 22 C. The Tag Game(思维 搜索)
- Educational Codeforces Round 4 D. The Union of k-Segments 排序,思维