K Smallest Sums
题解
\(k*k\) 矩阵,每行选一个,求前 \(k\) 小的值
等价于 \((k-1)*k\) 矩阵每行选一个构成的前 \(k\) 小的值任选一个,与第 \(k\) 行 \(k\) 个数任选一个,其和的前 \(k\) 小
无限递推。。。。
变成了两个长度为 \(k\) 的序列,从两个序列中各取一个数并求和,求前 \(k\) 小

code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int a[800][800],c[800],tem[800];
struct node
{
int x,y,v;
bool operator<(const node &b) const
{
return b.v<v;
}
};
void solve()
{
int n;
while(cin>>n)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>a[i][j];
}
sort(a[i]+1,a[i]+1+n);
}
for(int i=1;i<=n;i++) c[i]=a[1][i];
for(int i=2;i<=n;i++)
{
priority_queue<node> q;
for(int j=1;j<=n;j++) q.push({j,1,c[j]+a[i][1]});
for(int j=1;j<=n;j++)
{
auto [x,y,v]= q.top();
q.pop();
tem[j]=v;
if(y<n) q.push({x,y+1,c[x]+a[i][y+1]});
}
for(int j=1;j<=n;j++) c[j]=tem[j];
}
for(int i=1;i<n;i++) cout<<c[i]<<' ';
cout<<c[n]<<'\n';
}
}
int main()
{
//ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t=1;
//cin>>t;
while(t--) solve();
return 0;
}

浙公网安备 33010602011771号