前言
Lua 本是一个脚本语言,并不是用于算法竞赛,很多平台并不支持 lua语言。但是如果想用lua练一练语法,我在这里可以推荐一个网站,有兴趣可以在这进行练习。不过最头疼的是这个网站上编码,调试lua代码非常不人性,所以推荐可以使用本地的环境,或者是在线的lua编译器,那么下面就浅浅刷几道题吧。
1. FindK
题意
代码
-
io.read("n")
:读入一个数值,默认是"l"
读一行 -
string.gmatch(s, pattern)
:-
%w
:字母和数字 -
%g
:除空格外的可打印字符 -
%d
:数字 -
%s
:空白字符 -
四种修饰符:
+
:重复一次或多次*
:重复零次或多次?
:可选(出现零次或一次)
-
-
tonumber
:转数字
注意: 第一行我还有一个读空白符换行符的操作:_=io.read()
,不这样好像我也找不到啥好方法了。
local n, k, _ = io.read("n"), io.read("n"), io.read()
local a = {}
for _ = 1, 3 do
for i in string.gmatch(io.read(), "%w+") do
a[#a + 1] = tonumber(i)
end
end
table.sort(a)
print(a[k])
2. 题目列表
题意
goto ::label::
:类似continue
的操作_=io.read(1)
:读一个字节,也就相当于读后面的换行符io.lines()
:可迭代读入每一行table.sort()
:第二个参数,一个函数对象指定排序方式string.format
:格式化输出,类比printf
代码
local n, _ = io.read("n"), io.read(1)
local res = {}
for s in io.lines() do
if s == nil or s == "" then goto label end
local t = {}
for j in string.gmatch(s, "%w+") do
table.insert(t, j)
end
z = tonumber(t[3]) / tonumber(t[2])
t[2] = z
if z <= 0.3 then
t[3] = 5
elseif z <= 0.6 then
t[3] = 4
else
t[3] = 3
end
table.insert(res, t)
::label::
end
table.sort(res, function(a, b) return a[1] < b[1] end)
for i = 1, #res do
print(string.format("%s %d", res[i][1], res[i][3]))
end
3. 排列有序化
题意
-
树状数组求逆序对
-
math.ceil()
:浮点数向上取整
代码
local n, _ = io.read("n"), io.read() -- _ 把后面多余的空格换行读掉
local a = {}
for i in string.gmatch(io.read(), "%w+") do -- 读一行带空格的数字
table.insert(a, tonumber(i))
end
local N = math.ceil(1e5 + 10)
local tr = {}
local function sum(x)
local res, i = 0, x
while i >= 1 do
if tr[i] ~= nil then res = res + tr[i] end
i = i - (i & -i)
end
return res
end
local function add(x, v)
local i = x
while i <= N do
if tr[i] == nil then tr[i] = v else tr[i] = tr[i] + v end
i = i + (i & -i)
end
end
local res = 0
for i = 1, n do
local now = sum(a[i])
res = res + i - now - 1
add(a[i], 1)
end
local ra = {} -- 逆序a数组
for i = #a, 1, -1 do
ra[#ra + 1] = a[i]
end
tr = {} -- 清空tr数组
local res1 = 0
for i = 1, n do
local now = sum(ra[i])
res1 = res1 + i - now - 1
add(ra[i], 1)
end
print(math.min(res, res1)) -- math.min()
4. 幸运序列
题意
代码
local n = io.read("n")
local s = io.read()
local a = {}
local st = {}
-- !!!!!! 这里有负数的话,不能是 %w+
for i in string.gmatch(s, "%g+") do
a[#a + 1] = i
end
for i = 1, n - 1 do
st[math.abs(a[i] - a[i + 1])] = 1
end
for i = 1, n - 1 do
if st[i] == nil then
print("Unluck sequence")
os.exit()
end
end
print("Luck sequence")
体验下来,用Lua刷题真的很不方便,练练语法就好。
光速逃离~~~~