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

 

相关推荐

  1. 375

    2023-12-24 15:20:03       54 阅读
  2. 376

    2023-12-24 15:20:03       55 阅读
  3. 379VP

    2023-12-24 15:20:03       66 阅读
  4. 397 A~C

    2023-12-24 15:20:03       39 阅读
  5. 【上分日记】377( + dp)

    2023-12-24 15:20:03       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-24 15:20:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-24 15:20:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-24 15:20:03       82 阅读
  4. Python语言-面向对象

    2023-12-24 15:20:03       91 阅读

热门阅读

  1. 软件工程-第二章 计算机系统工程

    2023-12-24 15:20:03       53 阅读
  2. 【Python爬虫】第四课 动态爬取数据

    2023-12-24 15:20:03       55 阅读
  3. 排序算法——基数排序

    2023-12-24 15:20:03       61 阅读
  4. C++学习——STL

    2023-12-24 15:20:03       62 阅读
  5. 60 贪心算法解优势洗牌-田忌赛马问题

    2023-12-24 15:20:03       60 阅读
  6. 8.架构设计系列:常用设计模式的实践

    2023-12-24 15:20:03       51 阅读
  7. Python 常用模块re

    2023-12-24 15:20:03       56 阅读
  8. k8s中的namespace及创建方式

    2023-12-24 15:20:03       57 阅读
  9. 单例模式的四种具体写法

    2023-12-24 15:20:03       59 阅读
  10. Python学习9

    2023-12-24 15:20:03       48 阅读
  11. Npm使用技巧

    2023-12-24 15:20:03       56 阅读