Bootstrap

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

 

;