CodeForces - 459E - Pashmak and Graph

先上題目:ios

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.c++

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.ide

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

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 ui to vertex vi.ui

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

Output

Print a single integer — the answer to the problem.spa

Sample test(s)
input
3 3
1 2 1
2 3 1
3 1 1
output
1
input
3 3
1 2 1
2 3 2
3 1 3
output
3
input
6 7
1 2 1
3 2 5
2 4 2
2 5 2
2 6 9
5 4 3
4 3 4
output
6
Note

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

In the second sample the maximum trail is .orm

In the third sample the maximum trail is .blog

 

  題意:給你一個有向圖,問你最長的路徑有多長,這條最長路徑須要知足每一小段都要比前面的那一小段嚴格大。

  作法:通過分析,咱們能夠發現須要先貪心一下,先從權值比較小的邊開始計算,而後再進行dp,轉移方程是dp[v]=max(dp[u]+1,dp[v]),u是起點,v是終點,dp[k]保存以k爲終點的路徑的最長長度。這裏須要處理一下權值相等的狀況保證他們不會干擾就能夠了。這裏用的方法是借鑑別人的代碼的,對於長度相同的邊,咱們先記錄下排除長度長度相同的邊得等到的最大值,而後在賦值給dp[k]。

 

上代碼:

 

 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 }
/*459E*/
相關文章
相關標籤/搜索