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.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Source
Codeforces Round #460 (Div. 2)
My Solution
题意:给出一个可能有环可能不连通的图,找出一个路径其上出现最多的字母出现的次数最大,求这个最大值。
BFS、拓扑排序、dp
这题与以前一个求最长路径的题差不多,这里定义状态dp[i][j]表示从某点开始跑到节点i时路径上出现字母j+'a'的最大次数。
只需要按照拓扑序跑一遍dp即可,
ch[v] != j, dp[v][j] = max(dp[v][j], dp[u][j]);
ch[v] != j, dp[v][j] = max(dp[v][j], dp[u][j] + 1);
最后如果度数不为0的点则有环,ans无穷大,置为-1.
否则 ans = max(ans, dp[i][j]).
时间复杂度 O(26*n)
空间复杂度 O(26*n)
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
typedef pair ii;
const int MAXN = 3e5 + 8;
const LL MOD = 142857;
string s;
LL ch[MAXN];
vector sons[MAXN];
int deg[MAXN];
LL dp[MAXN][26];
queue que;
inline void bfs()
{
int fa, u, v, sz, i, j;
while(!que.empty()){
u = que.front().first;
fa = que.front().second;
que.pop();
sz = sons[u].size();
for(i = 0; i > n >> m;
cin >> s;
for(i = 1; i <= n; i++){
ch[i] = s[i-1] - 'a';
}
for(i = 0; i > u >> v;
sons[u].push_back(v);
}
for(i = 1; i <= n; i++){
sz = sons[i].size();
for(j = 0; j
Thank you!
------from ProLights