[POJ 3169] Layout

[题目链接]

        http://poj.org/problem?id=3169

[算法]

        差分约束系统

[代码]

        

#include <algorithm>  
#include <bitset>  
#include <cctype>  
#include <cerrno>  
#include <clocale>  
#include <cmath>  
#include <complex>  
#include <cstdio>  
#include <cstdlib>  
#include <cstring>  
#include <ctime>  
#include <deque>  
#include <exception>  
#include <fstream>  
#include <functional>  
#include <limits>  
#include <list>  
#include <map>  
#include <iomanip>  
#include <ios>  
#include <iosfwd>  
#include <iostream>  
#include <istream>  
#include <ostream>  
#include <queue>  
#include <set>  
#include <sstream>  
#include <stdexcept>  
#include <streambuf>  
#include <string>  
#include <utility>  
#include <vector>  
#include <cwchar>  
#include <cwctype>  
#include <stack>  
#include <limits.h>
using namespace std;
#define MAXN 1010
#define MAXM 20010
const int INF = 2e9;

struct edge
{
        int to,w,nxt;
} e[MAXM];

int i,n,ML,MD,a,b,l,tot;
int head[MAXN];

inline void addedge(int a,int b,int w)
{
        tot++;
        e[tot] = (edge){b,w,head[a]};
        head[a] = tot;
}
inline int spfa()
{
        int i,cur,v,w;
        static bool inq[MAXN];
        static int cnt[MAXN],dist[MAXN];
        queue< int > q;
        for (i = 1; i <= n; i++)
        {
                inq[i] = false;
                cnt[i] = 0;
                dist[i] = INF;
        }
        q.push(1);
        inq[1] = true;
        cnt[1] = 1;        
        dist[1] = 0;
        while (!q.empty())
        {
                cur = q.front();
                q.pop();
                inq[cur] = false;
                for (i = head[cur]; i; i = e[i].nxt)
                {
                        v = e[i].to;
                        w = e[i].w;
                        if (dist[cur] + w < dist[v])
                        {
                                dist[v] = dist[cur] + w;
                                if (!inq[v])
                                {
                                        q.push(v);
                                        inq[v] = true;
                                        cnt[v]++;
                                        if (cnt[v] > n) return -1;
                                }
                        }
                }
        }
        return dist[n] == INF ? -2 : dist[n]; 
}

int main() 
{
        
        scanf("%d%d%d",&n,&ML,&MD);
        for (i = 1; i <= ML; i++)
        {
                scanf("%d%d%d",&a,&b,&l);
                addedge(a,b,l);
        }
        for (i = 1; i <= MD; i++)
        {
                scanf("%d%d%d",&a,&b,&l);
                addedge(b,a,-l);
        }
        printf("%d
",spfa());
        
        return 0;
    
}
原文地址:https://www.cnblogs.com/evenbao/p/9394431.html