📌  相关文章
📜  通过在给定数组指定的位置放置数字来构造可能的最小 N 位数字

📅  最后修改于: 2021-10-28 01:46:10             🧑  作者: Mango

给定两个整数NM以及一个二维数组arr[] ,任务是构造N位数字的最小可能整数(不带前导零),使得从左边数arr[i][0]位是arr[i ][1] 。如果不可能构造任何这样的整数,则打印“No” 。否则,打印该数字。

例子:

朴素的方法:由于数字总是从09 ,最简单的方法是通过根据给定条件放置数字来检查每个超过0且小于10 N的整数的组合。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to check if num satisfies the
// arrangement specified by the vector A
bool check(int num, int N, int M,
           vector >& A)
{
    // Convert num to equivalent string
    string temp = to_string(num);
 
    // If the number of digits
    // is not equal to N
    if (temp.size() != N) {
        return false;
    }
 
    // Iterate over the vector A
    for (int i = 0; i < M; i++) {
 
        // If the digit at A[i].first position
        // not the same as A[i].second
        if (temp[A[i].first] != A[i].second) {
            return false;
        }
    }
 
    return true;
}
 
// Function to find the smallest integer
// satisfying the given conditions
void find_num(int N, vector >& A)
{
    int ans = -1;
 
    // Check for every combination upto 10^N
    for (int i = 0; i < pow(10, N); i++) {
 
        // If condition satisfies
        if (check(i, N, A.size(), A)) {
            ans = i;
            break;
        }
    }
 
    if (ans == -1)
        cout << "No";
    else
        cout << ans;
}
 
