pta L2-010 排座位

题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805066135879680

一道并查集版子题,还是蛮好做的;

等明天比完赛后总结一下并查集

Talk is cheap. Show me the code.

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,m,k;
 4 int re[110][110];//relationsh关系 
 5  //int height[110]; //树的高度 
 6 int s[110];//集合 
 7 void init_set()//初始化 
 8 {
 9     for(register int i=1;i<=n;i++)
10     {
11         s[i]=i;//所有集合按顺序初始化 
12         //height[i]=0;
13     }
14     
15 }
16 int find_set(int x)//查找函数,路径压缩 
17 {
18     if(x!=s[x])
19     s[x]=find_set(s[x]);
20     return s[x];
21 }
22 void union_set(int x,int y)//合并函数 
23 {
24     x=find_set(x);
25     y=find_set(y);
26     if(x!=y)
27     {
28         s[x]=s[y];
29     }
30 }
31 
32 /*void union_set(int x,int y)//合并函数优化 
33 {
34     x=find_set(x);
35     y=find_set(y);
36     if(height[x]==height[y])
37     {
38         height[x]=height[x]+1;
39         s[y]=x;
40     }
41     else
42     {
43         if(height[x]<height[y])
44         {
45             s[x]=y;
46         }
47         else
48         s[y]=x;
49     }
50 }*/
51 int main()
52 {
53     cin>>n>>m>>k;
54     init_set(); 
55     while(m--)
56     {
57         int a,b,c;
58         cin>>a>>b>>c;
59         re[a][b]=re[b][a]=c;
60         if(re[a][b]==1||re[b][a]==1)//如果是朋友 
61         union_set(a,b);//加到同一个集合 
62     }
63     for(register int i=1;i<=k;i++)
64     {
65         int a,b;
66         cin>>a>>b;
67         if(re[a][b]==1)
68         {
69             printf("No problem");
70         }
71         if(re[a][b]==0&&find_set(a)!=find_set(b))
72         {
73             printf("OK");
74         }
75         if(re[a][b]==-1&&find_set(a)==find_set(b))
76         {
77             printf("OK but...");
78         }
79         if(re[a][b]==-1&&find_set(a)!=find_set(b))
80         {
81             printf("No way");
82         }
83         if(i<k)
84         printf("\n");
85     }
86     return 0;
87 }

 

posted @ 2022-04-22 16:45  江上舟摇  阅读(55)  评论(0)    收藏  举报