POJ 2263 Heavy Cargo 多种解法

好题。这题可以有三种解法:1.Dijkstra   2.优先队列   3.并查集

我这里是优先队列的实现,以后有时间再用另两种方法做做。。方法就是每次都选当前节点所连的权值最大的边,然后BFS搜索。

代码:

#include <iostream>

#include <cstdio>

#include <cstring>

#include <cmath>

#include <algorithm>

#include <cstdlib>

#include <string>

#include <vector>

#include <map>

#include <queue>

#include <functional>

using namespace std;

#define N 100007



struct node

{

    int ind,wt;

    bool operator < (const node &a)const

    {

        return wt<a.wt;

    }

};

int start,endi,n,m,res;

int way[203][203],vis[203][203];

map<string,int> mp;

priority_queue<node> que;



void BFS()

{

    memset(vis,0,sizeof(vis));

    int i,maxi = 0,id;

    node now,next;

    for(i=1;i<=n;i++)

    {

        if(way[start][i] > maxi)

        {

            maxi = way[start][i];

            id = i;

        }

    }

    now.ind = id;

    now.wt = maxi;

    que.push(now);

    //printf("%d %d\n",start,endi);

    //printf("%d %d\n",now.ind,now.wt);

    res = 0;

    while(!que.empty())

    {

        now = que.top();

        que.pop();

        if(now.ind == endi)

        {

            if(now.wt > res)

                res = now.wt;

            while(!que.empty())

                que.pop();

            return;

        }

        for(i=1;i<=n;i++)

        {

            if(way[now.ind][i] && !vis[now.ind][i])

            {

                vis[now.ind][i] = vis[i][now.ind] = 1;

                next.ind = i;

                next.wt = min(now.wt,way[now.ind][i]);

                que.push(next);

                //printf("%d %d\n",next.ind,next.wt);

            }

        }

    }

}



int main()

{

    int cs = 1,i,j,w,num;

    string city1,city2;

    node ka,kb;

    while(scanf("%d%d",&n,&m)!=EOF && (n||m))

    {

        mp.clear();

        num = 1;

        memset(way,0,sizeof(way));

        for(i=0;i<m;i++)

        {

            cin>>city1;

            cin>>city2;

            scanf("%d",&w);

            if(!mp[city1])

                mp[city1] = num++;

            if(!mp[city2])

                mp[city2] = num++;

            way[mp[city1]][mp[city2]] = w;

            way[mp[city2]][mp[city1]] = w;

        }

        cin>>city1>>city2;

        start = mp[city1];

        endi = mp[city2];

        BFS();

        printf("Scenario #%d\n",cs++);

        printf("%d tons\n\n",res);

    }

    return 0;

}
View Code

 

你可能感兴趣的:(poj)