// Driver Code
int main()
{
 
    int N = 3;
    vector > A
        = { { 0, '7' }, { 2, '2' }, { 0, '7' } };
 
    find_num(N, A);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
    static class pair
    {
        int first;
        char second;
        public pair(int first, char second) 
        {
            this.first = first;
            this.second = second;
        }   
    };
 
// Function to check if num satisfies the
// arrangement specified by the vector A
static boolean check(int num, int N, int M,
           Vector A)
{
    // Convert num to equivalent String
    String temp = String.valueOf(num);
 
    // If the number of digits
    // is not equal to N
    if (temp.length() != N) {
        return false;
    }
 
    // Iterate over the vector A
    for (int i = 0; i < M; i++) {
 
        // If the digit at A[i].first position
        // not the same as A[i].second
        if (temp.charAt(A.get(i).first) != A.get(i).second) {
            return false;
        }
    }
 
    return true;
}
 
// Function to find the smallest integer
// satisfying the given conditions
static void find_num(int N, Vector A)
{
    int ans = -1;
 
    // Check for every combination upto 10^N
    for (int i = 0; i < Math.pow(10, N); i++) {
 
        // If condition satisfies
        if (check(i, N, A.size(), A)) {
            ans = i;
            break;
        }
    }
 
    if (ans == -1)
        System.out.print("No");
    else
        System.out.print(ans);
}
 
// Driver Code
public static void main(String[] args)
{
 
    int N = 3;
    Vector A = new Vector<>();
    A.add(new pair(0, '7' ));
    A.add(new pair(2, '2'));
    A.add(new pair( 0, '7'));
       
 
    find_num(N, A);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
 
# Function to check if num satisfies the
# arrangement specified by the vector A
def check(num, N, M, A) :
 
    # Convert num to equivalent string
    temp = str(num)
 
    # If the number of digits
    # is not equal to N
    if (len(temp) != N) :
        return False
 
    # Iterate over the vector A
    for i in range(M) :
 
        # If the digit at A[i].first position
        # not the same as A[i].second
        if (temp[A[i][0]] != A[i][1]) :
            return False
 
    return True
 
# Function to find the smallest integer
# satisfying the given conditions
def find_num(N, A) :
 
    ans = -1
 
    # Check for every combination upto 10^N
    for i in range(pow(10, N)) :
 
        # If condition satisfies
        if (check(i, N, len(A), A)) :
            ans = i
            break
 
    if (ans == -1) :
        print("No")
    else :
        print(ans)
 
 
N = 3
A = [ [ 0, '7' ], [ 2, '2' ], [ 0, '7' ] ]
 
find_num(N, A)
 
# This code is contributed by divyesh072019


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
    public class pair
    {
        public int first;
        public char second;
        public pair(int first, char second) 
        {
            this.first = first;
            this.second = second;
        }   
    };
 
// Function to check if num satisfies the
// arrangement specified by the vector A
static bool check(int num, int N, int M,
           List A)
{
    // Convert num to equivalent String
    String temp = String.Join("",num);
 
    // If the number of digits
    // is not equal to N
    if (temp.Length != N) {
        return false;
    }
 
    // Iterate over the vector A
    for (int i = 0; i < M; i++) {
 
        // If the digit at A[i].first position
        // not the same as A[i].second
        if (temp[A[i].first] != A[i].second) {
            return false;
        }
    }
 
    return true;
}
 
// Function to find the smallest integer
// satisfying the given conditions
static void find_num(int N, List A)
{
    int ans = -1;
 
    // Check for every combination upto 10^N
    for (int i = 0; i < Math.Pow(10, N); i++) {
 
        // If condition satisfies
        if (check(i, N, A.Count, A)) {
            ans = i;
            break;
        }
    }
 
    if (ans == -1)
        Console.Write("No");
    else
        Console.Write(ans);
}
 
// Driver Code
public static void Main(String[] args)
{
 
    int N = 3;
    List A = new List();
    A.Add(new pair(0, '7' ));
    A.Add(new pair(2, '2'));
    A.Add(new pair( 0, '7'));
       
    find_num(N, A);
}
}
 
// This code is contributed by shikhasingrajput


Javascript


C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find the smallest integer
// satisfying the given conditions
void find_num(int N, vector >& A)
{
    // Stores the digits at their
    // respective positions
    map mp;
 
    // Traverse the array
    for (int i = 0; i < A.size(); i++) {
 
        // If first digit required
        // to be placed is 0
        if (N > 1 and A[i].first == 0
            and A[i].second == 0) {
 
            // Not possible
            cout << "No";
            return;
        }
 
        // If multiple numbers are assigned
        // to be placed in a single position
        if (mp.find(A[i].first) != mp.end()
            and mp[A[i].first] != A[i].second) {
 
            // Not possible
            cout << "No";
            return;
        }
 
        // Assign the digits to their
        // respective positions
        mp[A[i].first] = A[i].second;
    }
 
    // Stores the result
    string ans = "";
 
    // Traverse for all N digits
    for (int i = 0; i < N; i++) {
 
        // For the first position
        if (N > 1 and i == 0) {
 
            // If digit is assigned
            // to the position
            if (mp.find(0) != mp.end()) {
                ans += to_string(mp[0]);
            }
 
            // Otherwise
            else {
                ans += to_string(1);
            }
        }
 
        else {
            // Add it to answer
            ans += to_string(mp[i]);
        }
    }
 
    cout << ans << "\n";
}
 
// Driver Code
int main()
{
 
    int N = 3;
    vector > A
        = { { 0, 7 }, { 2, 2 }, { 0, 7 } };
 
    find_num(N, A);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
static class pair
{
    int first, second;
     
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
 
// Function to find the smallest integer
// satisfying the given conditions
static void find_num(int N, pair []A)
{
     
    // Stores the digits at their
    // respective positions
    HashMap mp = new HashMap();
 
    // Traverse the array
    for(int i = 0; i < A.length; i++)
    {
         
        // If first digit required
        // to be placed is 0
        if (N > 1 && A[i].first == 0 &&
            A[i].second == 0)
        {
             
            // Not possible
            System.out.print("No");
            return;
        }
 
        // If multiple numbers are assigned
        // to be placed in a single position
        if (mp.containsKey(A[i].first) &&
            mp.get(A[i].first) != A[i].second)
        {
             
            // Not possible
            System.out.print("No");
            return;
        }
 
        // Assign the digits to their
        // respective positions
        mp.put(A[i].first, A[i].second);
    }
 
    // Stores the result
    String ans = "";
 
    // Traverse for all N digits
    for(int i = 0; i < N; i++)
    {
         
        // For the first position
        if (N > 1 && i == 0)
        {
 
            // If digit is assigned
            // to the position
            if (mp.containsKey(0))
            {
                 
                ans += String.valueOf(mp.get(0));
            }
 
            // Otherwise
            else
            {
                ans += String.valueOf(1);
            }
        }
        else
        {
             
            // Add it to answer
            if (mp.get(i) == null)
                ans += String.valueOf(0);
            else
                ans += String.valueOf(mp.get(i));
        }
    }
    System.out.print(ans + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 3;
    pair []A = { new pair(0, 7),
                 new pair(2, 2),
                 new pair(0, 7)};
                  
    find_num(N, A);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program to implement
# the above approach
 
# Function to find the smallest integer
# satisfying the given conditions
def find_num(N, A) :
 
    # Stores the digits at their
    # respective positions
    mp = {}
 
    # Traverse the array
    for i in range(len(A)) :
 
        # If first digit required
        # to be placed is 0
        if ((N > 1) and (A[i][0] == 0) and (A[i][1] == 0)) :
 
            # Not possible
            print("No")
            return
 
        # If multiple numbers are assigned
        # to be placed in a single position
        if ((A[i][0] in mp) and (mp[A[i][0]] != A[i][1])) :
 
            # Not possible
            print("No")
            return
 
        # Assign the digits to their
        # respective positions
        mp[A[i][0]] = A[i][1]
 
    # Stores the result
    ans = ""
 
    # Traverse for all N digits
    for i in range(N) :
 
        # For the first position
        if (N > 1 and i == 0) :
 
            # If digit is assigned
            # to the position
            if (0 in mp) :
                ans = ans + str(mp[0])
 
            # Otherwise
            else :
                ans = ans + str(1)
 
        else :
            # Add it to answer
            if i in mp :
                ans = ans + str(mp[i])
            else :
                ans = ans + str(0)
 
    print(ans)
 
# Driver code
N = 3
A = [ [ 0, 7 ], [ 2, 2 ], [ 0, 7 ] ]
 
find_num(N, A)
 
# This code is contributed by divyesh072019


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
public
 class pair
{
    public
 int first, second;
     
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
 
// Function to find the smallest integer
// satisfying the given conditions
static void find_num(int N, pair []A)
{
     
    // Stores the digits at their
    // respective positions
    Dictionary mp = new Dictionary();
 
    // Traverse the array
    for(int i = 0; i < A.Length; i++)
    {
         
        // If first digit required
        // to be placed is 0
        if (N > 1 && A[i].first == 0 &&
            A[i].second == 0)
        {
             
            // Not possible
            Console.Write("No");
            return;
        }
 
        // If multiple numbers are assigned
        // to be placed in a single position
        if (mp.ContainsKey(A[i].first) &&
            mp[A[i].first] != A[i].second)
        {
             
            // Not possible
            Console.Write("No");
            return;
        }
 
        // Assign the digits to their
        // respective positions
        if(mp.ContainsKey(A[i].first))
            mp[A[i].first] = A[i].second;
        else
        mp.Add(A[i].first, A[i].second);
    }
 
    // Stores the result
    String ans = "";
 
    // Traverse for all N digits
    for(int i = 0; i < N; i++)
    {
         
        // For the first position
        if (N > 1 && i == 0)
        {
 
            // If digit is assigned
            // to the position
            if (mp.ContainsKey(0))
            {
                 
                ans += String.Join("", mp[0]);
            }
 
            // Otherwise
            else
            {
                ans += String.Join("", 1);
            }
        }
        else
        {
             
            // Add it to answer
            if ( ! mp.ContainsKey(i) )
                ans += String.Join("", 0);
            else
                ans += String.Join("", mp[i]);
        }
    }
    Console.Write(ans + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 3;
    pair []A = { new pair(0, 7),
                 new pair(2, 2),
                 new pair(0, 7)};
                  
    find_num(N, A);
}
}
 
// This code is contributed by 29AjayKumar


输出:
702

时间复杂度: O(10 N * M)
辅助空间: O(N)

有效方法:按照以下步骤解决问题:

  • 初始化一个 Map,比如mp ,将数字分配到相应的位置。
  • 如果需要放置的第一个数字是0 ,则打印“否”,因为该数字不能包含前导零。
  • 遍历数组 arr[] 并在Map 中的相应索引处插入数字。
  • 运行从1N的循环,对于每个i ,检查是否为Map 中的i位置分配了一个数字。如果出现在Map 中,请将其添加到答案中。

下面是上述方法的实现:

C++

// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find the smallest integer
// satisfying the given conditions
void find_num(int N, vector >& A)
{
    // Stores the digits at their
    // respective positions
    map mp;
 
    // Traverse the array
    for (int i = 0; i < A.size(); i++) {
 
        // If first digit required
        // to be placed is 0
        if (N > 1 and A[i].first == 0
            and A[i].second == 0) {
 
            // Not possible
            cout << "No";
            return;
        }
 
        // If multiple numbers are assigned
        // to be placed in a single position
        if (mp.find(A[i].first) != mp.end()
            and mp[A[i].first] != A[i].second) {
 
            // Not possible
            cout << "No";
            return;
        }
 
        // Assign the digits to their
        // respective positions
        mp[A[i].first] = A[i].second;
    }
 
    // Stores the result
    string ans = "";
 
    // Traverse for all N digits
    for (int i = 0; i < N; i++) {
 
        // For the first position
        if (N > 1 and i == 0) {
 
            // If digit is assigned
            // to the position
            if (mp.find(0) != mp.end()) {
                ans += to_string(mp[0]);
            }
 
            // Otherwise
            else {
                ans += to_string(1);
            }
        }
 
        else {
            // Add it to answer
            ans += to_string(mp[i]);
        }
    }
 
    cout << ans << "\n";
}
 
// Driver Code
int main()
{
 
    int N = 3;
    vector > A
        = { { 0, 7 }, { 2, 2 }, { 0, 7 } };
 
    find_num(N, A);
}

Java

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
static class pair
{
    int first, second;
     
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
 
// Function to find the smallest integer
// satisfying the given conditions
static void find_num(int N, pair []A)
{
     
    // Stores the digits at their
    // respective positions
    HashMap mp = new HashMap();
 
    // Traverse the array
    for(int i = 0; i < A.length; i++)
    {
         
        // If first digit required
        // to be placed is 0
        if (N > 1 && A[i].first == 0 &&
            A[i].second == 0)
        {
             
            // Not possible
            System.out.print("No");
            return;
        }
 
        // If multiple numbers are assigned
        // to be placed in a single position
        if (mp.containsKey(A[i].first) &&
            mp.get(A[i].first) != A[i].second)
        {
             
            // Not possible
            System.out.print("No");
            return;
        }
 
        // Assign the digits to their
        // respective positions
        mp.put(A[i].first, A[i].second);
    }
 
    // Stores the result
    String ans = "";
 
    // Traverse for all N digits
    for(int i = 0; i < N; i++)
    {
         
        // For the first position
        if (N > 1 && i == 0)
        {
 
            // If digit is assigned
            // to the position
            if (mp.containsKey(0))
            {
                 
                ans += String.valueOf(mp.get(0));
            }
 
            // Otherwise
            else
            {
                ans += String.valueOf(1);
            }
        }
        else
        {
             
            // Add it to answer
            if (mp.get(i) == null)
                ans += String.valueOf(0);
            else
                ans += String.valueOf(mp.get(i));
        }
    }
    System.out.print(ans + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 3;
    pair []A = { new pair(0, 7),
                 new pair(2, 2),
                 new pair(0, 7)};
                  
    find_num(N, A);
}
}
 
// This code is contributed by Amit Katiyar

蟒蛇3

# Python3 program to implement
# the above approach
 
# Function to find the smallest integer
# satisfying the given conditions
def find_num(N, A) :
 
    # Stores the digits at their
    # respective positions
    mp = {}
 
    # Traverse the array
    for i in range(len(A)) :
 
        # If first digit required
        # to be placed is 0
        if ((N > 1) and (A[i][0] == 0) and (A[i][1] == 0)) :
 
            # Not possible
            print("No")
            return
 
        # If multiple numbers are assigned
        # to be placed in a single position
        if ((A[i][0] in mp) and (mp[A[i][0]] != A[i][1])) :
 
            # Not possible
            print("No")
            return
 
        # Assign the digits to their
        # respective positions
        mp[A[i][0]] = A[i][1]
 
    # Stores the result
    ans = ""
 
    # Traverse for all N digits
    for i in range(N) :
 
        # For the first position
        if (N > 1 and i == 0) :
 
            # If digit is assigned
            # to the position
            if (0 in mp) :
                ans = ans + str(mp[0])
 
            # Otherwise
            else :
                ans = ans + str(1)
 
        else :
            # Add it to answer
            if i in mp :
                ans = ans + str(mp[i])
            else :
                ans = ans + str(0)
 
    print(ans)
 
# Driver code
N = 3
A = [ [ 0, 7 ], [ 2, 2 ], [ 0, 7 ] ]
 
find_num(N, A)
 
# This code is contributed by divyesh072019

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
public
 class pair
{
    public
 int first, second;
     
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
 
// Function to find the smallest integer
// satisfying the given conditions
static void find_num(int N, pair []A)
{
     
    // Stores the digits at their
    // respective positions
    Dictionary mp = new Dictionary();
 
    // Traverse the array
    for(int i = 0; i < A.Length; i++)
    {
         
        // If first digit required
        // to be placed is 0
        if (N > 1 && A[i].first == 0 &&
            A[i].second == 0)
        {
             
            // Not possible
            Console.Write("No");
            return;
        }
 
        // If multiple numbers are assigned
        // to be placed in a single position
        if (mp.ContainsKey(A[i].first) &&
            mp[A[i].first] != A[i].second)
        {
             
            // Not possible
            Console.Write("No");
            return;
        }
 
        // Assign the digits to their
        // respective positions
        if(mp.ContainsKey(A[i].first))
            mp[A[i].first] = A[i].second;
        else
        mp.Add(A[i].first, A[i].second);
    }
 
    // Stores the result
    String ans = "";
 
    // Traverse for all N digits
    for(int i = 0; i < N; i++)
    {
         
        // For the first position
        if (N > 1 && i == 0)
        {
 
            // If digit is assigned
            // to the position
            if (mp.ContainsKey(0))
            {
                 
                ans += String.Join("", mp[0]);
            }
 
            // Otherwise
            else
            {
                ans += String.Join("", 1);
            }
        }
        else
        {
             
            // Add it to answer
            if ( ! mp.ContainsKey(i) )
                ans += String.Join("", 0);
            else
                ans += String.Join("", mp[i]);
        }
    }
    Console.Write(ans + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 3;
    pair []A = { new pair(0, 7),
                 new pair(2, 2),
                 new pair(0, 7)};
                  
    find_num(N, A);
}
}
 
// This code is contributed by 29AjayKumar
输出:
702

时间复杂度: O(N + M)
辅助空间: O(N)