#P1873. 第1题-登录检查
-
1000ms
Tried: 267
Accepted: 106
Difficulty: 3
所属公司 :
美团
时间 :2024年8月10日
-
算法标签>模拟
第1题-登录检查
java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String ans = sc.next();
String[] ts = new String[n];
int tn = 0;
HashSet<String> set = new HashSet<>();
for (int i = 0; i < n; ++i) {
String t = sc.next();
if (set.contains(t)) {
continue;
} else {
set.add(t);
ts[tn++] = t;
}
}
n = tn;
String s[] = new String[n];
for (int i = 0; i < n; ++i) {
s[i] = ts[i];
}
Arrays.sort(s, (a, b) -> a.length() - b.length());
for (int i = 0; i < n; ++i) {
int j = i;
boolean eq = s[j].equals(ans);
while (j + 1 < n && s[j + 1].length() == s[j].length()) {
if (s[++j].equals(ans)) {
eq = true;
}
}
if (eq) {
System.out.println(i + 1 + " " + (j + 1));
return;
}
i = j;
}
}
}
python
from collections import defaultdict
def min_max_attempts(n, correct_password, passwords):
# 按长度分组
length_groups = defaultdict(list)
for password in passwords:
length_groups[len(password)].append(password)
# 按长度排序
sorted_lengths = sorted(length_groups.keys())
min_attempts = max_attempts = 0
correct_length = len(correct_password)
for length in sorted_lengths:
if length > correct_length:
break
unique_passwords = set(length_groups[length])
group_size = len(unique_passwords)
if correct_password in unique_passwords:
# 最少尝试:正确密码在当前组的第一个
min_attempts += 1
# 最多尝试:正确密码在当前组的最后一个
max_attempts += group_size
return min_attempts, max_attempts
min_attempts += group_size
max_attempts += group_size
# 如果没有找到正确密码
return -1, -1
# 读取输入
n = int(input())
correct_password = input().strip()
passwords = [input().strip() for _ in range(n)]
# 计算结果
min_attempts, max_attempts = min_max_attempts(n, correct_password, passwords)
# 输出结果
print(min_attempts, max_attempts)
c++
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main(){
int n;
cin >> n;
string s;
cin >> s;
int true_len = s.size();
map<int, int> map1;
for (int i = 0; i < n; i++) {
string s1;
cin >> s1;
if(map1.find(s1.size()) == map1.end()) {
map1[s1.size()] = 1;
} else {
map1[s1.size()]++;
}
}
int pre_sum = 0;
int end_sum = 0;
for (auto &kv : map1) {
if(kv.first < true_len) {
pre_sum += kv.second;
}
if(kv.first <= true_len) {
end_sum += kv.second;
}
}
cout << pre_sum+1 << " " << end_sum << endl;
}
题目描述
小美准备登录美团, 需要输入密码, 小美忘记了密码, 只记得密码可能是 n 个字符串中的一个。小美会按照密码的长度从小到大依次尝试每个字符串, 对于相同长度的字符串, 小美随机尝试, 并且相同的密码只会尝试一次。小美想知道, 她最少需要尝试多少次才能登录成功, 最多需要尝试多少次才能登录成功。
小美不会重新尝试已经尝试过的字符串。成功登录后会立即停止尝试。
输入描述
第一行输入一个整数 n (1≤n≤1000) 代表密码字符串的个数。
第二行输入一个只由小写字母组成的字符串 s(1≤∣s∣≤1000)代表正确的密码。
接下来 n 行, 每行输入一个长度不超过 1000 的字符串, 代表小美记得的密码。
输出描述
在一行上输出两个整数, 表示最少和最多尝试次数。
样例输入输出
3
ab
abc
ab
ac
1 2
说明
小美可能按照 ["ab",“ac",“abc"] 的顺序尝试,第一次尝试成功,也可能按照 [“ac"“ab",“abc"] 的顺序尝试,第二次尝试成功。 小美在尝试"ac"发现不正确后不会继续尝试"ac"。