1337. The K Weakest Rows in a Matrix

class Solution {
public:
    vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
        vector<int> cnt;
        for(int i=0;i<mat.size();i++){
            int sum = 0;
            for(int j=0;j<mat[0].size();j++){
                sum += mat[i][j];
            }
            cnt.push_back(sum);
        }
        
        // return min->max index
        map<int, vector<int>> res;
        for(int i=0;i<cnt.size();i++){ // 2,4,1,2,5
            int ans = cnt[i]; // 
            if (res.find(ans)==res.end()){
                vector<int> indexes(1, i);
                res[ans] = indexes;
            }
            else{
                res[ans].push_back(i);
            }
        }
        
        // return k indexs
        vector<int> result;
        for(auto it=res.begin();it!=res.end();it++){
            vector<int> aa = it->second;
            for(int i=0;i<aa.size()&&result.size()<k;i++){
                result.push_back(aa[i]);
            }
            
            if(result.size()>=k){
                break;
            }
        }
        return result;
    }
};
Jonathan is fighting against DIO's Vampire minions. There are n of them with strengths a1,a2,…,an. Denote (l,r) as the group consisting of the vampires with indices from l to r. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise AND. More formally, the strength level of the group (l,r) is defined as f(l,r)=al&al+1&al+2&…&ar. Here, & denotes the bitwise AND operation. Because Jonathan would like to defeat the vampire minions fast, he will divide the vampires into contiguous groups, such that each vampire is in exactly one group, and the sum of strengths of the groups is minimized. Among all ways to divide the vampires, he would like to find the way with the maximum number of groups. Given the strengths of each of the n vampires, find the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths. Input The first line contains a single integer t (1≤t≤104) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer n (1≤n≤2⋅105) — the number of vampires. The second line of each test case contains n integers a1,a2,…,an (0≤ai≤109) — the individual strength of each vampire. The sum of n over all test cases does not exceed 2⋅105. Output For each test case, output a single integer — the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths.c++实现
07-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值