力扣377周赛第三题(图论题目)

typedef pair<int,int> PII;
bool st[1100];
int h[11000000],ne[11000000],w[11000000],e[11000000],idx;
int dist[50][50];
class Solution {
public:
    void add(int a,int b,int c)
    {
        e[idx] = b,ne[idx] = h[a],w[idx] = c,h[a] = idx++;
    }
    void heap_dijkstra(int index,int start)
    {
      dist[index][start] = 0;
      priority_queue<PII,vector<PII>,greater<PII>> heap;
      heap.push({0,start});
      while(!heap.empty())
      {
        auto t = heap.top();
        heap.pop();
        int k = t.second,dis = t.first;
        if(st[k]) continue;
        else st[k] = true;
         for(int i = h[k];i != -1;i = ne[i])
         {
            int j = e[i];
            if(dist[index][j] > dist[index][k] + w[i])
            {
                dist[index][j] = dist[index][k] + w[i];
                heap.push({dist[index][j],j});
            }
         }
      }
    }
    long long minimumCost(string source, string target, vector<char>& original, vector<char>& changed, vector<int>& cost) 
    {
         int n = original.size();
         memset(h,-1,sizeof(h));
         for(int i = 0;i < n;i++)
         {
            int a = original[i] - 'a';
            int b = changed[i] - 'a';
            int c = cost[i];
            add(a,b,c);
         }
         memset(dist,0x3f,sizeof(dist));
        
        for(int i = 0;i < 26;i++)
        {
            memset(st,0,sizeof(st));
            heap_dijkstra(i,i);//预处理出来 i字符 到任意字符的最短距离
        }
        
        long long res = 0;
        int m = source.size();
        for(int i = 0;i < m;i++)
        {
            int a = source[i] - 'a';
            int b = target[i] - 'a';
            if(dist[a][b] == 0x3f3f3f3f) return -1;
            res += dist[a][b];
        }
        return res;
    }
};

 

版权声明:本文为博主作者:乖的小肥羊原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/txh1873749380/article/details/135180251

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2024年1月3日
下一篇 2024年1月3日

相关推荐