给定一个字符矩阵,s[i][j]为+,-,0分别表示ai+……….aj的和为正,负,0。可以将连续和转化为前缀差,即s[i][j]为+可以表示为B[j]-B[i-1]为正,B[i]表示前i项的和,B[0]为0,然后拓扑排序找出相对关系再依次取值即可。注意相同的B[i],B[j]要注意保存,最后两者的值统一。最终输出结果a[i] = B[i]-B[i-1]l.
代码:
#include <iostream> #include <sstream> #include <cstdio> #include <climits> #include <cstring> #include <cstdlib> #include <string> #include <map> #include <cmath> #include <vector> #include <queue> #include <algorithm> #define esp 1e-6 #define pb push_back #define mp(a, b) make_pair((a), (b)) #define in freopen("in.txt", "r", stdin); #define out freopen("out.txt", "w", stdout); #define print(a) printf("%d ",(a)); #define bug puts("********))))))"); #define stop system("pause"); #define Rep(i, c) for(__typeof(c.end()) i = c.begin(); i != c.end(); i++) #define inf 0x0f0f0f0f using namespace std; typedef long long LL; typedef vector<int> VI; typedef pair<int, int> pii; typedef vector<pii,int> VII; typedef vector<int>:: iterator IT; const int maxn = 20; VI g[maxn], equa[maxn]; int du[maxn], L[maxn]; int B[maxn]; int n, cnt; bool toposort(void) { memset(du, 0, sizeof(du)); for(int i = 0; i <= n; i++) for(int j = 0; j < g[i].size(); j++) du[g[i][j]]++; queue<int> Q; for(int i = 0; i <= n; i++) if(!du[i]) Q.push(i); cnt = 0; while(!Q.empty()) { int x = Q.front(); Q.pop(); L[cnt++] = x; for(int i = 0; i < g[x].size(); i++) { int v = g[x][i]; du[v]--; if(!du[v]) Q.push(v); } } return cnt == n+1; } int main(void) { int T; for(int t = scanf("%d", &T); t <= T; t++) { for(int i = 0; i < maxn; i++) g[i].clear(),equa[i].clear(); memset(B, 0x0f, sizeof(B)); scanf("%d", &n); char s[1000]; scanf("%s", s); cnt = 0; for(int i = 1; i <= n; i++) for(int j = i; j <= n; j++) { if(s[cnt] == '+') g[i-1].pb(j); else if(s[cnt] == '-') g[j].pb(i-1); else equa[i-1].pb(j); cnt++; } toposort(); B[0] = 0; int k; for(int i = 0; i < cnt; i++) if(!B[L[k = i]]) break; for(int i = k -1; i >= 0; i--) B[L[i]] = i - k; for(int i = k+1; i < cnt; i++) B[L[i]] = i-k; for(int i = 0; i < cnt; i++) for(int j = 0; j < equa[L[i]].size(); j++) B[equa[L[i]][j]] = B[L[i]]; for(int i = 1; i <= n; i++) printf("%d ", B[i]-B[i-1]); puts(""); } return 0; }