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

Re:ac代码

Posted by WilliamACM at 2013-03-10 23:42:41 on Problem 1984
In Reply To:【很好并查集中档题】 很有收获,贴代码 Posted by:WilliamACM at 2013-03-10 23:42:18
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N=40005;
int fa[N];
struct node
{
    int s,t,l;
    int x,y;
}a[N],b[N];
int n,m;
bool cmp1(node a,node b)
{
    return a.l<b.l;
}
int fx[N];
int fy[N];
int FA(int x)
{
    if(x==fa[x]) return x;
    int ans=FA(fa[x]);
    if(fa[x]!=ans)
    {
        fx[x]+=fx[fa[x]];
        fy[x]+=fy[fa[x]];
    }
    return  fa[x]=ans;
}
int query(int s,int t)
{
    if(FA(s)!=FA(t)) return -1;
//    cout<<FA(s)<<endl;
//    printf("%d : %d %d \n",s,fx[s],fy[s]);
//    printf("%d : %d %d \n",t,fx[t],fy[t]);
    return abs(fx[s]-fx[t])+abs(fy[s]-fy[t]);
}
void Union(node a)
{
    int f1=FA(a.s);
    int f2=FA(a.t);
    if(f1==f2) return;
    fa[f1]=f2;
    fx[f1]=a.x-fx[a.s]+fx[a.t];
    fy[f1]=a.y-fy[a.s]+fy[a.t];
    query(a.s,a.t);
}
bool cmp2(node a,node b)
{
    return a.x<b.x;
}
void init()
{
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        int l;
        char ss[9];
        scanf("%d%d%d%s",&a[i].s,&a[i].t,&l,ss);
        switch(ss[0])
        {
            case 'E':a[i].y=l;break;
            case 'W':a[i].y=-l;break;
            case 'N':a[i].x=l;break;
            case 'S':a[i].x=-l;break;
        }
    }
    int q;
    scanf("%d",&q);
    for(int i=0;i<q;i++)
    {
        scanf("%d%d%d",&b[i].s,&b[i].t,&b[i].l);
        b[i].x=i;
    }
    sort(b,b+q,cmp1);
    int cnt=0;
    for(int i=1;i<=n;i++) fa[i]=i;
    for(int i=0;i<q;i++)
    {
        while(cnt<b[i].l)
        {
            Union(a[cnt++]);
        }
        b[i].y=query(b[i].s,b[i].t);
    }
    sort(b,b+q,cmp2);
    for(int i=0;i<q;i++)
    printf("%d\n",b[i].y);
}
int main()
{
   // freopen("in.txt","r",stdin);
    init();
//    cout << "Hello world!" << endl;
    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