Monday 4 May 2009

POJ 1220


以前屡试不爽的大数类在这里扛不住超内存了,于是发现了一个更有效的方式——简单说就是一边乘一边除。
其实下面的代码还很有改进空间,不过思想也就只这样的了。
#include <iostream>
#include <algorithm>
using namespace std;
inline char to_char(int ch) {
static const char table[]=
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return table[ch];
}
inline int from_char(char ch) {
static const int table[]= {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 62, 255, 255,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 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, 255, 255, 255, 255, 255, 255, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255,
255
};
return table[int(ch)];
}

int convert(char* dest, char* src, int from, int to) {
int mem[2048]={0},*tmp,*buff,len,i,j,carry;
tmp=mem; buff=mem+1024;
for(i=0;src[i];++i)
tmp[i]=from_char(src[i]);
for(len=i,j=0;len;++j){
carry=0;
for(i=0;i<len;++i){
carry*=from;
carry+=tmp[i];
buff[i]=carry/to;
carry%=to;
}
dest[j]=to_char(carry);
for(i=0;i<len&&buff[i]==0;++i,--len);
buff+=i;
swap(tmp,buff);
}
dest[j]=0;
return j;
}

int main(){
int n,f,t,len;
char str[1024],dest[1024];
for(cin>>n;n--;){
cin>>f>>t>>str;
cout<<f<<" "<<str<<endl<<t<<" ";
len=convert(dest,str,f,t);
for(--len;len>=0;--len) cout<<dest[len];
cout<<"\n\n";
}
return 0;
}

No comments:

Post a Comment