码迷,mamicode.com
首页 > 其他好文 > 详细

差分约束Poj 3169 Layout

时间:2014-06-07 06:11:19      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:c   class   blog   code   a   ext   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
int n;
const int INF=0xfffffff;
struct edge
{
    int val;int to;int next;
}e[111111];
 
int len;int head[11111];
 
void add(int from,int to,int val)
{
    e[len].to=to;e[len].val=val;e[len].next=head[from];head[from]=len++;
}
int dis[11111];
int spfa(int x)
{
    int vis[11111];
    for(int i=1;i<=n;i++) vis[i]=0;
    for(int i=1;i<=n;i++) dis[i]=INF;
    vis[x]=1; dis[x]=0;
    queue<int> q;
    q.push(x);  int cnt[11111]={0}; cnt[x]=1;
    while(!q.empty()){
        int cur=q.front(); q.pop();vis[cur]=0;
        for(int i=head[cur];i!=-1;i=e[i].next){
            int cc=e[i].to;
            if(dis[cc]>dis[cur]+e[i].val){
                dis[cc]=dis[cur]+e[i].val;
                if(!vis[cc]){
                    cnt[cc]++;if(cnt[cc]>n) return 0;
                    q.push(cc); vis[cc]=1;
                }
            }
        }
    }
    return 1;
}
 
int main()
{
    int m,l;
    while(scanf("%d%d%d",&n,&m,&l)!=EOF){
        len=0;memset(head,-1,sizeof(head));
        for(int i= 0;i<m;i++){
            int a,b,c;scanf("%d%d%d",&a,&b,&c);
            if(a>b) {int t=a;a=b;b=t;}
            add(a,b,c);
        }
        for(int i=0;i<l;i++){
            int a,b,c;scanf("%d%d%d",&a,&b,&c);
            if(a<b){int t=a;a=b;b=t;};
            add(a,b,-c);
        }
        if(!spfa(1)) printf("-1\n");
        else{
            if(dis[n]==INF)
                printf("-2\n");
            else
                printf("%d\n",dis[n]);
        }
    }
    return 0;
}

  

 

差分约束Poj 3169 Layout,布布扣,bubuko.com

差分约束Poj 3169 Layout

标签:c   class   blog   code   a   ext   

原文地址:http://www.cnblogs.com/yigexigua/p/3770382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!