HDU 3038 並查集 How Many Answers Are Wrong

        題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=3038    

        題目大意:給出n,m兩個數,n代表一串數字序列中數字的個數(序列未知),m代表了m次詢問,下面給出m行,每行有三個數字,A,B,S,代表從第A到第B個數的和爲S,詢問當前這一次S的值與上面的信息有無衝突,若有衝突則答案+1。

         本題借鑑了這位大神的博客http://blog.csdn.net/niushuai666/article/details/6981689   

         但一開始被這位博客中的樣例誤導,錯誤樣例如下,[1,5]的和爲100,但[1,2]的和爲200時衝突,但這是不對的。題目中只說數字爲整數,但有可能爲負數。所以只有噹噹前詢問中的A與B在前幾次詢問中出現過後纔有可能衝突,如[1,2]和爲100,[1,5]的和爲200,如給出[3,5]的和爲300則與前兩句衝突。

        樣例雖然錯了但這位大神的思路卻十分清晰。首先,我們將思路轉化,A到B的和可以轉化爲,B減去A-1的差,本題的關鍵是設置一個數組val[i],這個數組中的值的意思是i與父節點的差。

        (1)上文提到只有噹噹前詢問中的A與B在前幾次詢問中出現過後纔有可能衝突,所以,當A,B未出現時,求出A,B的父節點FA,FB,然後將FA,FB合併。合併原理如下,val[i]中存的是i與父節點的差,也可以理解爲向量i—>Fi。

         現在有兩向量A—>FA , B—>FB ,需要合成FA—>FB,

                      

        由向量的性質可以輕易推出(FA—>FB) = (B—>FB) - (B—>FA)

                         

        又由上圖可知 (B—>FA) =  (A—>FA) -  (A—>B)

        所以我們最終可以推出(FA—>FB) = (B—>FB) -  (A—>FA) +  (A—>B)

        即     ufs[fb]=fa;

                 val[fb]=val[a]-val[b]+s;

        (2)第二種情況爲給出的兩個端點的父節點一致,則說明兩者都已經出現過,這時僅需判斷本次詢問與我們已經儲存的信息是否矛盾。

                                   

            即判斷 (A—>B) = (A—>FAB) - (B—>FAB)

            即val[a]-val[b]=s

            

            下面爲代碼

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
#include <limits>
#include <vector>
#include <list>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <complex>

using namespace std;

#define debug cout<<"???"<<endl
#define sync std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
#define frein freopen("in.txt", "r", stdin)
#define freout freopen("out.txt", "w", stdout)

const int MAXN=200010;


int n,m;
int ufs[MAXN];
int val[MAXN];

void init(int n)
{
    for(int i=0;i<=n;i++)
        ufs[i]=i,val[i]=0;

}

int finda(int x)
{
    if(ufs[x]!=x)
    {
        int t=ufs[x];
        ufs[x]=finda(ufs[x]);
        val[x]+=val[t];
    }
    return ufs[x];
}


int main()
{

    while(cin>>n>>m)
    {
        init(n);
        int a,b,w;
        int ans=0;
        for(int i=1;i<=m;i++)
        {
            cin>>a>>b>>w;
            a--;
            int fa=finda(a);
            int fb=finda(b);
            if(fa!=fb)
            {
                ufs[fa]=fb;
                val[fa]=val[b]-val[a]+w;
            }
            else
            {
                if(val[a]-val[b]!=w) ans++;
            }

        }
        cout<<ans<<endl;

    }




}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章