Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

看了很多方法,代码都比较难理解,我这个比较好理解.

Posted by 17310320725 at 2018-08-29 10:43:14 on Problem 1679
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;
const int maxx = 500;
struct node
{
    int l,r,value;
} q[50000],fei[maxx];
int fa[maxx];
int n,m;

void init()
{
    for(int i=0; i<=n+10; i++)
        fa[i]= i;
}

bool cmd(node a,node b)
{
    return a.value < b.value;
}

int Find(int x)
{
    if (x != fa[x])
        fa[x] = Find(fa[x]);
    return fa[x];
}

bool Union(int x,int y)
{
    int xx = Find(x);
    int yy = Find(y);
    if (xx != yy)
    {
        fa[xx] = yy;
        return true;
    }
    return false;
}

int main()
{
    int t,ans,ano,l;
    bool vis,temp;
    cin>>t;
    while(t--)
    {
        l=0;
        cin>>n>>m;
        init();
        for(int i=0; i<m; i++)
            scanf("%d%d%d",&q[i].l,&q[i].r,&q[i].value);
        sort(q,q+m,cmd);
        ans = 0;
        for(int i=0; i<m; i++)
            if (Union(q[i].l,q[i].r))
            {
                ans += q[i].value;
                fei[l].l = q[i].l;
                fei[l].r = q[i].r;
                l++;
            }
        vis = temp = true;
        for(int i=0; i<l; i++)
        {
            init();
            ano = 0;
            for(int j=0; j<m; j++)
                if ( q[j].l != fei[i].l || q[j].r != fei[i].r )
                    if (Union(q[j].l,q[j].r))
                        ano += q[j].value;
            if (ano == ans)
            {
                for(int k=1; k<n; k++)
                    if (Find(k) != Find(k+1))
                    {
                        vis = false;
                        break;
                    }
                if (vis)
                    temp = false;
            }
            if (!temp)
                break;
        }
        if (temp)
            cout<<ans<<endl;
        else
            puts("Not Unique!");
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator