2021年度训练联盟热身训练赛第五场 H题In-place Sorting+贪心构造
題意:
給你n個小于101810^{18}1018的大數,問在可以再不改變序列位置,之改變數值中某數位的‘9’變為‘6’或將‘6’變為‘9’,求的最終序列由小到大,且字典序最小。
題目:
鏈接:https://ac.nowcoder.com/acm/contest/16741/H
來源:??途W
Woe is you – for your algorithms class you have to write a sorting algorithm, but you missed the relevant lecture! The subject was in-place sorting algorithms, which you deduce must be algorithms that leave each input number in its place and yet somehow also sort the sequence.
Of course you cannot change any of the numbers either, then the result would just be a difffferent sequence. But then it hits you: if you flflip a 6 upside-down, it becomes a 9, and vice versa! Certainly no one can complain about this since you changed none of the digits! The deadline to hand in the exercise is in fifive hours. Try to implement this sorting algorithm before then!
輸入描述:
The input consists of:
? A line with an integer n (2 ≤ n ≤ 10 000), the number of integers in the input sequence.
? n lines, the ith of which contains a positive integer xi (1 ≤ xi ≤ 1018), the ith number of the sequence.
輸出描述:
If the sequence cannot be sorted non-decreasingly by flipping some number 6 or 9 in input 1, output “not possible”. Otherwise, output “possible” followed by the sorted sequence - each number on its own line.
If there is more than one valid solution, please output the smallest sequence.
示例1
輸入
4
9
7
7
9
輸出
possible
6
7
7
9
示例2
輸入
4
97
96
66
160
輸出
possible
67
69
69
160
示例3
輸入
3
80
97
79
輸出
impossible
示例4
輸入
2
197
166
輸出
possible
167
169
分析:
是一道比較容易的題,但比賽時考慮太多,wa了十幾遍。。。下來看題解,有點想吐血
廢話不多說了,下面看分析:
- 貪心構造,使每個串在大于等于前一個串的前提下盡可能小。注意字符串之間的大小比較與數字之間大小比較的不同(以字符串形式輸入數字)。
依次遍歷n個串,分情況構造: - 當前串長度 > 前一個串長度。那直接把當前串的所有9變成6就可以了,變完之后當前串肯定還是大于前一個串。
- 當前串長度 < 前一個串長度。就算把當前串的所有6變成9也無力回天了,直接impossible結束。
- 當前串長度 = 前一個串長度。先還是把當前串的所有6變成9,如果還是比前一個串小,直接impossible結束;否則,從高位到低位,依次嘗試把9變回6,這個時候要注意,如果變了之后比前一個串小了,那就說明不能變,一定要還原回去!
AC代碼:
#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<iostream> using namespace std; typedef long long ll; const int M=1e4+10; string a[M]; int n; bool solve(string f,int ii){if(f.size()>a[ii-1].size()){for(int j=0;j<f.size();j++)if(f[j]=='9')f[j]='6';a[ii]=f;}else{if(f.size()<a[ii-1].size())return 0;for(int i=0;i<f.size();i++)if(f[i]=='6')f[i]='9';if(f<a[ii-1])return 0;for(int i=0;i<f.size();i++){if(f[i]=='9'){f[i]='6';if(f<a[ii-1])f[i]='9';}}a[ii]=f;}return 1; } int main(){cin>>n;int vis=0;a[0]="0";for(int i=1;i<=n;i++){cin>>a[i];if(vis==1)continue;if(!solve(a[i],i))vis=1;}if(vis==1) cout<<"impossible"<<endl;else{cout<<"possible"<<endl;for(int i=1;i<=n;i++)cout<<a[i]<<endl;}return 0; }想了想還是拋上我比賽時地錯誤代碼:
分析:
總結
以上是生活随笔為你收集整理的2021年度训练联盟热身训练赛第五场 H题In-place Sorting+贪心构造的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Canalys:2023 年 Q3 苹果
- 下一篇: 2021年度训练联盟热身训练赛第五场F题