您的位置:首页 > 其它

HDU 1534 Schedule Problem(差分约束)

2016-08-08 13:26 246 查看
思路:一道差分约束最长路求最小值,读懂题目连边求一次最长路就可以了

#include<bits/stdc++.h>
using namespace std;
const int maxn = 10010;
#define inf 1e9
vector<pair<int,int> >e[maxn];
int d[maxn],inq[maxn],a[maxn],cnt[maxn];
int n;
int spfa()
{
memset(inq,0,sizeof(inq));
memset(cnt,0,sizeof(cnt));
for(int i = 0;i<=n;i++)
d[i]=-inf;
queue<int>q;
q.push(0);
inq[0]=1;
d[0]=0;
while(!q.empty())
{
int u = q.front();
q.pop();
inq[u]=0;
for(int i = 0;i<e[u].size();i++)
{
int v = e[u][i].first;
if(d[v]<d[u]+e[u][i].second)
{
d[v]=d[u]+e[u][i].second;
if(!inq[v])
{
inq[v]=1;
q.push(v);
if(++cnt[v]>n)
return false;
}
}
}
}
return true;
}
int main()
{
int cas = 1;
while(scanf("%d",&n)!=EOF && n)
{
for(int i = 0;i<=n;i++)
e[i].clear();
for(int i = 1;i<=n;i++)
scanf("%d",&a[i]);
char s[105];
while(scanf("%s",s) && strcmp(s,"#")!=0)
{
int u,v;
scanf("%d%d",&u,&v);
if(strcmp(s,"FAS")==0)
e[v].push_back(make_pair(u,-a[u]));
if(strcmp(s,"FAF")==0)
e[v].push_back(make_pair(u,a[v]-a[u]));
if(strcmp(s,"SAF")==0)
e[v].push_back(make_pair(u,a[v]));
if(strcmp(s,"SAS")==0)
e[v].push_back(make_pair(u,0));
}
for(int i = 1;i<=n;i++)
e[0].push_back(make_pair(i,0));
printf("Case %d:\n",cas++);
if(spfa())
{
for(int i = 1;i<=n;i++)
printf("%d %d\n",i,d[i]);
}
else
printf("impossible\n");
printf("\n");
}
}


Description

A project can be divided into several parts. Each part should be completed continuously. This means if a part should take 3 days, we should use a continuous 3 days do complete it. There are four types of constrains among these parts
which are FAS, FAF, SAF and SAS. A constrain between parts is FAS if the first one should finish after the second one started. FAF is finish after finish. SAF is start after finish, and SAS is start after start. Assume there are enough people involved in the
projects, which means we can do any number of parts concurrently. You are to write a program to give a schedule of a given project, which has the shortest time.

Input

The input file consists a sequences of projects. 

Each project consists the following lines: 

the count number of parts (one line) (0 for end of input) 

times should be taken to complete these parts, each time occupies one line 

a list of FAS, FAF, SAF or SAS and two part number indicates a constrain of the two parts 

a line only contains a '#' indicates the end of a project 

Output

Output should be a list of lines, each line includes a part number and the time it should start. Time should be a non-negative integer, and the start time of first part should be 0. If there is no answer for the problem, you should give a non-line output containing
"impossible". 

A blank line should appear following the output for each project. 

Sample Input

3
2
3
4
SAF 2 1
FAF 3 2
#
3
1
1
1
SAF 2 1
SAF 3 2
SAF 1 3
#
0


Sample Output

Case 1:
1 0
2 2
3 1

Case 2:
impossible
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: