1 solutions

  • 0
    @ 2025-12-3 16:27:17

    C++ :

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<cmath>
    #include<cstring>
    #include<vector>
    #include<queue>
    #include<map>
    using namespace std;
    const long long N=5000+5,F=2147483647000000;
    long long n,m,e,Q,d[N],gs;
    struct pp
    {
    	long long t,v;
    	friend bool operator <(pp a,pp b)
    	{
    		return a.v>b.v;
    	}  
    };
    pp tmp,tmp1;
    vector<pp>c[N];
    priority_queue<pp>q;
    map<string,long long>mp;
    string st,sr;
    long long zh(string st)//杞崲
    {
    	if (mp[st]) return mp[st];
    	return mp[st]=++gs;
    } 
    long long dij(long long ss,long long tt)
    {
    	while (!q.empty()) q.pop();
    	for (int i=1;i<=n;i++) d[i]=F;
    	d[ss]=0; tmp.t=ss; tmp.v=0; q.push(tmp);
    	while (!q.empty())
    	{
    		pp tmp1=q.top(); q.pop();
    		long long x=tmp1.t,y=tmp1.v;
    		if (y!=d[x]) continue;
    		if (x==tt) return d[x]; 
    		for (int i=0;i<c[x].size();i++)
    		{
    			long long t=c[x][i].t,v=y+c[x][i].v;
    			if (v<d[t]) d[t]=v,tmp.t=t,tmp.v=v,q.push(tmp);
    		}
    	}
    	return -1;
    }
    int main()
    {
    	cin>>n>>m;
    	for (int i=1;i<=m;i++)
    	{
    		cin>>st>>sr>>e;
    		tmp.t=zh(sr); tmp.v=e;
    		c[zh(st)].push_back(tmp);
    //		cout<<zh(st)<<" "<<zh(sr)<<endl;
    	}
    	cin>>Q;
    	for (int i=1;i<=Q;i++)
    	{
    		cin>>st>>sr;
    //		cout<<zh(st)<<" "<<zh(sr)<<endl;
    		printf("%lld\n",dij(zh(st),zh(sr)));
    	}
    	return 0;
    }
    
    
    • 1

    Information

    ID
    886
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    (None)
    Tags
    (None)
    # Submissions
    0
    Accepted
    0
    Uploaded By