Problem Description
初始有 a,b 两个正整数,每次可以从中选一个大于 1 的数减 1,最后两个都会减到 1,我们想知道在过程中两个数互质的次数最多是多少。
Input
第一行一个正整数 test(1≤test≤1000000) 表示数据组数。
接下来 test 行,每行两个正整数 a,b(1≤a,b≤1000)。
Output
对于每组数据,一行一个整数表示答案。
Sample Input
1
2 3
Sample Output
4
样例解释
2 3 -> 1 3 -> 1 2 -> 1 1
官方解释:
用 f[i][j] 表示第一个数字从 ii 开始减,第二个数字从 jj 开始减的情况下最多有多少对互质的数字,f[i][j]从 f[i-1][j] 或 f[i][j-1转移过来。
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long int ll;
int t,f[1011][1011],n,m;
int gcd(int a,int b)//辗转相除求最小公约数
{
return b ? gcd(b,a%b):a;
}
int main()
{
scanf("%d",&t);
int n_max=1010;
for(int i=1;i<=n_max;i++)//动态规划
{
for(int j=1;j<=n_max;j++)
{
int t=0;
if (gcd(i,j)==1)//如果最大公约数是1则互质
t=1;
f[i][j]=max(f[i-1][j]+t,f[i][j-1]+t);//取最大值
//printf("%d %d %d\n",i,j,f[i][j]);
}
}
while(t--)
{
scanf("%d%d",&n,&m);
printf("%d\n",f[n][m]);
}
return 0;
}