<p>You are given an <code>m x n</code> matrix <code>mat</code> that has its rows sorted in non-decreasing order and an integer <code>k</code>.</p>

<p>You are allowed to choose <strong>exactly one element</strong> from each row to form an array.</p>

<p>Return <em>the </em><code>k<sup>th</sup></code><em> smallest array sum among all possible arrays</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,3,11],[2,4,6]], k = 5
<strong>Output:</strong> 7
<strong>Explanation:</strong> Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,3,11],[2,4,6]], k = 9
<strong>Output:</strong> 17
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
<strong>Output:</strong> 9
<strong>Explanation:</strong> Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.  
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == mat.length</code></li>
	<li><code>n == mat.length[i]</code></li>
	<li><code>1 &lt;= m, n &lt;= 40</code></li>
	<li><code>1 &lt;= mat[i][j] &lt;= 5000</code></li>
	<li><code>1 &lt;= k &lt;= min(200, n<sup>m</sup>)</code></li>
	<li><code>mat[i]</code> is a non-decreasing array.</li>
</ul>

class Solution {
public:
    vector<int> solve(vector<vector<int>>&mat,vector<int>&ans,int k,int r)
    {
        priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>>pq;
        pq.push({ans[0]+mat[r][0],{0,0}});
        vector<int>tmp;
        map<pair<int,int>,int>vis;
       /// cout<<r<<endl;
        while(k>0&&!pq.empty())
        {
            auto it=pq.top();
            pq.pop();
            int sum=it.first,i=it.second.first,j=it.second.second;
            //cout<<sum<<" "<<i<<" "<<j<<" "<<k<<endl;
            tmp.push_back(sum);
            if(i+1<ans.size()&&!vis[{i+1,j}]) {
                pq.push({ans[i+1]+mat[r][j],{i+1,j}});
               // cout<<i+1<<" "<<j<<" "<<vis[{i+1,j}]<<endl;
                vis[{i+1,j}]=1;
            }
            if(j+1<mat[r].size()&&!vis[{i,j+1}]){
                pq.push({ans[i]+mat[r][j+1],{i,j+1}});
                //cout<<i<<" "<<j+1<<" "<<vis[{i,j+1}]<<endl;
                vis[{i,j+1}]=1;
            }
            
            k--;
        }
        return tmp;
    }
    int kthSmallest(vector<vector<int>>& mat, int k) {
        int m=mat.size(),n=mat[0].size();
        if(m==1) return mat[0][k-1];
        vector<int>ans;
        for(int i=0;i<min(k,n);i++) ans.push_back(mat[0][i]);
        ans=solve(mat,ans,k,1);
        for(int r=2;r<m;r++)
        {
            ans=solve(mat,ans,k,r);
        }
        return ans[k-1];
    }
};
24151