zoukankan      html  css  js  c++  java
  • [luogu普及] ---P1032 字串变换

    目的

    1. 刷完100AC (最近很不舒服,写博客耗时啊
    2. 记录第一个字符串的题目

    参考

    https://www.luogu.org/blog/user20197/solution-p1032

    代码

    #include<cstdio>
    #include<map>
    #include<queue>
    #include<string>
    #include<iostream>
    #define MAX 20+9
    using namespace std;
    
    struct node{
    	string s;
    	int dis;
    };
    
    string original[MAX];
    string translate[MAX];
    int n;
    map <string, int> m;//判重 
    string x,y;
    int ans;
    
    string trans(const string &str, int i, int j)//在str的第i个位置使用第j种手法改变
    {
    	string ans = "";
    	if(i+original[j].length() > str.length() ) return ans;//???有必要? 
    	
    	for(int k = 0; k < original[j].length() ; k++) 
    		if(str[i+k] != original[j][k]) return ans;//判断是否可以变换
    		
    	ans = str.substr(0, i);//逐个拼接
    	ans += translate[j];
    	//ans += str.substr(i+original[j].length()); 
    	ans += str.substr(i+original[j].length() , str.length() );
    	return ans;
    } 
    
    void bfs() {
    	queue <node> q;
    	node str;
    	str.s  = x;
    	str.dis = 0;
    	q.push(str);
    	
    	while(!q.empty() ) {
    		node u = q.front() ;
    		q.pop() ;
    		if(m[u.s ]) continue;
    		
    		if(u.s  == y) {
    			ans = u.dis ;
    			break ;
    		}
    		m[u.s ] = 1;
    		
    		string tmp;
    		for(int i = 0; i < u.s.length() ; i++) {
    			for(int j = 0; j < n; j++) {
    				tmp = trans(u.s , i, j);
    				if(tmp != "") {
    					node e;
    					e.s = tmp;
    					e.dis = u.dis +1;
    					q.push(e); 
    				}
    			}
    		}
    	}
    	if (ans > 10 || ans == 0)// 不懂这题目,为啥0步不行 
            cout << "NO ANSWER!" << endl;
        else
            cout << ans << endl;
    }
    
    int main() {
    	cin>>x>>y;
    	while(cin>>original[n]>>translate[n]) n++;
    	bfs();
    	return 0;
    } 
    
  • 相关阅读:
    poj 1026 Cipher
    python中的global
    基于DL的文本分类综述
    K近邻算法学习
    聚类评价指标学习
    pytorch自动求导学习
    反向传播的推导
    二分搜索常用【转载】
    《Attention is all you need》论文学习
    5-28日|5-30日
  • 原文地址:https://www.cnblogs.com/tyner/p/11069831.html
Copyright © 2011-2022 走看看