算法设计题
1)100亿个数据项,每个平均1024长度,内存10G,设计数据结构和算法,实现查询和插入操作,优先方便查询。
2)算法题一,单入口单出口有向无环图,要求每条路径长度相等
1.矩阵存储有向图,列为起点,行为终点(N^2)
2. 找起点和终点:哪一列全为0,则为起点1;哪一行全为0,则为终点N。(N^2)
3. (动态规划)维护一数组,currmax[N],记录着每个点由起点到该点时最长的距离。即
currmax[i] = max(currmax[j])(j = 1...i-1) + 1
4. 然后求得currmax[N]为最长路径
5. 然后
for i= N : 1
for j = 1 : i
if M[j][i] = 1
addpoint(i , j , currmax[i] - currmax[j] - 1)//在第i和j点间添加currmax[i] - currmax[j] - 1个点
(O(N^2))
3)算法题二,6-100000间,证明哥德巴赫猜想。
function IsPrime(n:integer):boolean; //返回n是否素数,n>=2
var i,t:integer;
begin
i:=3;
t:=trunc(sqrt(n)); //只计算一次开方
while i<=t do
if ( n mod i = 0 ) then //i能整除n吗?
begin
result:=false; //n不是素数,提前退出
exit;
end
else
if (i=3) then i:=i+4 else i:=i+2; //只计算奇数,跳过尾数5的判断
result:=true;
end;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
flag,FstNum,SndNum,total,EndNum,Tmp,TmpTime:integer;
begin
lxbtotal.Clear;
FstNum:=1;
SndNum:=1;
flag:=0;
total:=0;
total:=strtoint(Edtname.text);
EndNum:=total mod 10; //计算原数的尾数
if (total>99999) and (total mod 2=0) then //判断输入的数是否是大于6位数的偶数
begin
Form1.Caption:='计算中。。。。。。';
TmpTime:=GetTickCount;
while SndNum>=FstNum do //当第一个数比第二个数大时跳出循环
begin
FstNum:=FstNum+2;
Tmp:=(FstNum+5) mod 10; //计算尾数
if ((Tmp=EndNum) or (Tmp=0)) then Continue; //尾数为5或加5后尾数相同就不会有解
SndNum:=total-FstNum; //计算第二个数
if (IsPrime(FstNum)) and (IsPrime(SndNum)) then //判断两数是否为素数
begin
lxbtotal.Items.Strings[flag]:=(inttostr(total)+'='+inttostr(FstNum)+'+'+inttostr(SndNum));//输出判断后的值
flag:=flag+1;
end;
end;
Label1.Caption:=format('总耗时为 %D 毫秒', [GetTickCount - TmpTime]);
Form1.Caption:='计算完毕';
end
else
begin
lxbtotal.Items.Add(inttostr(total)+'小于6位数或为奇数');//超出范围的提示
Edtname.SetFocus;
end;
lxbtotal.items.add(inttostr(flag)); //输出解的总数
end;