Sign of Matrix UVA

来源:互联网 发布:cocos2d 源码 编辑:程序博客网 时间:2024/06/05 11:37

比较有新意的一道题目,考察的是差分约束,列出相应的差分约束方程,然后变换(不等号的方向全部变换为一致), 最终建图,求最短路径,排序后求出绝对值之差的和即可,具体实现见如下代码:

#include<iostream>#include<vector>#include<string>#include<set>#include<stack>#include<queue>#include<map>#include<algorithm>#include<cmath>#include<iomanip>#include<cstring>#include<sstream>#include<cstdio>#include<deque>#include<functional>using namespace std;class Edge{public:int from, to, weight;Edge(int f, int t, int w) :from(f), to(t), weight(w){}};class Solve{public:int n;vector<Edge> edge;vector<int> G[300];int dist[300];bool visit[300];void addEdge(int from,int to,int weight){edge.push_back(Edge(from, to, weight));G[from].push_back(edge.size()-1);}bool getRes(){queue<int> q;int amount[300];for (int i = 0; i < 2 * n; i++){q.push(i);visit[i] = true;dist[i] = 0;amount[i] = 1;}while (!q.empty()){int id = q.front();q.pop();visit[id] = false;for (int i = 0; i < G[id].size(); i++){int ide = G[id][i];int to = edge[ide].to;if (dist[to] > dist[id] + edge[ide].weight){dist[to] = dist[id] + edge[ide].weight;if (!visit[to]){q.push(to);visit[to] = true;amount[to]++;if (amount[to] > 2 * n+1) return false;}}}}return true;}void Init(){edge.clear();for (int i = 0; i < 300; i++) G[i].clear();for (int i = 0; i < n; i++){string s;cin >> s;for (int ind = 0; ind < n; ind++){if (s[ind] == '+'){addEdge(i, ind + n, -1);}else if (s[ind] == '-'){addEdge(ind + n, i, -1);}else{ //s[ind]=='0'addEdge(i, ind + n, 0);addEdge(ind + n, i, 0);}}}}int Deal(){Init();if (getRes()){sort(dist,dist+2*n);int res = 0;for (int i = 0; i < 2 * n; i++){res += abs(dist[i] - dist[n - 1]);}return res;}else{return -1;}}};int main(){Solve a;int Case = 0;while (cin >> a.n){if (a.n == -1) break;Case++;int t = a.Deal();cout << "Case " << Case << ": " << t << endl;}return 0;}/*40+00-+--0+000+00*/