UVALive 6680-动态规划dp

来源:互联网 发布:python数据挖掘薪资 编辑:程序博客网 时间:2024/05/15 23:49

题意:给出一段对话,找出最长的对话,并输出这段对话的每一行。

思路:dp+dfs 建树,找最深度

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <stack>#include <sstream>#include <vector>#include <set>#include <map>#include <cmath>#include <string>#include <sstream>#include <list>using namespace std;#define pb push_back#define F first#define S second#define fin freopen("in.txt", "r", stdin)#define fout freopen("out.txt", "w", stdout)const int maxn = 50000 + 10;const int INF = 0x3f3f3f3f;const int MOD = 1e9 + 7;const double eps = 1e-8;const double PI = acos(-1.0);const int dir[4][2] = {0,1,1,0,0,-1,-1,0};const int dir2[8][2] = {0,1,1,1,1,0,1,-1,0,-1,-1,-1,-1,0,-1,1};typedef long long ll;typedef unsigned long long ull;typedef pair<int,int> P;vector<int> v[maxn];vector<int > ans;map<string,P> mp;int dp[maxn],pre[maxn], n;string s, name, word;bool  ok;void dfs(int u);int main(){    while (mp.clear() , cin >> n) {        getchar();        for (int i=0; i<n; i++) {            getline(cin, s);            stringstream ss(s);            ss >> name;            name.resize(name.size()-1); //取前name.size()-1个字符为串            dp[i] = 1; pre[i] = -1; //dp为深度,pre为前一行            while (ss >> word) {                if (word == name) continue;                if (mp[word].F + 1 > dp[i]) {                    dp[i] = mp[word].F + 1;                    pre[i] = mp[word].S;                }            }            if ( !mp.count(name) ) mp[name] = make_pair(dp[i], i);            if ( mp[name].F < dp[i] ) mp[name].F = dp[i], mp[name].S = i;        }        int pos = max_element(dp, dp+n) - dp; //得到数组中最大值所在的位置        printf("%d\n", dp[pos]);//输出深度        ok = true;        dfs(pos);        puts("");    }    return 0;}void dfs(int u) {    if (u == -1) return;    dfs(pre[u]);    if (!ok) printf(" ");    printf("%d", u+1);    ok = false;    return;}


0 0
原创粉丝点击