📌  相关文章
📜  从给定的子序列构建原始数组

📅  最后修改于: 2021-10-25 03:11:00             🧑  作者: Mango

给定一个整数N和一个整数数组的有效子序列,其中每个元素都不同且范围为[0, N – 1] ,任务是找到原始数组。

例子:

方法:从给定的子序列构建一个图。一一选择每个子序列,并在子序列中的两个相邻元素之间添加一条边。建好图后,对图进行拓扑排序。
请参阅拓扑排序以了解拓扑排序。这种拓扑排序是所需的数组。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to add edge to graph
void addEdge(vector adj[], int u, int v)
{
    adj[u].push_back(v);
}
 
// Function to calculate indegrees of all the vertices
void getindeg(vector adj[], int V, vector& indeg)
{
    // If there is an edge from i to x
    // then increment indegree of x
    for (int i = 0; i < V; i++) {
        for (auto x : adj[i]) {
            indeg[x]++;
        }
    }
}
 
// Function to perform topological sort
vector topo(vector adj[], int V, vector& indeg)
{
    queue q;
 
    // Push every node to the queue
    // which has no incoming edge
    for (int i = 0; i < V; i++) {
        if (indeg[i] == 0)
            q.push(i);
    }
    vector res;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        res.push_back(u);
 
        // Since edge u is removed, update the indegrees
        // of all the nodes which had an incoming edge from u
        for (auto x : adj[u]) {
            indeg[x]--;
            if (indeg[x] == 0)
                q.push(x);
        }
    }
    return res;
}
 
// Function to generate the array
// from the given sub-sequences
vector makearray(vector > v, int V)
{
 
    // Create the graph from the input sub-sequences
    vector adj[V];
    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v[i].size() - 1; j++) {
 
            // Add edge between every two consecutive
            // elements of the given sub-sequences
            addEdge(adj, v[i][j], v[i][j + 1]);
        }
    }
 
    // Get the indegrees for all the vertices
    vector indeg(V, 0);
    getindeg(adj, V, indeg);
 
    // Get the topological order of the created graph
    vector res = topo(adj, V, indeg);
    return res;
}
 
