力扣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;
    }
};
相关推荐
君义_noip3 小时前
信息学奥赛一本通 1661:有趣的数列 | 洛谷 P3200 [HNOI2009] 有趣的数列
c++·算法·组合数学·信息学奥赛·csp-s
程序员:钧念3 小时前
深度学习与强化学习的区别
人工智能·python·深度学习·算法·transformer·rag
英英_4 小时前
MATLAB数值计算基础教程
数据结构·算法·matlab
一起养小猫4 小时前
LeetCode100天Day14-轮转数组与买卖股票最佳时机
算法·leetcode·职场和发展
hele_two4 小时前
快速幂算法
c++·python·算法
l1t5 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
jllllyuz5 小时前
基于子集模拟的系统与静态可靠性分析及Matlab优化算法实现
算法·matlab·概率论
程序员-King.6 小时前
day143—递归—对称二叉树(LeetCode-101)
数据结构·算法·leetcode·二叉树·递归
BlockChain8886 小时前
字符串最后一个单词的长度
算法·go
爱吃泡芙的小白白6 小时前
深入解析:2024年AI大模型核心算法与应用全景
人工智能·算法·大模型算法