laoguo 题解分享 · 2024/4/22
封闭图形个数(编程题) - 题解
题意解析: 8有两个封闭图形,0、4、6、9有一个封闭图形,1、2、3、5、7有一个封闭图形,按照一个数字的封闭图形个数为第一关键字,数字的大小为第二关键字排序,所以在本题中0到1从小到大排序的结果是1 2 3 5 7 0 4 6 9 8。 思路: 用结构体记录当前数字的大小和封闭图形数目,读入时用个函数算出来存到结构体中,重载一下<运算符sort一下就可以了。是不是很简单。 代码: ``` #include <bits/stdc++.h> #define int long long using namespace std; const int N = 2e5 + 10; //定义结构体 struct A { //x指数字大小,y指当前数字封闭图形个数 int x, y; //重载<运算符 bool operator < (const A & u) const { //如果封闭图形个数相同,则比较数字大小 if (y == u.y) return x < u.x; return y < u.y; } }a[N]; //计算数字的封闭图形个数 int ttt(int x) { int res = 0; //如果数字是0,直接返回1,因为0进不去while if (x == 0) return 1; //判断非0数字 while (x) { //如果其中有8,加2,有0、4、6、9,加1 if (x % 10 == 8) res += 2; else if (x % 10 == 0 || x % 10 == 4 || x % 10 == 6 || x % 10 == 9) res ++; //别忘了把最后一位去掉 x /= 10; } return res; } void solve() { int n; cin >> n; //读入并计算封闭图形数目 for (int i = 1; i <= n; i ++ ) cin >> a[i].x, a[i].y = ttt(a[i].x); //排序 sort(a + 1, a + 1 + n); //输出 for (int i = 1; i <= n; i ++ ) cout << a[i].x << ' '; } signed main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t = 1; // cin >> t; while (t --) solve(); return 0; } ```
查看全文
2 0 1 6