Gym 101196D Lost in Translation(BFS)

Problem D Lost in Translation

题意:

         给出一个图,从顶点开始(English),寻找 到每个点优先满足路径最短时的最小花费。

思路:

         所谓路径最短优先,其实就是 bfs 逐层搜索。若同层中有指向同一节点但花费不同的边,取最小即可。每搜完一层统计一遍 ans,给搜到的点打上 vis 标记即可。

代码:


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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值