百度之星程序设计大赛 Problem C
题面
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
思路
动态规划的方向考虑,这个状态下的答案大于a-1或者b-1的情况下的最大值。
代码实现
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cstring >
#include<cmath>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn=20; 
inline int gcd (int a,int b) {
    if (b==0) return a;
    else return gcd (b,a%b);
}
int dp[1005][1005];
int main () {
    int t;
    for (int i=1;i<=1000;i++) {
        dp[i][1]=i;
    }
    for (int i=1;i<=1000;i++) dp[1][i]=i;
    for (int i=2;i<=1000;i++)
     for (int j=2;j<=1000;j++) {
         if (gcd (i,j)==1) {
             dp[i][j]=max (dp[i-1][j],dp[i][j-1])+1;
         }
         else {
             dp[i][j]=max (dp[i-1][j],dp[i][j-1]);
         }
     }
    cin>>t;
    while (t--) {
       int a,b;
       cin>>a>>b;
       cout<<dp[a][b]<<endl;
    }
    return 0;
}

                
            
        
浙公网安备 33010602011771号