题解:P12946 [GCJ Farewell Round #1] Colliding Encoding
Task
本题目要求写的比较清晰,简单说就是给定字符串和映射规则,判断是否有至少一对字符串的映射结果相同。
Solution
首先我们对字符串进行暴力替换,复杂度
法1:排序后查重
替换完后排序,依次检查当前串和前一个串是否相同。
复杂度为
code1
#include<bits/stdc++.h>
using namespace std;
int T,n;
const int N=6e4+4;
char D[30];
string s[N];
int main(){
cin>>T;
for(int tt=1;tt<=T;tt++){
for(int i=0;i<26;i++) {
int x; cin>>x;
D[i]=(char)(x+'0');
}
cin>>n;
for(int i=1;i<=n;i++) {
s[i]="";
string t; cin>>t;
for(int j=0;j<t.size();j++){
s[i]+=D[t[j]-'A'];
}
}
bool flag=false;
sort(s+1,s+n+1);
for(int i=1;i<=n;i++)
if(s[i]==s[i-1]){
flag=true;
break;
}
printf("Case #%d: ",tt);
if(flag) cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}
法2:哈希查重
直接将修改后的字符串作为其哈希值,存到一个哈希表中进行查重即可。可以直接用 STL 的 map。
复杂度同上。
code2
#include<bits/stdc++.h>
using namespace std;
int T,n;
const int N=6e4+4;
char D[30];
string s[N];
map<string,bool> mp;
int main(){
cin>>T;
for(int tt=1;tt<=T;tt++){
mp.clear();
for(int i=0;i<26;i++) {
int x; cin>>x;
D[i]=(char)(x+'0');
}
cin>>n;
bool flag=false;
for(int i=1;i<=n;i++) {
s[i]="";
string t; cin>>t;
string hashing="";
for(int j=0;j<t.size();j++)
hashing=hashing+D[t[j]-'A'];
// cout<<hashing<<'\n';
if(mp[hashing]) flag=true;
mp[hashing]=true;
}
printf("Case #%d: ",tt);
if(flag) cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}