A. Countdown
水题 求每位的整数大小加1之和 再判断一下最右位是否为0即可
代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); i ++ )
using namespace std;
inline int read()
{
register int x = 0, k = 1;
char c = getchar();
while (c < '0' || c > '9')
{
if (c == '-') k = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
{
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
return x * k;
}
int n;
void solve()
{
n = read();
int ans = 0; char c[200]; scanf("%s", c + 1);
rep(i, n) if (c[i] != '0') ans += c[i] - '0' + 1;
if (c[n] != '0') ans -- ;
printf("%d\n", ans);
}
int main()
{
int t;
t = read();
while (t -- )
{
solve();
}
return 0;
}
B. Swaps
水题 用一个nmax组来维护b数组前缀最大值 遍历a数组 二分求第一个大于当前ai的值的位置 两位置相加 维护一个最小步数值即可
代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i ++ )
using namespace std;
const int N = 1e5 + 10, INF = 1e8;
inline int read()
{
register int x = 0, k = 1;
char c = getchar();
while (c < '0' || c > '9')
{
if (c == '-') k = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
{
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
return x * k;
}
int n;
int a[N], b[N], mina[N], maxb[N];
void solve()
{
n = read();
mina[0] = INF, maxb[0] = 0;
rep(i, n) a[i] = read();
rep(i, n){
b[i] = read();
if (!i) maxb[i] = b[i];
else maxb[i] = max(maxb[i - 1], b[i]);
}
int ans = INF;
rep(i, n){
int tmp = upper_bound(maxb, maxb + n, a[i]) - maxb;
ans = min(ans, tmp + i);
}
printf("%d\n", ans);
}
int main()
{
int t;
t = read();
while (t -- )
{
solve();
}
return 0;
}
C. Book
给定一张拓扑图 每次从最小点到最大点开始遍历 删去可以删去的点 问最少遍历几轮能使得图中所有点被删掉
我们可以用一个优先队列来维护 每次删点 都判断一下出度是否变为0 如果变为0 再比较二者大小 选择放在k轮还是k+1轮
代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); i ++ )
using namespace std;
typedef pair<int, int> PII;
const int N = 2e5 + 10, INF = 1e8;
inline int read()
{
register int x = 0, k = 1;
char c = getchar();
while (c < '0' || c > '9')
{
if (c == '-') k = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
{
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
return x * k;
}
int n, din[N];
void solve()
{
n = read();
priority_queue<PII, vector<PII>, greater<PII> > Q;
vector<int> G[n + 1];
rep(i, n) din[i] = 0;
rep(i, n){
int cnt; cnt = read();
while (cnt -- ){
int b; b = read();
G[b].push_back(i);
din[i] ++ ;
}
}
int res = 0, ans;
rep(i, n) if (!din[i]) Q.push({1, i});
while (Q.size())
{
auto t = Q.top(); Q.pop();
res ++ , ans = t.first;
for (int j = 0; j < G[t.second].size(); j ++ )
{
int to = G[t.second][j];
din[to] -- ;
if (!din[to])
if (to > t.second) Q.push(make_pair(t.first, to));
else Q.push(make_pair(t.first + 1, to));;
}
}
if (res == n) printf("%d\n", ans);
else puts("-1");
}
int main()
{
int t;
t = read();
while (t -- )
{
solve();
}
return 0;
}