Home PAT 1158 Telefraud Detection
Post
Cancel

PAT 1158 Telefraud Detection

Link

并查集一定要这样:

1
2
3
4
5
6
7
8
9
10
11
int fa1=findFather(x), fa2=findFather(y);
//对大小关系无要求
if(fa1!=fa2) fa[fa1]=fa2;
//对大小关系有要求
if(fa1>fa2) fa[fa1]=fa2;
else fa[fa2]=fa1;
//or
if(fa1!=fa2){
    if(fa1<fa2) swap(fa1,fa2);
    fa[fa1]=fa2;
}

AC 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <map>
using namespace std;
const int N=1010;
int k,n,m;
int g[N][N];
vector<int>suspect;
map<int,vector<int>>ans;
int gang[N];
int findFather(int x){
    while(x!=gang[x]) x=gang[x]=gang[gang[x]];
    return x;
}
int main() {
    scanf("%d%d%d",&k,&n,&m);
    for(int i=1;i<=m;++i){
        int x,y,d;
        scanf("%d%d%d",&x,&y,&d);
        if(x!=y) g[x][y]+=d;
    }
    for(int i=1;i<=n;++i){
        int shortCall=0,callBack=0;
        for(int j=1;j<=n;++j){
            if(g[i][j]&&g[i][j]<=5){
                shortCall++;
                if(g[j][i]) callBack++;
            }
        }
        if(shortCall>k&&callBack*5<=shortCall)
            suspect.push_back(i);
    }
    if(suspect.empty()){
        printf("None\n");
        return 0;
    }
    for(int i=0;i<suspect.size();++i)
        gang[suspect[i]]=suspect[i];
    for(int i=0;i<suspect.size();++i)
        for(int j=i+1;j<suspect.size();++j){
            int x=suspect[i],y=suspect[j];
            if(g[x][y]&&g[y][x]){
                int fa1=findFather(x),fa2=findFather(y);
                if(fa1<fa2) gang[fa2]=fa1;
                else if(fa2<fa1) gang[fa1]=fa2;
            }
        }
    for(int i=0;i<suspect.size();++i){
        int fa=findFather(suspect[i]);
        ans[fa].push_back(suspect[i]);
    }
    for(auto &v:ans){
        for(int j=0;j<v.second.size();++j){
            if(j!=0) printf(" ");
            printf("%d",v.second[j]);
        }
        printf("\n");
    }
    return 0;
}
This post is licensed under CC BY 4.0 by the author.