CSU's 1256-day one-way street

Source: Internet
Author: User

Source: http://acm.csu.edu.cn/OnlineJudge/problem.php? Id = 1256

In a completely unidirectional directed graph, the minimum number of edges can be changed from 1 to n. Set the weight of the original edge to 0 and the weight of the edge in another direction to 1.

Resume list. Add_edge (u, v, 0); add_edge (v, U, 0); Use the spfa algorithm to find the minimum 1-> n weight, that is, the number of changes

Note that the maximum number of edges is 2*10000 rather than 10000, because this Te is really strange. It took a long time to find this error.

 1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #define INF 0x3f3f3f3f 5 const int maxn=5000+5,maxm=20000+5; 6 int first[maxn],next[maxm],v[maxm],w[maxm],dist[maxn],numedge; 7 bool done[maxn]; 8 void add_edge(int a,int b,int c) 9 {10     v[numedge]=b;11     next[numedge]=first[a];12     first[a]=numedge;13     w[numedge]=c;14     numedge++;15 }16 void spfa(void)17 {18     std::queue<int>q;19     q.push(1);20     done[1]=true;21     while(!q.empty()){22         int a=q.front();23         q.pop();24         done[a]=false;25         for(int e=first[a];e!=-1;e=next[e]){26             if(dist[v[e]]>dist[a]+w[e]){27                 dist[v[e]]=dist[a]+w[e];28                 if(!done[v[e]]){29                     q.push(v[e]);30                     done[v[e]]=true;31                 }32             }33         }34     }35 }36 int main()37 {38     int n,m;39     while(scanf("%d%d",&n,&m)!=EOF){40         memset(first,-1,sizeof(int)*(n+1));41         numedge=1;42         int a,b;43         for(int e=1;e<=m;e++){44             scanf("%d%d",&a,&b);45             add_edge(a,b,0);46             add_edge(b,a,1);47         }48         memset(done,false,sizeof(bool)*(n+1));49         for(int i=1;i<=n;i++)50             dist[i]=(i==1?0:INF);51         spfa();52         if(dist[n]>=INF)53             printf("-1\n");54         else55             printf("%d\n",dist[n]);56     }57     return 0;58 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.