pku 2983 Is the Information Reliable? 差分约束

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

题意:给定两种约束关系

Precise tip is in the form of P A B X, means defense station A is X light-years north of defense station B.

Vague tip is in the form of V A B, means defense station A is in the north of defense station B, at least 1 light-year, but the precise distance is unknown.

d[i]表示i与0的距离,在p关系可表示为x <=d[b] - d[a]<=x   V关系可以表示为 d[b] - d[a] >= 1。 化简约束关系: P: d[b] - d[a] <= x    d[a] - d[b] <= -c  V: d[a] - d[b] <= -1

求最短路,判断是否存在bellman_ford。在做的时候,用了个memset初始化g结果一直tle,去掉后就ac了,看来以后尽量自己写训话出事化。

 

#include <cstdio>
#include <cstring>
#include <iostream>
#define maxn 100007
using namespace std;

struct node
{
    int u,v,w;
}g[maxn*100];
int len;
int n,m,dis[1005];
const int inf = 99999999;

void add(int u,int v,int w)
{
    g[len].u = u;
    g[len].v = v;
    g[len].w = w;
    len++;
}
bool bellman_ford(int s)
{
    int i,j;
    for (i = 1; i <= n; ++i) dis[i] = inf;
    dis[s] = 0;
    for (i = 1; i < n; ++i)
    {
        bool flag = false;
        for (j = 0; j < len; ++j)
        {
            int u = g[j].u,v = g[j].v,w = g[j].w;
            if (dis[v] > dis[u] + w)
            {
                dis[v] = dis[u] + w;
                flag = true;
            }
        }
        if (!flag) return true;
    }
    for (j = 0; j < len; ++j)
    {
        int u = g[j].u,v = g[j].v,w = g[j].w;
        if (dis[v] > dis[u] + w) return false;
    }
    return true;
}
int main()
{
    int i;
    int a,b,c;
    char op[3];
    while (~scanf("%d%d",&n,&m))
    {
        len = 0;
        for (i = 0; i < m; ++i)
        {
            scanf("%s%d%d",op,&a,&b);
            if (op[0] == 'P')
            {
                scanf("%d",&c);
                add(b,a,-c);
                add(a,b,c);
            }
            else
            {
                add(b,a,-1);
            }
        }
        if (bellman_ford(1)) printf("Reliable\n");
        else printf("Unreliable\n");
    }
    return 0;
}

  

posted @ 2012-06-23 11:20  E_star  阅读(187)  评论(0编辑  收藏  举报