ZOJ 2027

一道變相的FLOYD,想通以後還是蠻簡單的,主要的難點是建圖和更新兩點之間的距離:

簡要的說一下,建圖的話就用MAP就好;

之後跟新兩點之間的距離需要引入一個maxcost數組,用於標記兩點之間的最大費用;這樣一來更新規則就有了:

cost[i][j]-maxcost[i][j]>cost[i][k]+cost[k][j]-max(maxcost[i][k],maxcost[k][j]);

以下是代碼:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<iostream>
#define INF 1000000
using namespace std;
char from[100],to[100];
char inputa[100],inputb[100];
int cost[105][105];
int maxcost[105][105];
int n,num;
map<string,int> judge;
void init()//初始化;
{
    judge.clear();
    for(int i=0;i<=100;i++)
    {
        for(int j=0;j<=100;j++)
        {
            maxcost[i][j]=0;
            if(i==j) cost[i][j]=0;
            else
                cost[i][j]=INF;
        }
    }
}
void floyd()//算法主體
{
    for(int k=1;k<=num;k++)
    {
        for(int i=1;i<=num;i++)
        {
            for(int j=1;j<=num;j++)
            {
                if(cost[i][j]-maxcost[i][j]>cost[i][k]+cost[k][j]-max(maxcost[i][k],maxcost[k][j]))//最爲關鍵的跟新規則;
                {
                    cost[i][j]=cost[i][k]+cost[k][j];
                    maxcost[i][j]=max(maxcost[i][k],maxcost[k][j]);
                }
            }
        }
    }
    return ;
}
int main()
{
    int c;
    while(cin>>from>>to){
        cin>>n;
        init();
        judge[from]=1;
        judge[to]=2;
        num=2;
        for(int i=0;i<n;i++)
        {
            int a,b;
            cin>>inputa>>inputb>>c;//建圖
            if(judge[inputa]==0)
            {
                judge[inputa]=++num;
            }
            if(judge[inputb]==0)
            {
                judge[inputb]=++num;
            }
            a=judge[inputa];
            b=judge[inputb];
            cost[a][b]=cost[b][a]=c;
            maxcost[a][b]=maxcost[b][a]=c;
        }
        floyd();
        printf("%d\n",cost[1][2]-maxcost[1][2]);//輸出
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章