https://codeforces.com/problemset/problem/1472/E
题意:有n个wi*hi 的方块,然后可以横着放可以竖着放。求 每个方块前面放置谁,可以不被挡住。不被挡住定义是,前面的方块的长宽都比后面的方块更小。
思路:
转化成数学就是 ai>aj&&bi>bj || ai>bj&&bi>aj
两个做法:
由于第一个条件是hi>hj&&wi>wj,第二个条件是hi>wi&&wj>hj
可以发现,左上是第二个条件的形式,但是当我们将长的作为w,短的作为h,其转化的图形就是第一个条件的。统一成一个条件了。
就可以模拟了。
贪心的一个细节:注意第一维同的时候第二维先按大的排。
w 2 3 3
h 3 2 4 这样更新导致取h的小会无法让第三个更新到。
换成
w 2 3 3
h 3 4 2 就可以了
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
struct P{
LL h,w,id;
}a[maxn];
LL pre[maxn];
vector<LL>v[maxn];
bool cmp(P A,P B){
if(A.w==B.w) return A.h>B.h;///要反过来
return A.w<B.w;
}
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
LL t;cin>>t;
while(t--){
LL n;cin>>n;
for(LL i=0;i<n+10;i++) v[i].clear();
for(LL i=1;i<=n;i++){
LL h,w;cin>>h>>w;
a[i].h=max(h,w);
a[i].w=min(h,w);
a[i].id=i;
}
sort(a+1,a+1+n,cmp);
v[a[1].id].push_back({-1});
LL pos=a[1].id;
LL pre=a[1].h;
LL width=a[1].w;
for(LL i=2;i<=n;i++){
if(a[i].h>pre&&a[i].w>width){
v[a[i].id].push_back({pos});
}
else v[a[i].id].push_back({-1});
if(pre>a[i].h){
pos=a[i].id;
width=a[i].w;
pre=a[i].h;
}
}
for(LL i=1;i<=n;i++){
cout<<v[i][0]<<" ";
}
cout<<"\n";
}
return 0;
}
第二种思路;
类似拆点,拆出来的编号是一样的。
每个点的两个长和宽分别赋值各形成一个点,放进去排序,这样就是两个状态都在里面比较。
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
struct P{
LL h,w,id;
}a[maxn*2];
LL tot=0;
vector<LL>v[maxn];
bool cmp(P A,P B){
if(A.h==B.h) return A.w>B.w;
return A.h<B.h;
}
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
LL t;cin>>t;
while(t--){
LL n;cin>>n;
tot=0;
for(LL i=0;i<n*2+10;i++) v[i].clear();
for(LL i=1;i<=n;i++){
LL h,w;cin>>h>>w;
a[++tot].h=h;a[tot].w=w;a[tot].id=i;
a[++tot].h=w;a[tot].w=h;a[tot].id=i;
}
sort(a+1,a+1+tot,cmp);
v[a[1].id].push_back({-1});
LL pos=a[1].id;
LL minw=a[1].w;
LL minh=a[1].h;
for(LL i=2;i<=tot;i++){
if(a[i].h>minh&&a[i].w>minw){
v[a[i].id].push_back({pos});
}
if(minw>a[i].w){
minw=a[i].w;
minh=a[i].h;
pos=a[i].id;
}
}
for(LL i=1;i<=n;i++){
if(v[i].size()==0) cout<<"-1"<<" ";
else cout<<v[i][0]<<" ";
}
cout<<"\n";
}
return 0;
}