You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
一、题意
二、思路
三、代码
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <utility>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int MAXN = 300300;
const int MOD7 = 1e9 + 7;
const int MOD9 = 1e9 + 9;
const int INF = 2e9;
const double EPS = 1e-6;
const double PI = 3.14159265358979;
const int dir_4r[] = { -1, 1, 0, 0 };
const int dir_4c[] = { 0, 0, -1, 1 };
const int dir_8r[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
const int dir_8c[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
struct Node {
char ch;//该结点的值
int val[26];//到达该结点时某个字母出现的最大次数
};
Node node[MAXN];
vector<int> mat[MAXN];
int inDegree[MAXN];
char ch[MAXN];
queue<int> que;//队列存储入度为零的结点
int main() {
int n, m, x, y;
scanf("%d%d", &n, &m);
scanf("%s", ch);
for (int i = 0; i < n; ++i) {
node[i].ch = ch[i] - 'a';
node[i].val[node[i].ch] = 1;
inDegree[i] = 0;
}
for (int i = 0; i < m; ++i) {
scanf("%d%d", &x, &y);
x--;
y--;
mat[x].push_back(y);
inDegree[y]++;
}
for (int i = 0; i < n; ++i) {
if (inDegree[i] == 0) {
que.push(i);
inDegree[i]--;//防止多次入队
}
}
int counter = 0;
while (!que.empty()) {
int cur = que.front();
que.pop();
counter++;
for (int i = 0; i < mat[cur].size(); ++i) {
int nxt = mat[cur][i];
for (int j = 0; j < 26; ++j) {
if (j == node[nxt].ch)
node[nxt].val[j] = max(node[nxt].val[j], node[cur].val[j] + 1);
else
node[nxt].val[j] = max(node[nxt].val[j], node[cur].val[j]);
}
inDegree[nxt]--;
if (inDegree[nxt] == 0)
que.push(nxt);
}
}
int ans = 0;
if (counter != n) {
ans = -1;
} else {
for (int i = 0; i < n; ++i)
for (int j = 0; j < 26; ++j)
ans = max(ans, node[i].val[j]);
}
cout << ans << endl;
//system("pause");
return 0;
}