hdu3592(差分约束)

来源:互联网 发布:网络舆情工作的重要性 编辑:程序博客网 时间:2024/04/30 00:56
差分约束
学习链接http://www.cnblogs.com/void/archive/2011/08/26/2153928.html
题意:给一些限制条件,求1到n的最大距离,可转化成求最短路径,将不等式化成  <= 的形式

有负边,要用SPFA,不能用dijkstra算法

代码如下:

#include<iostream>#include<algorithm>#include<cstring>#include<stack>#include<queue>#include<set>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#include<time.h>#include<math.h>#define N 1005#define inf 0x7ffffff#define eps 1e-9#define pi acos(-1.0)#define P system("pause")using namespace std;int mp[N][N],vis[N],dist[N],co[N];queue<int> q ;int n;int SPFA(int s){    while(!q.empty()) q.pop();    memset(vis,0,sizeof(vis));    memset(co,0,sizeof(co));    int i;    for(i = 1 ; i <= n; i++)        dist[i] = inf;    dist[s] = 0;    vis[s] = 1;    q.push(s);    co[s]++;    while(!q.empty())    {        int temp = q.front();//        cout<<temp<<endl;        q.pop();        for(i = 1; i <= n; i++)            if(dist[i] > dist[temp] + mp[temp][i])            {                dist[i] = dist[temp] + mp[temp][i];                if(!vis[i])                {                    co[i]++;                    q.push(i);                    vis[i] = 1;                    if(co[i] > n)                        return -1;                }            }        vis[temp] = 0;    }    return 1;}int main(){//freopen("input.txt","r",stdin);//freopen("output.txt","w",stdout);    int t;    scanf("%d",&t);    while(t--)    {        int x,y;        int i,j;        int a,b,c;        scanf("%d%d%d",&n,&x,&y);        for(i = 1; i <= n; i++)            for(j = 1; j <= n; j++)                mp[i][j] = inf;        //b - a <= c    b <= a + c   相当于d[u] <= d[v] + mp[v][u]        while(x--)        {            scanf("%d%d%d",&a,&b,&c);//一定要建有向图            mp[a][b] = c;        }        while(y--)        {            scanf("%d%d%d",&a,&b,&c);            mp[b][a]= -c;        }      //  s1-s0 >=0???        for(i = 1; i < n; i++)            mp[i][i+1] = 0;        int k = SPFA(1);        if(k == -1) printf("-1\n");//存在负圈的情况        else if(dist[n] == inf) printf("-2\n");//不连通的情况        else printf("%d\n",dist[n]);    }    return 0;}


0 0
原创粉丝点击