A. GCD Sum
模拟即可,代码如下
#include<iostream>
#include<stdio.h>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<unordered_set>
#include<set>
#include<map>
#include<sstream>
using namespace std;
#define int long long
const int INT = 0x3f3f3f3f;
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
int getSum(int n) {
int res = 0;
while (n) {
res += n % 10;
n /= 10;
}
return res;
}
unsigned main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int res = n;
while (gcd(res, getSum(res))==1) {
++res;
}
cout << res << endl;
}
}
B. Box Fitting
一开始的想法:从大到小,贪心:矩形从大到小排序,逐个加矩形的过程中,对某个矩形,放在满足条件的最下一层,最后统计层数。
结果test 3超时了,原代码如下:
#include<iostream>
#include<stdio.h>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<unordered_set>
#include<set>
#include<map>
#include<sstream>
using namespace std;
#define int long long
const int INT = 0x3f3f3f3f;
bool cmp(int a, int b) {
return a > b;
}
unsigned main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t;
cin >> t;
while (t--) {
int n, w;
cin >> n >> w;
vector<int>nums;
for (int i = 0; i < n; ++i) {
int x; cin >> x;
nums.push_back(x);
}
sort(nums.begin(), nums.end(), cmp);
vector<int>m(n, w);
int cnt = 0;
for (int i = 0; i < n; ++i) {
int j = 0;
while (m[j] - nums[i] < 0) {
++j;
}
m[j] -= nums[i];
cnt = (j < cnt) ? cnt : j;
}
cout << cnt+1 << "\n";
}
}
反思一下:没注意到条件,矩形长度为2的幂
tutial的方法不错,贴一下
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, box_width, w;
cin >> n >> box_width;
vector<int> counts(20);
for (int i = 0; i < n; i++) {
cin >> w;
counts[log2(w)]++;
}
int height = 1, space_left = box_width;
for (int iter = 0; iter < n; iter++) {
int largest = -1;
for (int size = 19; size >= 0; size--) {
if (counts[size] and (1 << size) <= space_left) {
largest = size;
break;
}
}
if (largest == -1) {
space_left = box_width;
height++;
for (int size = 19; size >= 0; size--) {
if (counts[size] and (1 << size) <= space_left) {
largest = size;
break;
}
}
}
counts[largest] -= 1;
space_left -= 1 << largest;
}
cout << height << endl;
}
}