这道题没有想到在加点时可以一直保证前缀的完美匹配,写了一个类似反悔的做法,考场上set重复,寄。
这道题可以把后来的表看成左部点,原来看成右部点,然后跑最小费用的二分图匹配。我们简单的手玩一下这个过程,发现如果你按分数先排序,从小到大去匹配的话,那么新的点是很难破坏前面的免费的匹配的。这启示我们贪心。
将点从小到大排序后,从小到大考虑,对于每个左部点,如果前面有和他相同国籍的点,则取最右边的直接匹配。剩下的点则一定无法完成免费匹配,这些点之间可以任意匹配而不影响答案。
剩下的点从左到右考虑,右部点随便找一个左边的点就好。
但是由于你固定了匹配,所以可能不合法,比如: ,其中左边的 和 是右部点,那么按原来的方法就会寄。
此时我们就需要拆掉一个免费的匹配,按照我们的方法,拆掉的匹配的左部点一定要比当前点小,右部点需要尽量大(可以有更多匹配左部点的机会)。拆掉匹配后,把多出的右部点也一起在匹配中考虑即可。
#include <bits/stdc++.h>
using namespace std;
const int maxn=4e5+10;
struct match{
int w,k2,w2;
bool operator < (const match o) const
{return w<o.w;}
};
int n,t[maxn],m;
struct animal{
int k,w,type,II;
bool operator < (const animal o) const
{return w==o.w?type<o.type:w<o.w;}
}a[maxn],b[maxn],c[maxn];
int cnt[maxn],len;
int ins[maxn];
vector< pair<int,int> > S[maxn];
vector< tuple<int,int,int> > mat;
set< tuple<int,int,int,int> > I;
set< tuple<int,int,int> > S2;
int rev[maxn];
int M[maxn];
int main()
{
//freopen("farm.in","r",stdin);
//freopen("farm.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d%d",&a[i].k,&a[i].w),a[i].type=0,t[i]=a[i].k,a[i].II=i;
for(int i=n+1;i<=2*n;i++)
scanf("%d%d",&a[i].k,&a[i].w),a[i].type=1,t[i]=a[i].k,a[i].II=i;
sort(t+1,t+1+2*n);
m=unique(t+1,t+1+2*n)-t-1;
for(int i=1;i<=2*n;i++)a[i].k=lower_bound(t+1,t+1+m,a[i].k)-t;
for(int i=n+1;i<=2*n;i++)cnt[a[i].k]++;
sort(a+1,a+1+2*n);
for(int i=1;i<=2*n;i++)
{
// printf("@%d %d %d\n",a[i].k,a[i].w,a[i].type);
if(a[i].type==0)S[a[i].k].push_back({a[i].w,i});
else
{
if(S[a[i].k].size())
{
int L=S[a[i].k].back().second;
mat.push_back(make_tuple(a[L].w,L,i));
rev[i]=S[a[i].k].back().second;
//printf("!%d %d %d\n",a[i].k,a[i].w,i);
S[a[i].k].pop_back();
}
else I.insert(make_tuple(a[i].w,1,a[i].k,i));
}
}
for(int i=1;i<=m;i++)
while(S[i].size())
{
int id=S[i].back().second;
I.insert(make_tuple(a[id].w,0,i,id));
S[i].pop_back();
}
sort(mat.begin(),mat.end());
int ptr=0;
//for(auto [a,b,c]:mat){printf("%d %d %d\n",a,b,c);}
//for(int i=1;i<=len;i++)
// printf("!%d %d %d\n",c[i].k,c[i].w,c[i].type);
vector<int> E;
int ans=0,cnt=0;
while(!I.empty())
{
int id,w,type,k;
tie(w,type,k,id)=*I.begin();
//printf("!%d %d %d %d\n",id,k,w,type);
I.erase(I.begin());
while(ptr<mat.size()&&get<0>(mat[ptr])<=w)
{
int W=get<0>(mat[ptr]);
int L=get<1>(mat[ptr]);
int R=get<2>(mat[ptr]);
S2.insert(make_tuple(a[R].w,L,R));
ptr++;
}
//printf("%d\n",cnt);
if(type==0)E.push_back(id);
else if(E.size())rev[id]=E.back(),E.pop_back(),ans++;
else
{
auto it=--S2.end();
//printf("%d %d\n",it->first,it->second);
int W,L,R;
tie(W,L,R)=*it;
I.insert(make_tuple(W,1,a[R].k,R));
rev[id]=L;
ans++;
S2.erase(it);
}
}
printf("%d\n",ans);
//for(int i=1;i<=2*n;i++)
// if(a[i].type==1)M[a[i].II-n]=a[rev[i]].II;
//for(int i=1;i<=n;i++)
// printf("%d %d\n",i,M[i]);
return 0;
}
/*
3
3 500
2 200
1 100
1 1000
3 700
3 400
4
2 1
4 2
1 5
3 6
8 3
4 4
2 7
10 8
*/