https://atcoder.jp/contests/abc218/tasks/abc218_d
直接暴力的思路没问题。
但是我开始写的时候test3死活不对。
进了调试才看到问题。
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
typedef pair<LL,LL>P;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
map<P,bool>map1;
int main(void){
int n;n=read();
for(int i=1;i<=n;i++)
{
int x,y;x=read();y=read();
map1[{x,y}]=true;
}
auto it1=map1.begin();
LL ans=0;
for(it1;it1!=map1.end();it1++)
{
for(auto it2=next(it1);it2!=map1.end();it2++)
{
P L =(*it1).first;
P R=(*it2).first;
if(L.first==R.first||L.second==R.second) continue;
if(map1[{L.first,R.second}]==true&&map1[{R.first,L.second}]==true)
{
///cout<<L.first<<" "<<
ans++;
}
}
}
printf("%lld\n",ans/2);
return 0;
}
如果输出进去的内容,会发现出来一些本不该存在在map中的点
7
0 1
1 0
2 0
2 1
2 2
3 0
3 2
如下调试出现了本不该存在的点
这是因为直接map[]访问会插入一个false的key。而循环下去就会越来越错。而且导致map越来越大,然后tle。
很早之前碰到过一次map的这种事情,但是很久没碰到了。为了防止额外开无用的key,使用map.find()或者map.find()或者set<pair<int,int>>
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
typedef pair<LL,LL>P;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
map<P,bool>map1;
int main(void){
int n;n=read();
for(int i=1;i<=n;i++)
{
int x,y;x=read();y=read();
map1[{x,y}]=true;
}
auto it1=map1.begin();
LL ans=0;
for(it1;it1!=map1.end();it1++)
{
for(auto it2=next(it1);it2!=map1.end();it2++)
{
P L =(*it1).first;
P R =(*it2).first;
if (L.first == R.first || L.second == R.second) continue;
if (!map1.count(L)) continue;
if (!map1.count(R)) continue;
if ( map1.count({L.first, R.second}) && map1.count({R.first, L.second}))
{
ans++;
}
}
}
printf("%lld\n",ans/2);
return 0;
}
或者直接存数组里遍历
const int maxn=2000;
map<pii,int> mp;
int x[maxn+5],y[maxn+5];
int main()
{
int n;
cin>>n;
repn(i,1,n)
{
cin>>x[i]>>y[i];
mp[{x[i],y[i]}]=1;
}
int ans=0;
repn(i,1,n)
{
repn(j,i+1,n)
{
int xa=x[i],xb=x[j],ya=y[i],yb=y[j];
if(xa==xb || ya==yb)continue;
if(!mp[{xa,yb}])continue;
if(!mp[{xb,ya}])continue;
++ans;
}
}
printf("%d",ans/2);
return 0;
}