ACM算法集4
十、貪心 *會議問題 (1) n個活動每個活動有一個開始時間和一個結束時間,任一時刻僅一項活動進行,求滿足活動數最多的情況。 解:按每項活動的結束時間進行排序,排在前面的優先滿足。 (2)會議室空閒時間最少。 (3)每個客戶有一個願付的租金,求最大利潤。 (4)共R間會議室,第i個客戶需使用i間會議室,費用相同,求最大利潤。 十一、回溯法框架 1. n皇后問題 procedure try(i:byte); var j:byte; begin if i=n+1 then begin print;exit;end; for j:=1 to n do if a[i] and b[j+i] and c[j-i] then begin x[i]:=j; a[j]:=false; b[j+i]:=false; c[j-i]:=false; try(i+1); a[j]:=true; b[i+j]:=true; c[j-i]:=true; end; end; 2.Hanoi Tower h(n)=2*h(n-1)+1 h(1)=1 初始所有銅片都在a柱上 procedure hanoi(n,a,b,c:byte); {將第n塊銅片從a柱通過b柱移到c柱上} begin if n=0 then exit; hanoi(n-1,a,c,b); {將上面的n-1塊從a柱通過c柱移到b柱上} write(n,’moved from’,a,’to’,c); hanoi(n-1,b,a,c);{ 將b上的n-1塊從b柱通過a柱移到c柱上 end; 初始銅片分佈在3個柱上,給定目標柱goal h[1..3,0..n]存放三個柱的狀態,now與nowp存最大的不到位的銅片的柱號和編號,h[I,0]存第I個柱上的個數。 Procedure move(k,goal:integer); {將最大不到位的k移到目標柱goal上} Begin If k=0 then exit; For I:=1 to 3 do For j:=1 to han[I,0] do If h[I,j]=k then begin now:=I;nowp:=j; end; {找到k的位置} If now<>goal then begin {若未移到目標} Move(k-1,6-now-goal); {剩下的先移到沒用的柱上} Writeln(k moved from now to goal); H[goal,h[goal,0]+1]:=h[now,nowp]; h[now,nowp]:=0; Inc(h[goal,0]); dec(h[now,0]); Move(k-1,goal); {剩下的移到目標上} End; 十二、DFS框架 NOIP2001 數的劃分 procedure work(dep,pre,s:longint); {入口爲work(1,1,n)} {dep爲當前試放的第dep個數,pre爲前一次試放的數,s爲當前剩餘可分的總數} var j:longint; begin if dep=n then begin if s>=pre then inc(r); exit; end; for j:=pre to s div 2 do work(dep+1,j,s-j); end; 類似: procedure try(dep:integer); var i:integer; begin if dep=k then begin if tot>=a[dep-1] then inc(sum); exit; end; for i:=a[dep-1] to tot div 2 do begin a[dep]:=i; dec(tot,i); try(dep+1); inc(tot,i); end; end;{try} 十三、BFS框架 IOI94 房間問題 head:=1; tail:=0; while tail<head do begin inc(tail); for k:=1 to n do if k方向可擴展 then begin inc(head); list[head].x:=list[tail].x+dx[k]; {擴展出新結點list[head]} list[head].y:=list[tail].y+dy[k]; 處理新結點list[head]; end; |