您的位置:首页 > 其它

【codeforces24A】Ring road

2015-09-04 10:58 686 查看
A. Ring road

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the
ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from
some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from
every city you can get to any other?

Input

The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai
to city bi, redirecting the traffic costs ci.

Output

Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.

Sample test(s)

Input

3

1 3 1

1 2 1

3 2 1

Output

1

Input

3

1 3 1

1 2 5

3 2 1

Output

2

Input

6

1 5 4

5 3 8

2 4 15

1 6 16

2 3 23

4 6 42

Output

39

Input

4

1 2 9

2 3 8

3 4 7

4 1 5

Output

0

题意 理解:有n个城市,他们之间有n条单向路,如果要将a到b之间的路调转方向,需要花c块钱,问,在保证所有的城市都能到达另一个城市的情况下,花费最少。

解题思路:这是一个单向环问题,最后就是要求顺时针走和逆时针修路最后谁花的钱最少。在存数据的时候用二维数组将题目给的本来的方向的路径值设为0,逆向的数值设为c,分两条路求花费,最后输出最小值。

code:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
using namespace std;
int a[105][105];
const int INF=1000;
int main()
{
int n,a1,b,c,l,lp,r,rp;
int mx1=0;
int mx2=0;
int mx;
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
a[i][j]=INF;
}
a[i][i]=0;
}
for(int i=0;i<n;i++){
scanf("%d%d%d",&a1,&b,&c);
a[a1][b]=0;
a[b][a1]=c;
}
if(n>3){
for(int i=2;i<=n;i++)
if(a[1][i]!=INF){
l=i;
break;
}
mx1+=a[1][l];
lp=1;
for(int i=l+1;i<=n;i++)
if(a[1][i]!=INF){
r=i;
break;
}
mx2+=a[1][r];
rp=1;
for(int i=1;i<=n;i++){
if(a[l][i]!=INF&&i!=lp&&i!=l){
mx1+=a[l][i];
lp=l;
l=i;
if(i==1)
break;
else{
i=0;
continue;
}
}
}
for(int i=1;i<=n;i++){
if(a[r][i]!=INF&&i!=rp&&i!=r){
mx2+=a[r][i];
rp=r;
r=i;
if(i==1)
break;
else{
i=0;
continue;
}
}
}
}
else
{
mx1=a[1][2]+a[2][3]+a[3][1];
mx2=a[1][3]+a[3][2]+a[2][1];
}
mx=min(mx1,mx2);
printf("%d\n",mx);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: