Problem 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
思路:这道题是明显的最小树形图,只不过我们不知道根节点是谁,如果一个个去枚举肯定时间接受不了,所以这里采用了一种虚根的办法,建立一个虚根,并且将其与每个顶点连接起来,寻找以虚根为根节点的最小树形图。
#include<cstdio>
#include<cstring>
#include<algorithm>
#define Inf 0x7f7f7f7f
using namespace std;
typedef long long LL;
const int N = 1005;
struct node{
int u,v;
LL w;
}edge[N*N];
int per[N],id[N],vis[N];
int n,m,pos;
LL in[N];//最小入边权
LL solve(int root,int V,int E){
LL ret=0;
while(true){
//1.找每个结点的最小入边权
for(int i=0;i<V;i++)
in[i]=Inf;//初始化无限大
for(int i=0;i<E;i++){
int u=edge[i].u;
int v=edge[i].v;
if(edge[i].w<in[v]&&u!=v){//说明顶点v有边权较小的入边
in[v]=edge[i].w;
per[v]=u;//u --> v
if(u==root)//这个点是实际的起点
pos=i;
}
}
for(int i=0;i<V;i++){ //判断是否存在最小树形图
if(i==root) continue;//除了根结点外有点没有入边
if(in[i]==Inf) return -1; //说明根结点不能到达i,图不连通
}
//2.找环
int cnt=0; //记录环数
memset(id,-1,sizeof(id));
memset(vis,-1,sizeof(vis));
in[root]=0;
for(int i=0;i<V;i++){
ret+=in[i];
int v=i;
while(vis[v]!=i&&id[v]==-1&&v!=root){
vis[v]=i;
v=per[v];
}
if(v!=root&&id[v]==-1){
for(int u=per[v];u!=v;u=per[u])
id[u]=cnt;
id[v]=cnt++;
}
}
// printf("ret: %lld\n",ret);
if(cnt==0) break;
for(int i=0;i<V;i++)
if(id[i]==-1) id[i]=cnt++;
//3.建新图,缩点,重新标记
for(int i=0;i<E;i++){
int u=edge[i].u;
int v=edge[i].v;
edge[i].u=id[u];
edge[i].v=id[v];
if(id[u]!=id[v])
edge[i].w-=in[v];
}
V=cnt;
root=id[root];
}
return ret;
}
int main(){
while(~scanf("%d%d",&n,&m)){
LL sum=0;
for(int i=0;i<m;i++){
scanf("%d%d%lld",&edge[i].u,&edge[i].v,&edge[i].w);
edge[i].u++;
edge[i].v++;
sum+=edge[i].w;
}
sum++; //权值+1,是为了成为最大权值的一条边
for(int i=m;i<n+m;i++){
edge[i].u=0;
edge[i].v=i-m+1;
edge[i].w=sum;
}
LL ans=solve(0,n+1,n+m);
if(ans==-1||ans-sum>=sum)
printf("impossible\n");
else printf("%lld %d\n",ans-sum,pos-m);
puts("");
}
return 0;
}