洛谷 P1144 最短路计数

17 篇文章 0 订阅
11 篇文章 0 订阅

题目

给出一个N个顶点M条边的无向无权图,顶点编号为1~N。问从顶点1开始,到其他每个点的最短路有几条。

题解

spfa跑一遍,用链表储存
千万要记得,是无向图!,所以每条边都要储存储存两次,正反各一次。

O(VE)

代码

const
  max=2000000;
type
  arr=record
        x,y,ne:longint;
      end;
var
  n,m,i,j:longint;
  d,c:array[1..max]of longint;
  a:array[1..max*2]of arr;
  ls:array[1..max]of longint;
  v:array[1..max*2] of longint;
  state:array[1..max*2]of longint;

procedure spfa;
var
  head,tail,t,x,y,ne:longint;

begin
  head:=0;tail:=1;
  v[1]:=1;
  state[1]:=1;
  while head<=tail do
    begin
      inc(head);
      t:=ls[state[head]];
      while t>0 do
          begin
            x:=a[t].x;y:=a[t].y;ne:=a[t].ne;
            if d[x]+1<d[y] then
              begin
                d[y]:=d[x]+1;
                if v[y]=0 then
                  begin
                    inc(tail);
                    v[y]:=1;
                    state[tail]:=y;
                    c[y]:=c[x] mod 100003;
                  end;
              end else
            if d[x]+1=d[y] then
              begin
                c[y]:=(c[y]+c[x]) mod 100003;
              end;
            t:=ne;
          end;
      v[state[head]]:=0;
    end;
end;

begin
  readln(n,m);
  fillchar(d,sizeof(d),$7f);

  for i:=1 to m do
    begin
      inc(j);
      readln(a[j].x,a[j].y);
      a[j].ne:=ls[a[j].x];
      ls[a[j].x]:=j;
      inc(j);
      a[j].x:=a[j-1].y;a[j].y:=a[j-1].x;
      a[j].ne:=ls[a[j].x];
      ls[a[j].x]:=j;
    end;
  d[1]:=0;
  c[1]:=1;
  spfa;
  for i:=1 to n do
    writeln(c[i]);
end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值