洛谷 P2587 [ZJOI2008]泡泡堂(贪心)

传送门


解题思路

田忌赛马这道题的加强版。

收回我不能用贪心来解决的话。

排序后每个序列都用两个指针记录已经使用的数的位置。(一定先使用两边)

具体策略为:
若最大的比对方大,则最大的上。
若最小的比对方大,则最小的上。
否则就用最小的打对面最大的。

AC代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<vector>
#include<ctime>
#include<set>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
template<class T>inline void read(T &x)
{
    x=0;register char c=getchar();register bool f=0;
    while(!isdigit(c))f^=c=='-',c=getchar();
    while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
    if(f)x=-x;
}
template<class T>inline void print(T x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)print(x/10);
    putchar('0'+x%10);
}
const int maxn=100005;
int n,a[maxn],b[maxn],ans,l,r,x,y;
int main(){
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<=n;i++) cin>>b[i];
	sort(a+1,a+n+1);
	sort(b+1,b+n+1);
	l=1,r=n,x=1,y=n;
	for(int i=1;i<=n;i++){
		if(a[l]>b[x]){
			ans+=2;
			l++;x++;
			continue;
		}
		if(a[r]>b[y]){
			ans+=2;
			r--;y--;
			continue;
		}
		if(a[l]==b[y]){
			ans+=1;
			l++;
			y--;
			continue;
		}
		l++;y--;
	}
	cout<<ans<<" ";
	l=1,r=n,x=1,y=n,ans=0;
	for(int i=1;i<=n;i++){
		if(b[l]>a[x]){
			l++;x++;
			continue;
		}
		if(b[r]>a[y]){
			r--;y--;
			continue;
		}
		if(b[l]==a[y]){
			ans+=1;
			l++;
			y--;
			continue;
		}
		l++;y--;
		ans+=2;
	}
	cout<<ans<<endl;
	return 0;
}
posted @ 2021-10-01 18:37  尹昱钦  阅读(28)  评论(0编辑  收藏  举报