POJ1258最小生成树简单题
生活随笔
收集整理的這篇文章主要介紹了
POJ1258最小生成树简单题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
? ? ? 給你個圖,讓你求一顆最小生成樹。
思路:
? ? ?裸題,克魯斯卡爾或者普利姆都行。
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef struct
{
? ? int a ,b ,c;
}NODE;
NODE node[100*100+10];
int mer[105];
bool camp(NODE a ,NODE b)
{
? ? return a.c < b.c;
}
int finds(int x)
{
? ? return x == mer[x] ? x : mer[x] = finds(mer[x]);
}
int main ()
{
? ? int n ,i ,j ,ans;
? ? while(~scanf("%d" ,&n))
? ? {
? ? ? ? int nowid = 0;
? ? ? ? for(i = 1 ;i <= n ;i ++)
? ? ? ? {
? ? ? ? ? ? for(j = 1 ;j <= n ;j ++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? nowid++;
? ? ? ? ? ? ? ? scanf("%d" ,&node[nowid].c);
? ? ? ? ? ? ? ? node[nowid].a = i ,node[nowid].b = j;
? ? ? ? ? ? }
? ? ? ? ? ? mer[i] = i;
? ? ? ? }
? ? ? ? sort(node + 1 ,node + nowid + 1 ,camp);
? ? ? ? ans = 0;
? ? ? ? for(i = 1 ;i <= nowid ;i ++)
? ? ? ? {
? ? ? ? ? ? int x = finds(node[i].a);
? ? ? ? ? ? int y = finds(node[i].b);
? ? ? ? ? ? if(x == y) continue;
? ? ? ? ? ? ans += node[i].c;
? ? ? ? ? ? mer[x] = y;
? ? ? ? }
? ? ? ? printf("%d\n" ,ans);
? ? }
? ? return 0;
}
? ? ? 給你個圖,讓你求一顆最小生成樹。
思路:
? ? ?裸題,克魯斯卡爾或者普利姆都行。
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef struct
{
? ? int a ,b ,c;
}NODE;
NODE node[100*100+10];
int mer[105];
bool camp(NODE a ,NODE b)
{
? ? return a.c < b.c;
}
int finds(int x)
{
? ? return x == mer[x] ? x : mer[x] = finds(mer[x]);
}
int main ()
{
? ? int n ,i ,j ,ans;
? ? while(~scanf("%d" ,&n))
? ? {
? ? ? ? int nowid = 0;
? ? ? ? for(i = 1 ;i <= n ;i ++)
? ? ? ? {
? ? ? ? ? ? for(j = 1 ;j <= n ;j ++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? nowid++;
? ? ? ? ? ? ? ? scanf("%d" ,&node[nowid].c);
? ? ? ? ? ? ? ? node[nowid].a = i ,node[nowid].b = j;
? ? ? ? ? ? }
? ? ? ? ? ? mer[i] = i;
? ? ? ? }
? ? ? ? sort(node + 1 ,node + nowid + 1 ,camp);
? ? ? ? ans = 0;
? ? ? ? for(i = 1 ;i <= nowid ;i ++)
? ? ? ? {
? ? ? ? ? ? int x = finds(node[i].a);
? ? ? ? ? ? int y = finds(node[i].b);
? ? ? ? ? ? if(x == y) continue;
? ? ? ? ? ? ans += node[i].c;
? ? ? ? ? ? mer[x] = y;
? ? ? ? }
? ? ? ? printf("%d\n" ,ans);
? ? }
? ? return 0;
}
總結
以上是生活随笔為你收集整理的POJ1258最小生成树简单题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: poj1190深搜 生日蛋糕
- 下一篇: POJ1456贪心(set或者并查集区间