题解:P10996 【MX-J3-T3】Tuple

· · 题解

考虑枚举分别以 a,d 开头、结尾的三元组,然后枚举两个中间值 b,c,查找是否存在 (a,b,c) 和 (b,c,d) 即可。

先给出代码:

#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++;
        }
    }
}

考虑前两个循环为整体 O(m),而后面的循环复杂度上限为 O(n),故时间复杂度为 O(nm+m\log m)(其实可以不排序直接枚举)。