【DP】 BZOJ 1023: [SHOI2008]cactus仙人掌图

分成环形dp和树形dp,然后环形dp用单调队列做。。。。

#include <iostream>
#include <queue> 
#include <stack> 
#include <map> 
#include <set> 
#include <bitset> 
#include <cstdio> 
#include <algorithm> 
#include <cstring> 
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 50005
#define maxm 20000005
#define eps 1e-7
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
// head

struct Edge
{
	int v;
	Edge *next;
}E[maxm], *H[maxn], *edges;

int dfn[maxn];
int low[maxn];
int fa[maxn];
int f[maxn];
int a[maxn << 1];
int q[maxn << 1];
int dfs_clock, n, m, ans;

void addedges(int u, int v)
{
	edges->v = v;
	edges->next = H[u];
	H[u] = edges++;
}

void init()
{
	dfs_clock = 0;
	edges = E;
	memset(H, 0, sizeof H);
	memset(dfn, 0, sizeof dfn);
	memset(f, 0, sizeof f);
}

void dp(int cnt)
{
	for(int i = 0; i < cnt; i++) a[i + cnt] = a[i];
	int l = 0, r = 0;
	for(int i = 0; i < 2 * cnt; i++) {
		while(l < r && i - q[l] > cnt / 2) l++;
		while(l < r && f[a[i]] > f[a[q[r-1]]] + i - q[r-1]) r--;
		q[r++] = i;
		if(l + 1 < r) ans = max(ans, f[a[i]] + f[a[q[l]]] + i - q[l]);
	}
	for(int i = 1; i < cnt; i++) {
		int t = min(i, cnt - i);
		f[a[0]] = max(f[a[0]], f[a[i]] + t);
	}
}

void dfs(int u)
{
	dfn[u] = low[u] = ++dfs_clock;
	for(Edge *e = H[u]; e; e = e->next) if(e->v != fa[u]) {
		int v = e->v;
		if(!dfn[v]) {
			fa[v] = u;
			dfs(v);
			low[u] = min(low[u], low[v]);
		}
		else low[u] = min(low[u], dfn[v]);
	}
	for(Edge *e = H[u]; e; e = e->next) if(e->v != fa[u]) {
		int v = e->v;
		if(fa[v] == u && low[v] > dfn[u]) {
			ans = max(ans, f[u] + f[v] + 1);
			f[u] = max(f[u], f[v] + 1);
		}
	}
	
	for(Edge *e = H[u]; e; e = e->next) if(e->v != fa[u]) {
		int v = e->v;
		if(fa[v] != u && dfn[u] == low[v]) {
			int cnt = 0, vn = v;
			a[cnt++] = u;
			do {
				a[cnt++] = vn;
				vn = fa[vn];
			}while(vn != u);
			dp(cnt);
		}
	}
	
}

void work()
{
	int m2;
	while(m--) {
		scanf("%d", &m2);
		for(int i = 1; i <= m2; i++) scanf("%d", &a[i]);
		for(int i = 2; i <= m2; i++) {
			addedges(a[i-1], a[i]);
			addedges(a[i], a[i-1]);
		}
	}
	ans = 0;

	fa[1] = 0;
	dfs(1);
	printf("%d\n", ans);
}

int main()
{
	while(scanf("%d%d", &n, &m) != EOF) {
		init();
		work();
	}
	
	
	return 0;
}


你可能感兴趣的:(dp)