dfs压缩 有向带权图

这篇博客介绍了如何使用深度优先搜索(DFS)压缩有向带权图,并通过快排优化处理过程。文章提供了详细的算法实现,包括递归过程`try`和排序过程`sort`,并最终输出路径数量和总权重。
摘要由CSDN通过智能技术生成
var i,j,total,max,r,path,n,m,x,y,z,s:integer;
    a:array[0..11] of integer;//链表
    b:array[1..100,1..2] of integer;//链表2
    c:array[1..100,1..3] of integer;//原表
    hash:array[1..100] of boolean;


procedure sort(l,r:integer);//快排的原因是qwq准备压缩
var i,j,x,y:integer;
  begin
      i:=l;
      j:=r;
      x:=c[(i+j) div 2,1];
      repeat
         while c[i,1]<x do  inc(i);
         while c[j,1]>x do  dec(j);
       if not(i>j) then
       begin
y:=c[i,1]; c[i,1]:=c[j,1]; c[j,1]:=y;
y:=c[i,2]; c[i,2]:=c[j,2]; c[j,2]:=y;
y:=c[i,3]; c[i,3]:=c[j,3]; c[j,3]:=y;
inc(i); dec(j);
       end;
       until i>j;
      if j>l then sort(l,j);
      if i<r then sort(i,r);
  end;


procedure try(k,p:integer);//递归过程
var i,j,total,qwq,v:integer;
  begin
    if k=n then begin inc(path);s:=s+p; end
           else
    begin
      for i:=a[k-1]+1 to a[k] do
        begin
          if hash[b[i,1]] then
          begin
  qwq:=b[i,1];
  v:=b[i,2];
  hash[qwq]:=false;
  try(qwq,p+v);
  hash[qwq]:=true;
   end;
        end;
    end;
  end;


  begin
    assign(input,'1.in');
    reset(input);
    assign(output,'1.out');
    rewrite(output);
    readln(n,m);
    fillchar(hash,sizeof(hash),true);
    for i:=1 to m do//把有向图变作无向图的过程
      begin
       readln(x,y,z);
       c[i,1]:=x;c[i,2]:=y;c[i,3]:=z;
       c[i+m,1]:=y;c[i+m,2]:=x;c[i+m,3]:=z;
      end;
    sort(1,2*m);
    max:=1;
    r:=0;
    hash[1]:=false;
    for i:=1 to 2*m do
        begin
          b[i,1]:=c[i,2];b[i,2]:=c[i,3];//b[i,1]存下一站,b[i,2]存权值(过路费)
          if max<>c[i,1] then begin a[max]:=i-1; max:=c[i,1]; end;//防止被孤立造成无解
        end;
    a[n]:=2*m;
    a[0]:=0;
    try(1,0);
    writeln(path,' ',s);
    close(input);
    close(output);
end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值