/* *State: Bellman_ford POJ1716 Accepted 640K 329MS C++ *题目大意: * 给n个区间,然后求一个最小的集合里面包含每个区间至少2个不同的元素。 * 注意元素均为整数。求这个最小集合的个数。 *解题思路: * 用差分约束条件来约束问题即可。设Si为0到i里面区间中为集合元素的个数。 * 有Su - S(v-1) >= 2, 0 <= S(n+1) - S(n) <= 1。根据这三个约束条件来 * 构图即可。 *解题困惑: * 为什么不能用最短路约束来求?看证明吧。由Bellman_ford改为spfa的时候wa * 了很多次,主要是因为初始化出问题了,init()的参数有可能是不对的,Bellman_ford * 不介意,因为它是枚举边就行,都不用考虑邻接表的顶点问题。 */
View Code
#include <iostream> #include <queue> #include <map> #include <string> #include <cstdio> #include <cstring> using namespace std; const int MAXN = 10005; const int MAXE = 1000005; const int inf = 0x3f3f3f3f; typedef struct _node { int u, v, w; int next; }N; N edge[MAXE]; int head[MAXN], cntEdge; void init() { cntEdge = 0; for(int i = 0; i < MAXN; i++) { head[i] = -1; } } void addEdge(int u, int v, int w) { edge[cntEdge].u = u; edge[cntEdge].v = v; edge[cntEdge].w = w; edge[cntEdge].next = head[u]; head[u] = cntEdge++; } int spfa(int s, int n) { int dis[MAXN], inQ[MAXN] = {0}, inN[MAXN] = {0}; for(int i = 0; i <= n; i++) dis[i] = -inf; queue<int> Q; Q.push(s); inQ[s] = 1; dis[s] = 0; while(!Q.empty()) { int pre = Q.front(); Q.pop(); inQ[pre] = 0; for(int f = head[pre]; f != -1; f = edge[f].next) { int son = edge[f].v; int w = edge[f].w; if(dis[pre] + w > dis[son]) { dis[son] = dis[pre] + w; if(!inQ[son]) { Q.push(son); inQ[son] = 1; } } } } /*for(int i = 0; i < n; i++) cout << dis[i] << " "; cout << endl;*/ return dis[n]; } int Bellman_ford(int s, int n) { int dis[MAXN]; for(int i = 0; i <= n; i++) dis[i] = -inf; dis[s] = 0; for(int i = 0; i < n-1; i++) { bool flag = false; for(int j = 0; j < cntEdge; j++) { int u = edge[j].u; int v = edge[j].v; int w = edge[j].w; if(dis[v] < dis[u] + w) { dis[v] = dis[u] + w; flag = true; } } if(!flag) break; } /*cout << "--------------" << endl; for(int i = 0; i <= 8; i++) cout << dis[i] << endl; cout << "--------------" << endl;*/ for(int f = 0; f < cntEdge; f++) { int u = edge[f].u, v = edge[f].v; int w = edge[f].w; if(dis[v] < dis[u] + w) return -1; } return dis[n] - dis[0]; } int main(void) { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif int n; while(scanf("%d", &n) == 1) { init(); int u, v, Max = -inf; for(int i = 0; i < n; i++) { scanf("%d %d", &u, &v); if(v + 1 > Max) Max = v + 1; addEdge(u, v + 1, 2); } for(int i = 0; i < Max; i++) { addEdge(i, i + 1, 0); addEdge(i + 1, i, -1); } //int sol = Bellman_ford(0, Max + 1); int sol = spfa(0, Max); printf("%d\n", sol); } return 0; }