- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试解决这个问题:https://open.kattis.com/problems/arbitrage
If you are going to travel to the World Finals, you cannot rely on Czech Crowns. You would have to exchange your money for various foreign currencies. This problem deals with multiple currencies and their exchange rates. Your task is to verify that some set of exchange rates is safe, namely detect a possibility of so-called arbitrage.
An arbitrage is a risk-free combination of buy and sell operations that gains profit from imbalance in market prices. The prices may apply to various things, typically stock exchange but also currencies.
Input The input consists of several test cases. Each case begins with a line containing one positive integer number 𝐶, 1≤𝐶≤200, the number of currencies.
The second line of each test case contains 𝐶 currency codes separated by a space. Each code is composed of 3 uppercase letters and all codes in one test case are different.
The third line contains one integer number 𝑅,0≤𝑅≤𝐶⋅(𝐶−1), the number of exchange rates available. Each of the following 𝑅 lines contains one exchange rate in the following format: first currency code, space, second currency code, space, integer number 𝐴𝑖, colon (’:’), and integer number 𝐵𝑖. The meaning is as follows: If you pay 𝐴𝑖 units of the first currency, you will get 𝐵𝑖 units of the second currency. You may assume that 1≤𝐴𝑖,𝐵𝑖≤100 and that the two currencies are different.
The last test case is followed by a line with 𝐶=0.
O(n^2)
中运行.
最佳答案
澄清一下,这个问题有两个输入大小的度量; C 是货币数量,R 是可用汇率的数量。从每种货币中使用 DFS 的“蛮力”解决方案是 O(C² + CR),其中通常 R 可以达到 O(C²) 本身。
该问题可以建模为在图中找到负权重循环。节点是货币,边是汇率对,边权重是-log(r)
汇率r
.使用负对数意味着当且仅当汇率的乘积大于 1 时,周期的权重之和为负。
寻找负权重循环通常是通过采用标准的最短路径算法来实现的,例如 Bellman-Ford在 O(CR) 时间内,或 Floyd-Warshall在 O(C³) 时间内。在 R 为 O(C) 或更大的情况下,这些都不比您的解决方案渐近更好,但可能值得进行基准测试,看看替代方案在实践中是否更快。
关于algorithm - 用图论找到套利,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59202026/
我是一名优秀的程序员,十分优秀!