Powered by:AB_IN 局外人
P1536 村村通
這個題就是給了你一些現有的路線,問還需要多少將它們都連起來?
其實就是問父節點之間的連線。
即可。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n, m, ans, a, b, u, v;
ll fa[1005];
#define rep(i,x,y) for (int i=(x);i<=(y);i++)
ll find(ll x) {
if(fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
int main() {
while(cin>>n>>m){
ans=0;
rep(i,1,n) fa[i] = i;
rep(i,1,m) {
cin>>a>>b;
u=find(a); v=find(b);
fa[u]=v;
}
rep(i,1,n) if(find(i)==i) ans++;
cout<<ans-1<<endl;
}
return 0;
}
P2256 一中校運會之百米跑
相當於把下標變成字符串,一樣做。
#include <bits/stdc++.h>
#define rep(i,x,y) for (int i=(x);i<=(y);i++)
using namespace std;
map<string,string>fa;
string find(string x) {
if(fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
string name,name1,name2,u,v;;
int n,m,t;
int main()
{
cin>>n>>m;
rep(i,1,n){
cin>>name;
fa[name]=name;
}
rep(i,1,m){
cin>>name1>>name2;
u=find(name1);v=find(name2);
fa[u]=v;
}
cin>>t;
while(t--){
cin>>name1>>name2;
u=find(name1);v=find(name2);
if(u==v) cout<<"Yes."<<endl;
else cout<<"No."<<endl;
}
return 0;
}
P1111 修復公路
定義兩個數組,一個是結構體數組,用來存儲數據。一個是fa
數組,用來進行並查集操作。當村莊減到只剩1時,輸出時間即可。
#include <bits/stdc++.h>
typedef long long ll;
#define rep(i,x,y) for (ll i=(x);i<=(y);i++)
using namespace std;
struct sa{
ll x,y,t;
}a[200005];
int fa[200005];
ll find(ll x) {
if(fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
ll cmp(struct sa &a,struct sa &b){
if(a.t!=b.t) return a.t<b.t;
}
ll n,m,u,v;
namespace IO{
char ibuf[1<<21],*ip=ibuf,*ip_=ibuf;
char obuf[1<<21],*op=obuf,*op_=obuf+(1<<21);
inline char gc(){
if(ip!=ip_)return *ip++;
ip=ibuf;ip_=ip+fread(ibuf,1,1<<21,stdin);
return ip==ip_?EOF:*ip++;
}
inline void pc(char c){
if(op==op_)fwrite(obuf,1,1<<21,stdout),op=obuf;
*op++=c;
}
inline ll read(){
register ll x=0,ch=gc(),w=1;
for(;ch<'0'||ch>'9';ch=gc())if(ch=='-')w=-1;
for(;ch>='0'&&ch<='9';ch=gc())x=x*10+ch-48;
return w*x;
}
template<class I>
inline void write(I x){
if(x<0)pc('-'),x=-x;
if(x>9)write(x/10);pc(x%10+'0');
}
class flusher_{
public:
~flusher_(){if(op!=obuf)fwrite(obuf,1,op-obuf,stdout);}
}IO_flusher;
}
using namespace IO;
int main()
{
n=read();m=read();
rep(i,1,m) a[i].x=read(),a[i].y=read(),a[i].t=read();
rep(i,1,n) fa[i]=i;
sort(a+1,a+1+m,cmp);
rep(i,1,m){
u=find(a[i].x);
v=find(a[i].y);
if(u!=v) fa[u]=v,n--;
if(n==1) {write(a[i].t);return 0;}
}
write(-1);
return 0;
}
完結。