题目链接:Codeforces 459E Pashmak and Graph
题目大意:给定一张有向图,每条边有它的权值,要求选定一条路线,保证所经过的边权值严格递增,输出最长路径。
解题思路:将边按照权值排序,每次将相同权值的边同时加入,维护每个点作为终止点的最大长度即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 3 * 1e5+5;
struct edge {
int u, v, w;
}s[maxn];
bool cmp (const edge& a, const edge& b) {
return a.w < b.w;
}
int n, m, d[maxn], f[maxn], val[maxn];
int main () {
scanf("%d%d", &n, &m);
memset(d, 0, sizeof(d));
memset(f, 0, sizeof(f));
memset(val, 0, sizeof(val));
for (int i = 0; i < m; i++)
scanf("%d%d%d", &s[i].u, &s[i].v, &s[i].w);
sort(s, s + m, cmp);
for (int i = 0; i < m; i++) {
int j;
for (j = i; s[j].w == s[i].w && j < m; j++);
for (int k = i; k < j; k++)
d[s[k].v] = max(d[s[k].v], f[s[k].u] + 1);
for (int k = i; k < j; k++)
f[s[k].v] = d[s[k].v];
i = j - 1;
}
int ans = 0;
for (int i = 1; i <= n; i++)
ans = max(ans, f[i]);
printf("%d\n", ans);
return 0;
}
Codeforces 459E Pashmak and Graph(dp+贪心)
时间: 2024-10-20 10:19:07