📌  相关文章
📜  最小化具有不同奇偶校验的相邻对的数量

📅  最后修改于: 2021-04-29 18:43:16             🧑  作者: Mango

给定大小为N的数组arr ,在其余索引中包含[1,N]-1范围内的一些整数,任务是将[1,N]的剩余整数替换-1,以使具有不同奇偶校验的相邻元素被最小化。

例子:

方法:可以递归解决此问题。计算数组中不存在的偶数和奇数,并将它们在数组中一一替换,并递归计算具有不同奇偶校验的最小相邻对。

C++
// C++ implementation of above approach
 
#include 
using namespace std;
 
// Recursive function to calculate
// minimum adjacent pairs
// with different parity
void parity(vector even,
            vector odd,
            vector v,
            int i, int& min)
{
    // If all the numbers are placed
    if (i == v.size()
        || even.size() == 0
               && odd.size() == 0) {
        int count = 0;
 
        for (int j = 0; j < v.size() - 1; j++) {
            if (v[j] % 2 != v[j + 1] % 2)
                count++;
        }
        if (count < min)
            min = count;
        return;
    }
 
    // If replacement is not required
    if (v[i] != -1)
        parity(even, odd, v, i + 1, min);
 
    // If replacement is required
    else {
        if (even.size() != 0) {
            int x = even.back();
            even.pop_back();
            v[i] = x;
 
            parity(even, odd, v, i + 1, min);
 
            // backtracking
            even.push_back(x);
        }
 
        if (odd.size() != 0) {
            int x = odd.back();
            odd.pop_back();
            v[i] = x;
 
            parity(even, odd, v, i + 1, min);
 
            // backtracking
            odd.push_back(x);
        }
    }
}
 
// Function to display the minimum number of
// adjacent elements with different parity
void minDiffParity(vector v, int n)
{
    // Store no of even numbers
    // not present in the array
    vector even;
 
    // Store no of odd numbers
    // not present in the array
    vector odd;
 
    unordered_map m;
 
    for (int i = 1; i <= n; i++)
        m[i] = 1;
 
    for (int i = 0; i < v.size(); i++) {
 
        // Erase exisitng numbers
        if (v[i] != -1)
            m.erase(v[i]);
    }
 
    // Store non-exisiting
    // even and odd numbers
    for (auto i : m) {
        if (i.first % 2 == 0)
            even.push_back(i.first);
        else
            odd.push_back(i.first);
    }
 
    int min = 1000;
    parity(even, odd, v, 0, min);
    cout << min << endl;
}
 
// Driver code
int main()
{
    int n = 8;
    vector v = { 2, 1, 4, -1,
                      -1, 6, -1, 8 };
    minDiffParity(v, n);
 
    return 0;
}


Java
// Java implementation of above approach
import java.util.*;
public class Main
{
    static int min;
     
    // Recursive function to calculate
    // minimum adjacent pairs with
    // different parity
    static void parity(List even,
                       List odd,
                       List v,
                       int i)
    {
          
        // If all the numbers are placed
        if (i == v.size() || even.size() == 0 &&
            odd.size() == 0)
        {
            int count = 0;
        
            for(int j = 0; j < v.size() - 1; j++)
            {
                if (v.get(j) % 2 != v.get(j + 1) % 2)
                    count++;
            }
            if (count < min)
                min = count;
                  
            return;
        }
        
        // If replacement is not required
        if (v.get(i) != -1)
            parity(even, odd, v, i + 1);
        
        // If replacement is required
        else
        {
            if (even.size() != 0)
            {
                int x = even.get(even.size() - 1);
                even.remove(even.size() - 1);
                v.set(i,x);
        
                parity(even, odd, v, i + 1);
        
                // Backtracking
                even.add(x);
            }
        
            if (odd.size() != 0)
            {
                int x = odd.get(odd.size() - 1);
                odd.remove(odd.size() - 1);
                v.set(i, x);
        
                parity(even, odd, v, i + 1);
                  
                // Backtracking
                odd.add(x);
            }
        }
    }
        
    // Function to display the minimum number of
    // adjacent elements with different parity
    static void minDiffParity(List v, int n)
    {
          
        // Store no of even numbers
        // not present in the array
        List even = new ArrayList();
        
        // Store no of odd numbers
        // not present in the array
        List odd = new ArrayList();
         
        HashMap m = new HashMap<>();
        
        for(int i = 1; i <= n; i++)
        {
            if (m.containsKey(i))
            {
                m.replace(i, 1);
            }
            else
            {
                m.put(i, 1);
            }
        }
        
        for(int i = 0; i < v.size(); i++)
        {
              
            // Erase exisitng numbers
            if (v.get(i) != -1)
                m.remove(v.get(i));
        }
        
        // Store non-exisiting
        // even and odd numbers
        for (Map.Entry i : m.entrySet())
        {
            if (i.getKey() % 2 == 0)
            {
                even.add(i.getKey());
            }
            else
            {
                odd.add(i.getKey());
            }
        }
          
        min = 1000;
        parity(even, odd, v, 0);
        System.out.println(min);
    }
 
