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.
The first line contains two integers n, m (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: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi.
It's guaranteed that the graph doesn't contain self-loops and multiple edges.
Print a single integer — the answer to the problem.
3 3 1 2 1 2 3 1 3 1 1
1
3 3 1 2 1 2 3 2 3 1 3
3
6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4
6
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 .
题目大意:
给你N个点,M条有向边,让你找到一条路径使得从起点到终点的路径上经过点边的权值是按照严格递增趋势的。
使得这条路径最长,问你最长会是多少。
思路:
我们首先对边权值按照从小到大排序,然后我们对于同一大小的权值边一起进行dp.
设定dp【i】表示到点i的最长路径长度。
那么有:dp【v】=max(dp【v】,pre【u】+1);
然后对pre【i】进行集体更新。
如果我们暴力更新的话,时间复杂度最高可以达到O(n*m);
那么我们考虑只对更新了的部分进行更新即可。
具体过程参考代码。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
int u,v,w;
}a[350000];
int cmp(node a,node b)
{
return a.w<b.w;
}
int pre[3500000];
int dp[350000];
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
memset(pre,0,sizeof(pre));
memset(dp,0,sizeof(dp));
for(int i=0;i<m;i++)scanf("%d%d%d",&a[i].u,&a[i].v,&a[i].w);
sort(a,a+m,cmp);
for(int i=0;i<m;i++)
{
queue<int>s;
int end=i;
while(end<m&&a[end].w==a[end+1].w)end++;
for(int j=i;j<=end;j++)
{
int tmp=dp[a[j].v];
dp[a[j].v]=max(pre[a[j].u]+1,dp[a[j].v]);
if(tmp!=dp[a[j].v])s.push(a[j].v);
}
while(!s.empty())
{
int u=s.front();
s.pop();
pre[u]=max(pre[u],dp[u]);
dp[u]=0;
}
i=end;
}
int output=0;
for(int i=1;i<=n;i++)output=max(output,pre[i]);
printf("%d\n",output);
}
}