• 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;
    }
    
  • 相关阅读:
    微人事项目-mybatis-持久层
    通过外键连接多个表
    springioc
    Redis 消息中间件 ServiceStack.Redis 轻量级
    深度数据对接 链接服务器 数据传输
    sqlserver 抓取所有执行语句 SQL语句分析 死锁 抓取
    sqlserver 索引优化 CPU占用过高 执行分析 服务器检查
    sql server 远程备份 bak 删除
    冒泡排序
    多线程 异步 beginInvoke EndInvoke 使用
  • 原文地址:https://www.cnblogs.com/jiupinzhimaguan/p/13806362.html
Copyright © 2020-2023  润新知