【NOIP2012】第二题·文化之旅

深度优先搜索(90分)
var n,m,k,S,T,i,j,u,v,d,now,res:longint; c,vt,vc:array[0..100]of longint; a,dist:array[0..100,0..100]of longint; procedure DFS(i:longint); var j:longint; begin if i=T then begin res:=now; exit; end; for j:=1 to n do if (dist[i,j]<>0)and(a[c[j],c[i]]=0)and(vt[j]=0)and(vc[c[j]]=0)and(now+dist[i,j]<res) then begin inc(now,dist[i,j]); vt[j]:=1; vc[c[j]]:=1; DFS(j); dec(now,dist[i,j]); vt[j]:=0; vc[c[j]]:=0; end; end; begin assign(input,'culture.in'); reset(input); assign(output,'culture.out'); rewrite(output); read(n,k,m,S,T); for i:=1 to n do read(c[i]); for i:=1 to k do for j:=1 to k do read(a[i,j]); for i:=1 to m do begin read(u,v,d); dist[u,v]:=d; dist[u,v]:=d; end; res:=maxlongint; vt[S]:=1; vc[c[S]]:=1; DFS(S); if res=maxlongint then writeln(-1) else writeln(res); close(input); close(output); end.

FOLYD算法
const
    INF=1000000;
var
    n,k,m,s,t,i,j,q,u,v,d:longint;
    a,dist:array[1..110,1..110] of longint;
    c:array[1..110] of longint;
begin
    assign(input,'culture.in'); reset(input);
    assign(output,'culture.out'); rewrite(output);
    readln(n,k,m,s,t);
    for i:=1 to n do
        for j:=1 to n do dist[i,j]:=INF;

    for i:=1 to n do read(c[i]);
    for i:=1 to k do
        for j:=1 to k do
            read(a[i,j]);
    for i:=1 to m do
    begin
        readln(u,v,d);
        if a[c[v],c[u]]=0 then dist[u,v]:=d;
        if a[c[u],c[v]]=0 then dist[v,u]:=d;
    end;


    for k:=1 to n do
        for i:=1 to n do
            for j:=1 to n do
                if dist[i,k]+dist[k,j]<dist[i,j] then  dist[i,j]:=dist[i,k]+dist[k,j];

    if dist[s,t]<INF then writeln(dist[s,t]) else writeln(-1);
    close(input); close(output);
end.

 

 
posted @ 2015-09-05 15:39  Kairos2000  阅读(282)  评论(0编辑  收藏  举报