Ural 1007 Code Words

Ural 1007 Code Words
根据输入数据的长度判断属于哪种情况,枚举所有可能即可。
2s的时间限制,C++ string效率很低地1.984s险过。
以下是我的代码:
#include<iostream>
#include
< string >
#include
< cstdio >
using   namespace  std;

int  GetValue( const   string   & s)
{
    
int  re( 0 );
    
for ( int  i = 0 ;i < s.size();i ++ )
        
if (s[i] == ' 1 ' )
            re
+= (i + 1 );
    
return  re;
}

int  main()
{
    
/*
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
    //
*/

    
int  n;
    scanf(
" %d " , & n);
    
string  s;
    
while (cin >> s)
    {
        
string  ans;
        
if (s.size() == n)
        {
            
bool  success( false );
            
int  value(GetValue(s));
            
if (value % (n + 1 ) == 0 )
            {
                ans
= s;
                success
= true ;
            }
            
for ( int  i = 0 ;i < s.size()  &&   ! success;i ++ )
                
if (s[i] == ' 1 '   &&  (value - i - 1 ) % (n + 1 ) == 0 )
                {
                    ans
= s;
                    ans[i]
= ' 0 ' ;
                    
break ;
                }
        }
        
else   if (s.size() == n + 1 )
        {
            
for ( int  i = 0 ;i < s.size();i ++ )
            {
                
string  t(s);
                t.erase(i,
1 );
                
if (GetValue(t) % (n + 1 ) == 0 )
                {
                    ans
= t;
                    
break ;
                }
            }
        }
        
else   if (s.size() == n - 1 )
        {
            
for ( int  i = 0 ;i <= s.size();i ++ )
            {
                
string  t(s);
                t.insert(i,
" 0 " );
                
if (GetValue(t) % (n + 1 ) == 0 )
                {
                    ans
= t;
                    
break ;
                }
                t
= s;
                t.insert(i,
" 1 " );
                
if (GetValue(t) % (n + 1 ) == 0 )
                {
                    ans
= t;
                    
break ;
                }
            }
        }
        cout
<< ans << endl;
    }

    
return   0 ;
}

你可能感兴趣的:(Ural 1007 Code Words)