题目分析
题目要求我们找到一个目标单词,使得所有旗帜上的单词通过最小次数的字母修改能够变为该目标单词。为了找到这个目标单词,我们需要分析出每个字母的分布,选择出现频率最高的字作为目标单词在该位置上的字,目标就是让修改次数最少。
我们选择用贪心解 ,建议加上贪心标签。
核心思路
对于每个位置,选择出现次数最多的字符作为目标,这样修改次数最少。
程序流程:
代码
#include<iostream>
#include<string>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin>>n>>m;
string s[105];
for(int i=1;i<=n;i++)
{
cin>>s[i];
}
int ans=0;
//对每个位置
for(int i=1;i<=m;i++)
{
int cnt[26]={0};
for(int x=0;x<n;i++)
{
cnt[s[i-1][x]-'a']++;
}
//最大值
int maxn=0;
for(int k=0;k<26;k++)
{
if(cnt[k]>maxn)
{
maxn=cnt[k];
}
}
//需要修改的次数=总数-最多出现的次数
ans+=n-maxn;
}
cout<<ans<<"\n";
//完结撒花!睡觉咯~~
return 0;
}等等!运行完你会发现代码运行出个大黑块TLE。所以让我们再优化一下…
#include<bits/stdc++.h>
using namespace std;
char x[100][101];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++)
{
cin>>x[i];
}
int ans=0;
//遍历每个字符
for(int i=1;i<=m;i++)
{
int cnt[26]={0};
for(int j=0;j<n;j++)
{
cnt[x[j][i-1]-'a']++;
}
//最大值
int maxn=0;
for(int t=0;t<26;t++)
{
maxn=max(maxn,cnt[t]);
}
ans+=n-maxn;
}
cout<<ans<<'\n';
//真正的完结撒花*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。
return 0;
}End.

