【51nod 1274】 最長遞增路徑 (dp)
阿新 • • 發佈:2018-12-09
**題目來源: Codility 基準時間限制:1 秒 空間限制:131072 KB 分值: 80 難度:5級演算法題** 一個無向圖,可能有自環,有重邊,每條邊有一個邊權。你可以從任何點出發,任何點結束,可以經過同一個點任意次。但是不能經過同一條邊2次,並且你走過的路必須滿足所有邊的權值嚴格單調遞增,求最長能經過多少條邊。
以此圖為例,最長的路徑是: 3 -> 1 -> 2 -> 3 -> 2 或 3 -> 1 -> 2 -> 3 -> 4 長度為4。 Input 第1行:2個數N, M,N為節點的數量,M為邊的數量(1 <= N <= 50000, 0 <= M <= 50000)。節點編號為0 至 N - 1。 第2 - M + 1行:每行3個數S, E, W,表示從頂點S到頂點E,有一條權值為W的邊(0 <= S, E <= N - 1, 0 <= W <= 10^9)。 Output
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#define maxx 50005
#define maxn 50050
#define ll long long
#define mod 1000000007
#define INF 0x3f3f3f3f
using namespace std;
struct node
{
int x,y,w;
}edge[maxx];
bool cmp(node x1,node x2)
{
return x1.w<x2.w;
}
int dp[maxx];
int temp[maxx];
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++)
scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].w);
sort(edge,edge+m,cmp);
for (int i=0,last=0;i<m;i++)
{
if(i==m-1||edge[i].w<edge[i+1].w)
{
for(int j=last;j<=i;j++)
{
temp[edge[j].x]=dp[edge[j].x];
temp[edge[j].y]=dp[edge[j].y];
}
for(int j=last;j<=i;j++)
{
dp[edge[j].x]=max(dp[edge[j].x],temp[edge[j].y]+1);
dp[edge[j].y]=max(dp[edge[j].y],temp[edge[j].x]+1);
}
last=i+1;
}
}
int ans=0;
for(int i=0;i<m;i++)
ans=max(ans,dp[i]);
cout<<ans<<endl;
return 0;
}