POJ 3249:Test for Job(拓扑排序+DP)

题意就是给一个有向无环图,每个点都有一个权值,求从入度为0的点到出度为0点路径上经过点(包括起点终点)的权值和的最大值。

分析:

  注意3点

  1.本题有多组数据

  2.可能有点的权值是负数,也就是结果可能为负,初值要设为负无穷。

  3.入度或出度为0的点不止一个。

  注意以上几点本题就很简单了,用到DP dis[i]:=max(dis[j],dis[i]+w[j])在拓扑排序过程同时进行即可。

  考前练练拓扑排序和指针。

代码:

program test;
type
  point=^node;
  node=record
       data:longint;
       next:point;
    end;
var
  a:array[0..100000]of point;
  w,u,v,dis,f:array[0..100000]of int64;
  n,i,m,t,x,y,num:longint;
  ans:int64;
  p:point;
function max(x,y:int64):int64;
begin
  if x>y then max:=x else max:=y;
end;
begin
  while  not eof do
  begin
  readln(n,m);
  for i:=1 to n do
    readln(w[i]);
  for i:=1 to n do
    a[i]:=nil;
  t:=0;  ans:=-maxlongint; num:=0;
  fillchar(u,sizeof(u),0);  fillchar(v,sizeof(v),0);
  for i:=1 to m do
   begin
     readln(x,y);
     new(p); p^.data:=y; p^.next:=a[x]; a[x]:=p;
     u[y]:=u[y]+1; v[x]:=v[x]+1;
   end;
  for i:=1 to n do dis[i]:=-maxlongint;
  for i:=1 to n do if u[i]=0 then begin inc(t); f[t]:=i; dis[i]:=w[i]; end;
  repeat
    x:=f[t]; dec(t); inc(num);
    new(p); p:=a[x];
    while p<>nil do
     begin
       y:=p^.data; dis[y]:=max(dis[y],dis[x]+w[y]);
       dec(u[y]);
       if u[y]=0 then
        begin
          inc(t); f[t]:=y;
        end;
       p:=p^.next;
     end;
  until num=n;
  for i:=1 to n do
   if v[i]=0 then ans:=max(ans,dis[i]);
  writeln(ans);
  end;
end.
View Code

 

转载于:https://www.cnblogs.com/qtyytq/p/4937661.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值