差分约束 poj 3169
Description
Windy has a country, and he wants to build an army to protect his country. He has picked up N girls and M boys and wants to collect them to be his soldiers. To collect a soldier without any privilege, he must pay 10000 RMB. There are some relationships between girls and boys and Windy can use these relationships to reduce his cost. If girl x and boy y have a relationship d and one of them has been collected, Windy can collect the other one with 10000-d RMB. Now given all the relationships between girls and boys, your assignment is to find the least amount of money Windy has to pay. Notice that only one relationship can be used when collecting one soldier.
Input
The first line of input is the number of test case.
The first line of each test case contains three integers, N, M and R.
Then R lines followed, each contains three integers xi, yi and di.
There is a blank line before each test case.
1 ≤ N, M ≤ 10000
0 ≤ R ≤ 50,000
0 ≤ xi < N
0 ≤ yi < M
0 < di < 10000
Output
Sample Input
2 5 5 8 4 3 6831 1 3 4583 0 0 6592 0 1 3063 3 3 4975 1 3 2049 4 2 2104 2 2 781 5 5 10 2 4 9820 3 2 6236 3 1 8864 2 4 8326 2 0 5156 2 0 1463 4 1 2439 0 4 4373 3 4 8889 2 4 3133
Sample Output
71071 54223
Source
//#include <bits/stdc++.h> #include<iostream> #include<cstdio> #include<queue> #include<cstring> #include<algorithm> using namespace std; #define maxn 100005 #define INF 9999999 typedef pair<int,int> pii; vector<pii> e[maxn]; int vis[maxn],cnt[maxn],d[maxn],n,ml,dl,flag; void add_edge(int x,int y,int z) { e[x].push_back(make_pair(y,z)); //e[y].push_back(make_pair(x,z)); } void init(int n) { for(int i=0; i<=n; i++) e[i].clear(); for(int i=0; i<=n; i++) d[i]=INF; } void spfa(int s) { queue<int>q; memset(vis,0,sizeof(vis)); flag=0; q.push(s); d[s]=0; vis[s]=1; while(!q.empty()) { int now=q.front(); cnt[now]++; //记录每个点的入队次数 if(cnt[now]>n) { flag=1; break; } vis[now]=0; q.pop(); for(int i=0; i<e[now].size(); i++) { int v=e[now][i].first; if(d[v]>d[now]+e[now][i].second) { d[v]=d[now]+e[now][i].second; if(!vis[v]) { q.push(v); vis[v]=1; } } } } if(flag) printf("-1\n"); else if(d[n]==INF) printf("-2\n"); else printf("%d\n",d[n]); } int main() { while(~scanf("%d %d %d",&n,&ml,&dl)) { init(n); for(int i=0; i<ml; i++) { int x,y,z; scanf("%d %d %d",&x,&y,&z); add_edge(x,y,z); } for(int i=0; i<dl; i++) { int x,y,z; scanf("%d %d %d",&x,&y,&z); add_edge(y,x,-z); //注意存边顺序,这个是个有向图,方向很重要 } for(int i=1;i<n;i++) e[i+1].push_back(make_pair(i,0)); //后一头牛一定在前一头牛前面 (其实不写也行,因为初始化的都是0,不可能出现负数) spfa(1); } }