Problem Description
Building a skyscraper is a huge task. It consists of n subtasks, numbered from 1, 2, …, n (n <1000).
There are some restrictions on subtasks, for example, after pouring concrete, you have to wait some time before removing the baffle plate. Such constraint could be represented by m (m<1000)inequalities. Ti+b ≤ Tj which means that subtask j has to wait for time b after subtask i starts. b is a constant different for each inequality, but they are ranged from 0 to 100, inclusively.
Your task is to write a program to determine whether all the constraints could be satisfied simultaneously. If the answer is “yes”. Find a solution that the beginning time of each subtask is the earliest. If the answer is “no”, simply output “NO SOLUTION” without quote. Note that the earliest time must satisfy that one of the subtask has to start at time 0.
Input
There are multiple test cases.
For each test case:
The first line contains n, m.
The next m lines, each line contains three integers i, j, b, corresponding to the inequalities in the description.
Output
For each test case:
If there is a valid plan, output n lines, each line represents the earliest start time of each subtask.
Otherwise output “NO SOLUTION” without quote.
Sample Input
5 6
l 2 0
1 5 1
2 5 1
3 1 5
4 1 4
4 3 1
5 5
1 2 3
1 5 1
2 5 1
5 1 5
4 1 4
Sample Output
6
6
1
0
7
NO SOLUTION
//by NOVA
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int mat[1001][1001],deg[1001],times[1001],n,m,sum;//times保存时间
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
int i,a,b,c;
memset(deg,0,sizeof(deg));
memset(mat,-1,sizeof(mat));
memset(times,0,sizeof(times));
sum=0;
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&c);
if(mat[a][b]==-1)
{
mat[a][b]=c;
deg[b]++;//注意对于每两个任务之间只能有一个入度,所以要预处理
}
else
{
mat[a][b]=max(mat[a][b],c);
}
}
queue<int> q;
for(i=1;i<=n;i++)
{
if(deg[i]==0)
{
q.push(i);
}
}
while(!q.empty())
{
int cur=q.front();
q.pop();
sum++;
for(i=1;i<=n;i++)
{
if(mat[cur][i]!=-1)
{
deg[i]--;
times[i]=max(times[i],times[cur]+mat[cur][i]);//保存最大时间
if(deg[i]==0)
{
q.push(i);
}
}
}
}
if(sum!=n)
{
printf("NO SOLUTION\n");
}
else
{
for(i=1;i<=n;i++)
{
printf("%d\n",times[i]);
}
}
}
return 0;
}