Codeforces 1291A - Even But Not Even

题目大意:

给定一个字符串数字(很大)

问能不能删除一些数字(或者不删除)

使得剩余的数字各位数相加是偶数,但是这整个数字是个奇数

 

解题思路:

统计字符串中单个数字奇数的个数

分情况

个数为0或者1时,显然不存在这样的数字,输出-1

个数大于等于2且为偶数时,只需要保证最后一位是奇数,从后往前删除字符直到遇到奇数位

个数大于2且为奇数时,保证最后一位为奇数,并且还要删除一位奇数

 1 #include
 2 using namespace std;
 3 void solve(){
 4     int n,i,n1=0;
 5     string s;
 6     cin>>n>>s;
 7     for(i=0;i)
 8         if((s[i]-'0')%2)
 9             n1++;
10     if(n1&&n1%2==0){
11         while(n&&(s[n-1]-'0')%2==0){
12             s.erase(n-1,1);
13             n--;
14         }
15     }
16     else if(n1>2){
17         while(n&&(s[n-1]-'0')%2==0){
18             s.erase(n-1,1);
19             n--;
20         }
21         s.erase(n-1,1);//遇到奇数,删除后继续删偶数
22         n--;
23         while(n&&(s[n-1]-'0')%2==0){
24             s.erase(n-1,1);
25             n--;
26         }
27     }
28     else
29         s="-1";
30     cout<'\n';
31 }
32 int main(){
33     ios::sync_with_stdio(0);
34     cin.tie(0);cout.tie(0);
35     int T;cin>>T;while(T--)
36         solve();
37     
38     return 0;
39 }

 

你可能感兴趣的:(Codeforces 1291A - Even But Not Even)