四种约束条件。。照做就行了。。
最长路建图。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <deque>
#define rep(i, l, r) for(int i=l; i<=r; i++)
#define down(i, l, r) for(int i=l; i>=r; i--)
#define N 100000
#define MAX 1<<30
using namespace std;
int read()
{
int x=0, f=1; char ch=getchar();
while (ch<'0' || ch>'9') { if (ch=='-') f=-1; ch=getchar(); }
while (ch>='0' && ch<='9') { x=x*10+ch-'0'; ch=getchar(); }
return x*f;
}
struct node{int y, v, n;} e[N*10]; int fir[N], en;
int n, v[N], d[N], c[N];
bool b[N], ans;
char s[50];
void Add(int x, int y, int v) { en++; e[en].y=y, e[en].v=v, e[en].n=fir[x], fir[x]=en; }
int main()
{
n=read(); int t=0;
while (n)
{
t++;
rep(i, 1, n) fir[i]=0; en=0; ans=true;
rep(i, 1, n) v[i]=read();
scanf("%s", s);
while (s[0] != '#')
{
int x=read(), y=read();
if (s[0]=='S' && s[2]=='S') Add(y, x, 0);
else if (s[0]=='S' && s[2]=='F') Add(y, x, v[y]);
else if (s[0]=='F' && s[2]=='S') Add(y, x, -v[x]);
else if (s[0]=='F' && s[2]=='F') Add(y, x, v[y]-v[x]);
scanf("%s", s);
}
deque <int> q;
rep(i, 1, n) b[i]=1, c[i]=1, d[i]=0, q.push_back(i);
while (!q.empty())
{
int x=q.front(), o=fir[x], y=e[o].y; b[x]=false; q.pop_front();
if (c[x] > n) { ans=false; break; }
while (o)
{
if (d[y] < d[x]+e[o].v)
{
d[y] = d[x]+e[o].v;
if (!b[y]) b[y]=1, c[y]++, !q.empty()&&d[y]>=d[q.front()] ? q.push_front(y) : q.push_back(y);
}
o=e[o].n, y=e[o].y;
}
}
printf("Case %d:\n", t);
if (!ans) printf("impossible\n"); else
{
int a=MAX; rep(i, 1, n) if (a > d[i]) a=d[i]; rep(i, 1, n) printf("%d %d\n", i, d[i]-a);
}
printf("\n"); n=read();
}
return 0;
}