zoukankan      html  css  js  c++  java
  • AcWing 853. 有边数限制的最短路

    Bellman-Ford

    基于迭代思想的暴力,而非贪心

    // 853.有边数限制的最短路
    #include <iostream>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    const int N = 510;
    const int M = 10010;
    const int INF = 0x3f3f3f3f;
    int head[N],e[M],w[M],net[M],cnt;
    int n,m,k;
    int dis[N],temp[N];
    void init() {
        cnt=0;
        fill(head,head+N,0);
        return;
    }
    void addedge(int x, int y, int z) {
        ++cnt;
        e[cnt]=y;
        w[cnt]=z;
        net[cnt]=head[x];
        head[x]=cnt;
        return;
    }
    void bellmanford() {
        fill(dis,dis+N,INF);
        dis[1]=0;
        for(int i=1;i<=k;++i) {
            for(int x=1;x<=n;++x) temp[x]=dis[x];
            for(int x=1;x<=n;++x) {
                for(int p=head[x];p;p=net[p]) {
                    int y=e[p];
                    int z=w[p];
                    if(temp[x]!=INF&&dis[y]>temp[x]+z) {
                        dis[y]=temp[x]+z;
                    }
                }
            }
        }
        return;
    }
    int main() {
        #ifdef ONLINE_JUDGE
        #else
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
        #endif
        init();
        scanf("%d%d%d",&n,&m,&k);
        for(int i=0;i<m;++i) {
            int x,y,z;
            scanf("%d%d%d",&x,&y,&z);
            addedge(x,y,z);
        }
        bellmanford();
        if(dis[n]==INF) printf("impossible");
        else printf("%d",dis[n]);
        return 0;
    }
    
  • 相关阅读:
    windows照样命令行gcc/g++
    我的Linux(Ubuntu)首秀
    简单分频原理与实现——计数器
    时序分析之Arrival Time
    DDS正弦信号发生器
    C/C++ 预处理器
    时序分析之Slack
    iOS单例
    static
    深浅拷贝
  • 原文地址:https://www.cnblogs.com/lemonbiscuit/p/14586344.html
Copyright © 2011-2022 走看看