大意:一些人按照序号排队,有些人相互喜欢,必须在一定的距离之内,而有些人,则必须相距一定的距离。

 

思路:差分约束,注意还有s[i]-s[i-1]>=0这一题目隐含条件,如果有负环则输出-1,如果距离无限远则输出-2,否则d[n];

 

CODE:

 

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int SIZE = 10010;
const int INF = 0x3f3f3f3f;
int u[4*SIZE], w[4*SIZE], v[4*SIZE], next[4*SIZE];
int first[SIZE], d[SIZE];
int n, ML, MD,cnt;
int sum[SIZE];

void read_graph(int u1, int v1, int w1)
{
    u[cnt] = u1, v[cnt] = v1, w[cnt] = w1;
    next[cnt] = first[u[cnt]];
    first[u[cnt]] = cnt++;
}

int spfa(int src)
{
    bool ins[SIZE] = {0};
    int stack[SIZE] = {0};
    int top = 0;
    for(int i = 0; i <= n; i++) d[i] = (i == src)? 0:INF;
    stack[top++] = src;
    while(top)
    {
        int x = stack[--top];
        ins[x] = 0;
        for(int e = first[x]; e!=-1; e = next[e]) if(d[v[e]] > d[x]+w[e])
        {
            d[v[e]] = d[x]+w[e];
            if(!ins[v[e]])
            {
                ins[v[e]] = 1;
                sum[v[e]]++;
                if(sum[v[e]] > n)
                {
                    return -1;
                }
                stack[top++] = v[e];
            }
        }
    }
    if(d[n] == INF) return -2;
    else return d[n];
}

void init()
{
    memset(first, -1sizeof(first));
    memset(sum, 0sizeof(sum));
    cnt = 0;
}

int main()
{
    int u1, v1, w1;
    int T;
    scanf("%d", &T);
    while(T--)
    { 
        init();
        scanf("%d%d%d", &n, &ML, &MD);
        for(int i = 1; i <= ML; i++)
        {
            scanf("%d%d%d", &u1, &v1, &w1);
            read_graph(u1, v1, w1);
        }
        for(int i = 1; i <= MD; i++)
        {
            scanf("%d%d%d", &u1, &v1, &w1);
            read_graph(v1, u1, -w1);
        }
        for(int i = 1; i <= n; i++)
            read_graph(i, i-10);
        int ans = spfa(1);
        printf("%d\n", ans);
    }
    return 0;
}

 

posted on 2012-09-17 18:05  有间博客  阅读(109)  评论(0编辑  收藏  举报