CodeForces - 459E - Pashmak and Graph
先上题目:
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 .
题意:给你一个有向图,问你最长的路径有多长,这条最长路径需要满足每一小段都要比前面的那一小段严格大。
做法:经过分析,我们可以发现需要先贪心一下,先从权值比较小的边开始计算,然后再进行dp,转移方程是dp[v]=max(dp[u]+1,dp[v]),u是起点,v是终点,dp[k]保存以k为终点的路径的最长长度。这里需要处理一下权值相等的情况保证他们不会干扰就可以了。这里用的方法是借鉴别人的代码的,对于长度相同的边,我们先记录下排除长度长度相同的边得等到的最大值,然后在赋值给dp[k]。
上代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <bits/stdc++.h> 2 #define MAX 300002 3 #define ll long long 4 using namespace std; 5 6 typedef struct edge{ 7 ll u,v,w; 8 9 bool operator < (const edge& o)const{ 10 return w<o.w; 11 } 12 }edge; 13 edge e[MAX]; 14 int n,m,maxn; 15 int dp[MAX],f[MAX]; 16 17 int main() 18 { 19 //freopen("data.txt","r",stdin); 20 ios::sync_with_stdio(false); 21 while(cin>>n>>m){ 22 memset(dp,0,sizeof(dp)); 23 memset(f,0,sizeof(f)); 24 for(int i=0;i<m;i++){ 25 cin>>e[i].u>>e[i].v>>e[i].w; 26 } 27 sort(e,e+m); 28 maxn=0; 29 for(int i=0;i<m;i++){ 30 int j; 31 for(j=i;j<m;j++) if(e[i].w!=e[j].w) break; 32 for(int k=i;k<j;k++){ 33 f[e[k].v]=max(dp[e[k].u]+1,f[e[k].v]); 34 } 35 for(int k=i;k<j;k++){ 36 dp[e[k].v]=max(f[e[k].v],dp[e[k].v]); 37 } 38 i=j-1; 39 } 40 for(int i=1;i<=n;i++) maxn=max(dp[i],maxn); 41 cout<<maxn<<endl; 42 } 43 return 0; 44 }