codeforces Round #261(div2) E解题报告

来源:互联网 发布:淄博网站搜索优化 编辑:程序博客网 时间:2024/06/04 19:27

E. Pashmak and Graph
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.

You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.

Help Pashmak, print the number of edges in the required path.

Input

The first line contains two integers nm (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: uiviwi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex uito vertex vi.

It's guaranteed that the graph doesn't contain self-loops and multiple edges.

Output

Print a single integer — the answer to the problem.

Sample test(s)
input
3 31 2 12 3 13 1 1
output
1
input
3 31 2 12 3 23 1 3
output
3
input
6 71 2 13 2 52 4 22 5 22 6 95 4 34 3 4
output
6
Note

In the first sample the maximum trail can be any of this trails: .

In the second sample the maximum trail is .

In the third sample the maximum trail is .

题目大意:

给出一张DAG图,每条边都有权值wi,要求求出一条最长路径,并且每条该路径上,权值严格单调递增。

解法:

由于要求每条边权值严格单调递增,我们就可以先把权值排序。然后逐个逐个放入图中,并计算出每个点的最大值dp[v]。

注意一种情况,这种排序会有很多权值一样的边在某一段操作中中出现,由于要求是严格单调的,所以我们得弄出一个缓冲数组,避免出现类似样例2的情况。

代码:

#include <cstdio>#include <vector>#include <algorithm>#include <cstring>#define M_max 3*123456#define N_max 3*123456using namespace std;struct typ1{int u, v, w;}line[M_max];int n, m, f[N_max], ans, dp[N_max];bool use[N_max];bool cmp(typ1 a, typ1 b) {if (a.w < b.w)return true;elsereturn false;}void init() {scanf("%d%d", &n, &m);for (int i = 1; i <= m; i++)scanf("%d%d%d", &line[i].u, &line[i].v, &line[i].w);sort(line+1, line+m+1, cmp);}void solve() {for (int i = 1; i <= m; i++) {int u = line[i].u, v = line[i].v, w = line[i].w;if (f[v] < dp[v])  f[v] = dp[v];if (f[v] < dp[u]+1)  f[v] = dp[u]+1;ans = max(f[v], ans);if (w != line[i+1].w)for (int j = i; j >= 1; j--) {dp[line[j].v] = f[line[j].v];if (line[j].w != line[j-1].w)  break;}}printf("%d\n", ans);}int main() {init();solve();}

0 0
原创粉丝点击