Monday 17 July 2017

UVA 10305 - Ordering Tasks

John has tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.
Input
The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1<=n<=100 and
m.is the number of tasks (numbered from 1 to n) and is the number of direct precedence relations between tasks. After this, there will be
lines with two integers and , representing the fact that task must be executed before task An instance with m= 0 will nish the input.
Output
For each instance, print a line with integers representing the tasks in a possible order of execution.
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3

MY accepted code Code:
#include<bits/stdc++.h>
using namespace std;
long long visited[100];
vector <int> grp[200];
map<int,int>vis;
stack<int>st;
int n;
int topologicalSortUtill(int v)
{
    vis[v] = 1;
    int l=grp[v].size();
    int u;
    for(int i=0; i<l; i++)
    {
        u=grp[v][i];
        if (!vis[u])
            topologicalSortUtill(u);

    }
    st.push(v);
}
int  topologicalSort()
{


    for(int i=1; i<=n; i++)
        vis[i]=0;
    for(int i=1; i<=n; i++)
        if(vis[i]==0)
            topologicalSortUtill(i);
            int c=0;
    while(st.empty()==0)
    {
        c++;

        cout<<st.top();
        if(c<n)
            cout<<" ";
        st.pop();
    }
    cout<<endl;
}
int main()
{
    int m,i,j,a,b;
    while(cin>>n>>m)
    {
        if(n==0&&m==0)
            break;
        for(i=1; i<=m; i++)
        {
            cin>>a>>b;
            grp[a].push_back(b);
        }
        //for(i=0;i<n;i++)
        topologicalSort();
    }
    return 0;
}
/*
6 6
5 2
5 0
4 0
4 1
2 3
3 1
*/

No comments:

Post a Comment