https://pintia.cn/problem-sets/994805342720868352/problems/994805456881434624
首先不難想到的是并查集,不過這里有一個關鍵的一點就是是字符串不是數字。
所以可以用哈希表來將字符串和數字編號來一一對應的映射起來。
其它的就是基本的并查集即可。
#include<bits/stdc++.h>
using namespace std
;
const int N
=1e4+10;
struct node
{string name
;int cnt
;
}Node
;
bool cmp(node a
,node b
) {return a
.name
<b
.name
;}
vector
<node
>ans
;
int p
[N
],cnt
[N
],sum
[N
],val
[N
],idx
=1;
int n
,k
;
unordered_map
<string
,int>hush1
;
unordered_map
<int,string
>hush2
;
unordered_map
<int,vector
<int>>mp
;
int find(int x
)
{if(x
!=p
[x
]) p
[x
]=find(p
[x
]);return p
[x
];
}
int main(void)
{cin
>>n
>>k
;for(int i
=1;i
<=n
;i
++) p
[i
]=i
,cnt
[i
]=1;for(int i
=1;i
<=n
;i
++){string a
,b
;int t
; cin
>>a
>>b
>>t
;if(!hush1
.count(a
)) hush1
[a
]=idx
++;hush2
[hush1
[a
]]=a
;if(!hush1
.count(b
)) hush1
[b
]=idx
++;hush2
[hush1
[b
]]=b
;if(find(hush1
[a
])!=find(hush1
[b
])){cnt
[find(hush1
[b
])]+=cnt
[find(hush1
[a
])];sum
[find(hush1
[b
])]+=sum
[find(hush1
[a
])]+t
;val
[hush1
[a
]]+=t
;val
[hush1
[b
]]+=t
;p
[find(hush1
[a
])]=find(hush1
[b
]);}else {val
[hush1
[a
]]+=t
;val
[hush1
[b
]]+=t
;sum
[find(hush1
[b
])]+=t
;}}for(int i
=1;i
<=n
;i
++) mp
[find(i
)].push_back(i
);for(auto i
=mp
.begin();i
!=mp
.end();i
++){auto temp
=i
->second
;if(temp
.size()<3) continue;if(sum
[i
->first
]<=k
) continue;int index
=0;for(int j
=0;j
<temp
.size();j
++){if(val
[temp
[j
]]>val
[temp
[index
]]) index
=j
;}Node
.name
=hush2
[temp
[index
]];Node
.cnt
=temp
.size();ans
.push_back(Node
);}cout
<<ans
.size()<<endl
;sort(ans
.begin(),ans
.end(),cmp
);for(int i
=0;i
<ans
.size();i
++) cout
<<ans
[i
].name
<<" "<<ans
[i
].cnt
<<endl
;return 0;
}
總結
以上是生活随笔為你收集整理的1034 Head of a Gang (30 分) 【难度: 中 / 知识点: 并查集】的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。