满足输出最晚开始时间的三个样例:
10 5 0 1 0 3 3 1 2 3 2 2 1 2 1 4 4 8 9 6 9 9 | 10 5 0 1 0 3 1 1 2 1 4 4 1 2 1 2 2 6 9 6 7 7 | 10 5 0 1 2 0 3 1 2 3 2 2 1 2 4 1 7 3 4 6 9 9 |
#include<iostream>
#include<cmath>
#include<map>
#include<climits>
using namespace std;
const int maxn = 365+5;
const int maxm = 100+5;
int p[maxm];
int t[maxm];
int early[maxm];
int last[maxm];
typedef multimap<int,int>::iterator Iterator;
int main(){
multimap<int,int> rel;
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++) {
cin>>p[i];
/*
(p[i],i)表示项目i的依赖项目为p[i],称i是依赖对象,p[i]是被依赖对象
依赖关系可以用multiset表示
*/
rel.insert(make_pair(p[i],i));
}
for(int i=1;i<=m;i++){
cin>>t[i];
}
bool flag = true;//默认最早开始时间满足n天训练
for(int i=1;i<=m;i++){
if(p[i]==0){
early[i] = 1;
}else{
early[i] = early[p[i]]+t[p[i]];
}
if(early[i]+t[i]-1>n) flag = false;//最早开始时间不满足n天训练
}
for(int i=1;i<=m;i++){
cout<<early[i]<<" ";
}
cout<<endl;
if(flag==true){
/*
由于满足依赖科目编号p[i]小于当前项目i的编号,因此可以从编号大的开始往前计算最晚开始时间
*/
for(int i=m;i>=1;i--){
//找项目i的被依赖对象,如果项目i没有被依赖对象,则依赖关系(i,p[i])不存在
pair<Iterator,Iterator> it = rel.equal_range(i);
if(it.first==it.second){//依赖关系不存在
last[i] = n - t[i] +1;
}else{//依赖关系存在
Iterator it1;
int value = INT_MAX;
for(it1 = it.first;it1 != it.second; ++it1) {
// cout<<it1->first<<" ==== "<<it1->second<<"---";
value = min(value,last[it1->second]);
// cout<<value<<endl;
}
last[i] = value - t[i];
}
// cout<<last[i]<<" ";
}
for(int i=1;i<=m;i++){
cout<<last[i]<<" ";
}
}
return 0;
}