如此编码#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#include<bits/stdc++.h>
using namespace std;
const int N = 25;
int n,m;
int a[N],c[N],b[N];
int main(){
cin>>n>>m;
for(int i = 1; i <= n; i++) cin>>a[i];
c[0] = 1;
c[1] = a[1];
for(int i = 2 ; i <= n; i++) c[i] = c[i-1] * a[i];
for(int i = 1; i <= n; i++){
b[i] = m % a[i];
m = m / a[i];
}
for(int i = 1; i <= n; i++) cout<<b[i]<<" ";
return 0;
}
|
何以包邮 ?#
暴力循环的写法,可以过 70%的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#include<bits/stdc++.h>
using namespace std;
const int N = 33;
int n, x;
int w[N];
int main(){
cin>>n>>x;
for(int i = 0; i < n; i++){
cin>>w[i];
}
int res = 1e8;
for(int i = 0; i < 1<<n; i++){
int sum = 0;
for(int j = 0; j < n; j++){
if(i >> j & 1){
sum += w[j];
}
}
if(sum >= x) res = min(sum, res);
}
cout<<res<<endl;
return 0;
}
|
用 dfs 暴搜的方法,同样过 70%的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#include<bits/stdc++.h>
using namespace std;
const int N = 33;
int n, x;
int w[N];
int res = 1e8;
void dfs(int u, int sum){
if(u == n){
if(sum >= x) res = min(res, sum);
}else{
dfs(u+1, sum);
dfs(u+1, sum + w[u]);
}
}
int main(){
cin>>n>>x;
for(int i = 0; i < n; i++){
cin>>w[i];
}
dfs(0, 0);
cout<<res<<endl;
return 0;
}
|
动态规划[[闫氏DP分析法]]
这个题我们可以转化为 01 背包问题。
01 背包问题是求解从 n 个物品中选择某几个物品使得在不超过背包容量 m 的情况下质量最大。
那么这个题,是希望选几本书在可以包邮(书本价格必须超过 x )的前提下,尽可能的价格少。
那么转化一下,选几本书,在价值不超过 sum-x 的情况下,总价格尽可能的多。这样选出来的书本是要扔的,剩下的就是满足上述要求留下来的书。
那么背包容量就是 sum-x,物品质量和体积都是书本的价格,这样就可以直接套板子了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#include<bits/stdc++.h>
using namespace std;
const int N = 33, M = 300010;
int n, x;
int w[N];
int f[M];
int main(){
cin>>n>>x;
int sum = 0;
for(int i = 0; i < n; i++){
cin>>w[i];
sum += w[i];
}
int m = sum - x;
for(int i = 0; i < n; i++){
for(int j = m; j >= w[i]; j-- ){
f[j] = max(f[j], f[j-w[i]]+w[i]);
}
}
cout<<sum - f[m]<<endl;
return 0;
}
|