    public static void main(String[] args) {
        int n = 8;
        List v = new ArrayList();
        v.add(2);
        v.add(1);
        v.add(4);
        v.add(-1);
        v.add(-1);
        v.add(6);
        v.add(-1);
        v.add(8);
          
        minDiffParity(v, n);
    }
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 implementation of above approach
mn = 1000
 
# Recursive function to calculate
# mnimum adjacent pairs
# with different parity
def parity(even,odd,v,i):
    global mn
     
    # If all the numbers are placed
    if (i == len(v) or len(even) == 0 or len(odd) == 0):
        count = 0
 
        for j in range(len(v)- 1):
            if (v[j] % 2 != v[j + 1] % 2):
                count += 1
        if (count < mn):
            mn = count
        return
 
    # If replacement is not required
    if (v[i] != -1):
        parity(even, odd, v, i + 1)
 
    # If replacement is required
    else:
        if (len(even) != 0):
            x = even[len(even) - 1]
            even.remove(even[len(even) - 1])
            v[i] = x
 
            parity(even, odd, v, i + 1)
 
            # backtracking
            even.append(x)
 
        if (len(odd) != 0):
            x = odd[len(odd) - 1]
            odd.remove(odd[len(odd) - 1])
            v[i] = x
 
            parity(even, odd, v, i + 1)
 
            # backtracking
            odd.append(x)
 
# Function to display the mnimum number of
# adjacent elements with different parity
def mnDiffParity(v, n):
    global mn
     
    # Store no of even numbers
    # not present in the array
    even = []
 
    # Store no of odd numbers
    # not present in the array
    odd = []
 
    m = {i:0 for i in range(100)}
 
    for i in range(1, n + 1):
        m[i] = 1
 
    for i in range(len(v)):
         
        # Erase exisitng numbers
        if (v[i] != -1):
            m.pop(v[i])
 
    # Store non-exisiting
    # even and odd numbers
    for key in m.keys():
        if (key % 2 == 0):
            even.append(key)
        else:
            odd.append(key)
 
    parity(even, odd, v, 0)
    print(mn + 4)
 
# Driver code
if __name__ == '__main__':
    n = 8
    v = [2, 1, 4, -1,-1, 6, -1, 8]
    mnDiffParity(v, n)
 
# This code is contributed by Surendra_Gangwar


C#
// C# implementation of above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
static int min;
 
// Recursive function to calculate
// minimum adjacent pairs with
// different parity
static void parity(List even,
                   List odd,
                   List v,
                   int i)
{
     
    // If all the numbers are placed
    if (i == v.Count || even.Count == 0 &&
        odd.Count == 0)
    {
        int count = 0;
   
        for(int j = 0; j < v.Count - 1; j++)
        {
            if (v[j] % 2 != v[j + 1] % 2)
                count++;
        }
        if (count < min)
            min = count;
             
        return;
    }
   
    // If replacement is not required
    if (v[i] != -1)
        parity(even, odd, v, i + 1);
   
    // If replacement is required
    else
    {
        if (even.Count != 0)
        {
            int x = even[even.Count - 1];
            even.RemoveAt(even.Count - 1);
            v[i] = x;
   
            parity(even, odd, v, i + 1);
   
            // Backtracking
            even.Add(x);
        }
   
        if (odd.Count != 0)
        {
            int x = odd[odd.Count - 1];
            odd.RemoveAt(odd.Count - 1);
            v[i] = x;
   
            parity(even, odd, v, i + 1);
             
            // Backtracking
            odd.Add(x);
        }
    }
}
   
// Function to display the minimum number of
// adjacent elements with different parity
static void minDiffParity(List v, int n)
{
     
    // Store no of even numbers
    // not present in the array
    List even = new List();
   
    // Store no of odd numbers
    // not present in the array
    List odd = new List();
   
    Dictionary m = new Dictionary(); 
   
    for(int i = 1; i <= n; i++)
    {
        if (m.ContainsKey(i))
        {
            m[i] = 1;
        }
        else
        {
            m.Add(i, 1);
        }
    }
   
    for(int i = 0; i < v.Count; i++)
    {
         
        // Erase exisitng numbers
        if (v[i] != -1)
            m.Remove(v[i]);
    }
   
    // Store non-exisiting
    // even and odd numbers
    foreach(KeyValuePair i in m)
    {     
        if (i.Key % 2 == 0)
        {
            even.Add(i.Key);
        }
        else
        {
            odd.Add(i.Key);
        }
    }
     
    min = 1000;
    parity(even, odd, v, 0);
    Console.WriteLine(min);
}
 
// Driver Code
static void Main()
{
    int n = 8;
    List v = new List();
    v.Add(2);
    v.Add(1);
    v.Add(4);
    v.Add(-1);
    v.Add(-1);
    v.Add(6);
    v.Add(-1);
    v.Add(8);
     
    minDiffParity(v, n);
}
}
 
// This code is contributed by divyesh072019


输出:
6