排序4 统计工龄
排好序后,统计每一个连续的相同数字的个数。
#include <iostream>
using namespace std;
const int N = 100010;
int n;
int a[N];
void quick_sort(int l, int r)
{
if (l >= r) return;
int x = a[l + r >> 1], i = l - 1, j = r + 1;
while (i < j)
{
do i ++; while (a[i] < x);
do j --; while (a[j] > x);
if (i < j) swap(a[i], a[j]);
}
quick_sort(l, j);
quick_sort(j + 1, r);
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++) cin >> a[i];
quick_sort(0, n - 1);
int cur = a[0], num = 0;
for (int i = 0; i < n; i ++)
{
if (a[i] != cur && num != 0)
{
if (cur != -1) printf("%d:%d\n", cur, num);
num = 0;
cur = a[i];
}
num ++;
}
printf("%d:%d\n", cur, num);
return 0;
}
排序5 PAT Judge
用结构体定义需要排序的属性,将所给的用户属性计算出来之后,直接调用 sort
函数。
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10010, K = 6;
int n, k, m;
int p[K];
struct User
{
int total_score, finish_num, id;
int score[K];
int valid;
// valid为1的排在valid为0的前面,然后分数递减排序,完成题目递减排序,id升序排列
bool operator< (const User &t) const
{
if (valid != t.valid) return valid > t.valid;
if (total_score != t.total_score) return total_score > t.total_score;
if (finish_num != t.finish_num) return finish_num > t.finish_num;
return id < t.id;
}
} user[N];
int main()
{
cin >> n >> k >> m;
for (int i = 1; i <= k; i ++) cin >> p[i];
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= k; j ++)
user[i].score[j] = -2;
while (m --)
{
int u_id, p_id, p_s;
cin >> u_id >> p_id >> p_s;
if (p_s >= 0 && !user[u_id].valid) // 是否在排行榜
user[u_id].valid = 1;
if (p_s > user[u_id].score[p_id]) // 是否更新答题分数
user[u_id].score[p_id] = p_s;
user[u_id].id = u_id; // id
}
for (int i = 1; i <= n; i ++)
{
if (!user[i].valid) continue;
for (int j = 1; j <= k; j ++)
{
if (user[i].score[j] >= 0)
user[i].total_score += user[i].score[j];
if (user[i].score[j] == p[j])
user[i].finish_num ++;
}
}
sort(user + 1, user + n + 1);
int rank = 1, pre = user[1].total_score;
for (int i = 1; user[i].valid == 1; i ++)
{
if (user[i].total_score != pre)
{
rank = i;
pre = user[i].total_score;
}
printf("%d %05d %d", rank, user[i].id, user[i].total_score);
for (int j = 1; j <= k; j ++)
{
int t = user[i].score[j];
if (t == -2) printf(" -");
else if (t == -1) printf(" 0");
else if (t >= 0) printf(" %d", t);
}
puts("");
}
return 0;
}
排序6 Sort with Swap(0, i)
待排序列中有若干个环,分为几种情况
(1)环中仅有一个元素,则不需要交换
(2)环中有 0,且元素数目为 n(n > 1)
,交换次数为 n - 1
(3)环中没有 0,且元素数目为 n(n > 1)
,交换次数为 n + 1
(先将 0 与环中任意元素交换,然后再把这个包含 0 的新环交换好)
#include <iostream>
using namespace std;
const int N = 100010;
int n;
int a[N];
bool st[N];
int main()
{
cin >> n;
for (int i = 0; i < n; i ++) cin >> a[i];
int res = 0, cur = 0;
for (int i = 0; !st[i]; i = a[i])
{
st[i] = true;
cur ++;
}
res += cur - 1;
for (int i = 0; i < n; i ++)
{
if (!st[i])
{
cur = 0;
for (int j = i; !st[j]; j = a[j])
{
st[j] = true;
cur ++;
}
if (cur == 1) continue;
res += cur + 1;
}
}
cout << res << endl;
return 0;
}