{ }codelper
用字典计数双指针P0434

连续播放的 k 首歌中只出现一次的歌

一家广播电台按播放顺序记录了一天里播放的 n 首歌的名字。
输入第一行给出 n 和 k,用一个空格分开。
输入第二行按播放顺序给出 n 个歌名,用一个空格分开。
歌名是由小写英文字母(a~z)组成的 1~12 个字符的字符串,名字相同就是同一首歌。
把连续播放的 k 首歌看作一个区间。
区间依次是第 1~k 首、第 2~(k+1) 首、…、第 (n−k+1)~n 首,一共 n−k+1 个。
对每个区间,求在该区间内恰好只出现一次的歌有几首。
如果区间内的歌都出现了两次或以上,该区间的值为 0。
按区间顺序把 n−k+1 个数输出在一行,用一个空格分开。

输入
1 ≤ k ≤ n ≤ 9,000,歌名由小写字母(a~z)组成,1~12 个字符
输出
每个区间内恰好只出现一次的歌的数量,按区间顺序在一行输出 n−k+1 个,用一个空格分开
样例 1 · stdin
7 3
rain sun rain moon moon sun rain
stdout
1 3 1 1 3
样例 2 · stdin
4 3
constructor apple constructor pie
stdout
1 3
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

这道题是拿着一个计数字典,把区间一格一格往后移。
不必每个区间从头重新数,只修改进来的歌和出去的歌的个数,同时修改“只出现一次的歌的数量”。
计数用 Python counts.get(song, 0) + 1,JS/TS Map 的 (counts.get(s) ?? 0) + 1,Java getOrDefault(s, 0) + 1,C# GetValueOrDefault(s) + 1,C++ ++counts[s](不存在的键从 0 开始),Craykon 字典() 和 包含。
C 没有字典,所以用 qsort 把名字排序并去掉重复,用 bsearch 找到的位置作为歌的编号,在 int 数组里计数。
陷阱一:在 JS/TS 中不要用对象 {} 计数。
对象一开始就继承了 constructor 这样的名字,所以 counts["constructor"] || 0 是一个函数,加 1 后变成字符串 "function Object() { [native code] }1"。
样例 2 就是这种情况,会输出 1 2 而不是答案 1 3。
Map 只有你放进去的键。
陷阱二:个数变化的四种情况都要处理。
进来时 0→1,只出现一次的歌多一首;1→2,少一首。
出去时 1→0,少一首;2→1,这首歌重新变成只出现一次,多一首。
漏掉最后一种情况,样例 1 的第二个区间就会是 2 而不是 3。
陷阱三:很多语言读取不存在的键会停下。
Python counts[song] += 1 抛出 KeyError,Java counts.get(s) + 1 把 null 拆箱成 int 时抛出 NullPointerException,C# counts[s] 抛出 KeyNotFoundException,Craykon counts[song] 因键不存在的错误而停止。
只有 C++ counts[s] 会新放入一个 0。
陷阱四:区间的边界。
从 0 数起的第 i 首歌进来时,第 i − k 首歌要出去,区间才始终是 k 首。
如果从 i > k 时才开始移除,第一首歌永远不会出去,从第二个区间起每个区间都多一首(样例 1 会变成 1 2 …)。
每当 i ≥ k − 1 时输出一个数,一共 n − k + 1 个。

