四、虫食算
(alpha.pas/dpr/c/cpp)
【问题描述】
所谓虫食算,就是原先的算式中有一部分被虫子啃掉了,需要我们根据剩下的数字来判定被啃掉的字母。来看一个简单的例子:
43#9865#045
+ 8468#6633
44445506978
其中#号代表被虫子啃掉的数字。根据算式,我们很容易判断:第一行的两个数字分别是5和3,第二行的数字是5。
现在,我们对问题做两个限制:
首先,我们只考虑加法的虫食算。这里的加法是N进制加法,算式中三个数都有N位,允许有前导的0。
其次,虫子把所有的数都啃光了,我们只知道哪些数字是相同的,我们将相同的数字用相同的字母表示,不同的数字用不同的字母表示。如果这个算式是N进制的,我们就取英文字母表午的前N个大写字母来表示这个算式中的0到N-1这N个不同的数字:但是这N个字母并不一定顺序地代表0到N-1)。输入数据保证N个字母分别至少出现一次。
BADC
+ CRDA
DCCC
上面的算式是一个4进制的算式。很显然,我们只要让ABCD分别代表0123,便可以让这个式子成立了。你的任务是,对于给定的N进制加法算式,求出N个不同的字母分别代表的数字,使得该加法算式成立。输入数据保证有且仅有一组解,
【输入文件】
输入文件alpha.in包含4行。第一行有一个正整数N(N<=26),后面的3行每行有一个由大写字母组成的字符串,分别代表两个加数以及和。这3个字符串左右两端都没有空格,从高位到低位,并且恰好有N位。
【输出文件】
输出文件alpha.out包含一行。在这一行中,应当包含唯一的那组解。解是这样表示的:输出N个数字,分别表示A,B,C……所代表的数字,相邻的两个数字用一个空格隔开,不能有多余的空格。
【样例输入】
5
ABCED
BDACE
EBBAA
【样例输出】
1 0 3 4 2
【数据规模】
对于30%的数据,保证有N<=10;
对于50%的数据,保证有N<=15;
对于全部的数据,保证有N<=26。
朴素方法是进行一次全排列,然后一次判断,能得40分
加上可行性剪枝然后进行一次预处理,预计能得70分
标程见http://baike.baidu.com/view/33324.htm
然后接下来有一种投机取巧的方法就是全排列的时候倒序枚举就能得100分AC
Pascal Code(投机取巧 倒序枚举)
program alpha;
var
n:longint;
s:array[1..3] of string;
a,b,c,ans,h,order:array[0..30] of longint;
procedure init;
begin
assign(input,'alpha.in');
assign(output,'alpha.out');
reset(input);
rewrite(output);
end;
procedure outit;
begin
close(input);
close(output);
halt;
end;
procedure pre;
var
i,k:longint;
u:array[0..30] of longint;
begin
fillchar(u,sizeof(u),0);
k:=0;
for i:=n downto 1 do
begin
if u[a[i]]=0 then
begin
u[a[i]]:=1;
k:=k+1;
order[k]:=a[i];
end;
if u[b[i]]=0 then
begin
u[b[i]]:=1;
k:=k+1;
order[k]:=b[i];
end;
if u[c[i]]=0 then
begin
u[c[i]]:=1;
k:=k+1;
order[k]:=c[i];
end;
end;
end;
procedure readdata;
var
i:longint;
begin
readln(n);
for i:=1 to 3 do
readln(s[i]);
//预处理 a+b=c
for i:=1 to n do
begin
a[i]:=ord(s[1][i])-ord('A')+1;
b[i]:=ord(s[2][i])-ord('A')+1;
c[i]:=ord(s[3][i])-ord('A')+1;
end;
{ for i:=1 to n do
write(a[i]);
writeln;
for i:=1 to n do
write(b[i]);
writeln;
for i:=1 to n do
write(c[i]);
writeln;}
pre;
end;
function check:integer;
var
i:longint;
begin
for i:=n downto 1 do
begin
if ((ans[a[i]]>=0)and(ans[b[i]]>=0)and(ans[c[i]]>=0))and((ans[c[i]]<>(ans[a[i]]+ans[b[i]]) mod n)and(ans[c[i]]<>(ans[a[i]]+ans[b[i]]+1) mod n)) then
begin
exit(0);
end;
end;
exit(1);
end;
procedure quan(x:longint);
var
i,jinwei:longint;
begin
if x>n then
begin
jinwei:=0;
{ ans[1]:=1;
ans[2]:=0;
ans[3]:=3;
ans[4]:=4;
ans[5]:=2;}
for i:=n downto 1 do
begin
if (ans[a[i]]+ans[b[i]]+jinwei)mod n<>ans[c[i]] then
exit;
jinwei:=(ans[a[i]]+ans[b[i]]+jinwei) div n;
end;
for i:=1 to n do
write(ans[i],' ');
outit;
end;
for i:=n-1 downto 0 do
begin
if h[i]=0 then
begin
ans[order[x]]:=i;
h[i]:=1;
if check=1 then quan(x+1);
h[i]:=0;
ans[order[x]]:=-1;
end;
end;
end;
procedure main;
var
i:longint;
begin
fillchar(h,sizeof(h),0);
for i:=0 to 30 do
ans[i]:=-1;
quan(1);
//for i:=1 to n do
//write(ans[i],' ');
end;
begin
init;
readdata;
main;
outit;
end.