题解:U630153 The cruel world!
xiaoliebao1115 · · 题解
sol
理想状态最优情况肯定是每行每列都选到了最小值。
我们考虑在这个基础上调整,先询问出每行每列最小值,定义一个矩阵
我们此时要去调整
注意到对于
重新设加的那个位置为
若有
观察这个图的性质,发现一个
令一个
一次调整过后会最多会将两个连通块连起来,发现此时被连的那个连通块的最优
操作次数
这个复杂度可以直接 DS 优化,或者直接不考虑其他连通块对于当前连通块的影响,直接给最优位置
另外此题的非交互版本有二分图最小基环树森林做法,不过很难作用于此题本身。
code
#include<bits/stdc++.h>
using namespace std;
extern "C" void setup(int i,int j);
extern "C" std::pair<int,int> query(int k,int opt);
#define ll long long
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
vector<vector<int>> c,id;
const int nn=2e5+105;
bool b[nn];
vector<int> e[nn];
struct node{
int i,j,mn;
inline void setup(){
i=0,j=0,mn=INT_MAX;
}
node(){
setup();
}
node(int _i,int _j,int _mn){i=_i,j=_j,mn=_mn;}
};
inline void chkmn(node &x,node y){
if(y.mn<x.mn) x=y;
}
node h[nn],l[nn];
int h2[nn],l2[nn],timer;
inline void con(int x,int y){
e[x].pb(y);
e[y].pb(x);
}
pii rev[nn];
inline void ins(int i,int j){
id[i][j]=++timer;
rev[timer]=mp(i,j);
if(h2[i]!=-1) con(h2[i],timer);
h2[i]=timer;
if(l2[j]!=-1) con(l2[j],timer);
l2[j]=timer;
}
queue<int> q;
vector<int> cl;
inline void ps(int x){
q.push(x);
b[x]=1;
cl.pb(x);
}
inline void col(int i,int j){
setup(i,j);
pii mzh=query(i,0);
h[i]=node(i,mzh.se,mzh.fi);
mzh=query(j,1);
l[j]=node(mzh.se,j,mzh.fi);
}
extern "C" long long solve(int n,int m){
memset(h2,-1,sizeof(h2)),memset(l2,-1,sizeof(l2));
c.resize(n),id.resize(n);
for(int i=0;i<n;i++) c[i].resize(m),id[i].resize(m);
ll ans=0;
for(int i=0;i<n;i++){
pii mzh=query(i,0);
h[i]=node(i,mzh.se,mzh.fi);
ans+=mzh.fi;
c[h[i].i][h[i].j]++,ins(h[i].i,h[i].j);
}
vector<pii> ve;
for(int j=0;j<m;j++){
pii mzh=query(j,1);
l[j]=node(mzh.se,j,mzh.fi);
c[l[j].i][l[j].j]++;
if(c[l[j].i][l[j].j]==1) ans+=mzh.fi,ins(l[j].i,l[j].j);
else ve.pb(mp(l[j].i,l[j].j));
}
for(int i=0;i<n;i++) setup(h[i].i,h[i].j);
for(int j=0;j<m;j++) if(c[l[j].i][l[j].j]==1) setup(l[j].i,l[j].j);
for(int i=0;i<n;i++){
pii mzh=query(i,0);
h[i]=node(i,mzh.se,mzh.fi);
}
for(int j=0;j<m;j++){
pii mzh=query(j,1);
l[j]=node(mzh.se,j,mzh.fi);
}
while(ve.size()){
vector<node> tmp;
for(int k=0;k<ve.size();k++){
node res;
ps(id[ve[k].fi][ve[k].se]);
while(!q.empty()){
int x=q.front();
int i=rev[x].fi,j=rev[x].se;
chkmn(res,h[i]),chkmn(res,l[j]);
q.pop();
for(int mzh:e[x]){
if(!b[mzh]) ps(mzh);
}
}
tmp.pb(res);
for(int x:cl) b[x]=0;
cl.clear();
}
for(pii mzh:ve) c[mzh.fi][mzh.se]=1;
ve.clear();
for(node mzh:tmp){
if(c[mzh.i][mzh.j]==0) ins(mzh.i,mzh.j),col(mzh.i,mzh.j),ans+=mzh.mn;
c[mzh.i][mzh.j]++;
if(c[mzh.i][mzh.j]==2) ve.pb(mp(mzh.i,mzh.j));
}
}
//for(pii mzh:ve){
// ps(id[mzh.fi][mzh.se]);
// node res;
// while(!q.empty()){
// int x=q.front();
// int i=rev[x].fi,j=rev[x].se;
// chkmn(res,h[i]),chkmn(res,l[j]);
// q.pop();
// for(int mzh:e[x]){
// if(!b[mzh]) ps(mzh);
// }
// }
// for(int x:cl) b[x]=0;
// cl.clear();
// ins(res.i,res.j),col(res.i,res.j),ans+=res.mn;
//}理论复杂度大的做法
return ans;
}