贪心

poj 2387 dijkstra

#include <iostream>
#include <vector>
using namespace std;
/**
 * poj 2387 link: http://poj.org/problem?id=2387
 */

int main(){
    int T, N;
    /**
     * 赋值INF要注意一定要够大
     */
    const int INF = 10000000;
    cin >> T >> N;
    vector<vector<int> > m(N + 1, vector<int>(N + 1, INF));
    vector<int> dist(N + 1, INF);
    vector<bool> visit(N+1, false);
    int s, e, d;
    while(T > 0){
        cin >> s >> e >> d;
        m[s][e] = m[e][s] = min(d,  m[e][s]);
        T--;
    }
    int origin = 1;
    
    for(int i = 1; i <= N; i++){
        dist[i] = m[origin][i];
    }

    dist[origin] = 0;
    visit[origin] = true;

    for(int c = 0; c < N; c++){
        int mini = INF;
        int idx = 1;
        for(int i = 1; i <= N; i++){
            if(!visit[i] && dist[i] < mini){
                mini = dist[i];
                idx = i;
            }
        }
        visit[idx] = true;
        for(int i = 1; i <= N; i++){
            if(!visit[i] && dist[idx] + m[idx][i] < dist[i]){
                dist[i] = dist[idx] + m[idx][i];
            }
        }
    }

    cout << dist[N] << endl;

    return 0;
}
#include <iostream>
using namespace std;
/**
 * http://poj.org/problem?id=1251
 */
const int maxN = 30;
const int INF = 0x3f3f3f3f;
int m[maxN][maxN];
int dist[maxN];
bool visit[maxN];
int n;
int prim(){
    int start = 0;
    int idx;
    int ans = 0;
    for(int i =0; i < n; i++) dist[i] = m[0][i]; 
    visit[start] = true;

    for(int c = 1; c < n; c++){
        int mini = INF;
        for(int i = 0; i < n; i++){
            if(!visit[i] && dist[i] < mini){
                mini = dist[i];
                idx = i;
            }
        }

        visit[idx] = true;
        ans += mini;
        for(int i = 0; i < n; i++){
            if(!visit[i] && m[idx][i] < dist[i]){
                dist[i] = m[idx][i];
            }
        }
    }

    return ans;
}

int main(){

    int  c, l;
    char s, e;
    while(cin >> n, n){
        
        
        for(int i = 0; i < n; i++){
            visit[i] = false;
            for(int j = 0; j < n; j++){
                m[i][j] = INF;
            }
        }
        int t = n;
        n = n - 1;        
        while(n > 0){
            cin >> s;
            cin >> c;
               
            while(c > 0){
                cin >> e >> l;
                
                m[s - 'A'][e - 'A'] = m[e - 'A'][s - 'A'] = l;
                c--;
            }

            n--;
            
        }

        n = t;
        for(int i = 0; i < n; i++) dist[i] = INF;

        cout << prim() << endl;
    }
    
    return 0;
}
posted @ 2019-08-30 17:01  qbits  阅读(133)  评论(0编辑  收藏  举报