Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
Year 2900. Many people left Earth and built some cities on Mars.
Currently there are N cities, some of which are connected by narrow one-way roads.
The president of Mars has decided to build police stations throughout the Mars. Given the cost of building police stations at each city, we cannot build them at all cities, due to the financial deficit. The only requirement is that every city must be reachable from some police station by roads. They expect the cost of all stations as low as possible.
Input
The first line for each case contains two integers n, m(0 < n <= 5,000. 0 < m <= 100,000), the number of cities and roads. The follows n lines each contains two integers, i, c ( 0 < i <= n . 0 < c <=10,000 ), c represents the cost of building a police station in city i , The next m lines each contains two integers u and v ( 0 < u, v <= n), indicating that there is a road form u to v .
Output
For each test case, print the minimum cost of stations.
Sample Input
Sample Output
Source
FZU 2006 ICPC Qualification Round I#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
#include<bitset>
#include<climits>
#include<list>
#include<iomanip>
#include<stack>
#include<set>
using namespace std;
stack<int>sk;
bool insk[5010];
int step,dfn[5010],low[5010],belong[5010],tol;
struct Edge
{
int to,next;
}edge[100010];
int head[5010],tail;
void add(int from,int to)
{
edge[tail].to=to;
edge[tail].next=head[from];
head[from]=tail++;
}
void dfs(int from)
{
dfn[from]=low[from]=++step;
sk.push(from);
insk[from]=1;
for(int i=head[from];i!=-1;i=edge[i].next)
{
int to=edge[i].to;
if(dfn[to]==0)
{
dfs(to);
low[from]=min(low[from],low[to]);
}
else if(insk[to])
low[from]=min(low[from],dfn[to]);
}
if(dfn[from]==low[from])
{
int v;
do
{
v=sk.top();
sk.pop();
insk[v]=0;
belong[v]=tol;
}while(v!=from);
tol++;
}
}
int cost[5010],in[5010],mn[5010];
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;i++)
{
int v,c;
scanf("%d%d",&v,&c);
cost[v]=c;
}
tail=0;
memset(head,-1,sizeof(head));
while(m--)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v);
}
tol=step=0;
memset(dfn,0,sizeof(dfn));
for(int i=1;i<=n;i++)
if(dfn[i]==0)
dfs(i);
memset(mn,127,sizeof(mn));
for(int i=1;i<=n;i++)
mn[belong[i]]=min(mn[belong[i]],cost[i]);
memset(in,0,sizeof(in));
for(int i=1;i<=n;i++)
for(int j=head[i];j!=-1;j=edge[j].next)
if(belong[i]!=belong[edge[j].to])
in[belong[edge[j].to]]++;
int ans=0;
for(int i=0;i<tol;i++)
if(in[i]==0)
ans+=mn[i];
printf("%d\n",ans);
}
}