Answer:
Here the given problem is modeled as a Graph problem.
Explanation:
Input:- n, k and the function d(pi,pj) which outputs an integer between 1 and n2
Algorithm:-We model each student as a node. So, there would be n nodes. We make a foothold between two nodes u and v (where u and v denote the scholars pu and pv respectively) iff d(pu,pv) > k. Now, Let's call the graph G(V, E) where V is that the vertex set of the graph ( total vertices = n which is that the number of students), and E is that the edge set of the graph ( where two nodes have edges between them if and only the drama between them is bigger than k).
We now need to partition the nodes of the graph into two sets S1 and S2 such each node belongs to precisely one set and there's no edge between the nodes within the same set (if there's a foothold between any two nodes within the same set then meaning that the drama between them exceeds k which isn't allowed). S1 and S2 correspond to the partition of scholars into two buses.
The above formulation is akin to finding out if the graph G(V,E) is a bipartite graph. If the Graph G(V, E) is bipartite then we have a partition of the students into sets such that the total drama <= k else such a partition doesn't exist.
Now, finding whether a graph is bipartite or not is often found using BFS (Breadth First algorithm) in O(V+E) time. Since V = n and E = O(n2) , the worst-case time complexity of the BFS algorithm is O(n2). The pseudo-code is given as
PseudoCode:
// Input = n,k and a function d(pi,pj)
// Edges of a graph are represented as an adjacency list
1. Make V as a vertex set of n nodes.
2. for each vertex u ∈ V
for each vertex v ∈ V
if( d(pu, pj) > k )
add vertex u to Adj[v] // Adj[v] represents adjacency list of v
add vertex v to Adj[u] // Adj[u] represents adjacency list of u
3. bool visited[n] // visited[i] = true if the vertex i has been visited during BFS else false
4. for each vertex u ∈ V
visited[u] = false
5. color[n] // color[i] is binary number used for 2-coloring the graph
6. for each vertex u ∈ V
if ( visited[u] == false)
color[u] = 0;
isbipartite = BFS(G,u,color,visited) // if the vertices reachable from u form a bipartite graph, it returns true
if (isbipartite == false)
print " No solution exists "
exit(0)
7. for each vertex u ∈V
if (color[u] == 0 )
print " Student u is assigned Bus 1"
else
print " Student v is assigned Bus 2"
BFS(G,s,color,visited)
1. color[s] = 0
2. visited[s] = true
3. Q = Ф // Q is a priority Queue
4. Q.push(s)
5. while Q != Ф {
u = Q.pop()
for each vertex v ∈ Adj[u]
if (visited[v] == false)
color[v] = (color[u] + 1) % 2
visited[v] = true
Q.push(v)
else
if (color[u] == color[v])
return false // vertex u and v had been assigned the same color so the graph is not bipartite
}
6. return true