poj1751 Highways

題目鏈接:http://poj.org/problem?id=1751
題意:給你一個n個點,點之間的邊權爲兩點間距離,而且有m條邊的距離爲0,現在讓你求這個圖的最小生成樹,且輸出最小生成樹上邊權不爲0的邊
解析:做最小生成樹的時候直接把邊存起來即可,最後輸出一下

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = 1e6+100;
struct node
{
    int u,v,c;
    node() {}
    node(int _u,int _v,int _c)
    {
        u = _u;
        v = _v;
        c = _c;
    }
    bool operator < (const node &b)const
    {
        return c<b.c;
    }
}a[maxn];
int fa[maxn];
int x[maxn],y[maxn];
int vis[1005][1005];
int getfa(int x)
{
    if(fa[x]==x)
        return fa[x];
    return fa[x] = getfa(fa[x]);
}
int dis(int x1,int y1,int x2,int y2)
{
    return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
}
int main(void)
{
    int n,m;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d %d",&x[i],&y[i]);
        fa[i] = i;
    }
    scanf("%d",&m);
    for(int i=0;i<m;i++)
    {
        int u,v;
        scanf("%d %d",&u,&v);
        vis[u][v] = 1;
    }
    int cnt = 0;
    for(int i=1;i<=n;i++)
    {
        for(int j=i+1;j<=n;j++)
        {
            if(vis[i][j] || vis[j][i])
                a[cnt++] = node(i,j,0);
            else
                a[cnt++] = node(i,j,dis(x[i],y[i],x[j],y[j]));
        }
    }
    sort(a,a+cnt);
    vector<pair<int,int> >ans;
    int cc = 0;
    for(int i=0;i<cnt;i++)
    {
        int t1 = getfa(a[i].u);
        int t2 = getfa(a[i].v);
        if(t1!=t2)
        {
            if(a[i].c>0)
                ans.push_back(make_pair(a[i].u,a[i].v));
            fa[t1] = t2;
            cc++;
            if(cc==n-1)
                break;
        }
    }
    for(int i=0;i<(int)ans.size();i++)
        printf("%d %d\n",ans[i].first,ans[i].second);
    return 0;
}
發佈了361 篇原創文章 · 獲贊 28 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章