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 odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
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.
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.
527
572
4573
3574
1357997531
-1
非常好的贪心,平时做的贪心,感觉都一个套路,今天换了,错了4次。。。。
题意:给一个奇数,这个数的长度为2到10的5次幂,求交换两个数,使变成偶数,并且最大!
思路:肯定是前边的偶数和最后一位数交换,选什么偶数,这就需要贪心了,记录最小偶数(相同的要后边)的位置,从左往右寻找换什么,如果这个偶数比最后一位小,就可以换了,或者这个数就是之前求出来的最小偶数,如果没有偶数,那就输出-1
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N=200000+10;
char a[N];
int main()
{
// freopen("shuju.txt","r",stdin);
cin>>a;
int len=strlen(a);
int mi=10,pos=-1;
for(int i=0;i<len;i++)
{
if((a[i]-'0')%2==0)
{
if(mi>=a[i]-'0')
{
mi=a[i];
pos=i;
}
}
}
if(pos==-1)
{
cout<<-1<<endl;
}
else
{
for(int i=0;i<len-1;i++)
{
if((a[i]-'0')%2==0)
{
if(a[len-1]>a[i]||i==pos)
{
char t=a[len-1];
a[len-1]=a[i];
a[i]=t;
// printf("%d %d\n",len-1,i);
cout<<a<<endl;
break;
}
}
}
}
return 0;
}