如题:http://poj.org/problem?id=1023
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 10018 | Accepted: 3381 |
Description
A Fun number system is a positional binary number system, where each bit can be either a negabit, or a posibit. For example consider a 3-bit fun number system Fun3, where bits in positions 0, and 2 are posibits, and the bit in position 1 is a negabit. (110)Fun3 is evaluated as 2^2-2^1 + 0 = 3. Now you are going to have fun with the Fun number systems! You are given the description of a k-bit Fun number system Funk, and an integer N (possibly negative. You should determine the k bits of a representation of N in Funk, or report that it is not possible to represent the given N in the given Funk. For example, a representation of -1 in the Fun3 number system (defined above), is 011 (evaluated as 0 - 2^1 + 2^0), and
representing 6 in Fun3 is impossible.
Input
The third line of each test data contains an integer N (-2^63 ≤ N < 2^63), the number to be represented in the Funk number
system by your program.
Output
Sample Input
2 3 pnp 6 4 ppnn 10
Sample Output
Impossible 1110
Source
思路:一开始我的思路是从高位来搜索,判断这一位是0或1,然后判断后面低位的数能否组成余下的数,由于负数的存在和N (-2^63 ≤ N < 2^63)的范围,在余下的数的时候会超界。
其实一个十进制的数肯定由唯一的二进制数来组成,即便是这几位正负给出,也是唯一的,因此每次判断最低位的数,如果N是奇数,最低位肯定是1,如果这位要求为正,
剩下的数,也就是这一位前面得数是(N-1)/2. 如果这一位要求为负,N=(N+1)/2.如果N偶数,这一位是0,N/=2;
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define ll _int64
char s[70];
int k;
ll n;
int res[70];
int main()
{
// freopen("C:\\1.txt","r",stdin);
int t;
cin>>t;
int i;
while(t--)
{
memset(res,0,sizeof(res));
cin>>k;
cin>>s;
scanf("%I64d",&n);
for(i=k-1;i>=0;i--)
{
if(n%2)
{
res[i]=1;
if(s[i]=='p')
n=(n-1)/2;
else
n=(n+1)/2;
}
else
{
res[i]=0;
n/=2;
}
}
if(n)
printf("Impossible\n");
else
{
for(i=0;i<=k-1;i++)
printf("%d",res[i]);
printf("\n");
}
}
return 0;
}