1. 程式人生 > >51nod 1274 最長遞增路徑(DP)

51nod 1274 最長遞增路徑(DP)

string lose 自己 ring mat pri color 16px eve

  一開始自己想了一種跑的巨慢。。寫了題解的做法又跑的巨快。。一臉懵逼

  顯然要求邊權遞增就不可能經過重復的邊了,那麽設f[i]為第i條邊出發能走多遠就好了,這是我一開始的寫法,可能dfs冗余狀態較多,跑的極慢

技術分享
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<map>
#define
ll long long using namespace std; const int maxn=500010,inf=1e9; struct poi{int too,dis,pre;}e[maxn]; int n,m,x,y,z,tot,ans; int last[maxn],dp[maxn]; void read(int &k) { int f=1;k=0;char c=getchar(); while(c<0||c>9)c==-&&(f=-1),c=getchar(); while(c<=9&&c>=
0)k=k*10+c-0,c=getchar(); k*=f; } void add(int x,int y,int z){e[++tot].too=y;e[tot].dis=z;e[tot].pre=last[x];last[x]=tot;} int dfs(int x,int fa) { if(dp[x])return dp[x];dp[x]=1; for(int i=last[e[x].too];i;i=e[i].pre) if(i!=fa&&e[i].dis>e[x].dis)dfs(i,x),dp[x]=max(dp[x],dp[i]+1
); return dp[x]; } int main() { read(n);read(m); for(int i=1;i<=m;i++)read(x),read(y),read(z),add(x,y,z),add(y,x,z); for(int i=1;i<=tot;i++)if(!dp[i])dfs(i,0); for(int i=1;i<=tot;i++)ans=max(ans,dp[i]); printf("%d\n",ans); return 0; }
View Code

  題解的做法是按照邊權排序,然後就可以用點來轉移了...

  (然後就踩在yyl頭上了

技術分享
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<map>
#define ll long long 
using namespace std;
const int maxn=500010,inf=1e9;
struct poi{int x,too,dis;}e[maxn];
int n,m,x,y,z,ans,last;
int g[maxn],f[maxn];
void read(int &k)
{
    int f=1;k=0;char c=getchar();
    while(c<0||c>9)c==-&&(f=-1),c=getchar();
    while(c<=9&&c>=0)k=k*10+c-0,c=getchar();
    k*=f;
}
bool cmp(poi a,poi b){return a.dis<b.dis;}
int main()
{
    read(n);read(m);
    for(int i=1;i<=m;i++)read(x),read(y),read(z),e[i].x=x,e[i].too=y,e[i].dis=z;
    sort(e+1,e+1+m,cmp);last=1;
    for(int i=1;i<=m;i++)
    if(i==m||e[i].dis<e[i+1].dis)
    {
        for(int j=last;j<=i;j++)
        g[e[j].too]=f[e[j].too],g[e[j].x]=f[e[j].x];
        for(int j=last;j<=i;j++)
        f[e[j].too]=max(f[e[j].too],g[e[j].x]+1),f[e[j].x]=max(f[e[j].x],g[e[j].too]+1);
        last=i+1;
    }
    for(int i=0;i<n;i++)ans=max(ans,f[i]);
    printf("%d\n",ans);
    return 0;
}
View Code

51nod 1274 最長遞增路徑(DP)