A song has n notes, numbered from 1 in order. Each note is written as an integer from 1 to 999. You are given q fragments, and each fragment lists m notes in order. A fragment appears at position s of the song if the m consecutive notes starting at note s of the song are equal to the fragment's notes, in order. Positions where the fragment appears are all counted separately, even if they overlap. If a fragment is longer than the song, it appears at no position. For each fragment, print one of the following three on one line. If the fragment appears at one or more positions of the song, print found, the number of positions, and the smallest of those positions, separated by single spaces. If it appears nowhere and some note of the fragment is nowhere in the song, print missing and, among such notes, the one written earliest in the fragment, separated by a single space. If it appears nowhere but every note of the fragment, taken one at a time, is somewhere in the song, print scattered. Notes are compared as numbers. So 1 1 does not appear in the song 11 1 2.
Input
The first line gives n, and the second line gives the n notes of the song separated by single spaces. The third line gives q, and each of the next q lines gives one fragment: m and then m notes, separated by single spaces. 1 ≤ n ≤ 1,000, 1 ≤ q ≤ 50, 1 ≤ m ≤ 20, every note is an integer from 1 to 999
Output
One line per fragment: found count first-position, missing note, or scattered. found, missing and scattered are written in English in every locale
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
This problem is about telling apart two questions: does a list hold 'one value', and does it hold 'several values in a row'. One note is asked with Python x in song, JS/TS song.includes(x), Java song.contains(x), C# song.Contains(x), C++ std::find(song.begin(), song.end(), x) != song.end(), Craykon song.Contains(x). C's standard bsearch works only on a sorted array, so for an unsorted song you write the loop yourself. A fragment in a row cannot be asked in one call like that. Python cuts and compares song[i:i + m] == frag, Java uses song.subList(i, i + m).equals(frag), C# song.GetRange(i, m).SequenceEqual(frag), C++ finds it with std::search, JS/TS compare each slot with every, C uses memcmp, and Craykon uses a nested loop. Java also has Collections.indexOfSubList, which only gives the first position, but this problem needs the count too. Trap 1: Python frag in song, JS song.includes(frag), Java song.contains(frag) and Craykon song.Contains(frag) look for 'one slot' equal to frag. The slots are integers, so it is always false. TS reports a type error for passing a number[] where a number is expected. Whether two lists are equal also differs by language. Python list ==, Java equals and C++ vector== compare contents, but JS/TS ===, C# List== and Craykon == only check whether it is the same list, so song.GetRange(i, m) == frag is always false. Trap 2: in Java, comparing slots of a List<Integer> with ==/!=, as in song.get(i + j) != frag.get(j), checks whether the Integer objects are the same. -128 to 127 share prepared objects, but by default 128 and above are made separately, so 200 and 200 come out different. Use equals or compare as int. Trap 3: if you join the song and the fragment with spaces and search the string (text.includes(key), key in text), you compare characters, not numbers, so 1 1 shows up inside 11 1 2 and 2 3 inside 12 3. Trap 4: searching for 1 1 with spaces on both ends avoids trap 3, but Python str.count counts without overlaps. The end space of one match also cannot serve as the start space of the next, so in 3 3 3 3 it counts 3 3 once instead of 3 times. Trap 5: if start positions only go up to i < n - m, the last position n - m is skipped, and a fragment that appears only at the very end, like 2 3 in example 1, comes out scattered. The condition is i + m <= n. Trap 6: the third argument of C memcmp is a number of bytes. Pass m and it compares only the first m bytes, that is about m/4 of the 4-byte ints. For 5 7 5 in example 1, m is 3, so only the first 3 bytes of the first note are compared, and it counts at every position holding 5. Pass m * sizeof(int).
Pythonmain.py · 27 lines
import sysdef judge(song, frag): n, m = len(song), len(frag) # 목록에 목록이 '이어서' 들어 있는지는 in으로 물을 수 없다: 자리마다 잘라서 비교한다 starts = [i + 1 for i in range(n - m + 1) if song[i:i + m] == frag] if starts: return f"found {len(starts)} {starts[0]}" for x in frag: if x not in song: # 음 하나는 in으로 묻는다 return f"missing {x}" return "scattered"def main(): lines = sys.stdin.read().split("\n") song = [int(t) for t in lines[1].split()] q = int(lines[2]) out = [] for i in range(q): nums = [int(t) for t in lines[3 + i].split()] out.append(judge(song, nums[1:])) print("\n".join(out))main()
JavaScriptmain.js · 22 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const song = lines[1].trim().split(/\s+/).map(Number);const q = Number(lines[2]);function judge(frag) { const n = song.length, m = frag.length; const starts = []; // 배열끼리 ===는 같은 배열인지를 본다: 자리마다 every로 하나씩 비교한다 for (let i = 0; i + m <= n; i++) { if (frag.every((x, j) => song[i + j] === x)) starts.push(i + 1); } if (starts.length > 0) return `found ${starts.length} ${starts[0]}`; const absent = frag.find((x) => !song.includes(x)); return absent === undefined ? "scattered" : `missing ${absent}`;}const out = [];for (let i = 0; i < q; i++) { const [, ...frag] = lines[3 + i].trim().split(/\s+/).map(Number); out.push(judge(frag));}console.log(out.join("\n"));
TypeScriptmain.ts · 24 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const song: number[] = lines[1].trim().split(/\s+/).map(Number);const q: number = Number(lines[2]);function judge(frag: number[]): string { const n = song.length, m = frag.length; const starts: number[] = []; // 배열끼리 ===는 같은 배열인지를 본다: 자리마다 every로 하나씩 비교한다 for (let i = 0; i + m <= n; i++) { if (frag.every((x, j) => song[i + j] === x)) starts.push(i + 1); } if (starts.length > 0) return `found ${starts.length} ${starts[0]}`; const absent: number | undefined = frag.find((x) => !song.includes(x)); return absent === undefined ? "scattered" : `missing ${absent}`;}const out: string[] = [];for (let i = 0; i < q; i++) { const frag: number[] = lines[3 + i].trim().split(/\s+/).map(Number).slice(1); out.push(judge(frag));}console.log(out.join("\n"));
JavaMain.java · 42 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;public class Main { static List<Integer> toList(String line, int skip) { String[] parts = line.trim().split("\\s+"); List<Integer> list = new ArrayList<>(); for (int i = skip; i < parts.length; i++) list.add(Integer.parseInt(parts[i])); return list; } static String judge(List<Integer> song, List<Integer> frag) { int n = song.size(), m = frag.size(); int count = 0, first = 0; for (int i = 0; i + m <= n; i++) { // List의 equals는 내용을 차례대로 비교한다 (==는 같은 객체인지만 본다) if (song.subList(i, i + m).equals(frag)) { if (count == 0) first = i + 1; count++; } } if (count > 0) return "found " + count + " " + first; for (int x : frag) { if (!song.contains(x)) return "missing " + x; } return "scattered"; } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); br.readLine(); List<Integer> song = toList(br.readLine(), 0); int q = Integer.parseInt(br.readLine().trim()); StringBuilder out = new StringBuilder(); for (int i = 0; i < q; i++) { out.append(judge(song, toList(br.readLine(), 1))).append('\n'); } System.out.print(out); }}
C#Main.cs · 42 lines
using System;using System.Collections.Generic;using System.Linq;using System.Text;class Program{ static string Judge(List<int> song, List<int> frag) { int n = song.Count, m = frag.Count; int count = 0, first = 0; for (int i = 0; i + m <= n; i++) { // List끼리 ==는 같은 객체인지를 본다: GetRange로 잘라 SequenceEqual로 내용을 비교한다 if (song.GetRange(i, m).SequenceEqual(frag)) { if (count == 0) first = i + 1; count++; } } if (count > 0) return $"found {count} {first}"; foreach (int x in frag) { if (!song.Contains(x)) return $"missing {x}"; } return "scattered"; } static void Main() { Console.ReadLine(); List<int> song = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(); int q = int.Parse(Console.ReadLine()); var out_ = new StringBuilder(); for (int i = 0; i < q; i++) { List<int> frag = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Skip(1).Select(int.Parse).ToList(); out_.Append(Judge(song, frag)).Append('\n'); } Console.Write(out_); }}
C++main.cpp · 37 lines
#include <algorithm>#include <iostream>#include <string>#include <vector>std::string judge(const std::vector<int>& song, const std::vector<int>& frag) { int count = 0; long first = 0; // std::search는 이어진 차례를 찾는다. 찾은 자리 바로 다음부터 다시 찾으면 겹친 것도 센다 auto it = std::search(song.begin(), song.end(), frag.begin(), frag.end()); while (it != song.end()) { if (count == 0) first = it - song.begin() + 1; count++; it = std::search(it + 1, song.end(), frag.begin(), frag.end()); } if (count > 0) return "found " + std::to_string(count) + " " + std::to_string(first); for (int x : frag) { if (std::find(song.begin(), song.end(), x) == song.end()) return "missing " + std::to_string(x); } return "scattered";}int main() { int n, q; std::cin >> n; std::vector<int> song(n); for (int& x : song) std::cin >> x; std::cin >> q; while (q--) { int m; std::cin >> m; std::vector<int> frag(m); for (int& x : frag) std::cin >> x; std::cout << judge(song, frag) << '\n'; } return 0;}
Cmain.c · 45 lines
#include <stdio.h>#include <string.h>static int song[1000], frag[20];/* 배열 a의 앞 len칸에 x가 있는지 하나씩 본다 */static int contains(const int *a, int len, int x) { for (int i = 0; i < len; i++) if (a[i] == x) return 1; return 0;}int main(void) { int n, q; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &song[i]); scanf("%d", &q); while (q--) { int m; scanf("%d", &m); for (int j = 0; j < m; j++) scanf("%d", &frag[j]); int count = 0, first = 0; for (int i = 0; i + m <= n; i++) { /* memcmp는 바이트 수를 받는다: int m개면 m * sizeof(int) */ if (memcmp(song + i, frag, m * sizeof(int)) == 0) { if (count == 0) first = i + 1; count++; } } if (count > 0) { printf("found %d %d\n", count, first); continue; } int absent = 0; for (int j = 0; j < m; j++) { if (!contains(song, n, frag[j])) { absent = frag[j]; break; } } if (absent) printf("missing %d\n", absent); else printf("scattered\n"); } return 0;}
Craykonmain.cray · 60 lines
// 줄을 나눠 수 목록으로 만든다. 앞의 skip개는 뺀다toNums(line, skip){ nums = []; parts = line.Split(); for (i = skip; i < parts.Count; i++) { nums.Add(parts[i].ToNumber()); } return nums;}judge(song, frag){ n = song.Count; m = frag.Count; count = 0; first = 0; // song.있나(frag)는 frag와 같은 '음 하나'를 찾는다: 자리마다 하나씩 비교한다 for (i = 0; i + m <= n; i++) { same = true; for (j = 0; j < m; j++) { if (song[i + j] != frag[j]) { same = false; break; } } if (same) { if (count == 0) { first = i + 1; } count++; } } if (count > 0) { return "found " + count + " " + first; } foreach (x in frag) { if (!song.Contains(x)) { return "missing " + x; } } return "scattered";}Console.ReadLine();song = toNums(Console.ReadLine(), 0);q = Console.ReadLine().ToNumber();for (k = 0; k < q; k++){ Console.WriteLine(judge(song, toNums(Console.ReadLine(), 1)));}