A。欧拉回路
束。
3 3 1 2 1 3 2 3 3 2 1 2 2 3 0
1 0
欧拉回路
学习到了如何判断无向图的连通性
使用并查集
看看最后父节点有几个 只有一个的话就为连通的
并查集最后一般是循环 father[i]==i 来判断各种关系
无向图欧拉回路条件:
1.连通 2.度全为奇数
编程实现如下
#include<iostream>
#include<cstdio>
using namespace std;
const int maxV=1000;
const int maxE=maxV*maxV/2+7;
int degree[maxV+7];
int pre[maxV+7];
int E,V;
void init(){
for(int i=1;i<=maxV;i++) pre[i]=i;
}
int find(int x){
int temp;
for(temp=x;pre[temp]!=temp;temp=pre[temp]);
while(x!=temp){
int t=pre[x];
pre[x]=temp;
x=t;
}
return temp;
}
void mix(int x,int y){
int fx=find(x), fy=find(y);
if(fx!=fy) pre[fx]=fy;
}
bool isEuler(){
for(int i=1;i<=V;i++){
if(degree[i]&1) return false;
}
return true;
}
bool isConnct(){
int cnt=0;
for(int i=1;i<=V;i++)
if(pre[i]==i) cnt++;
if(cnt==1) return true;
return false;
}
int main(){
while(~scanf("%d",&V)&&V){
scanf("%d",&E);
memset(degree,0,sizeof(degree));
init();
for(int i=1;i<=E;i++){
int fr,to;
scanf("%d%d",&fr,&to);
degree[fr]++;
degree[to]++;
mix(fr,to);
}
// if(isConnct()) cout<<"Y"<<endl;
if(isConnct()&&isEuler()) cout<<1<<endl;
else cout<<0<<endl;
}
return 0;
}
B.还是畅通工程
当N为0时,输入结束,该用例不被处理。
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3
5
Huge input, scanf is recommended.
Hint
方法思路是:
这道题目是求最小生成树
使用kruskal算法
每次取最小的边 ,判断这条边的两个节点是否已经取了,用并查集来维护
取了之后就加入并查集中
取权值最小的边,可以有多种方法,用优先队列,把边都放到优先队列中(超时)
用vector(超时) 用数组(156ms)就可以过
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int father[105];
int find_(int x){
if(x==father[x]) return x;
return father[x]=find_(father[x]);
}
int find(int x){
int temp;
for(temp=x;father[temp]!=temp;temp=father[temp]);
while(x!=temp){
father[x]=temp;
x=father[x];
}
return temp;
}
void merge(int u,int v){
int x=find(u);
int y=find(v);
if(x!=y)
father[x]=y;
}
class ss{
public:
int s,e,w;
friend bool operator < (const ss&a,const ss& o){
return a.w<o.w;
}
};
ss vec[100005];
int main(){
int n;
while(scanf("%d",&n)&&n){
int num=n*(n-1)/2;
int i;
for(i=0;i<num;i++){
scanf("%d%d%d",&vec[i].s,&vec[i].e,&vec[i].w);
}
for(i=1;i<=n;i++)
father[i]=i;
int ans=0;
sort(vec,vec+num);
/*while(!que.empty()){
ss tmp=que.top();
que.pop();
int s=tmp.s,e=tmp.e,w=tmp.w;
int x=find(s),y=find(e);
if(x!=y){
ans+=w;
father[x]=y;
}
}*/
for(i=0;i<num;i++){
ss tmp=vec[i];
int s=tmp.s,e=tmp.e,w=tmp.w;
int x=find(s),y=find(e);
if(x!=y){
ans+=w;
father[x]=y;
}
}
printf("%d\n",ans);
//cout<<ans<<endl;
}
return 0;
}