题解:P10996 【MX-J3-T3】Tuple
shinzAnmono · · 题解
考虑枚举分别以
先给出代码:
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<unordered_set>
std::unordered_set<long long>tpl;
std::unordered_map<long long,std::basic_string<int>>mp;
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n,m;
std::cin>>n>>m;
auto value=[&](int u,int v,int w){return (u-1ll)*n*n+(v-1)*n+w-1;};
for(int i=1,u,v,w;i<=m;i++){
std::cin>>u>>v>>w;
mp[value(1,u,w)]+=v;
tpl.insert(value(u,v,w));
}
long long ans=0;
for(auto p:mp){
int a=p.first/n+1,d=p.first%n+1;
std::basic_string<int>mid(p.second);
std::sort(mid.begin(),mid.end());
for(int i=0;i<mid.size();i++){
for(int j=i+1;j<mid.size();j++){
int b=mid[i],c=mid[j];
if(tpl.find(value(a,b,c))!=tpl.end()&&tpl.find(value(b,c,d))!=tpl.end())ans++;
}
}
}
std::cout<<ans<<"\n";
return 0;
}
分析时间复杂度。
for(auto p:mp){
int a=p.first/n+1,d=p.first%n+1;
std::basic_string<int>mid(p.second);
std::sort(mid.begin(),mid.end());
for(int i=0;i<mid.size();i++){
for(int j=i+1;j<mid.size();j++){
int b=mid[i],c=mid[j];
if(tpl.find(value(a,b,c))!=tpl.end()&&tpl.find(value(b,c,d))!=tpl.end())ans++;
}
}
}
考虑前两个循环为整体