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.
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.
2 3 pnp 6 4 ppnn 10
Impossible1110
题意:各个位数带符号的二进制。输入t表示有t个测试数据,k表示有k位,再输入k个字符,其中p表示+2^i,n表示-2^i,再输入一个十进制数long long n,满足则输出该二进制数,不满足输出Impossible,思路从高位到地位转二进制,取符合的值。如果计算到某位为偶数则该位0,p,n对下一位不影响;奇数时,该位为一,但p,n对下一位有影响,为p(虽然位为p并且为正数时不减无所谓,但为负数时需要减一)时需要减一,n时加一。如果有答案,则n此时为0
#include<iostream>
using namespace std;
char a[75];
int main()
{
long long n;
int i,t,k;
cin>>t;
while(t)
{
t-=1;
cin>>k;
cin>>a;
cin>>n;
while(k)
{
k-=1;
if(n%2==1||n%2==-1)//负数的余数会有负数
{
if(a[k]=='n')
{
n+=1;
}
else
{
n-=1;//当为负数时,因为p是表示正的,因此 需要减一
}
a[k]='1';
n/=2;
}
else
{
a[k]='0';
n/=2;
}
}
if(n)
{
cout<<"Impossible"<<endl;
}
else
{
cout<<a<<endl;
}
}
}