A.声控灯
#pragma GCC optimize(2)
#include <cstdio>
using namespace std;
int main()
{
int t;
scanf("%d", &t);
int n, m, nums[5];
for (int i = 0; i < t; i++)
{
scanf("%d%d", &n, &m);
for (int j = 0; j < m; j++)
scanf("%d", &nums[j]);
if (m == 3) printf("%d\n", nums[1]);
else if (m == 1) printf("1\n");
else if (m == 2 && n != 2 && nums[0] == 1) printf("1\n");
else if (m == 2 && n != 2 && nums[1] == n) printf("%d\n", n);
else printf("-1\n");
}
return 0;
}
b.构造字符串
#pragma GCC optimize(2)
#include <cstdio>
using namespace std;
typedef long long LL;
LL A[26];
int main()
{
LL n;
scanf("%lld", &n);
for (int i = 0; i < 26; i++)
scanf("%d", &A[i]);
LL x = 0;
for (int i = 0; i < 26; i++)
x += A[i]/n;
printf("%lld", x);
return 0;
}
c.情报战
思路:通过并查集将已知和的两数放入同一集合,再开两个数组分别记录各个集合是否被访问及集合内的元素。注意,当x==y时可视为情况1。
#pragma GCC optimize(2)
#include <cstdio>
using namespace std;
const int N = 300010;
int f[N], vis[N], cnt[N];
inline int find (int x)
{
if (x != f[x]) x = find(f[x]);
return f[x];
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) f[i] = i, cnt[i] = 1;
int op, x, y, ans = 0;
for (int i = 0; i < m; i++)
{
scanf("%d", &op);
if (op == 1)
{
scanf("%d", &x);
int fx = find(x);
if (!vis[fx]) ans += cnt[fx], vis[fx] = 1;
}
else if (op == 2)
{
scanf("%d%d", &x, &y);
if(x == y)
{
int fx = find(x);
if (!vis[fx]) ans += cnt[fx], vis[fx] = 1;
}
else
{
int fx = find(x), fy = find(y);
if(fx != fy)
{
if (!vis[fx] && vis[fy]) ans += cnt[fx];
else if(vis[fx] && !vis[fy]) ans += cnt[fy], vis[fy] = 1;
cnt[fy] += cnt[fx];
f[fx] = fy;
}
}
}
printf("%d\n", ans);
}
return 0;
}