// Driver code
int main()
{
    // Size of the required array
    int n = 10;
 
    // Given sub-sequences of the array
    vector > subseqs{ { 9, 1, 2, 8, 3 },
                                  { 6, 1, 2 },
                                  { 9, 6, 3, 4 },
                                  { 5, 2, 7 },
                                  { 0, 9, 5, 4 } };
 
    // Get the resultant array as vector
    vector res = makearray(subseqs, n);
 
    // Printing the array
    for (auto x : res) {
        cout << x << " ";
    }
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to add edge to graph
static void addEdge(ArrayList> adj,
                    int u, int v)
{
    adj.get(u).add(v);
}
 
// Function to calculate indegrees of all the vertices
static void getindeg(ArrayList> adj,
                        int V, ArrayList indeg)
{
     
    // If there is an edge from i to x
    // then increment indegree of x
    for(int i = 0; i < V; i++)
    {
        for(int x: adj.get(i))
        {
            indeg.set(x, indeg.get(x) + 1);
        }
    }
}
 
// Function to perform topological sort
static ArrayList topo(ArrayList> adj,
                                  int V, ArrayList indeg)
{
    Queue q = new LinkedList<>();
     
    // Push every node to the queue
    // which has no incoming edge
    for(int i = 0; i < V; i++)
    {
        if (indeg.get(i) == 0)
        {
            q.add(i);
        }
    }
    ArrayList res = new ArrayList();
     
    while (q.size() > 0)
    {
        int u = q.poll();
        res.add(u);
         
        // Since edge u is removed, update the
        // indegrees of all the nodes which had
        // an incoming edge from u
        for(int x: adj.get(u))
        {
            indeg.set(x, indeg.get(x) - 1);
             
            if (indeg.get(x) == 0)
            {
                q.add(x);
            }
        }
    }
    return res;
}
 
// Function to generate the array
// from the given sub-sequences
static ArrayList makearray(
    ArrayList> v, int V)
{
     
    // Create the graph from the
    // input sub-sequences
    ArrayList<
    ArrayList> adj = new ArrayList<
                                  ArrayList>();
    for(int i = 0; i < V; i++)
    {
        adj.add(new ArrayList());
    }
    for(int i = 0; i < v.size(); i++)
    {
        for(int j = 0; j < v.get(i).size() - 1; j++)
        {
             
            // Add edge between every two consecutive
            // elements of the given sub-sequences
            addEdge(adj, v.get(i).get(j),
                         v.get(i).get(j + 1));
        }
    }
     
    // Get the indegrees for all the vertices
    ArrayList indeg = new ArrayList();
    for(int i = 0; i < V; i++)
    {
        indeg.add(0);
    }
    getindeg(adj, V, indeg);
     
    // Get the topological order of the created graph
    ArrayList res = topo(adj, V, indeg);
    return res;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Size of the required array
    int n = 10;
     
    // Given sub-sequences of the array
    ArrayList<
    ArrayList> subseqs = new ArrayList<
                                      ArrayList>();
    subseqs.add(new ArrayList(
        Arrays.asList(9, 1, 2, 8, 3)));
    subseqs.add(new ArrayList(
        Arrays.asList(6, 1, 2)));
    subseqs.add(new ArrayList(
        Arrays.asList(9, 6, 3, 4)));
    subseqs.add(new ArrayList(
        Arrays.asList(5, 2, 7)));
    subseqs.add(new ArrayList(
        Arrays.asList(0, 9, 5, 4)));
         
    // Get the resultant array as vector
    ArrayList res = makearray(subseqs, n);
     
    // Printing the array
    for(int x: res)
    {
        System.out.print(x + " ");
    }
}
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python3 implementation of the approach
from collections import deque
adj=[[] for i in range(100)]
 
# Function to add edge to graph
def addEdge(u, v):
    adj[u].append(v)
 
# Function to calculate indegrees of all the vertices
def getindeg(V,indeg):
 
    # If there is an edge from i to x
    # then increment indegree of x
    for i in range(V):
        for x in adj[i]:
            indeg[x] += 1
 
 
# Function to perform topological sort
def topo(V,indeg):
    q = deque()
 
    # Push every node to the queue
    # which has no incoming edge
    for i in range(V):
        if (indeg[i] == 0):
            q.appendleft(i)
    res=[]
    while (len(q) > 0):
        u = q.popleft()
        res.append(u)
 
        # Since edge u is removed, update the indegrees
        # of all the nodes which had an incoming edge from u
        for x in adj[u]:
            indeg[x]-=1
            if (indeg[x] == 0):
                q.appendleft(x)
 
    return res
 
 
# Function to generate the array
# from the given sub-sequences
def makearray(v, V):
 
    # Create the graph from the input sub-sequences
    for i in range(len(v)):
        for j in range(len(v[i])-1):
 
            # Add edge between every two consecutive
            # elements of the given sub-sequences
            addEdge(v[i][j], v[i][j + 1])
 
 
    # Get the indegrees for all the vertices
    indeg=[0 for i in range(V)]
    getindeg(V, indeg)
 
    # Get the topological order of the created graph
    res = topo(V, indeg)
    return res
 
# Driver code
 
# Size of the required array
n = 10
 
# Given sub-sequences of the array
subseqs=[ [ 9, 1, 2, 8, 3 ],
        [ 6, 1, 2 ],
        [ 9, 6, 3, 4 ],
        [ 5, 2, 7 ],
        [ 0, 9, 5, 4 ] ]
 
# Get the resultant array as vector
res = makearray(subseqs, n)
 
# Printing the array
for x in res:
    print(x,end=" ")
     
# This code is contributed by mohit kumar 29


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to add edge to graph
static void addEdge(List> adj, int u, int v)
{
    adj[u].Add(v);
}
 
// Function to calculate indegrees of
// all the vertices
static void getindeg(List> adj, int V,
                          List indeg)
{
     
    // If there is an edge from i to x
    // then increment indegree of x
    for(int i = 0; i < V; i++)
    {
        foreach(int x in adj[i])
        {
            indeg[x]++;
        }
    }
}
 
// Function to perform topological sort
static List topo(List> adj, int V,
                           List indeg)
{
    Queue q = new Queue();
     
    // Push every node to the queue
    // which has no incoming edge
    for(int i = 0; i < V; i++)
    {
        if (indeg[i] == 0)
        {
            q.Enqueue(i);
        }
    }
    List res = new List();
     
    while (q.Count > 0)
    {
        int u = q.Dequeue();
        res.Add(u);
         
        // Since edge u is removed, update the
        // indegrees of all the nodes which had
        // an incoming edge from u
        foreach(int x in adj[u])
        {
            indeg[x]--;
            if (indeg[x] == 0)
            {
                q.Enqueue(x);
            }
        }
    }
    return res;
}
 
// Function to generate the array
// from the given sub-sequences
static List makearray(List> v, int V)
{
     
    // Create the graph from the
    // input sub-sequences
    List> adj = new List>();
    for(int i = 0; i < V; i++)
    {
        adj.Add(new List());
    }
    for(int i = 0; i < v.Count; i++)
    {
        for(int j = 0; j < v[i].Count - 1; j++)
        {
             
            // Add edge between every two consecutive
            // elements of the given sub-sequences
            addEdge(adj, v[i][j], v[i][j+1]);
        }
    }
     
    // Get the indegrees for all the vertices
    List indeg = new List();
    for(int i = 0; i < V; i++)
    {
        indeg.Add(0);
    }
    getindeg(adj, V, indeg);
     
    // Get the topological order
    // of the created graph
    List res = topo(adj, V, indeg);
    return res;
}
 
// Driver code
static public void Main()
{
     
    // Size of the required array
    int n = 10;
     
    // Given sub-sequences of the array
    List> subseqs = new List>();
    subseqs.Add(new List(){9, 1, 2, 8, 3});
    subseqs.Add(new List(){6, 1, 2});
    subseqs.Add(new List(){9, 6, 3, 4});
    subseqs.Add(new List(){5, 2, 7});
    subseqs.Add(new List(){0, 9, 5, 4});
     
    // Get the resultant array as vector
    List res = makearray(subseqs, n);
     
    // Printing the array
    foreach(int x in res)
    {
        Console.Write(x + " ");
    }
}
}
 
// This code is contributed by rag2127


Javascript


输出:
0 9 6 5 1 2 8 7 3 4

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程