A、牛牛爱奇数
class Solution {
public:
/**
* 返回一个数,代表让这些数都变成奇数的最少的操作次数
* @param n int整型 代表一共有多少数
* @param a int整型vector 代表n个数字的值
* @return int整型
*/
int solve(int n, vector<int>& a) {
// write code here
map<int, int> mp;
for (auto it : a) ++mp[it];
int cnt = 0;
for (auto i = mp.rbegin(); i != mp.rend(); ++i) {
int num = i->first, val = i->second;
if (num & 1) continue;
else {
int tmp = num >> 1;
if (!(tmp & 1)) mp[tmp] += val;
++cnt;
}
}
return cnt;
}
};
B、牛牛摆放花
const int N = 1e5 + 7;
int a[N];
int b[N];
class Solution {
public:
/**
* 返回按照这些花排成一个圆的序列中最小的“丑陋度”
* @param n int整型 花的数量
* @param array int整型vector 花的高度数组
* @return int整型
*/
int solve(int n, vector<int>& array) {
// write code here
int cnt = 0;
for (auto it : array) a[++cnt] = it;
sort(a + 1, a + 1 + cnt);
int l = 1, r = cnt, op = 1, tmp = 1;
while (tmp <= n) {
if (op) b[l++] = a[tmp++];
else b[r--] = a[tmp++];
op ^= 1;
}
b[0] = b[cnt];
int mini = -1e9;
for (int i = 1; i <= cnt; ++i)
mini = max(mini, abs(b[i] - b[i - 1]));
return mini;
}
};
C、星球游戏
typedef long long ll;
const int N = 1e5 + 7; //节点数
const int M = 2e5 + 7; //路径数
const ll INF = 0x3f3f3f3f;
int u[M], v[M], w[M];
ll d1[N]; //d1正向图
struct Node {
int v;
ll cost;
bool operator < (Node b)const {
return cost > b.cost;
}
};
vector<Node> e[N];
int n, m, st, ed;
ll ans;
void dijkstra(int s, ll d[]) {
priority_queue<Node> pq;
while (pq.size()) pq.pop();
fill(d, d + N, INF);
d[s] = 0;
pq.push(Node{ s,0 });
while (!pq.empty()) {
Node x = pq.top();
pq.pop();
if (d[x.v] < x.cost) continue; //原先这个节点花费更少 跳过
for (auto it : e[x.v]) {
if (d[it.v] > x.cost + it.cost) {
d[it.v] = x.cost + it.cost;
pq.push(Node{ it.v,d[it.v] });
}
}
}
}
class Solution {
public:
/**
*
* @param niuniu int整型vector 牛牛占领的p个星球的编号
* @param niumei int整型vector 牛妹占领的q个星球的编号
* @param path int整型vector<vector<>> m条隧道,每条隧道有三个数分别是ui,vi,wi。ui,vi分别是隧道的两边星球的编号,wi是它们之间的距离
* @param nn int整型 星球个数n
* @return int整型
*/
int Length(vector<int>& niuniu, vector<int>& niumei, vector<vector<int> >& path, int nn) {
// write code here
for (int i = 0; i <= nn; ++i) e[i].clear();
for (auto it : niuniu) e[0].push_back({ it,0 });
for (auto it : path) {
int u = it[0], v = it[1], w = it[2];
e[u].push_back(Node{ v, w });
e[v].push_back(Node{ u, w });
}
st = 0;
ans = INF;
dijkstra(st, d1);
for (auto it : niumei) {
ans = min(ans, d1[it]);
}
if (ans == INF) return -1;
return ans;
}
};