【BZOJ】1202: [HNOI2005]狡猾的商人

來源:互聯網
上載者:User

標籤:距離   tar   exp   csdn   ini   while   std   printf   --   

【演算法】並查集

【題解】

由於存在負數,判斷資訊合法性的途徑只有多個已知區間能組成一個已知大區間。

用並查集維護已知區間,每次將(x-1,y)連邊,就把這兩個端點送入並查集,後面如果需要合法性判斷時就要必然會訪問到他們之一。

每次的讀入v相當於v[y]-v[x-1],維護並查集每個節點到其根的距離。

連邊涉及並查集的合并時,即fa[fa[x-1]]=fa[y]時,要更新fa[x-1]的距離(原為0)為到新根fa[y]的距離,注意首碼和的方向問題就能得出計算式。

最後,注意find過程中更新距離時必須嚴格按照以下過程執行:

int t=find(fa[x]);

d[x]+=d[fa[x]];

fa[x]=t;

這是維護並查集距離的常用套路。

不明白本蒟蒻口胡的可以左轉:http://blog.csdn.net/cjk_cjk/article/details/46681371

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=110;int fa[maxn],d[maxn];int n,m,T;int find(int x){    if(fa[x]==x)return x;    int t=find(fa[x]);    d[x]+=d[fa[x]];    fa[x]=t;    return fa[x];}int main(){    scanf("%d",&T);    while(T--)     {         memset(d,0,sizeof(d));         scanf("%d%d",&n,&m);        for(int i=0;i<=n;i++)fa[i]=i;         bool flag=0;         for(int i=1;i<=m;i++)          {              int x,y,w;              scanf("%d%d%d",&x,&y,&w);              x--;              int p=find(x),q=find(y);              if(p!=q)               {                   fa[p]=q;                   d[p]=d[y]-(d[x]+w);//注意首碼和方向                }              else if(d[y]-d[x]!=w){flag=1;break;}          }         if(flag)printf("false\n");else printf("true\n");     }    return 0;}
View Code

 

【BZOJ】1202: [HNOI2005]狡猾的商人

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.