20210218: Likou Week 228 (Part 2)

topic

    1. The least number of balls in the bag
      Insert picture description here
  1. The minimum degree of connected triples in a graph
    Insert picture description here

Ideas and algorithms

  1. Classic binary search questions, set templates, mainly to figure out how to check whether each number traversed is not greater than maxOperations.
  2. It seems that it can be ended violently, and you can directly count the connection and the degree of access. The question gives the upper limit of n is 400, which is the typical limit of 3 degree complexity. It also indirectly shows that the triples can be retrieved brutally.

Code

    1. The least number of balls in the bag
class Solution {
    
    
    public int minimumSize(int[] nums, int maxOperations) {
    
    
        int low = 1;
        int high = 1000000001;
        while (low + 1 < high) {
    
    
            int mid = low + (high - low) / 2;
            if (check(nums,mid,maxOperations)) {
    
    
                high = mid;
            } else {
    
    
                low = mid;
            }
        }
        if (check(nums,low,maxOperations)) {
    
    
            return low;
        }
        return high;
    }

    public boolean check(int[] balls,int penalty,int maxOperations){
    
    
        int res = 0;
        for (int i: balls) {
    
    
            res += i / penalty;
            if (i % penalty == 0) {
    
    
                res -= 1;
            }
            if (res > maxOperations) {
    
    
                return false;
            }
        }
        return true;
    }
}
  1. The minimum degree of connected triples in a graph
class Solution {
    
    
public:
    int minTrioDegree(int n, vector<vector<int>>& edges) {
    
    
        int ans = INT_MAX;
        vector<int> Degrees(n);
        vector<vector<bool>> Connected(n,vector<bool>(n));

        // 统计是否连接以及出入度
        for (auto &edge : edges) {
    
    
            Connected[edge[0] - 1][edge[1] - 1] = true;
            Connected[edge[1] - 1][edge[0] - 1] = true;

            Degrees[edge[0] - 1]++;
            Degrees[edge[1] - 1]++;
        }

        // 直接遍历寻找三元组即可
        for (int i = 0; i < n; ++i) {
    
    
            for (int j = i + 1; j < n; ++j) {
    
    
                // 剪枝:直接砍掉两两不相连的
                if ( !Connected[i][j] ){
    
    
                    continue;
                }
                for (int k = j + 1; k < n; ++k) {
    
    
                    // 如果全部两两相连
                    if (Connected[i][k] && Connected[j][k]) {
    
    
                        ans = min(ans,Degrees[i] + Degrees[j] + Degrees[k] - 6);
                    }
                }
            }
        }
        return ans == INT_MAX ? -1 : ans;
    }
};

Write at the end

  1. Stay with your family in the last few days at home

Guess you like

Origin blog.csdn.net/qq_36828395/article/details/113888627