FZU,福州大學
Problem 2159 WuYouAccept: 78 Submit: 405
Time Limit: 1000 mSec Memory Limit : 32768 KB Problem Description
有兩個正整數A和B,這兩個數的位元相同且不含首碼0。A的一些位不能夠確定,用‘?’代替。已知A是滿足 A < B 的最大的A。求A 。
Input
第一行一個整數T(T<=1000),表示有T組資料。
每組資料兩行,第一行為A,第二行為B(0 < A,B <= 10^10000)。
Output
對於每組資料,輸出滿足A<B的最大的A。如果不存在,輸出-1。
Sample Input319?8?111 Sample Output17-1
Submit Back Status Discuss
AC代碼:
#include<stdio.h>#include<string.h>char last[100010],next[100010];int not_equal[100010],len;void work(){int i;bool flag=0;for(i=len-1;i>=0;i--){if(last[i]!='?'){if(last[i]<next[i])flag=1;else if(last[i]>next[i])flag=0;}else if(last[i]=='?'){if(not_equal[i]==1){last[i]='9';}else if(not_equal[i]==0 && flag==1){last[i]=next[i];}else if(not_equal[i]==0 && flag==0){if(next[i]=='0'){last[i]='9';flag=0;}else{last[i]=next[i]-1;flag=1;}}}}if(last[0]!='0' && strcmp(last,next)<0){printf("%s\n",last);}else printf("-1\n");}int main(){//freopen("b.txt","r",stdin);int t,i,j;scanf("%d",&t);while(t--){scanf("%s",last);scanf("%s",next);memset(not_equal,0,sizeof(not_equal));bool flag=0;len=strlen(last);for(i=0;i<len;i++){if(last[i]!='?'&&last[i]!=next[i])flag=1;if(flag){not_equal[i]=1;}}work();}return 0;}
下面這個為寫挫的。。(整個人都不好啦!!!)
代碼:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int main() {int T;char a[10005], b[10005];scanf("%d", &T);while(T--) {scanf("%s %s", a, b);int la = strlen(a), lb = strlen(b);if(la > lb) { printf("-1\n"); continue; }else if(la < lb) {for(int i=0; i<la; i++) {if(a[i] == '?') printf("9");else printf("%c", a[i]);}putchar(10); continue;}else if(la == lb) {int index = -1; for(int i=0; i<la; i++) {if(a[i] != b[i] && a[i] != '?') {index = i; break;}}if(index != -1 && a[index] < b[index]) {for(int i = 0; i <= index; i++) {if(a[i] == '?') printf("%c", b[i]);else printf("%c", a[i]);}for(int i = index + 1; i < la; i++) {if(a[i] == '?') printf("9");else printf("%c", a[i]);}putchar(10); continue;}else if(index != -1 && a[index] >= b[index]) {int index2 = -1;for(int i = index-1; i >= 0; i--) {if(a[i] == '?' && b[i] != '0') {index2 = i; break;} else if(a[i] == '?' && b[i] == '0') a[i] = '0';}if(index2 == -1 || (index2 == 0 && b[0] == '1') ) {printf("-1\n"); continue;} else {a[index2] = b[index2] - 1;}for(int i = 0; i <= index; i++) {if(a[i] == '?') printf("%c", b[i]);else printf("%c", a[i]);}for(int i = index + 1; i < la; i++) {if(a[i] == '?') printf("9");else printf("%c", a[i]);}putchar(10); continue;}else if(index == -1) {int index2 = -1;for(int i = la - 1; i >= 0; i--) {if(a[i] == '?' && b[i] != '0') {index2 = i; break;} else if(a[i] == '?' && b[i] == '0') a[i] = '0';}if(index2 == -1 || (index2 == 0 && b[0] == '1')) {printf("-1\n"); continue;} else a[index2] = b[index2] - 1;for(int i=0; i<la; i++) {if(a[i] == '?') printf("%c", b[i]);else printf("%c", a[i]);}putchar(10); continue;}}}return 0;}