【HDOJ】4956 Poor Hanamichi
基本数学题一道,看错位数,当成大数减做了,而且还把方向看反了。所求为最接近l的值。
1 #include <cstdio> 2 3 int f(__int64 x) { 4 int i, sum; 5 6 i = sum = 0; 7 while (x) { 8 if (i & 1) 9 sum -= x%10; 10 else 11 sum += x%10; 12 ++i; 13 x/=10; 14 } 15 return sum; 16 } 17 18 int main() { 19 __int64 l, r, x; 20 bool flg; 21 int t; 22 23 scanf("%d", &t); 24 while (t--) { 25 scanf("%I64d%I64d", &l, &r); 26 for (x=l;;++x) 27 if (x%11 == 3) 28 break; 29 flg = false; 30 while (x <= r) { 31 if (f(x) != 3) { 32 flg = true; 33 break; 34 } 35 x += 11; 36 } 37 if (flg) 38 printf("%I64d\n", x); 39 else 40 printf("-1\n"); 41 } 42 43 return 0; 44 }
好歹写出来大数减了,贴上吧。
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <string> 5 using namespace std; 6 7 string SRCB="11"; 8 bool stop; 9 10 int check(string s) { 11 int sum=0; 12 int len = s.length(); 13 int i = 0, j; 14 15 while (s[i]) { 16 --len; 17 j = s[i] - '0'; 18 if (len & 1) 19 sum -= j; 20 else 21 sum += j; 22 ++i; 23 } 24 return sum; 25 } 26 27 string Minus(string a,string b) { 28 string c="",ans="",t; 29 int flag=0, k=0; 30 31 if(a.length()<b.length()||(a.length()==b.length()&& a.compare(b)<0)) { 32 t=a; 33 a=b; 34 b=t; 35 stop=true; 36 return ""; 37 } 38 int i=a.length()-1,j=b.length()-1; 39 while(i>=0&&j>=0) { 40 if(a[i]+flag>b[j]) { 41 42 c+=a[i]+flag-b[j]+'0'; 43 flag=0; 44 } else if (a[i]+flag==b[j]) { 45 c+='0'; 46 flag=0; 47 } else { 48 c+=(a[i]-'0')+flag+10-(b[j]-'0')+'0'; 49 flag=-1; 50 } 51 i--; 52 j--; 53 k++; 54 } 55 while(i>=0) { 56 if(a[i]+flag<'0') { 57 c+=a[i]+flag+10; 58 flag=-1; 59 } else { 60 c+=a[i]+flag; 61 flag=0; 62 } 63 i--,k++; 64 } 65 int len=k-1; 66 while(c[len]=='0' && len>0) 67 len--; 68 for(j=0;j<=len;j++) 69 ans+=c[j]; 70 char tt; 71 for(i=0,j=ans.length()-1;i<j;i++,j--) { 72 tt = ans[i]; 73 ans[i] = ans[j]; 74 ans[j]=tt; 75 } 76 return ans; 77 } 78 79 int main() { 80 int t, tmp, ttmp; 81 string l, r, ans; 82 bool flag; 83 char x[3]; 84 //FILE *fout = fopen("data2", "w"); 85 86 scanf("%d", &t); 87 while (t--) { 88 cin >>l>>r; 89 flag = stop = false; 90 tmp = check(r); 91 ttmp = tmp%11; 92 if (ttmp < 0) 93 ttmp += 11; 94 if (ttmp > 3) { 95 x[0] = ttmp-3+'0'; 96 x[1] = '\0'; 97 ans = Minus(r, string(x)); 98 } else if (ttmp < 3) { 99 x[0] = 8+ttmp+'0'; 100 x[1] = '\0'; 101 ans = Minus(r, string(x)); 102 } else { 103 ans = r; 104 } 105 if (stop) { 106 printf("-1\n"); 107 continue; 108 } 109 while (l.length()<ans.length() || (l.length()==ans.length()&&l.compare(ans)<=0)) { 110 if (check(ans) != 3) { 111 flag = true; 112 break; 113 } 114 //cout <<ans<<endl; 115 ans = Minus(ans, SRCB); 116 if (stop) 117 break; 118 } 119 if (flag) { 120 cout <<ans<<endl; 121 //fprintf(fout, "%s\n", ans.data()); 122 } else { 123 printf("-1\n"); 124 //fprintf(fout, "-1\n"); 125 } 126 //fprintf(fout, "%d\n", ans); 127 } 128 //fclose(fout); 129 return 0; 130 }