codeforces 831D - Office Keys(贪心,排序)

http://codeforces.com/contest/831/problem/D

题目:在一条x坐标轴上,有n个人(a1,a2,an),k把钥匙(坐标b1,b2,bk),这n个人要任意捡一把钥匙,到达目标点p,要求所有人都到达目标点,花费时间最短

以后贪心想不出来,或者想法太过复杂,考虑能不能满足某种顺序来做…
思路:首先考虑怎么贪心答案最优,假设不连续的拿,分别考虑终点在左,中,右都能发现这样没有连续取的距离短,所以考虑连续拿n个,直接n2枚举起点,每次取每次情况最大值(题目要求所有人到p,所以找到最大值)的最小

#include
#include
#define fi first
#define se second
#define show(a) cout<<"Here is "<
#define show2(a,b) cout<<"Here is "<
#define show3(a,b,c) cout<<"Here is "<
using namespace std;
 
typedef long long ll;
typedef pair<int, int> P;
typedef pair<P, int> LP;
const ll inf = 1e17 + 10;
const int N = 3e6 + 10;
const ll mod = 10007;
const int base=131;
tr1::unordered_map<ll,ll> mp,can,vis;
ll n,block,m,id,t,x,y;
ll num[N],cnt;
ll a[N],b[N],k;
ll ans,flag;
//ll tree[N],tag[N];
//vector v[N];
 
 
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
 
	int p;
	cin>>n>>k>>p;
	for(int i=1;i<=n;i++) cin>>a[i];
	sort(a+1,a+n+1);
	for(int i=1;i<=k;i++) cin>>b[i];
	sort(b+1,b+k+1);
	ans=inf;
	for(int i=1;i<=k-n+1;i++)
	{
		ll sum=0;
		for(int j=1;j<=n;j++)
		{
			sum=max(sum,abs(a[j]-b[i+j-1])+abs(p-b[i+j-1]));
		}
		ans=min(ans,sum);
	}
	cout<<ans<<endl;
}

你可能感兴趣的:(贪心)