Description
张三是某工程公司的项目工程师。一天公司接下一项大型工程,该公司在大型工程的施工前,先要把整个工程划分为若干个子工程,并把这些子工程编号为1、2、…、N;这样划分之后,子工程之间就会有一些依赖关系,即一些子工程必须在某些子工程完成之后才能施工,公司需要工程师张三计算整个工程最少的完成时间。
对于上面问题,可以假设:
1、根据预算,每一个子工程都有一个完成时间。
2、子工程之间的依赖关系是:部分子工程必须在一些子工程完成之后才开工。
3、只要满足子工程间的依赖关系,在任何时刻可以有任何多个子工程同时在施工,也即同时施工的子工程个数不受限制。
现在对于给定的子工程规划情况,及每个子工程完成所需的时间,如果子工程划分合理则求出完成整个工程最少要用的时间,如果子工程划分不合理,则输出-1。
Input
第1行为正整数N,表示子工程的个数(N<=200)
第2行为N个正整数,分别代表子工程1、2、…、N的完成时间。
第3行到N+2行,每行有N-1个0或1,其中的第K+2行的这些0或1,分别表示“子工程K”与子工程1、2、…、K-1、K+1、…、N的依赖关系(K=1、2、…、N)。每行数据之间均用空格分开。
Output
如果子工程划分合理则输出完成整个工程最少要用的时间,如果子工程划分不合理,则输出-1。
Sample Input
project.in
5
5 4 12 7 2
0 0 0 0
0 0 0 0
0 0 0 0
1 1 0 0
1 1 1 1.
project.in
5
5 4 12 7 2
0 1 0 0
0 0 0 0
0 0 1 0
1 1 0 0
1 1 1 1
Sample Output
project.out
14
project.out
1
思路
topsort,判断有环输出0.
code:
#include<iostream>
#include<queue>
using namespace std;
int n,m,head[201],tot=1,rd[201];
int book[201],bok[2001];
int x,y;
struct f{
int to,next;
} a[40001];
void add(int x,int y)
{
a[tot].to=y;
a[tot].next=head[x];
head[x]=tot++;
return;
}
bool o;
queue<int> wj;
int main()
{
cin>>n;
for (int i=1;i<=n;i++) cin>>bok[i],book[i]=bok[i];
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
{
if (i==j) continue;
cin>>o;
rd[i]+=o;
if (o==1) add(j,i);
}
}
int o=0;
for (int j=1;j<=n;j++)
{
if (!rd[j])
{
o++;
wj.push(j);
}
}
if (o==0)
{
cout<<-1;
return 0;
}
while (wj.size())
{
x=wj.front();
wj.pop();
for (int i=head[x];i;i=a[i].next)
{
rd[a[i].to]--;
book[a[i].to]=max(book[a[i].to],bok[a[i].to]+book[x]);
if (rd[a[i].to]==0)
{
o++;
wj.push(a[i].to);
}
}
}
int s=0;
for (int i=1;i<=n;i++)
{
if (rd[i]!=0)
{
s=-1;
break;
}
s=max(s,book[i]);
}
cout<<s;
return 0;
}