C - Ice_cream’s world II
Crawling in process...
Crawling failed
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
After awarded lands to ACMers, the queen want to choose a city be her capital. This is an important event in ice_cream world, and it also a very difficult problem, because the world have N cities and M roads, every road was directed. Wiskey is a chief engineer in ice_cream world. The queen asked Wiskey must find a suitable location to establish the capital, beautify the roads which let capital can visit each city and the project’s cost as less as better. If Wiskey can’t fulfill the queen’s require, he will be punishing.
Input
Every case have two integers N and M (N<=1000, M<=10000), the cities numbered 0…N-1, following M lines, each line contain three integers S, T and C, meaning from S to T have a road will cost C.
Output
If no location satisfy the queen’s require, you must be output “impossible”, otherwise, print the minimum cost in this project and suitable city’s number. May be exist many suitable cities, choose the minimum number city. After every case print one blank.
Sample Input
3 1 0 1 1 4 4 0 1 10 0 2 10 1 3 20 2 3 30
Sample Output
impossible 40 0思路:建一个虚节点,向其他所有点连边值比其他所有边和大,为sum,最后一定会得到最小树形图,判断这个最小树形图的值比sum+sum大则说明选了两条这种边,无答案否则答案就是其减去sum,边就是选了root 的边,由此可知道树根#include<cstdio> #include<cstring> #include<iostream> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) typedef long long type; using namespace std; const int nn=1005; const int mm=17009; const long long oo=1e18; type sum; class Edge { public:int u,v;type w; }e[mm]; int id[nn],vis[nn],pre[mm],city; type in[nn]; type Directed_MST(int root,int V,int E) { type ret=0; while(1) { FOR(i,0,V-1)in[i]=oo; in[root]=0; int u,v; FOR(i,0,E-1) { u=e[i].u;v=e[i].v; if(u!=v&&e[i].w<in[v]) { in[v]=e[i].w;pre[v]=u; if(u==root) city=i; } } FOR(i,0,V-1) if(in[i]==oo)return -1; //find cicle int bcc_no=0; clr(vis,-1);clr(id,-1); FOR(i,0,V-1) { ret+=in[i];//if(in[i]==sum)city=i; v=i; while(vis[v]!=i&&id[v]==-1&&v!=root) vis[v]=i,v=pre[v]; if(v!=root&&id[v]==-1) { for(int u=pre[v];u!=v;u=pre[u]) id[u]=bcc_no; id[v]=bcc_no++; } } if(bcc_no==0)break; FOR(i,0,V-1) if(id[i]==-1) id[i]=bcc_no++; FOR(i,0,E-1) { u=e[i].u;v=e[i].v; e[i].u=id[u]; e[i].v=id[v]; if(id[u]^id[v])e[i].w-=in[v]; } V=bcc_no;root=id[root]; } return ret; } int main() { int n,m; while(~scanf("%d%d",&n,&m)) { sum=0; FOR(i,0,m-1) { scanf("%d%d%I64d",&e[i].u,&e[i].v,&e[i].w); sum+=e[i].w; } ++sum; FOR(i,0,n-1) e[i+m].u=n,e[i+m].v=i,e[i+m].w=sum; type ans=Directed_MST(n,n+1,n+m); //cout<<ans<<endl; ans-=sum; if(ans>=sum)printf("impossible\n"); else printf("%I64d %d\n",ans,city-m); printf("\n"); } return 0; }