2020 年百度之星·程序设计大赛 - 初赛一Dec 简单dp

题意:

Problem Description

初始有 a, ba,b 两个正整数,每次可以从中选一个大于 1 的数减 1,最后两个都会减到 1,我们想知道在过程中两个数互质的次数最多是多少。

Input

第一行一个正整数 test(1 \le test \le 1000000)test(1test1000000) 表示数据组数。

接下来 test 行,每行两个正整数 a, b(1 \le a, b \le 1000)a,b(1a,b1000)。

Output

对于每组数据,一行一个整数表示答案。

Sample Input
1
2 3
Sample Output
4

样例解释
2 3 -> 1 3 -> 1 2 -> 1 1

题解:

a,b范围1e3,那就dp解决问题,判断两个数是否互质用gcd就行

代码:

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <ctime>
#include <cstring>
#include <cstdlib>
#include <math.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=1e3+10;
const int eps=1e-6;
int dp[maxn][maxn];
int gcd(int a, int b)
{
    return !b?a:gcd(b,a%b);
}
int main()
{
    for(int i = 1; i <= 1000; i++)
    {
        for(int j = 1; j <= 1000; j++)
        {
            dp[i][j] = max(dp[i-1][j]+(gcd(i,j)==1),dp[i][j-1]+(gcd(i,j)==1));
        }
    }
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int a, b;
        scanf("%d%d",&a,&b);
        printf("%d\n",dp[a][b]);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/kongbursi-2292702937/p/13383604.html