919D - Substring - CodeForces Solution


dfs and similar dp graphs *1700

Please click on ads to support us..

Python Code:

import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def topological_sort():
    q, k = [], 0
    cnt = [0] * (n + 1)
    for i in range(1, n + 1):
        for j in G[i]:
            cnt[j] += 1
    for i in range(1, n + 1):
        if not cnt[i]:
            q.append(i)
    while len(q) ^ k:
        i = q[k]
        for j in G[i]:
            cnt[j] -= 1
            if not cnt[j]:
                q.append(j)
        k += 1
    return q

def f(u, v):
    return u * 26 + v

n, m = map(int, input().split())
s = [0] + list(input().rstrip())
G = [[] for _ in range(n + 1)]
for _ in range(m):
    x, y = map(int, input().split())
    G[x].append(y)
g = topological_sort()
if len(g) ^ n:
    ans = -1
    print(ans)
    exit()
dp = [0] * (26 * (n + 1))
for i in g:
    dp[f(i, s[i] - 97)] += 1
    for j in range(26):
        dp0 = dp[f(i, j)]
        for k in G[i]:
            u = f(k, j)
            dp[u] = max(dp[u], dp0)
ans = max(dp)
print(ans)

C++ Code:

#include <bits/stdc++.h>
#define N 300010
using namespace std;

struct Edge{
	int from, to, next;
} edge[N];

int head[N], tot;

inline void addedge(int u, int v){
	edge[++tot] = (Edge){u, v, head[u]}, head[u] = tot;
}

int f[N][26], n, m, d[N];
char s[N];
queue<int> Q;

int main(){
	scanf("%d%d", &n, &m);
	scanf("%s", s + 1);
	for (int i = 1; i <= m; i++){
		int x, y;
		scanf("%d%d", &x, &y);
		addedge(x, y);
		d[y] ++;
	}
	
	for (int i = 1; i <= n; i++){
		if (!d[i]){
			Q.push(i);
			f[i][s[i] - 'a'] = 1;
		}
	}
	
	int rem = n;
	while (!Q.empty()){
		int now = Q.front();
		Q.pop();
		rem --;
		for (int i = head[now]; i; i = edge[i].next){
			Edge e = edge[i];
			for (int j = 0; j < 26; j++){
				f[e.to][j] = max(f[e.to][j], f[now][j] + (s[e.to] - 'a' == j));
			}
			d[e.to] --;
			if (!d[e.to]) Q.push(e.to);
		}
	}
	
	if (rem) return puts("-1"), 0;
	
	int ans = 0;
	for (int i = 1; i <= n; i++){
		for (int j = 0; j < 26; j++){
			ans = max(ans, f[i][j]);
		}
	}
	
	printf("%d\n", ans);
	return 0;
}


Comments

Submit
0 Comments
More Questions

1674E - Breaking the Wall
1282A - Temporarily unavailable
1366C - Palindromic Paths
336A - Vasily the Bear and Triangle
926A - 2-3-numbers
276D - Little Girl and Maximum XOR
1253C - Sweets Eating
1047A - Little C Loves 3 I
758D - Ability To Convert
733A - Grasshopper And the String
216A - Tiling with Hexagons
1351B - Square
1225A - Forgetting Things
1717A - Madoka and Strange Thoughts
1717B - Madoka and Underground Competitions
61B - Hard Work
959B - Mahmoud and Ehab and the message
802G - Fake News (easy)
1717C - Madoka and Formal Statement
420A - Start Up
1031A - Golden Plate
1559C - Mocha and Hiking
427B - Prison Transfer
330A - Cakeminator
426A - Sereja and Mugs
363A - Soroban
1585C - Minimize Distance
1506E - Restoring the Permutation
1539A - Contest Start
363D - Renting Bikes