码迷,mamicode.com
首页 > 其他好文 > 详细

(带权并查集)

时间:2015-04-05 13:20:08      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

代数

Case Time Limit: 1000ms
Memory Limit: 65536KB
64-bit integer IO format: %lld      Java class name: Main

 

现有N个未知数A[1],A[2],…A[N],以及M个方程,每个方程都是形如A[s]+A[s+1]+A[s+2]+…A[t-1]+A[t]=c。现在求解这个方程组。

 

Input

 

输入的第一行为两个整数N和M(1<=N,M<=100000)。接下来的M行每行三个整数s,t,c(1 <= s, t <= N, 0 <= c < 10^9)。

 

Output

 

对于输入的每个方程,若该方程与前面的方程矛盾,则输出"Error!"并忽略这个方程,否则输出"Accepted!"。之后对于每个变量,若能求出这个变量的值,则输出这个变量,否则输出"Unknown!"。

 

Sample Input

3 5
1 3 3
1 3 2
2 3 2
1 1 0
1 1 1

Sample Output

Accepted!
Error!
Accepted!
Error! 
Accepted!
1
Unknown!
Unknown!

Source

Author

temperlsyer
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
#define maxn 100005
#define LL long long
int n,m,fa[maxn];
LL dist[maxn];
int find(int x)
{
    if(x==fa[x])
        return fa[x];
    int temp=fa[x];
    fa[x]=find(fa[x]);
    dist[x]+=dist[temp];
    return fa[x];
}
int ischeck(int s,int t,int c)
{
    int fx,fy;
    fx=find(s),fy=find(t);
    if(fx!=fy)
        return 1;
    else
    {
        if(dist[s]-dist[t]==c)
            return 1;
        else
            return 0;
    }
}
void Union(int s,int t,int c)
{
    int fx,fy;
    fx=find(s),fy=find(t);
    if(fx!=fy)
    {
        fa[fx]=fy;
        dist[fx]=dist[t]+c-dist[s];
    }
}
int isknow(int x)
{
    int y=x+1;
    int fx,fy;
    fx=find(x),fy=find(y);
    if(fx!=fy)
    {
        printf("Unknown!\n");
    }
    else
    {
        printf("%I64d\n",dist[x]-dist[y]);
    }
}
int main()
{
    int s,t,c;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(int i=1;i<maxn;i++)
            fa[i]=i,dist[i]=0;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&s,&t,&c);
            t++;
            if(ischeck(s,t,c))
            {
                Union(s,t,c);
                printf("Accepted!\n");
            }
            else
            {
                printf("Error!\n");
            }
        }
        for(int i=1;i<=n;i++)
            isknow(i);
    }
    return 0;
}

  

(带权并查集)

标签:

原文地址:http://www.cnblogs.com/a972290869/p/4393841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!