中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

瑪伊網(wǎng)站做兼職加入要多少錢廈門最快seo

瑪伊網(wǎng)站做兼職加入要多少錢,廈門最快seo,做網(wǎng)站的多錢,廣州專業(yè)做網(wǎng)站公司Powered by:NEFU AB-IN Link 文章目錄 3213. 最小代價(jià)構(gòu)造字符串題意思路代碼 3213. 最小代價(jià)構(gòu)造字符串 題意 給你一個(gè)字符串 target、一個(gè)字符串?dāng)?shù)組 words 以及一個(gè)整數(shù)數(shù)組 costs,這兩個(gè)數(shù)組長度相同。 設(shè)想一個(gè)空字符串 s。 你可以執(zhí)行以下操作任意次數(shù)&a…

Powered by:NEFU AB-IN

Link

文章目錄

  • 3213. 最小代價(jià)構(gòu)造字符串
    • 題意
    • 思路
    • 代碼

3213. 最小代價(jià)構(gòu)造字符串

題意

給你一個(gè)字符串 target、一個(gè)字符串?dāng)?shù)組 words 以及一個(gè)整數(shù)數(shù)組 costs,這兩個(gè)數(shù)組長度相同。

設(shè)想一個(gè)空字符串 s。

你可以執(zhí)行以下操作任意次數(shù)(包括零次):

選擇一個(gè)在范圍 [0, words.length - 1] 的索引 i。
將 words[i] 追加到 s。
該操作的成本是 costs[i]。
返回使 s 等于 target 的 最小 成本。如果不可能,返回 -1。

思路

字典樹/字符串哈希 + dp

  1. 使用 Trie 樹存儲(chǔ)單詞和成本:
    我們將所有的單詞和對應(yīng)的成本插入到一個(gè) Trie 樹中。Trie 樹是一種多叉樹,可以快速查找以某個(gè)前綴開頭的所有單詞。
    這樣我們就能在 Trie 樹中快速查找到以 target 中某個(gè)位置開始的所有前綴單詞及其成本。
  2. 動(dòng)態(tài)規(guī)劃(Dynamic Programming):
    使用一個(gè)動(dòng)態(tài)規(guī)劃數(shù)組 dp,其中 dp[i] 表示構(gòu)造 target 的前 i 個(gè)字符的最小成本。
    初始化 dp[0] = 0,表示構(gòu)造空字符串的成本為 0,其他位置初始化為無窮大,表示尚未計(jì)算到該位置。
  3. 遍歷目標(biāo)字符串:
    對于目標(biāo)字符串 target 的每一個(gè)位置 i,如果 dp[i] 是無窮大,表示不能從當(dāng)前位置開始構(gòu)造,則跳過。
    否則,使用 Trie 樹的 search 方法,從當(dāng)前位置 i 開始查找所有可能的前綴及其成本。
    對于每一個(gè)找到的前綴,更新 dp 數(shù)組:dp[i + length] = min(dp[i + length], dp[i] + cost),表示從當(dāng)前位置 i 開始構(gòu)造到 i + length 的最小成本。

代碼

# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, fabs, floor, gcd, log, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Dict, List, Tuple, TypeVar, Union# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)  # If using AR, modify accordingly
M = int(20)  # If using AR, modify accordingly
INF = int(2e9)
OFFSET = int(100)# Set recursion limit
setrecursionlimit(INF)class Arr:array = staticmethod(lambda x=0, size=N: [x] * size)array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])graph = staticmethod(lambda size=N: [[] for _ in range(size)])@staticmethoddef to_1_indexed(data: Union[List, str, List[List]]):"""Adds a zero prefix to the data and returns the modified data and its length."""if isinstance(data, list):if all(isinstance(item, list) for item in data):  # Check if it's a 2D arraynew_data = [[0] * (len(data[0]) + 1)] + [[0] + row for row in data]return new_data, len(new_data) - 1, len(new_data[0]) - 1else:new_data = [0] + datareturn new_data, len(new_data) - 1elif isinstance(data, str):new_data = '0' + datareturn new_data, len(new_data) - 1else:raise TypeError("Input must be a list, a 2D list, or a string")class Str:letter_to_num = staticmethod(lambda x: ord(x.upper()) - 65)  # A -> 0num_to_letter = staticmethod(lambda x: ascii_uppercase[x])  # 0 -> Aremoveprefix = staticmethod(lambda s, prefix: s[len(prefix):] if s.startswith(prefix) else s)removesuffix = staticmethod(lambda s, suffix: s[:-len(suffix)] if s.endswith(suffix) else s)class Math:max = staticmethod(lambda a, b: a if a > b else b)min = staticmethod(lambda a, b: a if a < b else b)class IO:input = staticmethod(lambda: stdin.readline().rstrip("\r\n"))read = staticmethod(lambda: map(int, IO.input().split()))read_list = staticmethod(lambda: list(IO.read()))class Std:@staticmethoddef find(container: Union[List[TYPE], str], value: TYPE):"""Returns the index of value in container or -1 if value is not found."""if isinstance(container, list):try:return container.index(value)except ValueError:return -1elif isinstance(container, str):return container.find(value)@staticmethoddef pairwise(iterable):"""Return successive overlapping pairs taken from the input iterable."""a, b = tee(iterable)next(b, None)return zip(a, b)@staticmethoddef bisect_left(a, x, key=lambda y: y):"""The insertion point is the first position where the element is not less than x."""left, right = 0, len(a)while left < right:mid = (left + right) >> 1if key(a[mid]) < x:left = mid + 1else:right = midreturn left@staticmethoddef bisect_right(a, x, key=lambda y: y):"""The insertion point is the first position where the element is greater than x."""left, right = 0, len(a)while left < right:mid = (left + right) >> 1if key(a[mid]) <= x:left = mid + 1else:right = midreturn leftclass SparseTable:def __init__(self, data: list, func=lambda x, y: x | y):"""Initialize the Sparse Table with the given data and function."""self.func = funcself.st = [list(data)]i, n = 1, len(self.st[0])while 2 * i <= n:pre = self.st[-1]self.st.append([func(pre[j], pre[j + i]) for j in range(n - 2 * i + 1)])i <<= 1def query(self, begin: int, end: int):"""Query the combined result over the interval [begin, end]."""lg = (end - begin + 1).bit_length() - 1return self.func(self.st[lg][begin], self.st[lg][end - (1 << lg) + 1])class TrieNode:def __init__(self):"""Initialize children dictionary and cost. The trie tree is a 26-ary tree."""self.children = {}self.cost = INFdef add(self, word, cost):"""Add a word to the trie with the associated cost."""node = selffor c in word:if c not in node.children:node.children[c] = Std.TrieNode()node = node.children[c]node.cost = min(node.cost, cost)def search(self, word):"""Search for prefixes of 'word' in the trie and return their lengths and costs."""node = selfans = []for i, c in enumerate(word):if c not in node.children:breaknode = node.children[c]if node.cost != INF:ans.append([i + 1, node.cost])  # i + 1 to denote length from startreturn ansclass StringHash:def __init__(self, s: str, mod: int = 1_070_777_777):"""Initialize the StringHash object with the string, base, and mod."""self.s = sself.mod = modself.base = random.randint(8 * 10 ** 8, 9 * 10 ** 8)self.n = len(s)self.pow_base = [1] + Arr.array(0, self.n)  # pow_base[i] = BASE^iself.pre_hash = Arr.array(0, self.n + 1)  # pre_hash[i] = hash(s[:i])self._compute_hash()def _compute_hash(self):"""Compute the prefix hash values and power of base values for the string."""for i, b in enumerate(self.s):self.pow_base[i + 1] = self.pow_base[i] * self.base % self.modself.pre_hash[i + 1] = (self.pre_hash[i] * self.base + ord(b)) % self.moddef get_sub_hash(self, l: int, r: int) -> int:"""Get the hash value of the substring s[l:r+1] """return (self.pre_hash[r + 1] - self.pre_hash[l] * self.pow_base[r - l + 1] % self.mod + self.mod) % self.moddef get_full_hash(self) -> int:"""Get the hash value of the full string"""return self.pre_hash[self.n]def compute_hash(self, word: str) -> int:"""Compute the hash value of a given word using the object's base and mod."""h = 0for b in word:h = (h * self.base + ord(b)) % self.modreturn h# ————————————————————— Division line ——————————————————————class Solution:def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:# Build the Trietrie = Std.TrieNode()for word, cost in zip(words, costs):trie.add(word, cost)n = len(target)dp = Arr.array(INF, n + 1)dp[0] = 0# Dynamic programming to calculate the minimum costfor i in range(n):if dp[i] == INF:continuefor length, cost in trie.search(target[i:]):dp[i + length] = min(dp[i + length], dp[i] + cost)return dp[n] if dp[n] != INF else -1class Solution:def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:n = len(target)target_hash = Std.StringHash(target)# 每個(gè) words[i] 的哈希值 -> 最小成本min_cost = defaultdict(lambda: INF)for w, c in zip(words, costs):h = target_hash.compute_hash(w)min_cost[h] = min(min_cost[h], c)# 獲取所有唯一的單詞長度sorted_lens = sorted(set(map(len, words)))dp = Arr.array(INF, n + 1)dp[0] = 0for i in range(n):if dp[i] == INF:continuefor sz in sorted_lens:if i + sz > n:break# 計(jì)算子串 target[i:i+sz] 的哈希值sub_hash = target_hash.get_sub_hash(i, i + sz - 1)dp[i + sz] = min(dp[i + sz], dp[i] + min_cost[sub_hash])return -1 if dp[n] == INF else dp[n]
http://www.risenshineclean.com/news/8040.html

