A. Array Balancing
新的存储方式: vector<int> a(n)
vector的用法新的输入方式
题解:
本题利用贪心的思路: 将更接近的两个数放在一起
这个代码是最开始的源码, 存在一些问题, 因为没有看数据范围, 导致wa, 蓝桥杯也没看到白白丢了 5 分, 一定要注意
#include <bits/stdc++.h>
using namespace std;
const int N = 30;
void run()
{
int n;
cin >> n;
vector<int> t(n), s(n);
for(int &x : t) cin >> x;
for(int &x : s) cin >> x;
for(int i = 0; i < n; i ++ )
if(t[i] > s[i]) swap(t[i], s[i]);
long long res = 0;
for(int i = 0; i < n - 1; i ++ )
res += abs(t[i] - t[i + 1]) + abs(s[i] - s[i + 1]);
cout << res << endl;
}
int main()
{
int _;
cin >> _;
while(_--) run();
return 0;
}
正确的代码
#include <bits/stdc++.h>
using namespace std;
void run()
{
int n;
cin >> n;
while(n -- )
{
int x;
cin >> x;
if(x == 0) // 特判, 以免死循环.....
{
cout << 0 << ' ';
continue; // 不要return
}
int res = 0x3f3f3f3f;
for(int X = 0; X <= 15; X ++ )
{
int t = x + X, Y = 0;
while(t % 2 == 0) t /= 2, Y ++ ;
//cout << t << ' ' << X << ' ' << Y << endl;
res = min(res, 15 - Y + X);
}
cout << res << ' ';
}
}
int main()
{
run();
}
要特判 0 不然会超时
B. Getting Zero
B. Getting Zero
第一: 32768 是2^15;
第二: m % 32768 == 0 一共有两种情况, 0 or 32768*x (x >= 1)
因此可以得出15步必出答案, 因为直接将 x 成 2^15 即可满足要求
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
while(n -- )
{
int x;
cin >> x;
int res = 0x3f3f3f3f;
for(int X = 0; X <= 15; X ++ )
{
int t = x + X, Y = 0;
while(t % 2 == 0) t /= 2, Y ++ ;
res = min(res, 15 - Y + X);
}
cout << res << ' ';
}
}
B. Yet Another Array Partitioning Task
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 10;
typedef pair<int, int> PII;
int a[N];
PII b[N];
bool st[N];
signed main()
{
int n, m, k;
cin >> n >> m >> k;
for(int i = 0; i < n; i ++ )
{
cin >> a[i];
b[i] = {a[i], i};
}
sort(b, b + n);
for(int i = 0; i < n - m * k; i ++ ) st[b[i].second] = true;
int res = 0;
for(int i = n - m * k; i < n; i ++ )
{
res += b[i].first;
}
cout << res <<endl;
int cnt = 0, s = 0;
for(int i = 0; i < n - 1; i ++ )
{
if(!st[i])
{
cnt ++ ;
}
if(cnt == m)
{
s ++ ;
if(s == k) break;
cout << i + 1 <<' ';
cnt = 0;
}
}
}
#include <iostream>
#include <algorithm>
#define int long long
using namespace std;
const int N = 2 * 1e5 + 10;
int n, m, k;
int a[N], b[N];
bool cmp(int x, int y)
{
return a[x] > a[y];
}
signed main()
{
cin >> n >> m >> k;
int ans = 0;
for (int i = 0; i < n; i++)
cin >> a[i], b[i] = i;
sort(b, b + n, cmp);
sort(b, b + m * k);
for (int i = 0; i < m * k; i++)
ans += a[b[i]];
cout << ans << endl;
for (int i = m; i < m * k; i += m)
cout << b[i] << ' ';
return 0;
}