Gym - 101196D Lost in Translation【BFS+优先队列】

26 篇文章 0 订阅
23 篇文章 0 订阅

题目链接:https://vjudge.net/problem/Gym-101196D
题意:给你n本书,给你m种翻译的路径和每条翻译路径的花费,这n本书的初始语言是English,让你把这n本书变为目标语言,在每本书的翻译路径是最短的情况下,问你最小花费为多少
解析:根据点和路径来建图,以English来进行BFS,每次要求找到路径最短且花费最小的,我采用的是优先队列来维护,每次从队列里取出队列里路径最短的且花费最小的,这样遍历完即为最优解

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <set>
#include <stack>
#include <map>
using namespace std;
const int maxn = 4505;
int n,m;
struct node
{
    int v,c,w;
    node() {}
    node(int _v,int _c,int _w)
    {
        v = _v;
        c = _c;
        w = _w;
    }
    bool operator < (const node &b)const
    {
        if(c==b.c)
            return w>b.w;
        return c>b.c;
    }
};
vector<node>G[maxn];
map<string,int>maple;
priority_queue<node> q;
string a[105];
int vis[maxn];
int bfs()
{
    memset(vis,0,sizeof(vis));
    q.push(node(0,0,0));
    int res = 0;
    while(!q.empty())
    {
        node now = q.top();
        q.pop();
        if(vis[now.v])
            continue;
        vis[now.v] = 1;
        res += now.w;
        for(int i=0;i<G[now.v].size();i++)
            q.push(node(G[now.v][i].v,now.c+1,G[now.v][i].w));
    }
    for(int i=0;i<=n;i++)
    {
        if(!vis[i])
            return -1;
    }
    return res;
}
int main()
{
    scanf("%d %d",&n,&m);
    maple["English"] = 0;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        maple[a[i]] = i;
    }
    for(int i=0;i<m;i++)
    {
        string l,r;
        int c;
        cin>>l>>r>>c;
        G[maple[l]].push_back(node(maple[r],1,c));
        G[maple[r]].push_back(node(maple[l],1,c));
    }
    int ans=bfs();
    if(ans==-1)
        puts("Impossible");
    else
        printf("%d\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值