您的位置:首页 > 其它

差分约束——HDOJ 1534

2012-02-25 23:22 381 查看
HDOJ 1534 Schedule Problem

/*
HDOJ 1534
差分约束系统,建图还是那么弱,刚接触了一道题目而已
看来还需要多多训练才行。
先更具题目的给出的地中情况:
FAS, SAF, FAF, SAS
S:start A:after F: finish
FAS x, y 表示x finish after y start
设start[i]表示第i部分最早开始的时间,time[i]表示完成第i部分所需时间
则有下列不等式
FAS x,y : start[x] + time[x] >= start[y]
SAF x,y : start[x] >= start[y] + time[y]
FAF x,y : start[x] + time[x] >= start[y] + time[y]
SAS x,y : start[x] >= start[y]
将全部start[x]放在左边,整理一下不等式
Start[x] >= start[y] - time[x];
Start[x] >= start[y] + time[y];
Start[x] >= start[y] + time[y] – time[x];
Start[x] >= start[y];
题目要求的是每一部分的最早开始时间,所以要求的是start[x]的一个下界
差分约束系统是通过求解最长路或者最短路来实现的
这道题目是要求下界,所以就是求最长路
*/

#include <iostream>
#include <string>
#define MAXN 1010
using namespace std;

struct Edge
{
int star;
int end;
int weight;
}edge[MAXN];

int n;
int dis[MAXN];
int time[MAXN];

bool Bellman_Ford(int m)
{
int i,j,k;
memset(dis,0,sizeof(dis));
for(i=1;i<n;i++)
{
for(j=0;j<m;j++)
{
if(dis[edge[j].star] + edge[j].weight > dis[edge[j].end])
{
dis[edge[j].end]=dis[edge[j].star] + edge[j].weight;
}
}
}
for(j=0;j<m;j++)
{
if(dis[edge[j].star] + edge[j].weight > dis[edge[j].end])
return false;
}
return true;
}

int main()
{
char str[4];
int i,j,k,x,y,count=0;
while(cin>>n)
{
if(n == 0)
break;
for(i=1;i<=n;i++)
cin>>time[i];
for(i=0;;i++)
{
cin>>str;
if(str[0] == '#')
break;
cin>>x>>y;
edge[i].star=y; //这里要注意起点和终点
edge[i].end=x; //因为要求的是star[x],所以x要作为有向边的终点
if(strcmp(str,"FAS")==0)
edge[i].weight=0-time[x];
else if(strcmp(str,"FAF")==0)
edge[i].weight=time[y]-time[x];
else if(strcmp(str,"SAF")==0)
edge[i].weight=time[y];
else
edge[i].weight=0;
}
if(Bellman_Ford(i))
{
cout<<"Case "<<++count<<":"<<endl;
for(i=1;i<=n;i++)
cout<<i<<" "<<dis[i]<<endl;
}
else
cout<<"impossible"<<endl;
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ini