Gym - 101196D Lost in Translation [BFS + Priority Queue]

Topic link: https://vjudge.net/problem/Gym-101196D
Title: Give you n books, give you m kinds of translation paths and the cost of each translation path. The initial language of this book is English, let you turn the n books into the target language. In the case of the shortest translation path of each book, ask how much is your minimum cost.
Analysis: Mapping is based on points and paths, BFS is based on English. Every time I need to find the shortest path and the least cost, I use priority queue to maintain it. Every time I take out the shortest path and the least cost from the queue, this is the best solution after traversing.

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

Posted by manlio on Mon, 11 Feb 2019 19:03:18 -0800