NBUT 2012 Summer Training -1 / [E] Exchange Rate

来源:互联网 发布:淘宝tab选项卡代码 编辑:程序博客网 时间:2024/06/01 13:15

[E] Exchange Rate


时间限制: 1000 ms 内存限制: 65535 K
问题描述
You know, every country's currency has an exchange rate to another country.
For example, 'Dollir' : 'RNB' is 1 : 6.
And exchanging from one currency to another currency, it will have a wastage.
Now give some currency and their each wastage from one currency exchanges to another. For every currency, you should tell me when it exchanges to other currency and finally exchanges to itself, the minimum wastage it will cost.


输入
This problem contains several cases.
The first line of each case is an integer N (2 <= N <= 100).
Then follows a decimal matrix(N * N). The Cell(i, j) indicates the wastage exchanging from ith currency to jth currency. (1.00 < Cell(i, j) <= 100.00).
You may consider that every currency can't exchange to itself directly, so every Cell(i, i) will be -1.
输出
For each case, you may output N lines.
Each line is an decimal, indicates exchanging from ith currency and finally it exchanges to itself, the minimum wastage it will cost.
Two decimal places.
样例输入
4
-1 1.00 2.00 10.00
1.00 -1 2.00 30.00
1.00 1.00 -1 50.00
50.00 50.00 1.0 -1
样例输出
2.00
2.00
3.00

12.00


分析

很简单的图论题。用Dijkstra每点到其他点的最短距离都求出来,然后找这个点的最小环(就是这个点到其他点的最短路+其他点到这个点的最短路)。

#include <cstdio>
#include <cmath>
#include <climits>
#include <cstring>
using namespace std;


int n;
double cost[101][101];
double d[101][101];
double dist[101];
int vis[101];


void dijkstra(int s,int n) // s为起点 s-t是所有点的集合
{
    for (int i=0;i<n;i++)
        dist[i]=INT_MAX;        //limits.h
    memset(vis,0,sizeof(vis));      //string.h


    dist[s]=0;
    int ok=1;
    while(ok)
    {
        ok=0;
        int min=INT_MAX;
        int k;
        for (int i=0;i<n;i++)
            if ((!vis[i])&&(dist[i]<min))
            {
                min=dist[i];
                k=i;
                ok=1;
            }
        vis[k]=1;
        for (int i=0;i<n;i++)
            if (!vis[i])
            {
                if (dist[i]>dist[k]+d[k][i])
                {
                    dist[i]=dist[k]+d[k][i];
                }
            }




    }
}


int main()
{
    while (scanf("%d",&n)!=EOF)
    {


        for (int i=0;i<n;i++)
            for (int j=0;j<n;j++)
                scanf("%lf",&d[i][j]);
        for (int i=0;i<n;i++)
        {
            dijkstra(i,n);
            cost[i][i]=-1;
            for (int j=0;j<n;j++)
                if (i!=j)
                cost[i][j]=dist[j];
        }


        for (int i=0;i<n;i++)
        {
            double  min=INT_MAX;
            for (int j=0;j<n;j++)
                if ((min>cost[i][j]+cost[j][i])&&(i!=j))
                    min=cost[i][j]+cost[j][i];
            printf("%.2lf\n",min);
        }


    }
    return 0;
}