Codeforces-2-Letter Strings
题意
多样例,给你n对字符串,每对字符串只有两个字符,判断只有一个字符不相同的字符串对数是多少
题解
只有一个字符不同,可以每次加上第一个字符为首形成的字符串和第二个字符为尾在此之前出现的次数,最后注意去重,因为只能有一个字符,如果输入相同的字符串,就会有重复。去重也很简单,只用减去 这个字符在此之前出现的次数的2倍,为什么是2倍,因为 加上了第一个字符为首的字符串个数 又 加上了第二个字符为尾的字符串个数。
代码
#include<iostream>
#include<map>
using namespace std;
int t,n;
string str;
int main(){
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
while(t--){
map<char,int>s1,s2;
map<string,int>ss;
long long cnt = 0;
cin >> n;
while(n--){
cin >>str;
cnt += s1[str[0]]; // 加上 1 号位相同的
cnt += s2[str[1]]; // 加上 2 号位相同的
cnt -= ss[str] << 1; // 自己跟自己的 1 号位 2 号位相等
s1[str[0]]++;
s2[str[1]]++;
ss[str]++;
}
cout << cnt << endl;
}
return 0;
}