扭蛋机:
#include<iostream>
using namespace std;
int main() {
int num;
while (cin >> num) {
string ret = "";
while (num != 0) {
if (num % 2 == 0) {
num = (num - 2) / 2;
ret = '3' + ret;
}
else {
num = (num - 1) / 2;
ret = '2' + ret;
}
}
cout << ret << endl;
}
return 0;
}
脸滚键盘:
#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
int main() {
int n;
string S;
while (getline(cin, S)) {
int i = 0;
while (S[i] != ' ') {
i++;
}
string str = S.substr(0, i);
// 不按照空格输入的字符串,能把字符串按照空格分开的函数
n = stoi(str);
string s = S.substr(i+1, S.size());
unordered_map<char, int> map;
/*cout << n << endl;
cout << s << endl;*/
for (char c : s) {
map[c]++;
}
//for (auto it = map.begin(); it != map.end(); it++) cout << it->first << " : " << it->second << endl;
int count = 0;
for (char c : s) {
if (map[c] == 1) {
if (count + 1 == n) {
cout << "[" << c << "]" << endl;
count++;
break;
}
else {
count++;
}
}
}
if (count < n) cout << "Myon~" << endl;
}
return 0;
}
并查集:
// 查找根节点并进行路径压缩
int find(int x) {
int t = x;
// 查找,最后的x就变成了根节点
while (x != fa[x]) {
x = fa[x];
}
// 路径压缩
while (t != x) {
int Tfa = fa[t];
fa[t] = x;
t = Tfa;
}
return x;
}
// 合并
void merge(int x, int y) {
int xRoot = find(x);
int yRoot = find(y);
if (xRoot != yRoot) {
fa[xRoot] = yRoot;
}
}
小A最多会新认识的多少人
- 并查集的方法
//并查集基本应用,最后别忘了减掉本身
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<vector>
using namespace std;
vector<int>f;
int find(int x) {
return x == f[x] ? x : f[x] = find(f[x]);
}
int main(void) {
int n, ix, m;
while (cin >> n >> ix >> m) {
f = vector<int>(n); // 全局向量运行时定义大小
for (int i = 0; i < n; i++)f[i] = i;
int ans = 0, b = 0;
while (m--) {
int x1, x2;
// cin >> x1 >> x2;
// scanf("%d,%d", &x1, &x2);
scanf_s("%d,%d", &x1, &x2); // vs不支持scanf
if (x1 == ix || x2 == ix)b++;
int fx = find(x1), fy = find(x2);
if (fx != fy)f[fx] = fy;
}
for (int i = 0; i < n; i++) {
if (find(ix) == find(i))ans++;
}
cout << ans - b - 1 << endl;
}
return 0;
}
- 图的深度遍历方法
#include<iostream>
#include<vector>
using namespace std;
const int maxn = 1e5 + 8;
vector<int> G[maxn];
int res = 0;
//深度遍历 找到一个集合的人
void dfs(int ai, vector<bool>& v) {
for (int i = 0; i < G[ai].size(); ++i) {
if (!v[G[ai][i]]) {
v[G[ai][i]] = true;
res++;
dfs(G[ai][i], v);
}
}
return;
}
int main() {
int n, ai, m;
cin >> n >> ai >> m;
//构建邻接表
while (m--) {
int p1, p2;
char chs;
cin >> p1 >> chs >> p2;
G[p1].push_back(p2);
G[p2].push_back(p1);
}
vector<bool> visited(n, false);
//除去本来就认识的人和自己
int already = G[ai].size() + 1;
dfs(ai, visited);
cout << res - already << endl;
return 0;
}