poj 2983 差分约束

大致题意:给出一些点的精确信息和模糊信息,精确信息给出两点的位置和距离,模糊信息给出两点的位置,但距离大于等于一。试确定是否所有的信息满足条件。

这道题让我对差分约束系统有了进一步的认识。设dist[i]表示源点到i的距离,精确条件可以判断出两个差分条件:假如a->bc则可以写成c>=dist[b]-dist[a]>=c;所以可得dist[b]<=dist[a]+c , dist[a]<=dist[b]-c;这就说明ab有一条长度为c的边,ba有一条长度为-c的边。模糊信息可以确定一个差分条件由dist[b]-dist[a]>=1可得:dist[a]<=dist[b]-1,说明ba有一条长度为-1的边。差分条件都找出来后在求最短路看是否有负环。

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
#define MAX_INT 123456789
struct node
{
	int v;
	int value;
	int next;
};
int visit[1001],head[1001],counter[1001],dist[1001],N;
node edge[1000000];
queue <int> Q;
int spfa(int n)
{
	int i,k,tail,front,e;
	while(!Q.empty()) Q.pop();
	for(tail=front=0,i=1;i<=n;i++)
	{
		dist[i]=MAX_INT;
		Q.push(i);
		visit[i]=1;
	}
	memset(counter,0,sizeof(counter));
	while(!Q.empty())
	{
		e=Q.front(),Q.pop();
		visit[e]=0;
		if(dist[e]==MAX_INT) dist[e]=0;
		for(i=head[e];i;i=edge[i].next)
		{
			k=edge[i].v;
			if(dist[k]>dist[e]+edge[i].value)
			{
				dist[k]=dist[e]+edge[i].value;
				if(!visit[k])
				{
					Q.push(k);
					visit[k]=1;
					if(++counter[k]>n-1) return 0;
				}
			}
		}
	}
	return 1;
}
int add(int s,int t,int w)
{
	node e={t,w,0};
	edge[N]=e;
	edge[N].next=head[s];
	head[s]=N++;
	return 0;
}
int main()
{
	int i,s,t,w,m,n;
	char c;
	//freopen("in.txt", "r", stdin);
             //freopen("out.txt","w", stdout);
	while(cin>>n>>m)
	{
		memset(head,0,sizeof(head));
		for(N=1,i=0;i<m;i++)
		{
			cin>>c;
			if(c=='P')
			{
				cin>>s>>t>>w;
				add(s,t,w);
				add(t,s,-w);
			}
			else if(c=='V')
			{
				cin>>s>>t;
				add(t,s,-1);
			}
			getchar();
		}
		if(spfa(n))
			cout<<"Reliable"<<endl;
		else
			cout<<"Unreliable"<<endl;
	}
	return 0;
}

附上几组测试数据:

input:

2 8
P 1 2 -4
P 1 1 5
V 2 2
V 2 1
V 1 2
P 1 2 -2
V 1 1
V 2 1

2 9
V 1 2
V 2 1
V 2 1
V 2 1
V 2 2
P 2 1 2
V 2 2
V 2 1
P 2 1 -2

7 1
P 1 4 6

1 10
P 1 1 1
P 1 1 -4
P 1 1 6
P 1 1 6
V 1 1
P 1 1 3
V 1 1
P 1 1 -3
V 1 1
P 1 1 7

8 3
P 3 2 6
V 8 7
V 5 7

1 2
P 1 1 7
V 1 1

8 4
V 2 6
V 7 6
P 7 3 -6
V 1 5

2 3
V 1 2
P 2 1 3
V 1 1

2 7
P 1 1 -1
V 1 1
V 1 2
V 1 1
P 1 2 -7
V 1 2
V 2 1

8 4
P 6 1 5
P 2 8 -6
V 1 1
P 2 6 2

6 4
V 2 4
P 6 3 0
P 1 3 8
V 3 2

8 3
P 3 5 8
P 2 7 1
P 5 8 -2

3 6
P 3 2 6
V 2 1
P 1 3 -8
V 2 3
V 1 2
V 3 3

1 1
V 1 1

9 2
V 1 8
P 2 9 -5

7 8
V 5 7
V 6 4
V 6 5
P 7 6 -5
V 1 7
V 1 5
V 5 6
V 6 7

10 10
V 7 10
V 6 8
P 7 6 -8
V 5 5
V 7 2
P 4 4 5
V 3 9
P 6 4 6
P 7 3 -1
P 3 10 1

1 4
P 1 1 2
V 1 1
P 1 1 6
P 1 1 8

6 9
V 3 2
V 5 3
P 1 3 2
V 3 6
V 1 6
V 3 6
P 3 6 -2
V 2 3
V 6 4

4 5
V 1 2
V 4 1
V 2 2
V 1 3
P 3 1 0

 

output:

Unreliable
Unreliable
Reliable
Unreliable
Reliable
Unreliable
Reliable
Unreliable
Unreliable
Unreliable
Reliable
Reliable
Unreliable
Unreliable
Reliable
Unreliable
Unreliable
Unreliable
Unreliable
Unreliable

posted @ 2011-08-18 16:37  书山有路,学海无涯  阅读(442)  评论(0编辑  收藏  举报