zoukankan      html  css  js  c++  java
  • Codeforces 1207C Gas Pipeline (dp)

    题目链接:http://codeforces.com/problemset/problem/1207/C

    题目大意是给一条道路修管道,相隔一个单位的管道有两个柱子支撑,管道柱子高度可以是1可以是2,道路中可能存在十字路口,如果有十字路口,管道高度必须升至2,其中输入数据为01字符串和n,a,b ,0是正常道路1是遇到十字路口,n是道路长度,a是修每单位管道需要花费的钱,b是每单位高度柱子需要花费的钱,求修完管道的最小花费。题目保证管道开始和结束的时候高度为1。

    思路:动态规划题目,用dp[ i ][ j ]表示道路为 i 长度时候当前管道高度为 j -1 的最小花费,dp [ i ] [ 0 ] 表示道路长度到 i 的时候当前管道高度为1的最小花费,dp [ i ] [ 1 ] 为道路长度为 i 时当前管道高度为2的最小花费 。  从最初dp[ 0 ] [ 0 ] = b(初始只有一个高度1的柱子,花费 b),dp[ 0 ] [ 1 ] = 1e16开始进行状态转移(初始柱子高不能为2,设为最大值,这里不能设置为inf,因为数据范围大,longlong可以超过inf)。dp数组有以下几种转移状态:

    1. 当遇到十字路口,高度必须为1,所以此时dp[ i ] [ 1 ] = dp[ i -1 ] [ 1 ] + 2 * b + a,dp[ i ] [ 0 ]为无限大

    2.遇到非十字路口,我们可以选择升高高度,也可以降下来,或者是延续上一个单位路段的高度,总结下来就是高度任意地可以变为1和2,记录其最小花费。

    那么如果将此时高度变为1  ,则 转移方程为 dp[ i ][ 0 ] = min(dp[ i -1 ] [ 0 ] + a+ b , dp [ i -1 ] [ 1 ] + 2 * a + b );

    如果高度变为2 则 dp [ i ] [ 1 ] = min ( dp [ i - 1] [ 0 ] +  2 * a + 2 * b  ,dp [ i - 1] [ 1 ] + a + 2 * b) ;

    这几种状态不断更新到dp[ n ][ 0 ] 就是最终最小花费

    AC代码:

    #include<iostream>
    #include<vector>
    #include<cstring>
    #define maxn 200005
    #define MAX 1e16
    using namespace std;
    int t,n;
    long long int a,b;
    long long int dp[maxn][2];
    int main(){
    	cin>>t;
    	while(t--){
    		cin>>n;
    		cin>>a>>b;
    		string s;
    		cin>>s;
    		dp[0][0] = b;
    		dp[0][1] = MAX;
    		for(int i = 0;i<n;i++){
    			if(s[i] == '0'){
    				dp[i+1][0] = min(dp[i][0]+a+b,dp[i][1]+2*a+b);
    				dp[i+1][1] = min(dp[i][0]+2*a+2*b,dp[i][1]+a+2*b);
    			}
    			else{
    				dp[i+1][1] = dp[i][1]+a+2*b;
    				dp[i+1][0] = MAX;
    			}
    		}
    	    cout<<dp[n][0]<<endl;
    	}
    	return 0;
    }
  • 相关阅读:
    SQL Server 阻止了对组件 'Ole Automation Procedures' 的 过程'sys.sp_OACreate' 的访问
    谷歌浏览器扩展程序manifest.json参数详解
    获取天气api
    UVA 10385 Duathlon
    UVA 10668 Expanding Rods
    UVALIVE 3891 The Teacher's Side of Math
    UVA 11149 Power of Matrix
    UVA 10655 Contemplation! Algebra
    UVA 11210 Chinese Mahjong
    UVA 11384 Help is needed for Dexter
  • 原文地址:https://www.cnblogs.com/AaronChang/p/12129634.html
Copyright © 2011-2022 走看看