Pythonmain.py · 25 行
n, k = map(int, input().split())songs = input().split()counts = {}once = 0  # 지금 구간에서 딱 한 번 나온 곡의 수out = []for i, song in enumerate(songs):    # 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다    c = counts.get(song, 0) + 1    counts[song] = c    if c == 1:        once += 1    elif c == 2:        once -= 1    if i >= k:        # 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다        old = songs[i - k]        c = counts[old] - 1        counts[old] = c        if c == 1:            once += 1        elif c == 0:            once -= 1    if i >= k - 1:        out.append(once)print(" ".join(map(str, out)))
JavaScriptmain.js · 24 行
const [nk, line] = require("fs").readFileSync(0, "utf8").split("\n");const [n, k] = nk.trim().split(" ").map(Number);const songs = line.trim().split(" ");// 객체 {}는 "constructor" 같은 이름을 이미 갖고 있다. Map은 넣은 열쇠만 갖는다const counts = new Map();let once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수const out = [];for (let i = 0; i < n; i++) {  // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다  const c = (counts.get(songs[i]) ?? 0) + 1;  counts.set(songs[i], c);  if (c === 1) once++;  else if (c === 2) once--;  if (i >= k) {    // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다    const old = songs[i - k];    const d = counts.get(old) - 1;    counts.set(old, d);    if (d === 1) once++;    else if (d === 0) once--;  }  if (i >= k - 1) out.push(once);}console.log(out.join(" "));
TypeScriptmain.ts · 25 行
import { readFileSync } from "node:fs";const [nk, line] = readFileSync(0, "utf8").split("\n");const [n, k] = nk.trim().split(" ").map(Number);const songs: string[] = line.trim().split(" ");// 객체 {}는 "constructor" 같은 이름을 이미 갖고 있다. Map은 넣은 열쇠만 갖는다const counts = new Map<string, number>();let once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수const out: number[] = [];for (let i = 0; i < n; i++) {  // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다  const c = (counts.get(songs[i]) ?? 0) + 1;  counts.set(songs[i], c);  if (c === 1) once++;  else if (c === 2) once--;  if (i >= k) {    // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다    const old = songs[i - k];    const d = (counts.get(old) ?? 0) - 1;    counts.set(old, d);    if (d === 1) once++;    else if (d === 0) once--;  }  if (i >= k - 1) out.push(once);}console.log(out.join(" "));
JavaMain.java · 36 行
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.StringJoiner; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String[] nk = br.readLine().trim().split(" ");        int n = Integer.parseInt(nk[0]);        int k = Integer.parseInt(nk[1]);        String[] songs = br.readLine().trim().split(" ");        // get은 없는 열쇠에 null을 돌려준다. getOrDefault로 0을 받는다        Map<String, Integer> counts = new HashMap<>();        int once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수        StringJoiner out = new StringJoiner(" ");        for (int i = 0; i < n; i++) {            // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다            int c = counts.getOrDefault(songs[i], 0) + 1;            counts.put(songs[i], c);            if (c == 1) once++;            else if (c == 2) once--;            if (i >= k) {                // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다                String old = songs[i - k];                int d = counts.get(old) - 1;                counts.put(old, d);                if (d == 1) once++;                else if (d == 0) once--;            }            if (i >= k - 1) out.add(Integer.toString(once));        }        System.out.println(out);    }}
C#Main.cs · 36 行
using System;using System.Collections.Generic; class Program{    static void Main()    {        string[] nk = Console.ReadLine().Trim().Split(' ');        int n = int.Parse(nk[0]);        int k = int.Parse(nk[1]);        string[] songs = Console.ReadLine().Trim().Split(' ');        // counts[없는 열쇠]를 읽으면 KeyNotFoundException이 난다. GetValueOrDefault는 0을 준다        var counts = new Dictionary<string, int>();        int once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수        var outList = new List<int>();        for (int i = 0; i < n; i++)        {            // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다            int c = counts.GetValueOrDefault(songs[i]) + 1;            counts[songs[i]] = c;            if (c == 1) once++;            else if (c == 2) once--;            if (i >= k)            {                // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다                string old = songs[i - k];                int d = counts[old] - 1;                counts[old] = d;                if (d == 1) once++;                else if (d == 0) once--;            }            if (i >= k - 1) outList.Add(once);        }        Console.WriteLine(string.Join(" ", outList));    }}
C++main.cpp · 29 行
#include <iostream>#include <string>#include <unordered_map>#include <vector> int main() {    std::ios::sync_with_stdio(false);    int n, k;    std::cin >> n >> k;    std::vector<std::string> songs(n);    for (auto& s : songs) std::cin >> s;    // counts[없는 열쇠]는 0으로 새로 생긴다    std::unordered_map<std::string, int> counts;    int once = 0;  // 지금 구간에서 딱 한 번 나온 곡의 수    for (int i = 0; i < n; i++) {        // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다        int c = ++counts[songs[i]];        if (c == 1) once++;        else if (c == 2) once--;        if (i >= k) {            // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다            int d = --counts[songs[i - k]];            if (d == 1) once++;            else if (d == 0) once--;        }        if (i >= k - 1) std::cout << (i >= k ? " " : "") << once;    }    std::cout << "\n";}
Cmain.c · 53 行
#include <stdio.h>#include <stdlib.h>#include <string.h> /* C에는 사전이 없다. 이름을 정렬해 겹친 것을 지우고, 이분 탐색으로 찾은 자리를 곡 번호로 쓴다 */#define MAXN 9000#define LEN 13 static char songs[MAXN][LEN];static char names[MAXN][LEN];static int id[MAXN];static int counts[MAXN]; static int cmp(const void* a, const void* b) {    return strcmp((const char*)a, (const char*)b);} int main(void) {    int n, k;    scanf("%d %d", &n, &k);    for (int i = 0; i < n; i++) {        scanf("%12s", songs[i]);        strcpy(names[i], songs[i]);    }    qsort(names, n, LEN, cmp);    int kinds = 0;    for (int i = 0; i < n; i++) {        if (kinds == 0 || strcmp(names[kinds - 1], names[i]) != 0) {            if (kinds != i) strcpy(names[kinds], names[i]);            kinds++;        }    }    for (int i = 0; i < n; i++) {        char* p = bsearch(songs[i], names, kinds, LEN, cmp);        id[i] = (int)((p - names[0]) / LEN);    }    int once = 0; /* 지금 구간에서 딱 한 번 나온 곡의 수 */    for (int i = 0; i < n; i++) {        /* 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다 */        int c = ++counts[id[i]];        if (c == 1) once++;        else if (c == 2) once--;        if (i >= k) {            /* 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다 */            int d = --counts[id[i - k]];            if (d == 1) once++;            else if (d == 0) once--;        }        if (i >= k - 1) printf(i >= k ? " %d" : "%d", once);    }    printf("\n");    return 0;}
Craykonmain.cray · 45 行
첫줄 = 控制台.读行().去空白().分割(" ");n = 첫줄[0].转数字();k = 첫줄[1].转数字();songs = 控制台.读行().去空白().分割(" ");// 사전에 없는 열쇠를 읽으면 멈춘다. 있나로 먼저 확인한다counts = 字典();once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수out = [];循环 (i = 0; i < n; i = i + 1){    song = songs[i];    如果 (!counts.包含(song))    {        counts[song] = 0;    }    // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다    counts[song] = counts[song] + 1;    如果 (counts[song] == 1)    {        once = once + 1;    }    否则 如果 (counts[song] == 2)    {        once = once - 1;    }    如果 (i >= k)    {        // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다        old = songs[i - k];        counts[old] = counts[old] - 1;        如果 (counts[old] == 1)        {            once = once + 1;        }        否则 如果 (counts[old] == 0)        {            once = once - 1;        }    }    如果 (i >= k - 1)    {        out.添加(once);    }}控制台.输出(out.连接(" "));