hdu5876 Sparse Graph(補圖的最短路)

來源:互聯網
上載者:User

這道題目是補圖最短路,是點(資料很大)然後把原圖變成另一半,然後求源點到其他點的最短路,這道題如果硬來的話一定是逾時的,這是不用想的,畢竟200000個點的話,邊本來是5500條,但是要是找補圖的邊的話那就是20萬*20萬-5500,大概是這麼多,這實在是太多了,肯定是不行的,所以呢暴力枚舉所有點,如果與起點相連的邊不在原圖中,那麼距離就是起點的距離+1,然後用BFS再把這些點設為起點,再枚舉剩下的沒算出距離的點。

#include <iostream>#include <set>#include <string.h>#include <queue>using namespace std;const int INF=0x3f3f3f3f;const int maxn=200005;const int maxm=5500*10;int tot,head[maxn];int vis[maxn],dis[maxn];int s;struct Edge{    int to,next,w;}edge[maxm];void init(){    tot=0;    memset(head,-1,sizeof(head));    memset(vis,0,sizeof(vis));}void addedge(int u,int v,int w){    edge[tot].to=v;    edge[tot].w=w;    edge[tot].next=head[u];    head[u]=tot++;}void bfs(int n){    set<int>s1;//顯示當前還有多少點不在補圖裡    set<int>s2;//我覺得相當於一個中間變數    set<int>::iterator it;    for(int i=1;i<=n;i++)    {        if(i!=s)            s1.insert(i);//把不是原點的點都加入集合裡    }    queue<int>q;    q.push(s);    for(int i=1;i<=n;i++)        dis[i]=INF;    dis[s]=0;    while(!q.empty())    {        int u=q.front();        q.pop();        for(int i=head[u];i!=-1;i=edge[i].next)        {            int v=edge[i].to;            if(!s1.count(v))//如果v沒有出現過,則跳過                continue;            s1.erase(v);否則把該點從s1中刪除,加到s2裡,            s2.insert(v);        }        for( it=s1.begin();it!=s1.end();it++)        {            q.push(*it);            dis[*it]=dis[u]+1;        }        s1.swap(s2);//然後再把s1,s2交換,這樣的話s1裡面就又是沒有加進補圖裡的點了        s2.clear();    }}int main(){    ios::sync_with_stdio(false);    int T,n,m,a,b;    cin>>T;    while(T--)    {        init();        cin>>n>>m;        for(int i=1;i<=m;i++)        {            cin>>a>>b;            addedge(a,b,1);            addedge(b,a,1);        }        cin>>s;        bfs(n);        for(int i=1;i<=n;i++)        {            if(i==s)                continue;                cout<<dis[i];            if(i==n)                cout<<endl;            else cout<<" ";        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.