zoukankan      html  css  js  c++  java
  • String distance (zifu)

    Description


    For two different strings, we have a set of operation methods to make them the same,the specific method is:
    Modify a character (such as replacing "( ext{a})" with "( ext{b})")
    Delete a character (e.g. change "( ext{traveling})" to "( ext{traveing})")
    For example, for the two strings "( ext{abcdefg})" and "( ext{abcdef})", we think we can achieve the goal by adding or subtracting a "( ext{g})". Whether we increase or decrease "( ext{g})", we only need one operation. We define the number of times required for this operation as the distance between two strings.
    Given any two strings, write an algorithm to calculate their distance.

    Format


    Input

    Line 1 has an integer (n). Indicates the number of groups of test data. ((n leq 50))
    Next, there are a total of n lines, with two strings in each line, separated by spaces, indicating the two strings to be calculated.
    The length of the string does not exceed 1000.

    Output

    Output an integer for each set of test data, which is the distance between two strings

    Sample


    Input

    3
    abcdefg   abcdef
    ab ab
    mnklj jlknm
    

    Output

    1
    0
    4
    

    Sample Code


    #include<iostream>
    #include<cmath>
    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<algorithm>
    using namespace std;
    
    int t,m,n;
    char a[1005],b[1005];
    int f[1005][1005];//The minimum distance between two strings.
    
    int main() {
    	freopen("zifu.in","r",stdin);
    	freopen("zifu.out","w",stdout);
    	cin>>t;
    	while(t--) {
    		// scanf("%s%s",a,b);
    		cin>>a>>b;   //When cin encounters a space, the input is deemed to be over. Same for scanf.
    		m=strlen(a);
    		n=strlen(b);
    		for(int i=1; i<=m; i++) f[i][0]=i;
    		for(int i=1; i<=n; i++) f[0][i]=i; //Initialization of the boundary.
    		for(int i=1; i<=m; i++)
    			for(int j=1; j<=n; j++)
    				if(a[i-1]==b[j-1]) f[i][j]=f[i-1][j-1];//Determine whether you need to change.
    				else f[i][j]=min(min(f[i-1][j],f[i][j-1]),f[i-1][j-1])+1;//Delete a[i] and insert b[j-1] after a[i]. This a[i] is b[j] and choose the one with the least number of changes.
    		cout<<f[m][n]<<endl;
    	}
    	return 0;
    }
    
  • 相关阅读:
    C#获取视频文件播放长度
    ViewState跨页传值
    radio点击事件
    js屏蔽鼠标右键
    js获取url参数
    js页面跳转
    android 界面刷新功能
    android RadioButton单选按钮效果
    android TextView实现跑马灯效果(字体滚动)
    android 圆角效果
  • 原文地址:https://www.cnblogs.com/jiupinzhimaguan/p/13806362.html
Copyright © 2011-2022 走看看