Ice_cream’s world II
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
无根最小树形图
添加一个超级原点,从原点向1-n所有点建立一个权值为sum的有向边,sum = 所有边权和加1,然后跑以超级原点为root跑最小树形图,最终的答案 = ans-sum, root 是超级原点指向的点,用边和点的对应关系可以进行映射确定。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 1e3 + 10;
const int maxm = 4e4 + 10;
const long long INF = ((1LL) << 60);
const double eps = 1e-8;
#define type long long
int rt;
type in[maxn];
int id[maxn],used[maxn],pre[maxn];
struct edge
{
int u,v;
type c;
edge(int x = 0, int y = 0, type z = 0) : u(x),v(y),c(z) {}
}es[maxm];
type MTG(int root, int n, int m)
{
type res = 0;
while(1)
{
for(int i = 1; i <= n; i++) in[i] = INF,id[i] = used[i] = -1;
for(int i = 0; i < m; i++)
{
int u = es[i].u;
int v = es[i].v;
if(es[i].c < in[v] && u != v)
{
in[v] = es[i].c,pre[v] = u;
if(u == root) rt = i;
}
}//找最小的入边
for(int i = 1; i <= n; i++)
{
if(i == root) continue;
res += in[i];
if(in[i] == INF) return -1;
}//加入所有的入边权到答案中
int cnt = 0;
for(int i = 1; i <= n; i++)//枚举每个点为起点进行找环
{
int v = i;
while(v != root && used[v] != i && id[v] == -1) used[v] = i,v = pre[v];
if(v != root && id[v] == -1)//找到环的时候进行缩点编号
{
++cnt;
id[v] = cnt;
for(int u = pre[v]; u != v; u = pre[u]) id[u] = cnt;
}
}
if(cnt == 0) break;//无环则退出
for(int i = 1; i <= n; i++)
if(id[i] == -1) id[i] = ++cnt;
for(int i = 0; i < m; i++)//更新边
{
int u = es[i].u;
int v = es[i].v;
es[i].u = id[u];
es[i].v = id[v];
if(u != v) es[i].c -= in[v]; //更新边权
}
n = cnt;//更新节点数目和根节点编号
root = id[root];
}
return res;
}
int n,m;
int main()
{
while(~scanf("%d%d",&n,&m))
{
type sum = 1;
for(int i = 0; i < m; i++)
{
int u,v;
type c;
scanf("%d%d%lld",&u,&v,&c);
u++,v++;
sum += c;
es[i] = edge(u,v,c);
}
for(int i = 1; i <= n; i++)
{
es[m+i-1] = edge(n+1,i,sum);
}
type ans = MTG(n+1,n+1,m+n);
//cout << ans << endl;
//printf("Case #%d: ",++cs);
if(ans >= 2*sum) printf("impossible\n\n");
else printf("%lld %d\n\n",ans-sum,rt-m);
}
return 0;
}