计蒜客 Our Journey of Dalian Ends 最小费用最大流

Life is a journey, and the road we travel has twists and turns, which sometimes lead us to unexpected places and unexpected people.

Now our journey of Dalian ends. To be carefully considered are the following questions.

Next month in Xian, an essential lesson which we must be present had been scheduled.

But before the lesson, we need to attend a wedding in Shanghai.

We are not willing to pass through a city twice.

All available expressways between cities are known.

What we require is the shortest path, from Dalian to Xian, passing through Shanghai.

Here we go.

Input Format

There are several test cases.

The first line of input contains an integer tt which is the total number of test cases.

For each test case, the first line contains an integer m~(m\le 10000)m (m10000) which is the number of known expressways.

Each of the following mm lines describes an expressway which contains two string indicating the names of two cities and an integer indicating the length of the expressway.

The expressway connects two given cities and it is bidirectional.

Output Format

For eact test case, output the shortest path from Dalian to Xian, passing through Shanghai, or output -11 if it does not exist.

样例输入
3
2
Dalian Shanghai 3
Shanghai Xian 4
5
Dalian Shanghai 7
Shanghai Nanjing 1
Dalian Nanjing 3
Nanjing Xian 5
Shanghai Xian 8
3
Dalian Nanjing 6
Shanghai Nanjing 7
Nanjing Xian 8
样例输出
7
12
-1
题目来源

2017 ACM-ICPC 亚洲区(乌鲁木齐赛区)网络赛

从Dalian -> Xian 必须经过Shanghai , 每个城市最多经过一次。 最短路。

1 、必须经过Shanghai , 虚拟T ,   add(出Shanghai , T,  2 , 0 )

2、 虚拟源点S, add(S , Dalian , 1 , 0)  add(S , Xian , 1 , 0 )  

3 、每个城市最多经过一次 :

                u 不为上海add(入u , 出u , 1 , 0) ;

                u 为上海   add(入u , 出u , 2 , 0) 

4、 (u , v, w )    =>   add(出u , 入v , inf , w )  add(出v , 入u , inf , w )

跑最小费用最大流, 若最大流为2则存在解。 相当于, 从Dalian到Shanghai,  从Xian到Shanghai ( 每个城市最多一次) , 的两条路径,且最小费用。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.StringTokenizer;


public class Main {
    
    public static void main(String[] args) {
        new Task().solve();
    }
}

class Task {
    InputReader in = new InputReader(System.in) ;
    PrintWriter out = new PrintWriter(System.out) ;
    
    final long inf = Long.MAX_VALUE>>1 ;
    Map<String , Integer> hash = new HashMap<String, Integer>() ;
    int citySzie  ;
    
    int find(String key){
    	Integer value = hash.get(key) ;
    	if(value == null){
    		value = citySzie++ ;
    		hash.put(key, value) ;
    	}
    	return value ;
    }
    
    void solve(){
    	MinCostMaxFlow minCostMaxFlow = new MinCostMaxFlow() ;
    	int t = in.nextInt() ;
    	while(t-- > 0){
    		hash.clear() ; 
    		int m = in.nextInt() ;
    		int[] u = new int[m] ;
    		int[] v = new int[m] ;
    		long[] w = new long[m] ;
    		citySzie = 0 ;
    		for(int i = 0 ; i < m ; i++){
    			u[i] = find(in.next()) ;
    			v[i] = find(in.next()) ;
    			w[i] = in.nextLong() ;
    		}
    		int S = 2 * citySzie ;
    		int SH = find("Shanghai") ;
    		int T = 2 * citySzie + 1 ;
    		minCostMaxFlow.init(T) ;
    		minCostMaxFlow.addedge(S, find("Dalian"), 1, 0);
    		minCostMaxFlow.addedge(S, find("Xian"), 1, 0);
    		minCostMaxFlow.addedge(SH+citySzie, T, 2, 0);
    		for(int i = 0 ; i < citySzie ; i++){
    			if(i == SH){
    				minCostMaxFlow.addedge(i, i+citySzie, 2, 0) ;
    			}
    			else{
    				minCostMaxFlow.addedge(i, i+citySzie, 1, 0) ;
    			}
    		}
    		for(int i = 0 ; i < m ; i++){
    			minCostMaxFlow.addedge(u[i]+citySzie , v[i], inf , w[i]) ;
    			minCostMaxFlow.addedge(v[i]+citySzie , u[i], inf , w[i]) ;
    		}
    		minCostMaxFlow.doMCMF(S, T) ;
    		if(minCostMaxFlow.maxFlow != 2){
    			out.println(-1) ;
    		}
    		else{
    			out.println(minCostMaxFlow.minCost) ;
    		}
    	}
    	out.flush() ; 
    }
    
}

