题意:
给出k个数字x[i],和两个数字a,b(a≥b);每一步只能执行两个操作:
1.a-- ;
2. a-a%x[i];
求使a到b的最短操作步骤;
解法:
此题之前的版本:http://codeforces.com/problemset/problem/251/C,可用dp做,当时以为贪心不行。
( 大概解法是:dp[i]=min{dp[i],dp[i]-dp[i]%j } 2≤j≤k,
然后因为 2..k的最小公倍数必过,所以过了最小公倍数后,操作又是一样的了,所以步骤数也是相同,据此划分出一个区间所需要的步骤数,简化运算)
但这题用dp超时了,而且最小公倍数部分,x[i]一多没法求,一开始以为存在以下情况,假设下面六个连续的数 A>B>C>D>E>F,存在A到F这样的最短步骤A->B->F,如果用贪心的话可能是 A->C->E->F,所以贪心会错,但后来证实贪心没错,证明方法如下:
令dp[k]表示b到b+k所需要的步骤,可知dp[k]=dp[k-t]+1; (a>k-t≥b)
t=1时:易知dp[k]是一个递增的数列,即dp[k]≥dp[k-t];
t≠1时:假设dp[k]≤dp[k-t],则可得dp[k-1]≤dp[k-t]+1=dp[k],与假设矛盾,所以dp[k]≥dp[k-t]+1;
以下是codeforces上的题解说明:
Let dp[k] denotes the minimum number of steps to transform b+k to b. In each step, you could only choose i which makes b+k-(b+k) mod x[i] minimal to calc dp[k]. It works bacause dp[0..k-1] is a monotone increasing function. Proof: - Say dp[k]=dp[k-t]+1.If t==1, then dp[0..k] is monotone increasing obviously.Otherwise dp[k-1]<=dp[k-t]+1=dp[k] (there must exist a x[i] makes b+k-1 also transform to b+k-t,and it is not necessarily the optimal decision of dp[k-1]). So dp[k] is a monotone increasing function, we can greedily calc dp[a-b].
In the first glance, it looks like something which will run in square complexity. But actually is linear. That is because, we could cut exactly max{xi} in each 2 step. It can be proof by induction.
So the remians work is to delete those same xi, and watch out some situation could cause degeneration. Many of us failed in this last step and got TLE.
题解补充了会TLE的原因,x[i]的重复以及当 a接近b时部分x[i]是可以删除的
代码如下:
#include <bits/stdc++.h>
#define ll __int64
#define lld I64d
using namespace std;
const int maxn=200050;
ll x[maxn];
int main()
{
ll i,j,a,b,n,len,sum=0;
scanf("%lld",&n);
for(i=0;i<n;i++)
scanf("%lld",&x[i]);
scanf("%lld%lld",&a,&b);
sort(x,x+n);
len=unique(x,x+n)-x;
ll t;
while(a>b)
{
t=a-1;
for(i=0;i<len && i>-1;i++)
{
if(a-a%x[i] <b)
x[i--]=x[--len];
else
<span style="white-space:pre"> </span>t=min(t,a-a%x[i]);
}
a=t;
sum++;
}
printf("%lld\n",sum);
return 0;
}