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

cpp 复制代码
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;
    }
};
相关推荐
Morriser莫2 分钟前
图论Day2学习心得
算法·图论
KarrySmile7 分钟前
Day53--图论--106. 岛屿的周长(卡码网),110. 字符串接龙(卡码网),105. 有向图的完全联通(卡码网)
深度优先·图论·广度优先·广搜·岛屿的周长·字符串接龙·有向图的完全联通
zyd09159 分钟前
代码随想录Day50:图论(图论理论、深度搜索理论、所有可达路径、广度搜索理论)
java·数据结构·算法·leetcode·图论
Cl_rown去掉l变成C12 分钟前
第R5周:天气预测
人工智能·python·深度学习·算法·tensorflow2
CoovallyAIHub1 小时前
VisDrone数据集,专为无人机视觉任务打造
深度学习·算法·计算机视觉
啊阿狸不会拉杆1 小时前
《算法导论》第 22 章 - 基本的图算法
c++·算法·排序算法·图论·拓扑学
Warren981 小时前
Java后端面试题(含Dubbo、MQ、分布式、并发、算法)
java·开发语言·分布式·学习·算法·mybatis·dubbo
现在,此刻10 小时前
leetcode 11. 盛最多水的容器 -java
java·算法·leetcode
☆璇10 小时前
【C++】哈希的应用:位图和布隆过滤器
算法·哈希算法
一株月见草哇12 小时前
Matlab(4)
人工智能·算法·matlab