#include<bits/stdc++.h>
using namespace std;
const int N = 3e5+10, M = 3e5+10;
int h[N], ne[M], e[M],idx,d[N];
char w[N];
int n,m;
//f[N]用来存储每个
int dist[N],g[N];
void add(int a, int b) // 添加一条边a->b,边权为c
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
bool topsort(){
queue<int> queue;
int cnt = 0;
for(int i = 1; i <= n; i++){
if(d[i] == 0){
queue.push(i);
}
}
while (!queue.empty()){
auto x = queue.front();
queue.pop();
g[cnt++] = x;
for(auto u = h[x];~u; u = ne[u]){
int tmp = e[u];
if(! --d[tmp]){
queue.push(tmp);
}
}
}
if(cnt != n ){
return false;
}
return true;
}
int main()
{
scanf("%d%d",&n,&m);
memset(h,-1,sizeof h);
scanf("%s",w+1);
while(m--){
int a,b;
scanf("%d%d", &a, &b);
add(a,b);
++d[b];
}
bool flag = topsort();
if(!flag){
puts("-1");
}else{
int res = 0;
for(char c = 'a'; c <= 'z'; c++){
for(int i = n-1; i >= 0; i--){
int t = g[i];
//w[t] == c的话表示权值是1
int v = w[t] == c;
dist[t] = v;
for(int j = h[t]; ~j; j = ne[j]){
int k = e[j];
dist[t] = max(dist[t],v + dist[k]);
}
res = max(res,dist[t]);
}
}
cout << res <<endl;
return 0;
}
}
topsort求最长路
#include <bits/stdc++.h>
using namespace std;
const int N = 100, M = 10000;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
bool st[N];
int q[N], d[N];
int n, m;
int hh = 0, tt = -1;
void add(int a, int b, int c) // 添加一条边a->b,边权为c
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
bool topsort()
{
// d[i] 存储点i的入度
for (int i = 1; i <= n; i ++ )
if (!d[i])
q[ ++ tt] = i;
while (hh <= tt)
{
int t = q[hh ++ ];
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (-- d[j] == 0)
q[ ++ tt] = j;
}
}
// 如果所有点都入队了,说明存在拓扑序列;否则不存在拓扑序列。
return tt == n - 1;
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while(m -- ){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
d[b] ++ ;
}
topsort();
for(int i = 0; i < tt; i ++ ){
int x = q[i];
for(int j = h[x]; ~j; j = ne[j]){
int t = e[j];
dist[t] = max(dist[t], dist[x] + w[j]);
}
}
int res = 0;
for(int i = 1; i <= n; i ++ ){
res = max(res, dist[i]);
}
printf("%d", res);
return 0;
}