1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<bitset> #include<vector> #include<set>
using namespace std; const int N=5e2+10,M=2.5e6+10;
template <class T> inline void read(T &x) { x=0;bool f=0; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();} while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); if(f)x=-x; } template <class T,class ...T1> inline void read(T &x,T1 &...x1) { read(x),read(x1...); } template <class T> inline void write(T res) { if(res < 0) putchar('-'), res = -res; if(res > 9) write(res / 10); putchar(res % 10 + '0'); } template <> inline void write(char c) {putchar(c);} template <> inline void write(const char *s) { while(*s) putchar(*s ++); } template <class T, class ...ARC> inline void write(T res, ARC ...com) { write(res), write(com...);}
struct Node { int id; int x; bool operator<(const Node &t)const{return x==t.x?id<t.id:x<t.x;} }; int T,n,m,k; vector<Node>a; multiset<Node>s; bitset<(M<<1)>f[N]; bool vis[N]; inline void work(const vector<Node> &a) { s.clear(); for(auto x:a)if(x.x)s.insert(x); int si=s.size(); for(int i=1;i<si;i++) { Node x=*s.begin(),y=*s.rbegin(); s.erase(x),s.erase(y); write(x.id,' ',x.x,' ',y.id,' ',k-x.x,'\n'); y.x-=k-x.x; s.insert(y); } } inline void solve() { read(n,m,k); a.clear(); for(int i=1;i<=n;i++) { int x; read(x); a.push_back({i,x}); } if(m>=n-1) { for(auto &x:a) { while(x.x>=k&&m>n-1) x.x-=k,write(x.id,' ',k,'\n'),m--; if(!x.x)n--; } return work(a); } for(int i=0;i<=n;i++)f[i].reset(); f[0][M]=1; for(int i=1;i<=n;i++) { int cost=k-a[i-1].x; if(cost>0)f[i]=f[i-1]|f[i-1]<<cost; else f[i]=f[i-1]|f[i-1]>>(-cost); } if(!f[n][M+k])return puts("-1"),void();
int lim=n-1,now=k; vector<Node>ans; while(now) { for(int i=lim;~i;i--) { int cost=k-a[i].x; if(f[i][M+now-cost]) { now-=cost; lim=i-1; ans.push_back(a[i]); break; } } } work(ans); memset(vis,0,sizeof(vis)); for(auto x:ans)vis[x.id]=1; ans.clear(); for(auto x:a) if(!vis[x.id]) ans.push_back(x); work(ans); }
int main() { freopen("dish.in","r",stdin); freopen("dish.out","w",stdout); read(T); while(T--)solve(); return 0; }
|