CF159A Friends or Not
Solution
数据规模较小,字符串长度只有 \(20\),判断相等时使用 hash 或暴力均可。
具体地,我们枚举一个消息记录,然后暴力扫一遍,如果满足以下条件:
- 传递的方向相反。
- 时间之差不为 \(0\) 且小于等于 \(d\)。
就加入答案,注意需要判断重复,用 map 套 pair 就可以了。
这里给出 hash 的实现方法,时间复杂度 \(O(n^2\log n)\)。
Code
#include<bits/stdc++.h>
#define mkp make_pair
#define int long long
using namespace std;
#define fi first
#define se second
using ll=long long;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
using ull=unsigned long long;
inline void read(int &x){
char ch=getchar();
int r=0,w=1;
while(!isdigit(ch))w=ch=='-'?-1:1,ch=getchar();
while(isdigit(ch))r=(r<<1)+(r<<3)+(ch^48),ch=getchar();
x=r*w;
}
const int N=1007,K=133;
struct node{
int a,b,t;
}p[N];
char c[N][43],cc[N][43];
int get(char *s,int n){
ull res=0;
for(int i=1;i<=n;i++)
res=res*K+s[i];
return res;
}
int ans[N];
map<pair<int,int>,bool>mp;
main(){
int n,d;read(n);read(d);
for(int i=1;i<=n;i++){
scanf("%s",c[i]+1);p[i].a=get(c[i],strlen(c[i]+1));
scanf("%s",cc[i]+1);p[i].b=get(cc[i],strlen(cc[i]+1));
read(p[i].t);
}
int ss=0;
for(int i=1;i<n;i++){
for(int j=i+1;j<=n;j++){
int tt=abs(p[i].t-p[j].t);
if(p[i].a==p[j].b&&p[i].b==p[j].a&&tt>0&&tt<=d){
int aa=p[i].a,bb=p[i].b;
if(aa>bb)swap(aa,bb);
if(mp[mkp(aa,bb)])continue;
mp[mkp(aa,bb)]=1;ans[++ss]=i;
}
}
}
printf("%lld\n",ss);
for(int i=1;i<=ss;i++){
for(int j=1;j<=strlen(c[ans[i]]+1);j++)
putchar(c[ans[i]][j]);
putchar(' ');
for(int j=1;j<=strlen(cc[ans[i]]+1);j++)
putchar(cc[ans[i]][j]);
putchar('\n');
}
return 0;
}