您的位置:首页 > 其它

Codeforces 706 C. Hard problem (dp)

2016-08-13 00:39 381 查看
题目链接:http://codeforces.com/problemset/problem/706/C

给你n个字符串,可以反转任意一个字符串,反转每个字符串都有其对应的花费ci。

经过操作后是否能满足字符串str[i]>=str[i-1],能就输出最小花费,不能输出-1。

dp[i][0] 表示不反转i的最小花费(str[i] >= str[i - 1] || str[i] >= reverse(str[i - 1]))

dp[i][1] 则表示反转i的最小花费...

初始dp[1][0] = 0, dp[1][1] = c[1]

要是dp[i][0/1]等于-1 就不能转移了

代码写的有点糟糕,还是太渣...

//#pragma comment(linker, "/STACK:102400000, 102400000")
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
typedef pair <int, int> P;
const int N = 1e5 + 5;
string str
;
LL num
, inf = 1e15;
LL dp
[2];

int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
for(int i = 1; i <= n; ++i)
cin >> num[i];
for(int i = 1; i <= n; ++i)
cin >> str[i];
int ok = 0;
memset(dp, -1, sizeof(dp));
dp[1][0] = 0, dp[1][1] = num[1];
for(int i = 2; i <= n; ++i) {
string str1 = str[i - 1]; //未反转
reverse(str[i - 1].begin(), str[i - 1].end());
string str2 = str[i]; //未反转
reverse(str[i].begin(), str[i].end());
if(dp[i - 1][0] == -1 && dp[i - 1][1] == -1) {
ok = -1; //不行了
break;
}
if(dp[i - 1][0] != -1) {
if(str2 >= str1) {
dp[i][0] = dp[i - 1][0];
}
if(str[i] >= str1) {
dp[i][1] = dp[i - 1][0] + num[i];
}
}
if(dp[i - 1][1] != -1) {
if(str2 >= str[i - 1]) {
dp[i][0] = min(dp[i - 1][1], dp[i][0] == -1 ? inf : dp[i][0]);
}
if(str[i] >= str[i - 1]) {
dp[i][1] = min(dp[i - 1][1] + num[i], dp[i][1] == -1 ? inf : dp[i][1]);
}
}
str[i] = str2; //赋值未反转
}
if(ok == -1) {
cout << -1 << endl;
}
else if(dp
[0] != -1 && dp
[1] != -1) {
cout << min(dp
[0], dp
[1]) << endl;
}
else if(dp
[0] != -1) {
cout << dp
[0] << endl;
}
else if(dp
[1] != -1) {
cout << dp
[1] << endl;
}
else {
cout << -1 << endl;
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: