zoukankan      html  css  js  c++  java
  • 51nod 1274 最长递增路径(DP)

      一开始自己想了一种跑的巨慢。。写了题解的做法又跑的巨快。。一脸懵逼

      显然要求边权递增就不可能经过重复的边了,那么设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
    ",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
    ",ans);
        return 0;
    }
    View Code
  • 相关阅读:
    【focus-lei 】微服务
    queryURLParams
    时间字符串的处理
    str.charAt()与str[]的区别
    数组去重函数封装
    数组去重的几种方法
    splice与slice区别
    变量与属性名的区别
    parseInt parseFloat Number三者转换的方式
    原生js实现选项卡样式切换的几种方式。
  • 原文地址:https://www.cnblogs.com/Sakits/p/7396184.html
Copyright © 2011-2022 走看看