POJ-2421 最小生成树 算法复习计划
2014-07-22 09:42
399 查看
比赛的时候常常做出来的题目都是模拟和水题或者是DP什么的,复习一下算法以免忘掉
基本是裸地最小生成树,给出矩阵转化为边,然后把已建好的边的权值改为0,最后用kruskal就好了。
基本是裸地最小生成树,给出矩阵转化为边,然后把已建好的边的权值改为0,最后用kruskal就好了。
#include <cstring> #include <string> #include <fstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cctype> #include <algorithm> #include <queue> #include <set> #include <vector> #include <stack> #include <ctime> #include <cstdlib> #include <functional> #include <cmath> using namespace std; #define PI acos(-1.0) #define maxn 1005 #define eps 1e-7 #define INF 0x7FFFFFFF #define ff sqrt(5.0) typedef long long ll; int n,m,cnt,father[maxn]; struct node { int s; int next; int w; }edge[maxn*maxn];//邻接表 int map[maxn][maxn];//邻接矩阵 int find(int x)//寻找根节点 { int r=x; while(father[r]!=r) { r=father[r]; } return r; } bool unoin(int x,int y)//判断是否构成环 { int fx=find(x); int fy=find(y); if(fx!=fy)//不构成环 { father[fx]=fy; return 1; } return 0;//构成环 } void kruskal()//算法 { int ans=0; for(int i=0;i<cnt;i++) { if(unoin(edge[i].s,edge[i].next)) { ans+=edge[i].w; } } cout<<ans<<endl; } bool cmp(node a,node b)//从小到大排列 { return a.w<b.w; } int main() { for(int i=0;i<=maxn;i++) { father[i]=i; } scanf("%d",&n); cnt=0; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { scanf("%d",&map[i][j]); } } for(int i=1;i<n;i++) { for(int j=i+1;j<=n;j++) { if(map[i][j]!=0) { edge[cnt].s=i; edge[cnt].next=j; edge[cnt++].w=map[i][j]; } } } scanf("%d",&m); int p,q; while(m--) { scanf("%d %d",&p,&q); for(int i=0;i<cnt;i++) { if((edge[i].s==p&&edge[i].next==q)||(edge[i].s==q&&edge[i].next==p)) { edge[i].w=0; break; } } } sort(edge,edge+cnt,cmp); kruskal(); return 0; }
相关文章推荐
- POJ2421——最小生成树复习
- poj 1251 1258 2421 2485(最小生成树prime)
- POJ 1251--Jungle Roads(最小生成树,Prime算法)
- 分量算法poj 1751 Highways 最小生成树之Kruskal(克鲁斯卡尔)算法
- 初级->图算法->最小生成树 poj 3026 Borg Maze
- (kruscal12.1.1)POJ 2421 Constructing Roads(使用kruscal算法来生成最小生成树&&计算最小带权路径和)
- poj 2421 Constructing Roads 最小生成树
- POJ 2421 Constructing Roads(最小生成树)
- POJ2421 prim算法求最小生成树
- POJ-1251 Jungle Roads 最小生成树 两种算法的简单模板
- poj 2421 最小生成树(prime) 模版题
- 最小生成树 POJ——Truck History(没看懂题,直接根据测试用例YY的,我的Kusal 写法复习)
- 【算法复习】图的最小生成树(Prim&Kruskal)
- POJ 2421 最小生成树
- poj 2421 Constructing Roads 最小生成树(已经存在几条边) KRUSKAL
- POJ 1861 Network [最小生成树算法MST-kruskal 数据结构-并查集 union-find sets]
- 初级->图算法->最小生成树 poj 1258 Agri-Net
- Poj 2421 Constructing Roads(Prim 最小生成树)
- POJ 2421 图的最小生成树 prim算法 模板代码的利用
- poj 1751 Highways 最小生成树之Kruskal(克鲁斯卡尔)算法