2020 年百度之星·程序设计大赛 - 初赛一 Dec 二维DP,预处理

problem

Dec Accepts: 1284 Submissions: 4572
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
初始有 a, ba,b 两个正整数,每次可以从中选一个大于 1 的数减 1,最后两个都会减到 1,我们想知道在过程中两个数互质的次数最多是多少。

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

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

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

Sample Input
1
2 3
Sample Output
4

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

solution

  • 二维dp,不是减a就是减b,分别从两个状态转移过来,顺便加上当前的gcd,dp(i,j) = max(dp(i-1,j)+gcd(), dp(i,j-1)+gcd);
  • 因为数据都在1e3,所以全部预处理完输出。
  • cin会超时!!!
#include<cstdio>
#include<algorithm>
using namespace std;
int dp[1010][1010];
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;
}

猜你喜欢

转载自blog.csdn.net/qq_33957603/article/details/107522667