constexprint N = 32; int cnt1[N], cnt2[N]; int len;
structcmp { booloperator()(string a, string b){ for (int i = 0, n = a.size(); i < n; i++) { if (a[i] != b[i]) return a[i] < b[i]; } returntrue; } };
inlineboolisBrother(string a){ int n = a.size(); if (n != len) returnfalse; memset(cnt2, 0, sizeof cnt2); for (int i = 0; i < n; i++) cnt2[a[i] - 97]++; for (int i = 0; i < 32; i++) if (cnt1[i] && cnt1[i] != cnt2[i]) returnfalse; returntrue; }
intmain() { cin.tie(nullptr)->sync_with_stdio(false); int n; vector<string> v; string s; int k; for (; cin >> n;) { string t; for (int i = 0; i < n; i++) { cin >> t; v.push_back(t); } cin >> s; cin >> k; } len = s.size(); for (int i = 0; i < len; i++) cnt1[s[i] - 97]++; vector<string> bro; for (auto &each : v) { if (each.size() != len || each == s) continue; if (isBrother(each)) bro.push_back(each); } priority_queue<string, vector<string>, cmp> max_heap; for (auto &each : bro) { max_heap.push(each); for (; max_heap.size() > k; max_heap.pop()); } //for (; !max_heap.empty(); max_heap.pop()) cout << max_heap.top() << endl; cout << bro.size() << endl; cout << (max_heap.size() >= k ? max_heap.top() : "") << endl; return0; }
publicclassMain{ staticfinalint N = 32; staticint[] cnt1 = newint[N]; privatestaticvoidsolve(Scanner in){ int n = in.nextInt(); String[] ss = new String[n]; for (int i = 0; i < n; i++) { ss[i] = in.next(); } String s = in.next(); int k = in.nextInt(); int len = s.length(); for (int i = 0; i < len; i++) { cnt1[s.charAt(i) - 97]++; } Queue<String> maxHeap = new PriorityQueue<>(new Comparator<String>() { @Override publicintcompare(String a, String b){ for (int i = 0, n = a.length(); i < n; i++) { char ca = a.charAt(i); char cb = b.charAt(i); if (ca != cb) return cb - ca; } return0; } }); int broCnt = 0; for (String each : ss) { if (each.length() != len || each.equals(s)) continue; if (isBrother(each)) { broCnt++; maxHeap.add(each); for (; maxHeap.size() > k; maxHeap.poll()); } } System.out.println(broCnt); if (maxHeap.size() >= k) System.out.println(maxHeap.peek()); } privatestaticbooleanisBrother(String s){ int[] cnt2 = newint[N]; for (int i = 0, n = s.length(); i < n; i++) { cnt2[s.charAt(i) - 97]++; } for (int i = 0; i < N; i++) { if (cnt1[i] != 0 && cnt1[i] != cnt2[i]) returnfalse; } returntrue; } publicstaticvoidmain(String[] args){ Scanner in = new Scanner(System.in); for (; in.hasNext();) { solve(in); } } }