求最小环(floyd,dijkstra)

给出一个无向图,求图中的最小环。

利用floyd f[k,i,j]的性质来求。

program tt;
const max=1000000;
var n,m,i,j,k,x,y,z,ans:longint;
    f,g:array[1..100,1..100]of longint;
function min(a,b:longint):longint;
begin
 if a<b then min:=a else min:=b;
end;
begin
 while not eof do 
  begin
   readln(n,m);
   for i:=1 to n do 
    for j:=1 to n do 
	 begin 
	  f[i,j]:=max;
	  g[i,j]:=max;
	 end;
   for i:=1 to m do
    begin
     readln(x,y,z);
     if f[x,y]>z then 
	  begin 
	   f[x,y]:=z;
       f[y,x]:=z;
	   g[x,y]:=z;
	   g[y,x]:=z;
	  end;
	end;
   ans:=max;
   for k:=1 to n do
    begin
	 for i:=1 to k-1 do
	  for j:=i+1 to k-1 do//无向图,一半
	   if (g[i,k]<max)and(g[k,j]<max)and(f[i,j]<max) then
	    ans:=min(ans,f[i,j]+g[i,k]+g[k,j]);//保证是个环
	 for i:=1 to n do
	  for j:=1 to n do
	   if (f[i,k]<max)and(f[k,j]<max) then 
	    f[i,j]:=min(f[i,j],f[i,k]+f[k,j]);//更新
	end;
   if ans=max then 
    writeln('No solution.')
   else
    writeln(ans);
  end;
end.

Dijkstra:

    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/zz_ylolita/article/details/42066715
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