Algorithm


Problem link- https://www.spoj.com/problems/PFDEP/

PFDEP - Project File Dependencies

 

Project managers, such as the UNIX utility make, are used to maintain large software projects made up from many components. Users write a project file specifying which components (called tasks) depend on others and the project manager can automatically update the components in the correct order.

Problem

Write a program that reads a project file and outputs the order in which the tasks should be performed.

Input

For simplicity we represent each task by an integer number from 1,2,,N1,2,…,� (where N is the total number of tasks). The first line of input specifies the number N of tasks and the number M of rules, such that N100�≤100M100�≤100.

The rest of the input consists of M rules, one in each line, specifying dependencies using the following syntax:

T0�0 k T1�1 T2�2  Tk��

This rule means that task number T0�0 depends on k tasks T1,T2,,Tk�1,�2,…,�� (we say that task T0�0 is the target and T1,,Tk�1,…,�� are dependents).

Note that tasks numbers are separated by single spaces and that rules end with a newline. Rules can appear in any order, but each task can appear as target only once.

Your program can assume that there are no circular dependencies in the rules, i.e. no task depends directly or indirectly on itself.

Output

The output should be a single line with the permutation of the tasks 1N1…� to be performed, ordered by dependencies (i.e. no task should appear before others that it depends on).

To avoid ambiguity in the output, tasks that do not depend on each other should be ordered by their number (lower numbers first).

Example

Input:
5 4
3 2 1 5
2 2 5 3
4 1 3
5 1 1

Output:
1 5 3 2 4

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <sstream>
#include <cstdio>
#define f(i, n) for(int i = 0; i < n; i++)
#define s(n) scanf("%d", &n)
#define inf (int)1e9
using namespace std;

int main()
{
	vector<int> v[101];
	bool vis[101];
	int n, m;
	int aa, k, temp, p = 0;
	while(s(n)!=-1)
	{
		s(m);
		f(i,m)
		{
			s(aa);s(k);
			p=0;
			while(k--)
			{
				s(temp);
				v[aa].push_back(temp);
			}
		}
		memset(vis,0,sizeof(vis));
		f(k,n)
		{
			for(int i=1;i<=n;i++)
			{
				int ct=0;
				if(vis[i])continue;
				f(j,v[i].size())
				{	
					if(!vis[v[i][j]])
					{
						ct++;
					}
				}
				if(ct==0)
				{
					vis[i]=true;
					printf("%d ",i);
					break;
				}	
			}
		}
		printf("\n");
	}
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
5 4
3 2 1 5
2 2 5 3
4 1 3
5 1 1

Output

x
+
cmd
1 5 3 2 4
Advertisements

Demonstration


SPOJ Solution-Project File Dependencies-Solution in C, C++, Java, Python

Previous
SPOJ Solution - Test Life, the Universe, and Everything - Solution in C, C++, Java, Python