【CodeForces - 508B】Anton and currency you all know (思维贪心)
題干:
Berland, 2016. The exchange rate of?currency you all know?against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of?currency you all know?against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an?oddpositive integer?n. Help Anton to determine the exchange rate of?currency you all know?for tomorrow!
Input
The first line contains an odd positive integer?n?— the exchange rate of?currency you all know?for today. The length of number?n's representation is within range from?2?to?105, inclusive. The representation of?n?doesn't contain any leading zeroes.
Output
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print??-?1.
Otherwise, print the exchange rate of?currency you all know?against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
Examples
Input
527Output
572Input
4573Output
3574Input
1357997531Output
-1題目大意:
給出一個長度小于10^5的奇數(shù),交換其中兩位,使其變成一個偶數(shù),若有多種做法輸出交換后數(shù)字最大的。若不能構(gòu)造出一個偶數(shù),輸出-1。
解題報告:
? 直接貪心,如果沒有偶數(shù)就輸出-1,否則肯定有解。如果有大于s[len]的偶數(shù)那就從前面往后找第一個(因為越靠前越好),否則就從后面往前面找第一個,交換就完事了。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e5 + 5; char s[MAX]; int main() {cin>>(s+1);int len = strlen(s+1);int flag = 0,ok=0;int tar = s[len]-'0';for(int i = 1; i<=len; i++) {if((s[i]-'0')%2==0) flag = 1;}if(flag == 0) {puts("-1");return 0 ;}for(int i = 1; i<=len; i++) {int cur = s[i]-'0';if(cur%2==0 && tar > cur) {swap(s[i],s[len]);ok=1;break;}}if(ok==1) {printf("%s",s+1);return 0 ;}for(int i = len; i>=1; i--) {int cur = s[i]-'0';if(cur%2==0 /*&& tar<cur*/) {swap(s[i],s[len]);break;}}printf("%s",s+1);return 0 ;}?
總結(jié)
以上是生活随笔為你收集整理的【CodeForces - 508B】Anton and currency you all know (思维贪心)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【ZOJ - 3870】Team For
- 下一篇: 著名演员李崇霄去世:年仅51岁、曾参演《