+-字符串
时间限制:1000 ms | 内存限制:65535 KB
难度:1
- 描述
- Shiva得到了两个只有加号和减号的字符串,字串长度相同。Shiva一次可以把一个加号和它相邻的减号交换。他想知道最少需要多少次操作才能把第一个字符串变换成第二个字符串。你现在要去帮助他完成那个这个问题。
- 输入
- 多组测试数据
每组数据有两行,每行包含一个由”+”和”-“最成的字符串。每个子符串长度不超过5000。 - 输出
- 仅一个整数,输出最少需要操作的次数。如果答案不存在,输出-1。
- 样例输入
-
++-+--+ -++--++
- 样例输出
-
4
- 来源
- NBOJ
- 上传者
- TC_周亿
-
1 #include <stdio.h> 2 #include <string.h> 3 char str1[5050],str2[5050]; 4 int main() 5 { 6 while(scanf("%s%s",str1,str2)!=EOF) 7 { 8 int i,j,t=0,sum=0,len; 9 len=strlen(str1); 10 for(i=0;i<len;i++) 11 { 12 if(str1[i]!=str2[i]) 13 { 14 for(j=i+1;j<len;j++) 15 if(str1[j]==str2[i]) 16 break; 17 if(j==len) 18 t=-1; 19 sum+=j-i; 20 str1[j]=str1[i]; 21 } 22 } 23 if(t) 24 printf("%d ",t); 25 else 26 printf("%d ",sum); 27 } 28 return 0; 29 }