Cod sursa(job #3331910)

Utilizator TimofeiFilipTimofei Filip Emanuel TimofeiFilip Data 1 ianuarie 2026 17:21:53
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include<bits/stdc++.h>
using namespace std;

const int NMAX = 5e5 + 5;

struct node {
    int length_max, position;
    node(int l, int p) {
        this->length_max = l;
        this->position = p;
    }
};
struct Compare {
    bool operator()(node const &a, node const &b) {
        return a.length_max < b.length_max;
    }
};
priority_queue<node, vector<node>, Compare> best[27];

int dyn[NMAX];

int main() {
    freopen("raci.in", "r", stdin);
    freopen("raci.out", "w", stdout);

    int n, k;

    scanf("%d %d", &n, &k);

    for (int i = 1; i <= n; i++) {
        char word[11];
        cin>>word;
        int first_letter = word[0] - 'a';
        int last_letter = word[strlen(word) - 1] - 'a';

        while((!best[first_letter].empty()) && (i - best[first_letter].top().position > k))
            best[first_letter].pop();
        if (!best[first_letter].empty())
            dyn[i] = best[first_letter].top().length_max + 1;
        else
            dyn[i] = 1;
        best[last_letter].push(node(dyn[i], i));

    }
    int lmax = 0;

    for (int i = 1; i <= n; i++) {
        lmax = max(lmax, dyn[i]);
    }
    printf("%d", lmax);

    return 0;
}