UVa 11710 Expensive subway

很简单的最小生成树问题,主要优点不一样的是,需要用到map

代码如下:

#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <cstring>
using namespace std;

const int N = 500;
const int INF = 100000000;
int n, m, st;
int g[N][N], p[N];
map < string, int > mymap;
int prim() {
    int d[N];
    int ans = 0;
    bool vis[N];
    memset( vis, 0, sizeof(vis));
    for ( int i = 1; i <= n; ++i ) d[i] = INF;
    int v, mi;
    d[st] = 0;
    for ( int u = 1; u <= n; ++u ) {
        mi = INF;
        for ( int i = 1; i <= n; ++i ) if ( !vis[i] && d[i] < mi ) v = i, mi = d[i];
        vis[v] = true;
        ans += mi;
        for ( int i = 1; i <= n; ++i ) if ( !vis[i] && d[i] > g[v][i] ) d[i] = g[v][i], p[i] = v;
    }
    return ans;
}
int main() 
{
    while ( cin >> n >> m, !( n == 0 && m == 0 ) ) {
        for ( int i = 1; i <= n; ++i ) for ( int j = i; j <= n; ++j ) g[i][j] = g[j][i] = INF;
        for ( int i = 1; i <= n; ++i ) {
            string name;
            cin >> name;
            mymap[name] = i;
        }
        for ( int i = 1; i <= m; ++i ) {
            string n1, n2; 
            int cost;
            cin >> n1 >> n2 >> cost;
            int u = mymap[n1], v = mymap[n2];
            g[u][v] = g[v][u] = cost;
        }
        string start; cin >> start; st = mymap[start];
        for ( int i = 1; i <= n; ++i ) p[i] = -1;
        int ans = prim();
        int num = 0;
        for ( int i = 1; i <= n; ++i ) if ( p[i] == -1 ) num++;
        if ( num > 1 ) cout << "Impossible" << endl;
        else cout << ans << endl;
    }
}


你可能感兴趣的:(UVa 11710 Expensive subway)