题意:寻找路线中出现次数最多的字母个数;
判断是否有回路,如果有回路就可以无限循环就直接输出-1,如果没有回路,则可以用dfs或者拓扑排序解决
dfs:
#include<bits/stdc++.h>
using namespace std;
const int MAX = 3e5 + 7;
vector<int > v[MAX];
char s[MAX];
int vis[MAX], a[MAX][26], ans = 0;
bool dfs(int x)
{
vis[x] = -1;
for(int i = 0; i != v[x].size(); i++)
{
if(!vis[v[x][i]] && !dfs(v[x][i]) || vis[v[x][i]] == -1)
return 0;
for(int j = 0; j < 26; j++)
a[x][j] = max(a[x][j], a[v[x][i]][j]);
}
ans = max(ans, ++a[x][s[x] - 'a']);
return vis[x] = 1;
}
int main()
{
int n, m;
cin >> n >> m >> s + 1;
for(int i = 0, xx, yy; i < m; i++)
{
cin >> xx >> yy;
v[xx].push_back(yy);
}
for(int i = 1; i <= n; i++)
if(!vis[i] && !dfs(i))
{
cout << "-1" << endl;
return 0;
}
cout << ans << endl;
return 0;
}
拓扑排序:
#include<bits/stdc++.h>
using namespace std;
const int MAX = 3e5 + 7;
char s[MAX];
int a[MAX][26], let[MAX], pre[MAX];
vector<int > v[MAX];
int main()
{
int n, m, num = 0, ans = -MAX;
cin >> n >> m >> s + 1;
for(int i = 1; i <= n; i++)
let[i] = s[i] - 'a';
for(int i = 0, x, y; i < m; i++)
{
cin >> x >> y;
v[x].push_back(y);
pre[y]++;
}
queue<int >q;
for(int i = 1; i <= n; i++)
{
if(!pre[i])
{
q.push(i);
a[i][let[i]] = 1;
num++;
}
}
while(!q.empty())
{
int f = q.front();
q.pop();
for(int i = 0; i < v[f].size(); i++)
{
int u = v[f][i];
for(int j = 0; j < 26; j++)
a[u][j] = max(a[u][j], a[f][j] + (let[u] == j));
pre[u]--;
if(!pre[u])
{
q.push(u);
num++;
}
}
}
if(num != n)
return cout << "-1" << endl, 0;
for(int i = 1; i <= n; i++)
for(int j = 0; j < 26; j++)
ans = max(ans, a[i][j]);
cout << ans << endl;
}