class MinCostMaxFlow{  
    final int MAXN = 10000*2 + 8 ;  
    final int MAXM = 10000*5 + 8 ;  
    final long INF = Long.MAX_VALUE>>1 ;  
    class Edge{  
        int to,next ;
        long cap,flow,cost ;  
        public Edge(int to , long cap , long cost , long flow , int next) {  
            this.to = to ;  
            this.cap = cap ;  
            this.cost = cost ;  
            this.flow = flow ;  
            this.next = next ;  
        }  
    }  
    Edge[] edge = new Edge[MAXM] ;  
    int[] head = new int [MAXN] ;  
    int tol ;  
    int[] pre = new int[MAXN] ;  
    long[] dis = new long[MAXN] ;  
    boolean[] vis = new boolean[MAXN] ;  
    int N;  
      
    void init(int n){   
        N = n + 2 ;  
        tol = 0;  
        Arrays.fill(head , -1) ;  
    }  
      
    void addedge(int u,int v,long cap,long cost){  
        edge[tol] = new Edge(v, cap, cost, 0, head[u]) ;  
        head[u] = tol++;  
        edge[tol] = new Edge(u, 0, -cost, 0, head[v]) ;  
        head[v] = tol++;  
    }  
  
    boolean spfa(int s,int t){  
        Queue<Integer> q = new LinkedList<Integer>() ;  
        for(int i = 0 ; i < N ; i++){  
            dis[i] = INF ;  
            vis[i] = false ;  
            pre[i] = -1 ;  
        }  
        dis[s] = 0 ;  
        vis[s] = true ;  
        q.add(s) ;  
        while(! q.isEmpty()){  
            int u = q.poll() ;  
            vis[u] = false ;  
            for(int i = head[u] ; i != -1 ; i = edge[i].next){  
                int v = edge[i].to ;  
                if(edge[i].cap > edge[i].flow && dis[v] > dis[u] + edge[i].cost){  
                    dis[v] = dis[u] + edge[i].cost ;  
                    pre[v] = i ;  
                    if(! vis[v]){  
                        vis[v] = true;  
                        q.add(v);  
                    }  
                }  
            }  
        }  
        if(pre[t] == -1)return false; //找不到一条增广路径  
        else return true;  
    }  
  
    long maxFlow ;  
    long minCost ;  
    void doMCMF(int s,int t){  
        maxFlow = 0 ;  
        minCost = 0 ;  
        while(spfa(s , t)){  
        	long Min = INF ;  
            for(int i = pre[t] ; i != -1 ; i = pre[edge[i^1].to])  
                Min = Math.min(Min ,  edge[i].cap - edge[i].flow) ;  
  
            for(int i = pre[t] ; i != -1 ; i = pre[edge[i^1].to]){  
                edge[i].flow += Min;  
                edge[i^1].flow -= Min;  
                minCost += edge[i].cost * Min ;  
            }  
            maxFlow += Min ;  
        }  
    }  
}  
 

class InputReader {    
    public BufferedReader reader;    
    public StringTokenizer tokenizer;    
    
    public InputReader(InputStream stream) {    
        reader = new BufferedReader(new InputStreamReader(stream), 32768);    
        tokenizer = new StringTokenizer("");    
    }    
    private void eat(String s) {    
        tokenizer = new StringTokenizer(s);    
    }    
    
    public String nextLine() {     
        try {    
            return reader.readLine();    
        } catch (Exception e) {    
            return null;    
        }    
    }    
    
    public boolean hasNext() {    
        while (!tokenizer.hasMoreTokens()) {    
            String s = nextLine();    
            if (s == null)    
                return false;    
            eat(s);    
        }    
        return true;    
    }    
    
    public String next() {    
        hasNext();    
        return tokenizer.nextToken();    
    }    
    
    public int nextInt() {    
        return Integer.parseInt(next());    
    }    
    
    public int[] nextInts(int n) {    
        int[] nums = new int[n];    
        for (int i = 0; i < n; i++) {    
            nums[i] = nextInt();    
        }    
        return nums;    
    }    
    
    public long nextLong() {    
        return Long.parseLong(next());    
    }    
    
    public double nextDouble() {    
        return Double.parseDouble(next());    
    }    
    
    public BigInteger nextBigInteger() {    
        return new BigInteger(next());    
    }    
    
}    





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值