+-String time limit: +Ms | Memory Limit:65535KB Difficulty:1
-
Describe
-
Shiva got two strings with a plus and minus sign, and the string is the same length. Shiva you can swap a plus sign with its adjacent minus sign at a time. He wanted to know how many operations it would take to transform the first string into a second string. You are going to help him with the problem now.
-
Input
-
Multiple sets of test data
Each set of data has two rows, each containing a string that is the most formed by "+" and "-". Each substring string has a length of not more than 5000.
-
Output
-
Only an integer that outputs the minimum number of operations required. If the answer does not exist, output-1.
-
Sample input
-
-
Sample output
-
4
-
Source
-
Nboj
-
Uploaded by
-
tc_ Zhou Yi
Ideas:
This problem and Hangzhou electric ant that problem can be the same, because the plus (or minus) is the same, so when we move, the same symbols can cross each other! First find the corresponding position of the character at a different position and then the array a back to the same character in the array b in the same character (in the process of looking for the number of steps to add to min) that is required to exchange the number of times, and then just find the same to stop, the swap ended, and then continue to traverse backwards, Until all the corresponding positions on the Traverse are equal!
Code:
#include <stdio.h> #include <string.h>char a[5005],b[5005];int main () {while (scanf ("%s%s", A, b)!=eof) {int Len1=strlen (a); int Len2=strlen (b); int cnt1=0,cnt2=0;for (int i=0;i<len1;i++) {if (a[i]== ' + ') cnt1++;} for (int j=0;j<len2;j++) {if (b[j]== ' + ') {cnt2++;}} if (len1!=len2| | Cnt1!=cnt2) {printf (" -1\n"); continue;} int min=0;for (int i=0;i<len1;i++) {if (A[i]!=b[i])//Find unequal characters {for (int j=i+1;j<len2;j++) {min++;//Save the number of interchanges if (b[i]= =A[J])//Find the value equal to the number in the B array at that position {A[i]=a[j]; break;//stop swapping}}}}printf ("%d\n", Min);} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Nyoj 915 +-string "string"