A题 题意:
东东在玩游戏“Game23”。
在一开始他有一个数字n,他的目标是把它转换成m,在每一步操作中,他可以将n乘以2或乘以3,他可以进行任意次操作。输出将n转换成m的操作次数,如果转换不了输出-1。
Input
输入的唯一一行包括两个整数n和m(1<=n<=m<=5*10^8).
Output
输出从n转换到m的操作次数,否则输出-1.
Simple Input 1
120 51840
Simple Output 1
7
Simple Input 2
42 42
Simple Output 2
0
Simple Input 3
48 72
Simple Output 3
-1
思路:
先判断m是否能整除n,如果可以再看是否能被2,3整除,如果可以输出结果如果不可以输出-1.
代码:
#include
#include
#include
using namespace std;
int n, m;
int ct = 0;
int main()
{
cin >> n >> m;
if (m % n != 0)//如果不能整除输出-1
{
cout << -1 << endl;
return 0;
}
int t = m / n;
while (t % 2 == 0)
{
ct++;
t = t / 2;
}
if (t == 1)
{
cout << ct << endl;
return 0;
}
else
{
while (t % 3 == 0)
{
ct++;
t = t / 3;
}
if (t == 1)
{
cout << ct << endl;
return 0;
}
else
{
cout << -1 << endl;
}
}
return 0;
}
B题 题意:
东东有两个序列A和B。
他想要知道序列A的LIS和序列AB的LCS的长度。
注意,LIS为严格递增的,即a1 Input
第一行两个数n,m(1<=n<=5,000,1<=m<=5,000)
第二行n个数,表示序列A
第三行m个数,表示序列B
Output
输出一行数据ans1和ans2,分别代表序列A的LIS和序列AB的LCS的长度
Simple Input
5 5
1 3 2 5 4
2 4 3 1 5
Simple Output
3 2
思路:
LIS:
定义fi表示以Ai为结尾的最长上升序列,初始化fi=1
转移过程:如果fj
LCS:
初始化:设定f[i][j]为A1,A2,A3…Ai和B1,B2,B3,….Bj的LCS长度,并且初始化f[1][0]=f[0][1]=f[0][0]=0
转移:如果fi==fj则f[i][j]=f[i-1][j-1]+1
否则f[i][j]=max(f[i-1][j],f[i]f[j-1])
最终答案:f[n][m];
【程序设计【Week10】作业】代码:
#include
#include
#include
using namespace std;
int n, m, ans;
int A[5001], B[5001], f[5001], LCS[5001][5001];
int main()
{
cin >> n >> m;
for (int i = 1;
i <= n;
i++)
cin >> A[i];
for (int i = 1;
i <= m;
i++)
cin >> B[i];
//LIS
for (int i = 1;
i <= n;
i++)f[i] = 1;
//初始化为0
for (int i = 1;
i <= n;
i++)
for (int j = 1;
j < i;
j++)
if (A[j] < A[i])
f[i] = max(f[i], f[j] + 1);
for (int i = 1;
i <= n;
i++)
ans = max(ans, f[i]);
cout << ans << " ";
//LCS
LCS[1][0] = LCS[0][1] = LCS[0][0] = 0;
for (int i = 1;
i <= n;
i++)
for (int j = 1;
j <= m;
j++)
{
if (A[i] == B[j])
LCS[i][j] = LCS[i - 1][j - 1] + 1;
else
LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1]);
}
cout << LCS[n][m] << endl;
return 0;
}
C题 题意:
YJQ 上完第10周的程序设计思维与实践后,想到一个绝妙的主意,他对拿数问题做了一点小修改,使得这道题变成了 拿数问题 II。
给一个序列,里边有 n 个数,每一步能拿走一个数,比如拿第 i 个数, Ai = x,得到相应的分数 x,但拿掉这个 Ai 后,x+1 和 x-1 (如果有 Aj = x+1 或 Aj = x-1 存在) 就会变得不可拿(但是有 Aj = x 的话可以继续拿这个 x)。求最大分数。
Input
第一行包含一个整数 n (1?≤n≤?105),表示数字里的元素的个数
第二行包含n个整数a1, a2, …, an (1?≤ai≤?105)
Output
输出一个整数:n你能得到最大分值。
Example
Input
2
1 2
Output
2
Input
3
1 2 3
Output
4
Input
9
1 2 1 3 2 2 2 2 3
Output
10
Hint
对于第三个样例:先选任何一个值为2的元素,最后数组内剩下4个2。然后4次选择2,最终得到10分。
思路:
这个题和课上的思路很类似,不同的点在于当AJ=X的时候可以选择,所以初始化两个数组,dp[i]考虑从[1…i]能拿的最大分数
课上的题是:dp[i]=max(dp[i-1],dp[i-2]+A[i])既考虑拿还是不拿
而作业题的变化在于:dp[i]=max(dp[i-1],dp[i-2]+i*x[i]); 即加上相等数值的所有数。
代码:
#include
#include
#include
using namespace std;
int n;
long long dp[100005], x[100005];
int main()
{
int temp;
memset(dp, 0, sizeof(dp));
memset(x, 0, sizeof(x));
cin >> n;
for (int i = 0;
i < n;
i++)
{
cin >> temp;
x[temp]++;
}
dp[0] = x[0];
dp[1] = x[1];
for (int i = 2;
i < 100005;
i++)
{
dp[i] = max(dp[i - 2] + (long long)i * x[i], dp[i - 1]);
}
cout << dp[100000] << endl;
}