力扣 第 341 场周赛代码---50minAK

T1 一最多的行

class Solution {
public:
    vector<int> rowAndMaximumOnes(vector<vector<int>>& g) {
        int n = g.size(), m = g[0].size();
        int res = 0, row = 0;
        for(int i = 0; i < n; i ++)
        {
            int sum = 0;
            for(int j = 0; j < m; j ++)
                sum += g[i][j] == 1;
            if(sum > res) 
            {
                res = sum;
                row = i;
            }
        }
        return {row, res};
    }
};

T2 找出可整除性得分最大的整数 — 模拟

class Solution {
public:
    int maxDivScore(vector<int>& a, vector<int>& b) {
        int maxv = 0, ans = 2e9;
        for(auto x : b)
        {
            int sum = 0;
            for(auto v : a)
                if(v % x == 0) sum ++;
            if(sum > maxv)
            {
                maxv = sum;
                ans = x;
            }
            else if(sum == maxv) ans = min(ans, x);
        }
        return ans;
    }
};

T3 构造有效字符串的最少插入数 — 贪心

class Solution {
public:
    int addMinimum(string s) {
        int res = 1;
        for(int i = 1; i < s.size(); i ++)
            if(s[i] <= s[i - 1]) res ++;
        res = 3 * res - s.size();
        return res;
    }
};

T4 最小化旅行的价格总和 — 暴搜 + 树形dp

class Solution {
public:
    vector<int> g[210];
    int f[200][2] = {0};
    int minimumTotalPrice(int n, vector<vector<int>>& edges, vector<int>& price, vector<vector<int>>& trips) {

        vector<int> w = price;
        vector<int> cnt(200, 0);
        for(auto &e : edges)
        {
            g[e[0]].push_back(e[1]);
            g[e[1]].push_back(e[0]);
        }
        
        function<void(int, int, int, vector<int>)> get_value = [&](int u, int fa, int ed, vector<int> path)
        {
            if(u == ed)
            {
                for(auto x : path) cnt[x] ++;
                return ;
            }
            for(auto v : g[u])
            {
                if(v == fa) continue;
                path.push_back(v);
                get_value(v, u, ed, path);
                path.pop_back();
            }
    	};
        
        for(auto &e : trips)
            get_value(e[0], -1, e[1], {e[0]});
        
        int sum = 0;
        for(int i = 0; i < n; i ++) w[i] = price[i] * cnt[i], sum += w[i];
        
        function<void(int,int)> dfs = [&](int u,int fa)
        {
            f[u][1] = w[u];
            for(auto v : g[u])
            {
                if(fa == v) continue;
                dfs(v, u);
                f[u][0] += max(f[v][0], f[v][1]);
                f[u][1] += f[v][0];
            }
    	};
        
        dfs(0, -1);
        int res = sum - max(f[0][0], f[0][1]) / 2;
        
        return res;
    }
};

你可能感兴趣的:(比赛补题,c++)