标签:输出 转化 temp class nbsp c++ bit tor 通过
题目:判断一个数能否通过一个数组中的数相乘而得到(数组中的数使用次数不限)
例如:第一行输入目标数x,第二行再输入一个数组(每个数用空格隔开),如果能则输出1,不能则输出-1;
输入例1:
20
2 3 5 7
输出:
1
解释:20 = 2*2*5,可以组成,所以输出1.
输入例2:
20
3 5 7
输出:
-1
解释:无法组成,所以输出-1.
解题思路:转化成完全背包问题来解决(因为每个因子都可以使用无限次)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main(){
int x;
string str_x;
while(getline(cin, str_x) ){
x = atoi(str_x.c_str());
string str;
getline(cin, str);
istringstream temp(str);
vector<int> arr;
int cur;
while(temp>>cur){
arr.push_back(cur);
}
vector<int> dp(x+1, 0);
// vector<int> dp(x+1, -1000);
dp[1] = 1;
for(int i=0; i<arr.size(); i++){
for(int j=arr[i]; j<=x; j++ ){
if(j%arr[i]==0){
dp[j] = max(dp[j], dp[j/arr[i] ]);
}
}
}
if(dp[x]>0) cout<<1<<endl;
else cout<<-1<<endl;
}
return 0;
}
判断一个数能否通过一个数组中的数相乘而得到(数组中的数使用次数不限)
标签:输出 转化 temp class nbsp c++ bit tor 通过
原文地址:https://www.cnblogs.com/liugl7/p/11438016.html