相關(guān)文章:

  • 怎么樣做網(wǎng)站的目錄結(jié)構(gòu)友情鏈接買賣代理
  • 使用mvs2010做網(wǎng)站營銷型網(wǎng)站建設(shè)案例
  • 長葛網(wǎng)站制作成功的品牌推廣案例分析
  • 一個(gè)做女性服裝批發(fā)的網(wǎng)站_最好的關(guān)鍵詞選擇是百度seo價(jià)格
  • 站酷網(wǎng)頁版廣州網(wǎng)站排名優(yōu)化報(bào)價(jià)
  • 美圖秀秀可以做網(wǎng)站嗎昆明新聞?lì)^條最新消息
  • 上海市建設(shè)工程招標(biāo)造價(jià)網(wǎng)站百度搜索排名與點(diǎn)擊有關(guān)嗎
  • 網(wǎng)站建設(shè)設(shè)電工培訓(xùn)課程
  • 營銷型網(wǎng)站建設(shè)虧1關(guān)鍵詞推廣軟件排名
  • 做網(wǎng)站seo優(yōu)化百度一下網(wǎng)頁搜索
  • 做視頻網(wǎng)站用哪個(gè)軟件好松原頭條新聞今日新聞最新
  • 手機(jī)網(wǎng)站制作方法大型網(wǎng)站制作
  • 安徽安慶中考成績查詢醫(yī)療網(wǎng)站優(yōu)化公司
  • 承接博彩網(wǎng)站建設(shè)seo關(guān)鍵詞搜索優(yōu)化
  • 做購物網(wǎng)站適合的服務(wù)器快速開發(fā)平臺(tái)
  • wordpress播放本地mp3站內(nèi)seo是什么意思
  • 2017年做網(wǎng)站好難企業(yè)策劃
  • 怎么做網(wǎng)站維護(hù)國外網(wǎng)站排名前十
  • 移民網(wǎng)站制作一網(wǎng)信息一個(gè)簡單便捷的新聞網(wǎng)站
  • 自定義網(wǎng)站模塊seo優(yōu)化教學(xué)視頻
  • php網(wǎng)站開發(fā) pdfseo顧問賺錢嗎
  • 學(xué)校網(wǎng)站制作三只松鼠網(wǎng)絡(luò)營銷策劃書
  • 動(dòng)易門戶網(wǎng)站價(jià)格新網(wǎng)站多久會(huì)被百度收錄
  • 如何進(jìn)行網(wǎng)站推廣百度熱搜榜
  • 現(xiàn)在如何給網(wǎng)站做外鏈百度指數(shù)怎么下載
  • 新疆網(wǎng)站制作網(wǎng)站關(guān)鍵詞免費(fèi)優(yōu)化
  • wordpress對應(yīng)國家語言百度站長工具seo查詢
  • 泰安網(wǎng)絡(luò)推廣長沙seo招聘
  • 網(wǎng)站建設(shè)官網(wǎng)怎么收費(fèi)網(wǎng)址查詢域名解析
  • 管理咨詢網(wǎng)站網(wǎng)絡(luò)做推廣廣告公司