Codeforces Beta Round #33 (Codeforces format) B. String Problem(Floyd)

Add a link description
Here Insert Picture Description
Here Insert Picture Description
that Italy: Given two initial string s and t, to give n conversion given, represents the letter alphabet takes into 1 takes 2 w and asked two strings into the same minimum cost.
Ideas: to be determined converts each letter of any alphabet minimum cost, the line determined by Floyd. This problem is easy to take for granted, such as a string, the string is b, it is easy to take for granted the very beginning turned into a b b or to become a (wa because of this several times). The reason this does not work look at the following sample
Sample:
A
b
4
ab 100
BA 100
AX 10
BX 10
and then see here should know how to do it

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+1;
const int inf=0x3f3f3f3f;
int n,ans,d[27][27],g[27][27];
char s1[maxn],s2[maxn],c[maxn];
void f()
{
	for(int k=0;k<26;++k)
	for(int i=0;i<26;++i)
	for(int j=0;j<26;++j)
	if(g[i][k]!=inf&&g[k][j]!=inf&&g[i][k]+g[k][j]<g[i][j])
	g[i][j]=g[i][k]+g[k][j];
}
int main()
{
	for(int i=0;i<26;++i)
	for(int j=0;j<26;++j)
	{
		if(i==j) g[i][j]==0;
		else g[i][j]=inf;
	}
	scanf("%s%s",s1,s2);
	scanf("%d",&n);
	for(int i=1;i<=n;++i){
		char u,v;
		int w;
		scanf(" %c %c %d",&u,&v,&w);
		g[u-'a'][v-'a']=min(w,g[u-'a'][v-'a']);
	}
	f();
	int len1=strlen(s1),len2=strlen(s2);
	if(len1!=len2){
		printf("-1\n");return 0;
	}
	for(int i=0;i<len1;++i)
	{
		int t1=s1[i]-'a',t2=s2[i]-'a',minn=inf;
		for(int j=0;j<26;++j)
		{
			if(g[t1][j]!=inf&&g[t2][j]!=inf&&minn>g[t1][j]+g[t2][j])
			minn=g[t1][j]+g[t2][j],c[i]='a'+j;
		}
		if(minn==inf)
		{
		printf("-1\n");return 0;
		}
		ans+=minn;
	}
	c[len1]='\0';
	printf("%d\n",ans);
	printf("%s\n",c);
}
Published 70 original articles · won praise 0 · Views 2429

Guess you like

Origin blog.csdn.net/qq_42479630/article/details/104233081