poj1087(题意难懂)

这道题容易读懂,但是建图比较不容想到,源点到用电器建边,用电器到插头建边,插头到汇点建边,且权值都为1,置配器的两个插头节点建立权值为INF的边
抽象出现,其实最终的最大流量就是能够接通的电器数,只要用电器数-maxf就ok了。

这里被map函数搞死了,以后记得组后用string不要用char  map<string,int>

/*
* this code is made by LinMeiChen
* Problem:
* Type of Problem:
* Thinking:
* Feeling:
*/
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<list>
using namespace std;
typedef long long lld;
typedef unsigned int ud;
#define INF_MAX 0x3f3f3f3f
#define eatline() char chch;while((chch=getchar())!='\n')continue;
#define MemsetMax(a) memset(a,0x3f,sizeof a)
#define MemsetZero(a) memset(a,0,sizeof a)
#define MemsetMin(a) memset(a,-1,sizeof a)
#define MemsetFalse(a) MemsetZero(a)
#define PQ priority_queue
#define Q queue
#define maxn 100005
#define maxm 1000005
struct Edge
{
	int v, f;
	int next;
}E[maxm];
int head[maxn], level[maxn];
int k;

void add_edge(int u, int v, int f)
{
	E[k].v = v;
	E[k].f = f;
	E[k].next = head[u];
	head[u] = k++;

	E[k].v = u;
	E[k].f = 0;
	E[k].next = head[v];
	head[v] = k++;
}

bool BFS(int s, int t)
{
	memset(level, -1, sizeof level);
	Q<int>q;
	q.push(s);
	level[s] = 0;
	while (!q.empty())
	{
		int u = q.front(); q.pop();
		for (int i = head[u]; i != -1; i = E[i].next)
		{
			int v = E[i].v;
			if (level[v] == -1 && E[i].f > 0)
			{
				level[v] = level[u] + 1;
				q.push(v);
			}
		}
	}
	return level[t] >= 0;
}

int DFS(int u, int maxf, int t)
{
	if (u == t)
		return maxf;
	int res = 0;
	for (int i = head[u]; i != -1; i = E[i].next)
	{
		int v = E[i].v;
		if (level[v] == level[u] + 1 && E[i].f > 0)
		{
			int f = DFS(v, min(maxf - res, E[i].f), t);
			E[i].f -= f;
			E[i ^ 1].f += f;
			res += f;
			if (res == maxf)
				return res;
		}
	}
	if (res == 0)
		level[u] = -1;
	return res;
}

int Dinic(int s, int t)
{
	int ans = 0;
	while (BFS(s, t))
		ans += DFS(s, INF_MAX, t);
	return ans;
}

map<string,int>mp;

int main()
{
	int n, m, l;
	char str[30], ss[30];
	int indx;
	while (scanf("%d", &n) != EOF)
	{
		int s = 0, t=maxn-2 ;
		indx = 1;
		mp.clear();
		memset(head, -1, sizeof head);
		k = 0;

		for (int i = 1; i <= n; i++)
		{
			scanf("%s", str);
			mp[str] = indx++;
			add_edge(mp[str], t, 1);//插头到汇点连边
		}

		scanf("%d", &m);

		for (int i = 1; i <= m; i++)
		{
			scanf("%s%s", ss, str);

			if (!mp[ss])
				mp[ss] = indx++;
			if (!mp[str])
				mp[str] = indx++;
			add_edge(s, mp[ss], 1);//源点到用电器连边
			add_edge(mp[ss], mp[str], 1);//用电器到插头连边		
		}

		scanf("%d", &l);

		for (int i = 1; i <= l; i++)
		{
			scanf("%s%s", ss, str);
			
			if (!mp[ss])
				mp[ss] = indx++;
			if (!mp[str])
				mp[str] = indx++;

			add_edge(mp[ss], mp[str], INF_MAX);//置配器
		}

		printf("%d\n",m-Dinic(s, t));
	}
	return 0;
}

你可能感兴趣的:(栈,poj)