您的位置:首页 > 其它

渡轮问题(动态规划)

2016-04-08 21:47 267 查看
Description  Palmia河在某国从东向西流,并把该国分成南北两个部份。河的两岸共有n个城市,且北岸的某个城市与南岸的某个城市是友好城市,而且对应的关系是一一对应。如下图:  现要求在两个友好城市之间建立一条航线,但由于天气关系,所有的航线都不能相交,因此就可能所有城市都建立航线。如上图,则最多可建立两条航线可保证航线不交叉。Input  第一行为一个数n(n<=5000),表示城市的个数。第二行为n个数,表示南边n个城市离河的源头的距离(小于2^31-1)。第三行为n个数,表示北边n个城市离河的源头的距离(<2^31-1),距离为整数。Output  一个数,能建立最多的航线。Sample Input
5     //表示友好城市的对数

1 2 3 4 5

3 2 1 5 4
Sample Output
2



解题思路:求最长不下降序列,状态转移方程为:

L(Si)=max{L(Sj)}+11<=j,且SjSi为航线的终点坐标值。时间复杂度:O(n^2)程序:const
maxn=50000;
var
n,i,j,t:longint;
f,a,b:array[0..maxn] of longint;procedure qsort(l,r:longint);
var
i,j,mid:longint;
begin
if l>=r then exit;
i:=l;j:=r;
mid:=a[l+random(r-l+1)];
repeat
while a[i]
while a[j]>mid do
dec(j);
if i<=j thenbegina[0]:=a[i];a[i]:=a[j];a[j]:=a[0];b[0]:=b[i];b[i]:=b[j];b[j]:=b[0];inc(i);dec(j);end;
until i>j;
qsort(l,j);
qsort(i,r);
end;begin
readln(n);
for i:=1 to n do
read(a[i]);
for i:=1 to n do
read(b[i]);
randomize;
qsort(1,n);
for i:=1 to n do
f[i]:=1;
for i:=n-1 downto 1 do
begint:=0;
for
j:=i+1 to n doif (b[j]>b[i]) and (f[j]>t) then
t:=f[j];
if
t>0 then f[i]:=t+1;
end;
t:=1;
for i:=2 to n do
if f[i]>f[t] then
t:=i;
writeln(f[t]);
end.版权属于: Chris
原文地址: http://blog.sina.com.cn/s/blog_83ac6af80102v9rh.html
转载时必须以链接形式注明原始出处及本声明。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: